context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
#if !NOT_UNITY3D
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;
using UnityEngine;
using UnityEngine.Serialization;
using Zenject.Internal;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Zenject
{
public abstract class Context : MonoBehaviour
{
[FormerlySerializedAs("Installers")]
[SerializeField]
List<MonoInstaller> _installers = new List<MonoInstaller>();
[SerializeField]
List<MonoInstaller> _installerPrefabs = new List<MonoInstaller>();
[SerializeField]
List<ScriptableObjectInstaller> _scriptableObjectInstallers = new List<ScriptableObjectInstaller>();
List<InstallerBase> _normalInstallers = new List<InstallerBase>();
public IEnumerable<MonoInstaller> Installers
{
get
{
return _installers;
}
set
{
_installers.Clear();
_installers.AddRange(value);
}
}
public IEnumerable<MonoInstaller> InstallerPrefabs
{
get
{
return _installerPrefabs;
}
set
{
_installerPrefabs.Clear();
_installerPrefabs.AddRange(value);
}
}
public IEnumerable<ScriptableObjectInstaller> ScriptableObjectInstallers
{
get
{
return _scriptableObjectInstallers;
}
set
{
_scriptableObjectInstallers.Clear();
_scriptableObjectInstallers.AddRange(value);
}
}
// Unlike other installer types this has to be set through code
public IEnumerable<InstallerBase> NormalInstallers
{
get
{
return _normalInstallers;
}
set
{
_normalInstallers.Clear();
_normalInstallers.AddRange(value);
}
}
public abstract DiContainer Container
{
get;
}
public void AddNormalInstaller(InstallerBase installer)
{
_normalInstallers.Add(installer);
}
void CheckInstallerPrefabTypes()
{
foreach (var installer in _installers)
{
Assert.IsNotNull(installer, "Found null installer in Context '{0}'", this.name);
#if UNITY_EDITOR
Assert.That(PrefabUtility.GetPrefabType(installer.gameObject) != PrefabType.Prefab,
"Found prefab with name '{0}' in the Installer property of Context '{1}'. You should use the property 'InstallerPrefabs' for this instead.", installer.name, this.name);
#endif
}
foreach (var installerPrefab in _installerPrefabs)
{
Assert.IsNotNull(installerPrefab, "Found null prefab in Context");
#if UNITY_EDITOR
Assert.That(PrefabUtility.GetPrefabType(installerPrefab.gameObject) == PrefabType.Prefab,
"Found non-prefab with name '{0}' in the InstallerPrefabs property of Context '{1}'. You should use the property 'Installer' for this instead",
installerPrefab.name, this.name);
#endif
Assert.That(installerPrefab.GetComponent<MonoInstaller>() != null,
"Expected to find component with type 'MonoInstaller' on given installer prefab '{0}'", installerPrefab.name);
}
}
protected void InstallInstallers()
{
CheckInstallerPrefabTypes();
// Ideally we would just have one flat list of all the installers
// since that way the user has complete control over the order, but
// that's not possible since Unity does not allow serializing lists of interfaces
// (and it has to be an inteface since the scriptable object installers only share
// the interface)
//
// So the best we can do is have a hard-coded order in terms of the installer type
//
// The order is:
// - Normal installers given directly via code
// - ScriptableObject installers
// - MonoInstallers in the scene
// - Prefab Installers
//
// We put ScriptableObject installers before the MonoInstallers because
// ScriptableObjectInstallers are often used for settings (including settings
// that are injected into other installers like MonoInstallers)
var allInstallers = _normalInstallers.Cast<IInstaller>()
.Concat(_scriptableObjectInstallers.Cast<IInstaller>()).Concat(_installers.Cast<IInstaller>()).ToList();
foreach (var installerPrefab in _installerPrefabs)
{
Assert.IsNotNull(installerPrefab, "Found null installer prefab in '{0}'", this.GetType().Name());
var installerGameObject = GameObject.Instantiate(installerPrefab.gameObject);
installerGameObject.transform.SetParent(this.transform, false);
var installer = installerGameObject.GetComponent<MonoInstaller>();
Assert.IsNotNull(installer, "Could not find installer component on prefab '{0}'", installerPrefab.name);
allInstallers.Add(installer);
}
foreach (var installer in allInstallers)
{
Assert.IsNotNull(installer,
"Found null installer in '{0}'", this.GetType().Name());
Container.Inject(installer);
installer.InstallBindings();
}
}
protected void InstallSceneBindings()
{
foreach (var binding in GetInjectableComponents().OfType<ZenjectBinding>())
{
if (binding == null)
{
continue;
}
if (binding.Context == null)
{
InstallZenjectBinding(binding);
}
}
// We'd prefer to use GameObject.FindObjectsOfType<ZenjectBinding>() here
// instead but that doesn't find inactive gameobjects
foreach (var binding in Resources.FindObjectsOfTypeAll<ZenjectBinding>())
{
if (binding == null)
{
continue;
}
if (binding.Context == this)
{
InstallZenjectBinding(binding);
}
}
}
void InstallZenjectBinding(ZenjectBinding binding)
{
if (!binding.enabled)
{
return;
}
if (binding.Components == null || binding.Components.IsEmpty())
{
Log.Warn("Found empty list of components on ZenjectBinding on object '{0}'", binding.name);
return;
}
string identifier = null;
if (binding.Identifier.Trim().Length > 0)
{
identifier = binding.Identifier;
}
foreach (var component in binding.Components)
{
var bindType = binding.BindType;
if (component == null)
{
Log.Warn("Found null component in ZenjectBinding on object '{0}'", binding.name);
continue;
}
var componentType = component.GetType();
switch (bindType)
{
case ZenjectBinding.BindTypes.Self:
{
Container.Bind(componentType).WithId(identifier).FromInstance(component, true);
break;
}
case ZenjectBinding.BindTypes.BaseType:
{
Container.Bind(componentType.BaseType()).WithId(identifier).FromInstance(component, true);
break;
}
case ZenjectBinding.BindTypes.AllInterfaces:
{
Container.BindAllInterfaces(componentType).WithId(identifier).FromInstance(component, true);
break;
}
case ZenjectBinding.BindTypes.AllInterfacesAndSelf:
{
Container.BindAllInterfacesAndSelf(componentType).WithId(identifier).FromInstance(component, true);
break;
}
default:
{
throw Assert.CreateException();
}
}
}
}
protected abstract IEnumerable<Component> GetInjectableComponents();
}
}
#endif
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using C1.Win.C1TrueDBGrid;
using PCSComSale.Order.BO;
using PCSComSale.Order.DS;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
namespace PCSSale.Order
{
/// <summary>
/// Summary description for CustomerAndItemReference.
/// </summary>
public class CustomerAndItemReference : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnSave;
private C1.Win.C1TrueDBGrid.C1TrueDBGrid dgrdData;
private System.Windows.Forms.Button btnCustomerSearch;
private System.Windows.Forms.Label lblCustomerName;
private System.Windows.Forms.Label lblCustomer;
private System.Windows.Forms.TextBox txtCustomerName;
private System.Windows.Forms.Button btnCustomerNameSearch;
private System.Windows.Forms.Label lblCCN;
private C1.Win.C1List.C1Combo cboCCN;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private const string THIS = "PCSSale.Order.CustomerAndItemReference";
private const string V_VENDORCUSTOMER = "V_VendorCustomer";
private const string CUSTOMER_FLD = "Customer";
private bool blnHasError = false;
private System.Windows.Forms.TextBox txtCustomer;
private DataTable dtbGridLayOut = new DataTable();
private CustomerAndItemReferenceBO boCustomerAndItem = new CustomerAndItemReferenceBO();
private SO_CustomerItemRefMasterVO voCustomMaster = new SO_CustomerItemRefMasterVO();
private System.Windows.Forms.TextBox txtCurrency;
private System.Windows.Forms.Label lblCurrency;
private DataSet dstData = new DataSet();
public CustomerAndItemReference()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(CustomerAndItemReference));
this.btnClose = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.cboCCN = new C1.Win.C1List.C1Combo();
this.btnCustomerSearch = new System.Windows.Forms.Button();
this.lblCCN = new System.Windows.Forms.Label();
this.btnCustomerNameSearch = new System.Windows.Forms.Button();
this.txtCustomerName = new System.Windows.Forms.TextBox();
this.txtCustomer = new System.Windows.Forms.TextBox();
this.lblCustomerName = new System.Windows.Forms.Label();
this.lblCustomer = new System.Windows.Forms.Label();
this.dgrdData = new C1.Win.C1TrueDBGrid.C1TrueDBGrid();
this.txtCurrency = new System.Windows.Forms.TextBox();
this.lblCurrency = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).BeginInit();
this.SuspendLayout();
//
// btnClose
//
this.btnClose.AccessibleDescription = "";
this.btnClose.AccessibleName = "";
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnClose.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnClose.Location = new System.Drawing.Point(608, 386);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(60, 23);
this.btnClose.TabIndex = 14;
this.btnClose.Text = "&Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnDelete
//
this.btnDelete.AccessibleDescription = "";
this.btnDelete.AccessibleName = "";
this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnDelete.Enabled = false;
this.btnDelete.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnDelete.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnDelete.Location = new System.Drawing.Point(64, 386);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(60, 23);
this.btnDelete.TabIndex = 12;
this.btnDelete.Text = "&Delete";
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnHelp
//
this.btnHelp.AccessibleDescription = "";
this.btnHelp.AccessibleName = "";
this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnHelp.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnHelp.Location = new System.Drawing.Point(547, 386);
this.btnHelp.Name = "btnHelp";
this.btnHelp.Size = new System.Drawing.Size(60, 23);
this.btnHelp.TabIndex = 13;
this.btnHelp.Text = "&Help";
//
// btnSave
//
this.btnSave.AccessibleDescription = "";
this.btnSave.AccessibleName = "";
this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnSave.Enabled = false;
this.btnSave.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnSave.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnSave.Location = new System.Drawing.Point(3, 386);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(60, 23);
this.btnSave.TabIndex = 11;
this.btnSave.Text = "&Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// cboCCN
//
this.cboCCN.AccessibleDescription = "";
this.cboCCN.AccessibleName = "";
this.cboCCN.AddItemSeparator = ';';
this.cboCCN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cboCCN.Caption = "";
this.cboCCN.CaptionHeight = 17;
this.cboCCN.CharacterCasing = System.Windows.Forms.CharacterCasing.Normal;
this.cboCCN.ColumnCaptionHeight = 17;
this.cboCCN.ColumnFooterHeight = 17;
this.cboCCN.ComboStyle = C1.Win.C1List.ComboStyleEnum.DropdownList;
this.cboCCN.ContentHeight = 15;
this.cboCCN.DeadAreaBackColor = System.Drawing.Color.Empty;
this.cboCCN.EditorBackColor = System.Drawing.SystemColors.Window;
this.cboCCN.EditorFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.cboCCN.EditorForeColor = System.Drawing.SystemColors.WindowText;
this.cboCCN.EditorHeight = 15;
this.cboCCN.FlatStyle = C1.Win.C1List.FlatModeEnum.System;
this.cboCCN.GapHeight = 2;
this.cboCCN.ItemHeight = 15;
this.cboCCN.Location = new System.Drawing.Point(588, 6);
this.cboCCN.MatchEntryTimeout = ((long)(2000));
this.cboCCN.MaxDropDownItems = ((short)(5));
this.cboCCN.MaxLength = 32767;
this.cboCCN.MouseCursor = System.Windows.Forms.Cursors.Default;
this.cboCCN.Name = "cboCCN";
this.cboCCN.RowDivider.Color = System.Drawing.Color.DarkGray;
this.cboCCN.RowDivider.Style = C1.Win.C1List.LineStyleEnum.None;
this.cboCCN.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.cboCCN.Size = new System.Drawing.Size(80, 21);
this.cboCCN.TabIndex = 1;
this.cboCCN.PropBag = "<?xml version=\"1.0\"?><Blob><Styles type=\"C1.Win.C1List.Design.ContextWrapper\"><Da" +
"ta>Group{AlignVert:Center;Border:None,,0, 0, 0, 0;BackColor:ControlDark;}Style2{" +
"}Style5{}Style4{}Style7{}Style6{}EvenRow{BackColor:Aqua;}Selected{ForeColor:High" +
"lightText;BackColor:Highlight;}Style3{}Inactive{ForeColor:InactiveCaptionText;Ba" +
"ckColor:InactiveCaption;}Footer{}Caption{AlignHorz:Center;}Normal{BackColor:Wind" +
"ow;}HighlightRow{ForeColor:HighlightText;BackColor:Highlight;}Style1{}OddRow{}Re" +
"cordSelector{AlignImage:Center;}Heading{Wrap:True;BackColor:Control;Border:Raise" +
"d,,1, 1, 1, 1;ForeColor:ControlText;AlignVert:Center;}Style8{}Style10{}Style11{}" +
"Style9{AlignHorz:Near;}</Data></Styles><Splits><C1.Win.C1List.ListBoxView AllowC" +
"olSelect=\"False\" Name=\"\" CaptionHeight=\"17\" ColumnCaptionHeight=\"17\" ColumnFoote" +
"rHeight=\"17\" VerticalScrollGroup=\"1\" HorizontalScrollGroup=\"1\"><ClientRect>0, 0," +
" 118, 158</ClientRect><VScrollBar><Width>16</Width></VScrollBar><HScrollBar><Hei" +
"ght>16</Height></HScrollBar><CaptionStyle parent=\"Style2\" me=\"Style9\" /><EvenRow" +
"Style parent=\"EvenRow\" me=\"Style7\" /><FooterStyle parent=\"Footer\" me=\"Style3\" />" +
"<GroupStyle parent=\"Group\" me=\"Style11\" /><HeadingStyle parent=\"Heading\" me=\"Sty" +
"le2\" /><HighLightRowStyle parent=\"HighlightRow\" me=\"Style6\" /><InactiveStyle par" +
"ent=\"Inactive\" me=\"Style4\" /><OddRowStyle parent=\"OddRow\" me=\"Style8\" /><RecordS" +
"electorStyle parent=\"RecordSelector\" me=\"Style10\" /><SelectedStyle parent=\"Selec" +
"ted\" me=\"Style5\" /><Style parent=\"Normal\" me=\"Style1\" /></C1.Win.C1List.ListBoxV" +
"iew></Splits><NamedStyles><Style parent=\"\" me=\"Normal\" /><Style parent=\"Normal\" " +
"me=\"Heading\" /><Style parent=\"Heading\" me=\"Footer\" /><Style parent=\"Heading\" me=" +
"\"Caption\" /><Style parent=\"Heading\" me=\"Inactive\" /><Style parent=\"Normal\" me=\"S" +
"elected\" /><Style parent=\"Normal\" me=\"HighlightRow\" /><Style parent=\"Normal\" me=" +
"\"EvenRow\" /><Style parent=\"Normal\" me=\"OddRow\" /><Style parent=\"Heading\" me=\"Rec" +
"ordSelector\" /><Style parent=\"Caption\" me=\"Group\" /></NamedStyles><vertSplits>1<" +
"/vertSplits><horzSplits>1</horzSplits><Layout>Modified</Layout><DefaultRecSelWid" +
"th>17</DefaultRecSelWidth></Blob>";
//
// btnCustomerSearch
//
this.btnCustomerSearch.AccessibleDescription = "";
this.btnCustomerSearch.AccessibleName = "";
this.btnCustomerSearch.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnCustomerSearch.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnCustomerSearch.Location = new System.Drawing.Point(190, 6);
this.btnCustomerSearch.Name = "btnCustomerSearch";
this.btnCustomerSearch.Size = new System.Drawing.Size(24, 20);
this.btnCustomerSearch.TabIndex = 4;
this.btnCustomerSearch.Text = "...";
this.btnCustomerSearch.Click += new System.EventHandler(this.btnCustomerSearch_Click);
//
// lblCCN
//
this.lblCCN.AccessibleDescription = "";
this.lblCCN.AccessibleName = "";
this.lblCCN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.lblCCN.ForeColor = System.Drawing.Color.Maroon;
this.lblCCN.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCCN.Location = new System.Drawing.Point(550, 8);
this.lblCCN.Name = "lblCCN";
this.lblCCN.Size = new System.Drawing.Size(38, 19);
this.lblCCN.TabIndex = 0;
this.lblCCN.Text = "CCN";
this.lblCCN.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnCustomerNameSearch
//
this.btnCustomerNameSearch.AccessibleDescription = "";
this.btnCustomerNameSearch.AccessibleName = "";
this.btnCustomerNameSearch.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnCustomerNameSearch.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnCustomerNameSearch.Location = new System.Drawing.Point(374, 28);
this.btnCustomerNameSearch.Name = "btnCustomerNameSearch";
this.btnCustomerNameSearch.Size = new System.Drawing.Size(24, 20);
this.btnCustomerNameSearch.TabIndex = 9;
this.btnCustomerNameSearch.Text = "...";
this.btnCustomerNameSearch.Click += new System.EventHandler(this.btnCustomerNameSearch_Click);
//
// txtCustomerName
//
this.txtCustomerName.AccessibleDescription = "";
this.txtCustomerName.AccessibleName = "";
this.txtCustomerName.Location = new System.Drawing.Point(92, 28);
this.txtCustomerName.MaxLength = 400;
this.txtCustomerName.Name = "txtCustomerName";
this.txtCustomerName.Size = new System.Drawing.Size(281, 20);
this.txtCustomerName.TabIndex = 8;
this.txtCustomerName.Text = "";
this.txtCustomerName.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtCustomerName_KeyDown);
this.txtCustomerName.Validating += new System.ComponentModel.CancelEventHandler(this.txtCustomerName_Validating);
//
// txtCustomer
//
this.txtCustomer.AccessibleDescription = "";
this.txtCustomer.AccessibleName = "";
this.txtCustomer.Location = new System.Drawing.Point(92, 6);
this.txtCustomer.MaxLength = 40;
this.txtCustomer.Name = "txtCustomer";
this.txtCustomer.Size = new System.Drawing.Size(98, 20);
this.txtCustomer.TabIndex = 3;
this.txtCustomer.Text = "";
this.txtCustomer.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtCustomer_KeyDown);
this.txtCustomer.Validating += new System.ComponentModel.CancelEventHandler(this.txtCustomer_Validating);
//
// lblCustomerName
//
this.lblCustomerName.AccessibleDescription = "";
this.lblCustomerName.AccessibleName = "";
this.lblCustomerName.ForeColor = System.Drawing.Color.Maroon;
this.lblCustomerName.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCustomerName.Location = new System.Drawing.Point(4, 28);
this.lblCustomerName.Name = "lblCustomerName";
this.lblCustomerName.Size = new System.Drawing.Size(88, 20);
this.lblCustomerName.TabIndex = 7;
this.lblCustomerName.Text = "Customer Name";
this.lblCustomerName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblCustomer
//
this.lblCustomer.AccessibleDescription = "";
this.lblCustomer.AccessibleName = "";
this.lblCustomer.ForeColor = System.Drawing.Color.Maroon;
this.lblCustomer.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCustomer.Location = new System.Drawing.Point(4, 6);
this.lblCustomer.Name = "lblCustomer";
this.lblCustomer.Size = new System.Drawing.Size(75, 20);
this.lblCustomer.TabIndex = 2;
this.lblCustomer.Text = "Customer";
this.lblCustomer.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// dgrdData
//
this.dgrdData.AccessibleDescription = "";
this.dgrdData.AccessibleName = "";
this.dgrdData.AllowAddNew = true;
this.dgrdData.AllowDelete = true;
this.dgrdData.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.dgrdData.CaptionHeight = 17;
this.dgrdData.CollapseColor = System.Drawing.Color.Black;
this.dgrdData.ExpandColor = System.Drawing.Color.Black;
this.dgrdData.FilterBar = true;
this.dgrdData.FlatStyle = C1.Win.C1TrueDBGrid.FlatModeEnum.System;
this.dgrdData.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.dgrdData.GroupByCaption = "Drag a column header here to group by that column";
this.dgrdData.Images.Add(((System.Drawing.Image)(resources.GetObject("resource"))));
this.dgrdData.Location = new System.Drawing.Point(3, 53);
this.dgrdData.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder;
this.dgrdData.Name = "dgrdData";
this.dgrdData.PreviewInfo.Location = new System.Drawing.Point(0, 0);
this.dgrdData.PreviewInfo.Size = new System.Drawing.Size(0, 0);
this.dgrdData.PreviewInfo.ZoomFactor = 75;
this.dgrdData.PrintInfo.ShowOptionsDialog = false;
this.dgrdData.RecordSelectorWidth = 17;
this.dgrdData.RowDivider.Color = System.Drawing.Color.DarkGray;
this.dgrdData.RowDivider.Style = C1.Win.C1TrueDBGrid.LineStyleEnum.Single;
this.dgrdData.RowHeight = 15;
this.dgrdData.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.dgrdData.Size = new System.Drawing.Size(665, 327);
this.dgrdData.TabIndex = 10;
this.dgrdData.Text = "c1TrueDBGrid1";
this.dgrdData.BeforeColEdit += new C1.Win.C1TrueDBGrid.BeforeColEditEventHandler(this.dgrdData_BeforeColEdit);
this.dgrdData.ButtonClick += new C1.Win.C1TrueDBGrid.ColEventHandler(this.dgrdData_ButtonClick);
this.dgrdData.AfterColUpdate += new C1.Win.C1TrueDBGrid.ColEventHandler(this.dgrdData_AfterColUpdate);
this.dgrdData.BeforeColUpdate += new C1.Win.C1TrueDBGrid.BeforeColUpdateEventHandler(this.dgrdData_BeforeColUpdate);
this.dgrdData.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dgrdData_KeyDown);
this.dgrdData.PropBag = "<?xml version=\"1.0\"?><Blob><DataCols><C1DataColumn Level=\"0\" Caption=\"Part Number" +
"\" DataField=\"Code\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level" +
"=\"0\" Caption=\"Part Name\" DataField=\"Description\"><ValueItems /><GroupInfo /></C1" +
"DataColumn><C1DataColumn Level=\"0\" Caption=\"Model\" DataField=\"Revision\"><ValueIt" +
"ems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Customer Part" +
" No.\" DataField=\"CustomerItemCode\"><ValueItems /><GroupInfo /></C1DataColumn><C1" +
"DataColumn Level=\"0\" Caption=\"Customer Code\" DataField=\"CustomerItemModel\"><Valu" +
"eItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Unit Price" +
"\" DataField=\"UnitPrice\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn " +
"Level=\"0\" Caption=\"Selling UM\" DataField=\"MST_UnitOfMeasureCode\"><ValueItems /><" +
"GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Category\" DataField=" +
"\"ITM_CategoryCode\"><ValueItems /><GroupInfo /></C1DataColumn></DataCols><Styles " +
"type=\"C1.Win.C1TrueDBGrid.Design.ContextWrapper\"><Data>Style58{AlignHorz:Near;}S" +
"tyle59{AlignHorz:Near;}HighlightRow{ForeColor:HighlightText;BackColor:Highlight;" +
"}Style50{}Style51{}Style52{AlignHorz:Near;ForeColor:Maroon;}Style53{AlignHorz:Ne" +
"ar;}Style54{}Caption{AlignHorz:Center;}Style56{}Normal{Font:Microsoft Sans Serif" +
", 8.25pt;}Style25{}Selected{ForeColor:HighlightText;BackColor:Highlight;}Editor{" +
"}Style31{}Style18{}Style19{}Style14{}Style15{}Style16{AlignHorz:Near;ForeColor:M" +
"aroon;}Style17{AlignHorz:Near;}Style10{AlignHorz:Near;}Style11{}Style12{}Style13" +
"{}Style44{}Style46{AlignHorz:Near;ForeColor:Maroon;}Style63{}Style62{}Style61{}S" +
"tyle60{}Style38{}Style37{}Style34{AlignHorz:Near;ForeColor:Maroon;}Style35{Align" +
"Horz:Near;}Style32{}OddRow{}Style29{AlignHorz:Near;}Style28{AlignHorz:Near;}Styl" +
"e27{}Style26{}RecordSelector{AlignImage:Center;}Footer{}Style23{AlignHorz:Near;}" +
"Style22{AlignHorz:Near;ForeColor:Maroon;}Style21{}Style55{}Group{AlignVert:Cente" +
"r;Border:None,,0, 0, 0, 0;BackColor:ControlDark;}Style57{}Inactive{ForeColor:Ina" +
"ctiveCaptionText;BackColor:InactiveCaption;}EvenRow{BackColor:Aqua;}Heading{Wrap" +
":True;BackColor:Control;Border:Raised,,1, 1, 1, 1;ForeColor:ControlText;AlignVer" +
"t:Center;}Style49{}Style48{}Style24{}Style1{}Style20{}Style41{AlignHorz:Near;}St" +
"yle40{AlignHorz:Near;ForeColor:Maroon;}Style43{}FilterBar{}Style42{}Style45{}Sty" +
"le47{AlignHorz:Near;}Style9{}Style8{}Style39{}Style36{}Style5{}Style4{}Style7{}S" +
"tyle6{}Style33{}Style30{}Style3{}Style2{}</Data></Styles><Splits><C1.Win.C1TrueD" +
"BGrid.MergeView Name=\"\" CaptionHeight=\"17\" ColumnCaptionHeight=\"17\" ColumnFooter" +
"Height=\"17\" FilterBar=\"True\" MarqueeStyle=\"DottedCellBorder\" RecordSelectorWidth" +
"=\"17\" DefRecSelWidth=\"17\" VerticalScrollGroup=\"1\" HorizontalScrollGroup=\"1\"><Cli" +
"entRect>0, 0, 661, 323</ClientRect><BorderSide>0</BorderSide><CaptionStyle paren" +
"t=\"Style2\" me=\"Style10\" /><EditorStyle parent=\"Editor\" me=\"Style5\" /><EvenRowSty" +
"le parent=\"EvenRow\" me=\"Style8\" /><FilterBarStyle parent=\"FilterBar\" me=\"Style13" +
"\" /><FooterStyle parent=\"Footer\" me=\"Style3\" /><GroupStyle parent=\"Group\" me=\"St" +
"yle12\" /><HeadingStyle parent=\"Heading\" me=\"Style2\" /><HighLightRowStyle parent=" +
"\"HighlightRow\" me=\"Style7\" /><InactiveStyle parent=\"Inactive\" me=\"Style4\" /><Odd" +
"RowStyle parent=\"OddRow\" me=\"Style9\" /><RecordSelectorStyle parent=\"RecordSelect" +
"or\" me=\"Style11\" /><SelectedStyle parent=\"Selected\" me=\"Style6\" /><Style parent=" +
"\"Normal\" me=\"Style1\" /><internalCols><C1DisplayColumn><HeadingStyle parent=\"Styl" +
"e2\" me=\"Style16\" /><Style parent=\"Style1\" me=\"Style17\" /><FooterStyle parent=\"St" +
"yle3\" me=\"Style18\" /><EditorStyle parent=\"Style5\" me=\"Style19\" /><GroupHeaderSty" +
"le parent=\"Style1\" me=\"Style21\" /><GroupFooterStyle parent=\"Style1\" me=\"Style20\"" +
" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>1" +
"49</Width><Height>15</Height><DCIdx>0</DCIdx></C1DisplayColumn><C1DisplayColumn>" +
"<HeadingStyle parent=\"Style2\" me=\"Style22\" /><Style parent=\"Style1\" me=\"Style23\"" +
" /><FooterStyle parent=\"Style3\" me=\"Style24\" /><EditorStyle parent=\"Style5\" me=\"" +
"Style25\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style27\" /><GroupFooterStyle pa" +
"rent=\"Style1\" me=\"Style26\" /><Visible>True</Visible><ColumnDivider>DarkGray,Sing" +
"le</ColumnDivider><Width>175</Width><Height>15</Height><DCIdx>1</DCIdx></C1Displ" +
"ayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style28\" /><Style pa" +
"rent=\"Style1\" me=\"Style29\" /><FooterStyle parent=\"Style3\" me=\"Style30\" /><Editor" +
"Style parent=\"Style5\" me=\"Style31\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style" +
"33\" /><GroupFooterStyle parent=\"Style1\" me=\"Style32\" /><Visible>True</Visible><C" +
"olumnDivider>DarkGray,Single</ColumnDivider><Width>63</Width><Height>15</Height>" +
"<DCIdx>2</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\"" +
" me=\"Style58\" /><Style parent=\"Style1\" me=\"Style59\" /><FooterStyle parent=\"Style" +
"3\" me=\"Style60\" /><EditorStyle parent=\"Style5\" me=\"Style61\" /><GroupHeaderStyle " +
"parent=\"Style1\" me=\"Style63\" /><GroupFooterStyle parent=\"Style1\" me=\"Style62\" />" +
"<Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Height>15<" +
"/Height><DCIdx>7</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=" +
"\"Style2\" me=\"Style52\" /><Style parent=\"Style1\" me=\"Style53\" /><FooterStyle paren" +
"t=\"Style3\" me=\"Style54\" /><EditorStyle parent=\"Style5\" me=\"Style55\" /><GroupHead" +
"erStyle parent=\"Style1\" me=\"Style57\" /><GroupFooterStyle parent=\"Style1\" me=\"Sty" +
"le56\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Wi" +
"dth>65</Width><Height>15</Height><DCIdx>6</DCIdx></C1DisplayColumn><C1DisplayCol" +
"umn><HeadingStyle parent=\"Style2\" me=\"Style46\" /><Style parent=\"Style1\" me=\"Styl" +
"e47\" /><FooterStyle parent=\"Style3\" me=\"Style48\" /><EditorStyle parent=\"Style5\" " +
"me=\"Style49\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style51\" /><GroupFooterStyl" +
"e parent=\"Style1\" me=\"Style50\" /><Visible>True</Visible><ColumnDivider>DarkGray," +
"Single</ColumnDivider><Width>81</Width><Height>15</Height><DCIdx>5</DCIdx></C1Di" +
"splayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style34\" /><Style" +
" parent=\"Style1\" me=\"Style35\" /><FooterStyle parent=\"Style3\" me=\"Style36\" /><Edi" +
"torStyle parent=\"Style5\" me=\"Style37\" /><GroupHeaderStyle parent=\"Style1\" me=\"St" +
"yle39\" /><GroupFooterStyle parent=\"Style1\" me=\"Style38\" /><Visible>True</Visible" +
"><ColumnDivider>DarkGray,Single</ColumnDivider><Width>113</Width><Height>15</Hei" +
"ght><DCIdx>3</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Sty" +
"le2\" me=\"Style40\" /><Style parent=\"Style1\" me=\"Style41\" /><FooterStyle parent=\"S" +
"tyle3\" me=\"Style42\" /><EditorStyle parent=\"Style5\" me=\"Style43\" /><GroupHeaderSt" +
"yle parent=\"Style1\" me=\"Style45\" /><GroupFooterStyle parent=\"Style1\" me=\"Style44" +
"\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>" +
"116</Width><Height>15</Height><DCIdx>4</DCIdx></C1DisplayColumn></internalCols><" +
"/C1.Win.C1TrueDBGrid.MergeView></Splits><NamedStyles><Style parent=\"\" me=\"Normal" +
"\" /><Style parent=\"Normal\" me=\"Heading\" /><Style parent=\"Heading\" me=\"Footer\" />" +
"<Style parent=\"Heading\" me=\"Caption\" /><Style parent=\"Heading\" me=\"Inactive\" /><" +
"Style parent=\"Normal\" me=\"Selected\" /><Style parent=\"Normal\" me=\"Editor\" /><Styl" +
"e parent=\"Normal\" me=\"HighlightRow\" /><Style parent=\"Normal\" me=\"EvenRow\" /><Sty" +
"le parent=\"Normal\" me=\"OddRow\" /><Style parent=\"Heading\" me=\"RecordSelector\" /><" +
"Style parent=\"Normal\" me=\"FilterBar\" /><Style parent=\"Caption\" me=\"Group\" /></Na" +
"medStyles><vertSplits>1</vertSplits><horzSplits>1</horzSplits><Layout>Modified</" +
"Layout><DefaultRecSelWidth>17</DefaultRecSelWidth><ClientArea>0, 0, 661, 323</Cl" +
"ientArea><PrintPageHeaderStyle parent=\"\" me=\"Style14\" /><PrintPageFooterStyle pa" +
"rent=\"\" me=\"Style15\" /></Blob>";
//
// txtCurrency
//
this.txtCurrency.AccessibleDescription = "";
this.txtCurrency.AccessibleName = "";
this.txtCurrency.Location = new System.Drawing.Point(298, 6);
this.txtCurrency.MaxLength = 40;
this.txtCurrency.Name = "txtCurrency";
this.txtCurrency.ReadOnly = true;
this.txtCurrency.Size = new System.Drawing.Size(98, 20);
this.txtCurrency.TabIndex = 6;
this.txtCurrency.Text = "";
//
// lblCurrency
//
this.lblCurrency.AccessibleDescription = "";
this.lblCurrency.AccessibleName = "";
this.lblCurrency.ForeColor = System.Drawing.Color.Black;
this.lblCurrency.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCurrency.Location = new System.Drawing.Point(224, 6);
this.lblCurrency.Name = "lblCurrency";
this.lblCurrency.Size = new System.Drawing.Size(56, 20);
this.lblCurrency.TabIndex = 5;
this.lblCurrency.Text = "Currency";
this.lblCurrency.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// CustomerAndItemReference
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(672, 413);
this.Controls.Add(this.txtCurrency);
this.Controls.Add(this.lblCurrency);
this.Controls.Add(this.dgrdData);
this.Controls.Add(this.txtCustomerName);
this.Controls.Add(this.txtCustomer);
this.Controls.Add(this.cboCCN);
this.Controls.Add(this.btnCustomerSearch);
this.Controls.Add(this.lblCCN);
this.Controls.Add(this.btnCustomerNameSearch);
this.Controls.Add(this.lblCustomerName);
this.Controls.Add(this.lblCustomer);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnSave);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.KeyPreview = true;
this.Name = "CustomerAndItemReference";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Customer And Item Reference";
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.CustomerAndItemReference_KeyDown);
this.Closing += new System.ComponentModel.CancelEventHandler(this.CustomerAndItemReference_Closing);
this.Load += new System.EventHandler(this.CustomerAndItemReference_Load);
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void CustomerAndItemReference_Load(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".CustomerAndItemReference_Load()";
try
{
Security objSecurity = new Security();
this.Name = THIS;
objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName);
//Load CCN and set default CCN
UtilsBO boUtils = new UtilsBO();
DataSet dstCCN = boUtils.ListCCN();
cboCCN.DataSource = dstCCN.Tables[MST_CCNTable.TABLE_NAME];
cboCCN.DisplayMember = MST_CCNTable.CODE_FLD;
cboCCN.ValueMember = MST_CCNTable.CCNID_FLD;
FormControlComponents.PutDataIntoC1ComboBox(cboCCN,dstCCN.Tables[MST_CCNTable.TABLE_NAME],MST_CCNTable.CODE_FLD,MST_CCNTable.CCNID_FLD,MST_CCNTable.TABLE_NAME);
//get grid layout
dtbGridLayOut = FormControlComponents.StoreGridLayout(dgrdData);
if (SystemProperty.CCNID != 0)
{
cboCCN.SelectedValue = SystemProperty.CCNID;
}
BindDataToGrid(0, 0);
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="pintPartyID"></param>
/// <param name="pintCCNID"></param>
private void BindDataToGrid(int pintPartyID, int pintCCNID)
{
dstData = boCustomerAndItem.ListDetailByMasterID(pintPartyID, pintCCNID);
dgrdData.DataSource = dstData.Tables[0];
FormControlComponents.RestoreGridLayout(dgrdData, dtbGridLayOut);
dgrdData.Columns[SO_CustomerItemRefDetailTable.UNITPRICE_FLD].NumberFormat = "##############,0.0000";
dgrdData.Columns[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].DataWidth = 50;
dgrdData.Columns[SO_CustomerItemRefDetailTable.UNITPRICE_FLD].DataWidth = 10;
dgrdData.Columns[SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].DataWidth = 20;
dgrdData.Splits[0].DisplayColumns[ITM_ProductTable.CODE_FLD].Button = true;
dgrdData.Splits[0].DisplayColumns[ITM_ProductTable.DESCRIPTION_FLD].Button = true;
dgrdData.Splits[0].DisplayColumns[MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD].Button = true;
dgrdData.Splits[0].DisplayColumns[ITM_ProductTable.REVISION_FLD].Locked = true;
voCustomMaster.CustomerItemRefMasterID = ((SO_CustomerItemRefMasterVO)boCustomerAndItem.GetObjectMasterByID(pintPartyID, pintCCNID)).CustomerItemRefMasterID;
if (pintPartyID != 0)
{
dgrdData.Splits[0].DisplayColumns[ITM_ProductTable.CODE_FLD].Locked = false;
dgrdData.Splits[0].DisplayColumns[ITM_ProductTable.DESCRIPTION_FLD].Locked = false;
dgrdData.Splits[0].DisplayColumns[SO_CustomerItemRefDetailTable.UNITPRICE_FLD].Locked = false;
dgrdData.Splits[0].DisplayColumns[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].Locked = false;
dgrdData.Splits[0].DisplayColumns[SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].Locked = false;
dgrdData.Splits[0].DisplayColumns[MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD].Locked = false;
btnSave.Enabled = true;
btnDelete.Enabled = true;
}
}
/// <summary>
/// Select Customer by Code
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCustomerSearch_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".btnCustomerSearch_Click()";
try
{
Hashtable htbCriteria = new Hashtable();
DataRowView drwResult = null;
htbCriteria = new Hashtable();
htbCriteria.Add(CUSTOMER_FLD, (int)PartyTypeEnum.CUSTOMER);
drwResult = FormControlComponents.OpenSearchForm(V_VENDORCUSTOMER, MST_PartyTable.CODE_FLD, txtCustomer.Text.Trim(), htbCriteria, true);
if (drwResult != null)
{
txtCustomer.Text = drwResult[MST_PartyTable.CODE_FLD].ToString();
txtCustomer.Tag = drwResult[MST_PartyTable.PARTYID_FLD];
txtCustomerName.Text = drwResult[MST_PartyTable.NAME_FLD].ToString();
BindDataToGrid(int.Parse(txtCustomer.Tag.ToString()), int.Parse(cboCCN.SelectedValue.ToString()));
voCustomMaster.PartyID = int.Parse(txtCustomer.Tag.ToString());
voCustomMaster.CCNID = int.Parse(cboCCN.SelectedValue.ToString());
txtCurrency.Text = drwResult["MST_PartyCurrency"].ToString();
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Select Customer by Name
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCustomerNameSearch_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".btnCustomerNameSearch_Click()";
try
{
Hashtable htbCriteria = new Hashtable();
DataRowView drwResult = null;
htbCriteria = new Hashtable();
htbCriteria.Add(CUSTOMER_FLD, (int)PartyTypeEnum.CUSTOMER);
drwResult = FormControlComponents.OpenSearchForm(V_VENDORCUSTOMER, MST_PartyTable.NAME_FLD, txtCustomerName.Text.Trim(), htbCriteria, true);
if (drwResult != null)
{
txtCustomer.Text = drwResult[MST_PartyTable.CODE_FLD].ToString();
txtCustomer.Tag = drwResult[MST_PartyTable.PARTYID_FLD];
txtCustomerName.Text = drwResult[MST_PartyTable.NAME_FLD].ToString();
BindDataToGrid(int.Parse(txtCustomer.Tag.ToString()), int.Parse(cboCCN.SelectedValue.ToString()));
voCustomMaster.PartyID = int.Parse(txtCustomer.Tag.ToString());
voCustomMaster.CCNID = int.Parse(cboCCN.SelectedValue.ToString());
txtCurrency.Text = drwResult["MST_PartyCurrency"].ToString();
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close();
}
/// <summary>
/// Validating event: - OpenSeachForm
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtCustomer_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".txtCustomer_Validating()";
try
{
Hashtable htbCriteria = new Hashtable();
DataRowView drwResult = null;
if(txtCustomer.Text.Trim() == string.Empty)
{
txtCustomer.Tag = null;
txtCustomerName.Text = string.Empty;
btnSave.Enabled = false;
btnDelete.Enabled = false;
BindDataToGrid(0, 0);
return;
}
htbCriteria = new Hashtable();
htbCriteria.Add(CUSTOMER_FLD, 0);
drwResult = FormControlComponents.OpenSearchForm(V_VENDORCUSTOMER, MST_PartyTable.CODE_FLD, txtCustomer.Text.Trim(), htbCriteria, false);
if (drwResult != null)
{
txtCustomer.Text = drwResult[MST_PartyTable.CODE_FLD].ToString();
txtCustomer.Tag = drwResult[MST_PartyTable.PARTYID_FLD];
txtCustomerName.Text = drwResult[MST_PartyTable.NAME_FLD].ToString();
voCustomMaster.PartyID = int.Parse(txtCustomer.Tag.ToString());
voCustomMaster.CCNID = int.Parse(cboCCN.SelectedValue.ToString());
txtCurrency.Text = drwResult["MST_PartyCurrency"].ToString();
BindDataToGrid(int.Parse(txtCustomer.Tag.ToString()), int.Parse(cboCCN.SelectedValue.ToString()));
}
else
e.Cancel = true;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Validating data on Customer Name
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtCustomerName_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".txtCustomer_Validating()";
try
{
Hashtable htbCriteria = new Hashtable();
DataRowView drwResult = null;
if(txtCustomerName.Text.Trim() == string.Empty)
{
txtCustomer.Tag = null;
txtCustomer.Text= string.Empty;
txtCustomerName.Text = string.Empty;
btnSave.Enabled = false;
btnDelete.Enabled = false;
BindDataToGrid(0, 0);
return;
}
htbCriteria = new Hashtable();
htbCriteria.Add(CUSTOMER_FLD, 0);
drwResult = FormControlComponents.OpenSearchForm(V_VENDORCUSTOMER, MST_PartyTable.NAME_FLD, txtCustomerName.Text.Trim(), htbCriteria, false);
if (drwResult != null)
{
txtCustomer.Text = drwResult[MST_PartyTable.CODE_FLD].ToString();
txtCustomer.Tag = drwResult[MST_PartyTable.PARTYID_FLD];
txtCustomerName.Text = drwResult[MST_PartyTable.NAME_FLD].ToString();
voCustomMaster.PartyID = int.Parse(txtCustomer.Tag.ToString());
voCustomMaster.CCNID = int.Parse(cboCCN.SelectedValue.ToString());
txtCurrency.Text = drwResult["MST_PartyCurrency"].ToString();
BindDataToGrid(int.Parse(txtCustomer.Tag.ToString()), int.Parse(cboCCN.SelectedValue.ToString()));
}
else
e.Cancel = true;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Button click to open search form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgrdData_ButtonClick(object sender, C1.Win.C1TrueDBGrid.ColEventArgs e)
{
const string METHOD_NAME = THIS + ".dgrdData_ButtonClick()";
try
{
if (!btnSave.Enabled)
{
return;
}
DataRowView drwResult = null;
Hashtable htbCondition = new Hashtable();
if (dgrdData.Col == dgrdData.Columns.IndexOf(dgrdData.Columns[ITM_ProductTable.CODE_FLD]))
{
//open the search form to select Product
if (cboCCN.SelectedValue != null)
{
htbCondition.Add(ITM_ProductTable.CCNID_FLD, cboCCN.SelectedValue.ToString());
}
else
{
htbCondition.Add(ITM_ProductTable.CCNID_FLD, 0);
}
drwResult = dgrdData.AddNewMode == AddNewModeEnum.AddNewCurrent
? FormControlComponents.OpenSearchForm(ITM_ProductTable.TABLE_NAME, ITM_ProductTable.CODE_FLD,
dgrdData[dgrdData.Row, ITM_ProductTable.CODE_FLD].
ToString(), htbCondition, true)
: FormControlComponents.OpenSearchForm(ITM_ProductTable.TABLE_NAME, ITM_ProductTable.CODE_FLD,
dgrdData.Columns[ITM_ProductTable.CODE_FLD].Text.Trim(),
htbCondition, true);
if (drwResult != null)
{
dgrdData.EditActive = true;
FillItemData(drwResult.Row);
}
}
if (dgrdData.Col == dgrdData.Columns.IndexOf(dgrdData.Columns[ITM_ProductTable.DESCRIPTION_FLD]))
{
//open the search form to select Product
if (cboCCN.SelectedValue != null)
{
htbCondition.Add(ITM_ProductTable.CCNID_FLD, cboCCN.SelectedValue.ToString());
}
else
{
htbCondition.Add(ITM_ProductTable.CCNID_FLD, 0);
}
drwResult = dgrdData.AddNewMode != AddNewModeEnum.NoAddNew
? FormControlComponents.OpenSearchForm(ITM_ProductTable.TABLE_NAME,
ITM_ProductTable.DESCRIPTION_FLD,
dgrdData[dgrdData.Row, ITM_ProductTable.DESCRIPTION_FLD].
ToString(), htbCondition, true)
: FormControlComponents.OpenSearchForm(ITM_ProductTable.TABLE_NAME,
ITM_ProductTable.DESCRIPTION_FLD,
dgrdData.Columns[ITM_ProductTable.DESCRIPTION_FLD].Text.
Trim(), htbCondition, true);
if (drwResult != null)
{
dgrdData.EditActive = true;
FillItemData(drwResult.Row);
}
}
if (dgrdData.Col == dgrdData.Columns.IndexOf(dgrdData.Columns[MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD]))
{
//open the search form to select Unit Of Measure
drwResult = FormControlComponents.OpenSearchForm(MST_UnitOfMeasureTable.TABLE_NAME, MST_UnitOfMeasureTable.CODE_FLD,
dgrdData.AddNewMode != AddNewModeEnum.NoAddNew
? dgrdData[dgrdData.Row,MST_UnitOfMeasureTable.TABLE_NAME +MST_UnitOfMeasureTable.CODE_FLD].ToString()
: dgrdData.Columns[MST_UnitOfMeasureTable.TABLE_NAME +MST_UnitOfMeasureTable.CODE_FLD].Text.Trim(),
htbCondition, true);
if (drwResult != null)
{
dgrdData[dgrdData.Row, SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD] = drwResult[SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD];
dgrdData[dgrdData.Row, MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD] = drwResult[MST_UnitOfMeasureTable.CODE_FLD];
}
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// - Fill data into item code, item description, item revision, stock unit of measure
/// - Fill data into start/due date time based on current server date time
/// - Fill data into AGC, cost method, estimated cost based on product item setup
/// </summary>
private void FillItemData(DataRow pdrowData)
{
int i = dgrdData.Row;
dgrdData[i, ITM_ProductTable.CODE_FLD] = pdrowData[ITM_ProductTable.CODE_FLD].ToString();
dgrdData[i, ITM_ProductTable.DESCRIPTION_FLD] = pdrowData[ITM_ProductTable.DESCRIPTION_FLD].ToString();
dgrdData[i, ITM_ProductTable.REVISION_FLD] = pdrowData[ITM_ProductTable.REVISION_FLD].ToString();
dgrdData[i, SO_CustomerItemRefDetailTable.PRODUCTID_FLD] = pdrowData[ITM_ProductTable.PRODUCTID_FLD].ToString();
dgrdData[i, ITM_CategoryTable.TABLE_NAME + ITM_CategoryTable.CODE_FLD] = pdrowData[ITM_ProductTable.CATEGORYID_FLD
+ "_" + ITM_CategoryTable.CODE_FLD].ToString();
dgrdData[i, SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD] = pdrowData[ITM_ProductTable.SELLINGUMID_FLD].ToString();
DataRowView drwViewUM = FormControlComponents.OpenSearchForm(MST_UnitOfMeasureTable.TABLE_NAME, MST_UnitOfMeasureTable.UNITOFMEASUREID_FLD,
pdrowData[ITM_ProductTable.SELLINGUMID_FLD].ToString(), null, false);
if (drwViewUM != null)
{
dgrdData[i, MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD] = drwViewUM[MST_UnitOfMeasureTable.CODE_FLD];
}
dgrdData.Col = dgrdData.Splits[0].DisplayColumns.IndexOf(dgrdData.Splits[0].DisplayColumns[ITM_ProductTable.CODE_FLD]);
dgrdData.Focus();
}
private void CustomerAndItemReference_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.F12)
{
dgrdData.Row = dgrdData.RowCount;
dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[ITM_ProductTable.CODE_FLD]);
dgrdData.Focus();
}
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
/// <summary>
/// Open search form & check data
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgrdData_BeforeColUpdate(object sender, C1.Win.C1TrueDBGrid.BeforeColUpdateEventArgs e)
{
const string METHOD_NAME = THIS + ".dgrdData_BeforeColUpdate()";
try
{
if (e.Column.DataColumn.Value.ToString() == string.Empty)
{
return;
}
Hashtable htbCriteria = new Hashtable();
DataRowView drwResult = null;
switch (e.Column.DataColumn.DataField)
{
case ITM_ProductTable.CODE_FLD:
# region open Product search form
if (cboCCN.SelectedIndex >= 0)
{
htbCriteria.Add(MST_CCNTable.CCNID_FLD, cboCCN.SelectedValue.ToString());
}
else
{
htbCriteria.Add(MST_CCNTable.CCNID_FLD, 0);
}
drwResult = FormControlComponents.OpenSearchForm(ITM_ProductTable.TABLE_NAME, ITM_ProductTable.CODE_FLD, dgrdData.Columns[e.Column.DataColumn.DataField].Text.Trim(), htbCriteria, false);
if (drwResult != null)
{
e.Column.DataColumn.Tag = drwResult.Row;
}
else
{
e.Cancel = true;
}
#endregion
break;
case ITM_ProductTable.DESCRIPTION_FLD:
# region open Product search form
if (cboCCN.SelectedIndex >= 0)
{
htbCriteria.Add(MST_CCNTable.CCNID_FLD, cboCCN.SelectedValue.ToString());
}
else
{
htbCriteria.Add(MST_CCNTable.CCNID_FLD, 0);
}
drwResult = FormControlComponents.OpenSearchForm(ITM_ProductTable.TABLE_NAME, ITM_ProductTable.DESCRIPTION_FLD, dgrdData.Columns[e.Column.DataColumn.DataField].Text.Trim(), htbCriteria, false);
if (drwResult != null)
{
e.Column.DataColumn.Tag = drwResult.Row;
}
else
{
e.Cancel = true;
}
#endregion
break;
case MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD:
#region open Unit form
drwResult = FormControlComponents.OpenSearchForm(MST_UnitOfMeasureTable.TABLE_NAME, MST_UnitOfMeasureTable.CODE_FLD, dgrdData.Columns[MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD].Text.Trim(), htbCriteria, false);
if (drwResult != null)
{
e.Column.DataColumn.Tag = drwResult.Row;
}
else
{
e.Cancel = true;
}
#endregion
break;
}
//check lead time offset
if (e.Column.DataColumn.DataField == SO_CustomerItemRefDetailTable.UNITPRICE_FLD)
{
try
{
if (e.Column.DataColumn.Value.ToString() != string.Empty)
{
decimal intUnitPrice = decimal.Parse(e.Column.DataColumn.Value.ToString());
if (intUnitPrice <= 0)
{
PCSMessageBox.Show(ErrorCode.MESSAGE_CANNOT_INPUT_NEGATIVE_NUMBER, MessageBoxIcon.Error);
e.Cancel = true;
}
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.MESSAGE_CANNOT_INPUT_NEGATIVE_NUMBER, MessageBoxIcon.Error);
e.Cancel = true;
}
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Commit data into grid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgrdData_AfterColUpdate(object sender, C1.Win.C1TrueDBGrid.ColEventArgs e)
{
const string METHOD_NAME = THIS + ".dgrdData_AfterColUpdate()";
try
{
if (e.Column.DataColumn.DataField == ITM_ProductTable.CODE_FLD || e.Column.DataColumn.DataField == ITM_ProductTable.DESCRIPTION_FLD)
{
if ((e.Column.DataColumn.Tag == null) ||(e.Column.DataColumn.Text.Trim() == string.Empty))
{
dgrdData[dgrdData.Row, ITM_ProductTable.CODE_FLD] = string.Empty;
dgrdData[dgrdData.Row, ITM_ProductTable.DESCRIPTION_FLD] = string.Empty;
dgrdData[dgrdData.Row, ITM_ProductTable.REVISION_FLD] = string.Empty;
dgrdData[dgrdData.Row, ITM_ProductTable.PRODUCTID_FLD] = DBNull.Value;
dgrdData[dgrdData.Row, SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD] = DBNull.Value;
dgrdData[dgrdData.Row, MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD] = DBNull.Value;
}
else
{
FillItemData((DataRow) e.Column.DataColumn.Tag);
return;
}
}
if (e.Column.DataColumn.DataField == MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD)
{
if ((e.Column.DataColumn.Tag == null) ||(e.Column.DataColumn.Text.Trim() == string.Empty))
{
dgrdData[dgrdData.Row, SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD] = DBNull.Value;
dgrdData[dgrdData.Row, MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD] = DBNull.Value;
}
else
{
dgrdData[dgrdData.Row, SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD] = ((DataRow) e.Column.DataColumn.Tag)[MST_UnitOfMeasureTable.UNITOFMEASUREID_FLD];
}
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Keydown event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgrdData_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.F4:
if (btnSave.Enabled)
{
dgrdData_ButtonClick(sender, null);
}
break;
case Keys.Delete:
FormControlComponents.DeleteMultiRowsOnTrueDBGrid(dgrdData);
break;
}
}
/// <summary>
/// Validate all data, and some business rules
/// </summary>
/// <returns></returns>
private bool ValidateData()
{
if (txtCustomer.Text.Trim() == string.Empty)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Exclamation);
txtCustomer.Focus();
return false;
}
//check madatory field in grid
for (int i = 0; i < dgrdData.RowCount; i++)
{
if (dgrdData[i, ITM_ProductTable.CODE_FLD].ToString().Trim() == string.Empty)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error);
dgrdData.Row = i;
dgrdData.Col = dgrdData.Splits[0].DisplayColumns.IndexOf(dgrdData.Splits[0].DisplayColumns[ITM_ProductTable.CODE_FLD]);
dgrdData.Focus();
return false;
}
if (dgrdData[i, MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD].ToString().Trim() == string.Empty)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error);
dgrdData.Row = i;
dgrdData.Col = dgrdData.Splits[0].DisplayColumns.IndexOf(dgrdData.Splits[0].DisplayColumns[MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD]);
dgrdData.Focus();
return false;
}
if (dgrdData[i, SO_CustomerItemRefDetailTable.UNITPRICE_FLD].ToString().Trim() == string.Empty)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error);
dgrdData.Row = i;
dgrdData.Col = dgrdData.Splits[0].DisplayColumns.IndexOf(dgrdData.Splits[0].DisplayColumns[SO_CustomerItemRefDetailTable.UNITPRICE_FLD]);
dgrdData.Focus();
return false;
}
if (dgrdData[i, SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].ToString() == string.Empty)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error);
dgrdData.Row = i;
dgrdData.Col = dgrdData.Splits[0].DisplayColumns.IndexOf(dgrdData.Splits[0].DisplayColumns[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD]);
dgrdData.Focus();
return false;
}
}
for (int i = 0; i < dgrdData.RowCount; i++)
{
for (int j = i + 1; j < dgrdData.RowCount; j++)
{
if (dgrdData[i, SO_CustomerItemRefDetailTable.PRODUCTID_FLD].ToString() == dgrdData[j, SO_CustomerItemRefDetailTable.PRODUCTID_FLD].ToString())
{
PCSMessageBox.Show(ErrorCode.DUPLICATE_KEY, MessageBoxIcon.Error);
dgrdData.Row = i;
dgrdData.Col = dgrdData.Splits[0].DisplayColumns.IndexOf(dgrdData.Splits[0].DisplayColumns[ITM_ProductTable.CODE_FLD]);
dgrdData.Focus();
return false;
}
if (dgrdData[i, SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].ToString() == dgrdData[j, SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].ToString()
&& dgrdData[i, SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].ToString() == dgrdData[j, SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].ToString())
{
PCSMessageBox.Show(ErrorCode.DUPLICATE_KEY, MessageBoxIcon.Error);
dgrdData.Row = i;
dgrdData.Col = dgrdData.Splits[0].DisplayColumns.IndexOf(dgrdData.Splits[0].DisplayColumns[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD]);
dgrdData.Focus();
return false;
}
}
}
return true;
}
/// <summary>
/// Save event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".btnSave_Click()";
try
{
blnHasError = true;
if (!dgrdData.EditActive && ValidateData() && btnSave.Enabled)
{
boCustomerAndItem.UpdateMasterAndDetail(voCustomMaster, dstData);
PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
//Reload
BindDataToGrid(int.Parse(txtCustomer.Tag.ToString()), int.Parse(cboCCN.SelectedValue.ToString()));
blnHasError = false;
txtCustomer.Focus();
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void btnDelete_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".AutoFillItemReference()";
try
{
if (btnDelete.Enabled && !dgrdData.EditActive && PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
boCustomerAndItem.DeleteMasterAndDetail(voCustomMaster);
txtCustomer.Text = string.Empty;
txtCustomer.Tag = null;
txtCustomerName.Text = string.Empty;
BindDataToGrid(0, 0);
btnSave.Enabled = false;
btnDelete.Enabled = false;
txtCustomer.Focus();
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void txtCustomer_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.F4)
{
btnCustomerSearch_Click(sender, new EventArgs());
}
}
private void txtCustomerName_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.F4)
{
btnCustomerNameSearch_Click(sender, new EventArgs());
}
}
private void CustomerAndItemReference_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".AutoFillItemReference()";
try
{
if (dstData != null && dstData.GetChanges() != null)
{
DialogResult confirmDialog = PCSMessageBox.Show(ErrorCode.MESSAGE_QUESTION_STORE_INTO_DATABASE, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
switch (confirmDialog)
{
case DialogResult.Yes:
//Save before exit
btnSave_Click(btnSave, new EventArgs());
if (blnHasError)
{
e.Cancel = true;
}
break;
case DialogResult.No:
break;
case DialogResult.Cancel:
e.Cancel = true;
break;
}
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void dgrdData_BeforeColEdit(object sender, C1.Win.C1TrueDBGrid.BeforeColEditEventArgs e)
{
if (txtCustomer.Text.Trim() == string.Empty)
{
e.Cancel = true;
}
}
}
}
| |
/*
* 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.Cache
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Cache.Query;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Portable;
using Apache.Ignite.Core.Impl.Portable.IO;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Portable;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Native cache wrapper.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
internal class CacheImpl<TK, TV> : PlatformTarget, ICache<TK, TV>
{
/** Duration: unchanged. */
private const long DurUnchanged = -2;
/** Duration: eternal. */
private const long DurEternal = -1;
/** Duration: zero. */
private const long DurZero = 0;
/** Ignite instance. */
private readonly Ignite _ignite;
/** Flag: skip store. */
private readonly bool _flagSkipStore;
/** Flag: keep portable. */
private readonly bool _flagKeepPortable;
/** Flag: async mode.*/
private readonly bool _flagAsync;
/** Flag: no-retries.*/
private readonly bool _flagNoRetries;
/**
* Result converter for async InvokeAll operation.
* In future result processing there is only one TResult generic argument,
* and we can't get the type of ICacheEntryProcessorResult at compile time from it.
* This field caches converter for the last InvokeAll operation to avoid using reflection.
*/
private readonly ThreadLocal<object> _invokeAllConverter = new ThreadLocal<object>();
/// <summary>
/// Constructor.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="flagSkipStore">Skip store flag.</param>
/// <param name="flagKeepPortable">Keep portable flag.</param>
/// <param name="flagAsync">Async mode flag.</param>
/// <param name="flagNoRetries">No-retries mode flag.</param>
public CacheImpl(Ignite grid, IUnmanagedTarget target, PortableMarshaller marsh,
bool flagSkipStore, bool flagKeepPortable, bool flagAsync, bool flagNoRetries) : base(target, marsh)
{
_ignite = grid;
_flagSkipStore = flagSkipStore;
_flagKeepPortable = flagKeepPortable;
_flagAsync = flagAsync;
_flagNoRetries = flagNoRetries;
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get
{
return _ignite;
}
}
/** <inheritDoc /> */
public bool IsAsync
{
get { return _flagAsync; }
}
/** <inheritDoc /> */
public IFuture GetFuture()
{
throw new NotSupportedException("GetFuture() should be called through CacheProxyImpl");
}
/** <inheritDoc /> */
public IFuture<TResult> GetFuture<TResult>()
{
throw new NotSupportedException("GetFuture() should be called through CacheProxyImpl");
}
/// <summary>
/// Gets and resets future for previous asynchronous operation.
/// </summary>
/// <param name="lastAsyncOpId">The last async op id.</param>
/// <returns>
/// Future for previous asynchronous operation.
/// </returns>
/// <exception cref="System.InvalidOperationException">Asynchronous mode is disabled</exception>
internal IFuture<TResult> GetFuture<TResult>(int lastAsyncOpId)
{
if (!_flagAsync)
throw IgniteUtils.GetAsyncModeDisabledException();
var converter = GetFutureResultConverter<TResult>(lastAsyncOpId);
_invokeAllConverter.Value = null;
return GetFuture((futId, futTypeId) => UU.TargetListenFutureForOperation(Target, futId, futTypeId, lastAsyncOpId),
_flagKeepPortable, converter);
}
/** <inheritDoc /> */
public string Name
{
get { return DoInOp<string>((int)CacheOp.GetName); }
}
/** <inheritDoc /> */
public bool IsEmpty
{
get { return Size() == 0; }
}
/** <inheritDoc /> */
public ICache<TK, TV> WithSkipStore()
{
if (_flagSkipStore)
return this;
return new CacheImpl<TK, TV>(_ignite, UU.CacheWithSkipStore(Target), Marshaller,
true, _flagKeepPortable, _flagAsync, true);
}
/// <summary>
/// Skip store flag getter.
/// </summary>
internal bool IsSkipStore { get { return _flagSkipStore; } }
/** <inheritDoc /> */
public ICache<TK1, TV1> WithKeepPortable<TK1, TV1>()
{
if (_flagKeepPortable)
{
var result = this as ICache<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of portable cache. WithKeepPortable has been called on an instance of " +
"portable cache with incompatible generic arguments.");
return result;
}
return new CacheImpl<TK1, TV1>(_ignite, UU.CacheWithKeepPortable(Target), Marshaller,
_flagSkipStore, true, _flagAsync, _flagNoRetries);
}
/** <inheritDoc /> */
public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
IgniteArgumentCheck.NotNull(plc, "plc");
long create = ConvertDuration(plc.GetExpiryForCreate());
long update = ConvertDuration(plc.GetExpiryForUpdate());
long access = ConvertDuration(plc.GetExpiryForAccess());
IUnmanagedTarget cache0 = UU.CacheWithExpiryPolicy(Target, create, update, access);
return new CacheImpl<TK, TV>(_ignite, cache0, Marshaller, _flagSkipStore, _flagKeepPortable, _flagAsync, _flagNoRetries);
}
/// <summary>
/// Convert TimeSpan to duration recognizable by Java.
/// </summary>
/// <param name="dur">.Net duration.</param>
/// <returns>Java duration in milliseconds.</returns>
private static long ConvertDuration(TimeSpan? dur)
{
if (dur.HasValue)
{
if (dur.Value == TimeSpan.MaxValue)
return DurEternal;
long dur0 = (long)dur.Value.TotalMilliseconds;
return dur0 > 0 ? dur0 : DurZero;
}
return DurUnchanged;
}
/** <inheritDoc /> */
public ICache<TK, TV> WithAsync()
{
return _flagAsync ? this : new CacheImpl<TK, TV>(_ignite, UU.CacheWithAsync(Target), Marshaller,
_flagSkipStore, _flagKeepPortable, true, _flagNoRetries);
}
/** <inheritDoc /> */
public bool KeepPortable
{
get { return _flagKeepPortable; }
}
/** <inheritDoc /> */
public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
LoadCache0(p, args, (int)CacheOp.LoadCache);
}
/** <inheritDoc /> */
public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
LoadCache0(p, args, (int)CacheOp.LocLoadCache);
}
/// <summary>
/// Loads the cache.
/// </summary>
private void LoadCache0(ICacheEntryFilter<TK, TV> p, object[] args, int opId)
{
DoOutOp(opId, writer =>
{
if (p != null)
{
var p0 = new CacheEntryFilterHolder(p, (k, v) => p.Invoke(new CacheEntry<TK, TV>((TK)k, (TV)v)),
Marshaller, KeepPortable);
writer.WriteObject(p0);
writer.WriteLong(p0.Handle);
}
else
writer.WriteObject<CacheEntryFilterHolder>(null);
writer.WriteObjectArray(args);
});
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp((int)CacheOp.ContainsKey, key) == True;
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOp((int)CacheOp.ContainsKeys, writer => WriteEnumerable(writer, keys)) == True;
}
/** <inheritDoc /> */
public TV LocalPeek(TK key, params CachePeekMode[] modes)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp<TV>((int)CacheOp.Peek, writer =>
{
writer.Write(key);
writer.WriteInt(EncodePeekModes(modes));
});
}
/** <inheritDoc /> */
public TV Get(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp<TK, TV>((int)CacheOp.Get, key);
}
/** <inheritDoc /> */
public IDictionary<TK, TV> GetAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOp((int)CacheOp.GetAll,
writer => WriteEnumerable(writer, keys),
input =>
{
var reader = Marshaller.StartUnmarshal(input, _flagKeepPortable);
return ReadGetAllDictionary(reader);
});
}
/** <inheritdoc /> */
public void Put(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
DoOutOp((int)CacheOp.Put, key, val);
}
/** <inheritDoc /> */
public TV GetAndPut(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOp<TK, TV, TV>((int)CacheOp.GetAndPut, key, val);
}
/** <inheritDoc /> */
public TV GetAndReplace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOp<TK, TV, TV>((int)CacheOp.GetAndReplace, key, val);
}
/** <inheritDoc /> */
public TV GetAndRemove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp<TK, TV>((int)CacheOp.GetAndRemove, key);
}
/** <inheritdoc /> */
public bool PutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOp((int) CacheOp.PutIfAbsent, key, val) == True;
}
/** <inheritdoc /> */
public TV GetAndPutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOp<TK, TV, TV>((int)CacheOp.GetAndPutIfAbsent, key, val);
}
/** <inheritdoc /> */
public bool Replace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOp((int)CacheOp.Replace2, key, val) == True;
}
/** <inheritdoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
return DoOutOp((int)CacheOp.Replace3, key, oldVal, newVal) == True;
}
/** <inheritdoc /> */
public void PutAll(IDictionary<TK, TV> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
DoOutOp((int) CacheOp.PutAll, writer => WriteDictionary(writer, vals));
}
/** <inheritdoc /> */
public void LocalEvict(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp((int) CacheOp.LocEvict, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public void Clear()
{
UU.CacheClear(Target);
}
/** <inheritdoc /> */
public void Clear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOp((int)CacheOp.Clear, key);
}
/** <inheritdoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp((int)CacheOp.ClearAll, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public void LocalClear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOp((int) CacheOp.LocalClear, key);
}
/** <inheritdoc /> */
public void LocalClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp((int)CacheOp.LocalClearAll, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public bool Remove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp((int)CacheOp.RemoveObj, key) == True;
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOp((int)CacheOp.RemoveBool, key, val) == True;
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp((int)CacheOp.RemoveAll, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public void RemoveAll()
{
UU.CacheRemoveAll(Target);
}
/** <inheritDoc /> */
public int LocalSize(params CachePeekMode[] modes)
{
return Size0(true, modes);
}
/** <inheritDoc /> */
public int Size(params CachePeekMode[] modes)
{
return Size0(false, modes);
}
/// <summary>
/// Internal size routine.
/// </summary>
/// <param name="loc">Local flag.</param>
/// <param name="modes">peek modes</param>
/// <returns>Size.</returns>
private int Size0(bool loc, params CachePeekMode[] modes)
{
int modes0 = EncodePeekModes(modes);
return UU.CacheSize(Target, modes0, loc);
}
/** <inheritDoc /> */
public void LocalPromote(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp((int)CacheOp.LocPromote, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public TR Invoke<TR, TA>(TK key, ICacheEntryProcessor<TK, TV, TA, TR> processor, TA arg)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(processor, "processor");
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TA)a), typeof(TK), typeof(TV));
return DoOutInOp((int)CacheOp.Invoke, writer =>
{
writer.Write(key);
writer.Write(holder);
},
input => GetResultOrThrow<TR>(Unmarshal<object>(input)));
}
/** <inheritdoc /> */
public IDictionary<TK, ICacheEntryProcessorResult<TR>> InvokeAll<TR, TA>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TA, TR> processor, TA arg)
{
IgniteArgumentCheck.NotNull(keys, "keys");
IgniteArgumentCheck.NotNull(processor, "processor");
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TA)a), typeof(TK), typeof(TV));
return DoOutInOp((int)CacheOp.InvokeAll, writer =>
{
WriteEnumerable(writer, keys);
writer.Write(holder);
},
input =>
{
if (IsAsync)
_invokeAllConverter.Value = (Func<PortableReaderImpl, IDictionary<TK, ICacheEntryProcessorResult<TR>>>)
(reader => ReadInvokeAllResults<TR>(reader.Stream));
return ReadInvokeAllResults<TR>(input);
});
}
/** <inheritdoc /> */
public ICacheLock Lock(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOp((int)CacheOp.Lock, writer =>
{
writer.Write(key);
}, input => new CacheLock(input.ReadInt(), Target));
}
/** <inheritdoc /> */
public ICacheLock LockAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOp((int)CacheOp.LockAll, writer =>
{
WriteEnumerable(writer, keys);
}, input => new CacheLock(input.ReadInt(), Target));
}
/** <inheritdoc /> */
public bool IsLocalLocked(TK key, bool byCurrentThread)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp((int)CacheOp.IsLocalLocked, writer =>
{
writer.Write(key);
writer.WriteBoolean(byCurrentThread);
}) == True;
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics()
{
return DoInOp((int)CacheOp.Metrics, stream =>
{
IPortableRawReader reader = Marshaller.StartUnmarshal(stream, false);
return new CacheMetricsImpl(reader);
});
}
/** <inheritDoc /> */
public IFuture Rebalance()
{
return GetFuture<object>((futId, futTyp) => UU.CacheRebalance(Target, futId));
}
/** <inheritDoc /> */
public ICache<TK, TV> WithNoRetries()
{
if (_flagNoRetries)
return this;
return new CacheImpl<TK, TV>(_ignite, UU.CacheWithNoRetries(Target), Marshaller,
_flagSkipStore, _flagKeepPortable, _flagAsync, true);
}
/// <summary>
/// Gets a value indicating whether this instance is in no-retries mode.
/// </summary>
internal bool IsNoRetries
{
get { return _flagNoRetries; }
}
#region Queries
/** <inheritDoc /> */
public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
if (string.IsNullOrEmpty(qry.Sql))
throw new ArgumentException("Sql cannot be null or empty");
IUnmanagedTarget cursor;
using (var stream = IgniteManager.Memory.Allocate().Stream())
{
var writer = Marshaller.StartMarshal(stream);
writer.WriteBoolean(qry.Local);
writer.WriteString(qry.Sql);
writer.WriteInt(qry.PageSize);
WriteQueryArgs(writer, qry.Arguments);
FinishMarshal(writer);
cursor = UU.CacheOutOpQueryCursor(Target, (int) CacheOp.QrySqlFields, stream.SynchronizeOutput());
}
return new FieldsQueryCursor(cursor, Marshaller, _flagKeepPortable);
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
IUnmanagedTarget cursor;
using (var stream = IgniteManager.Memory.Allocate().Stream())
{
var writer = Marshaller.StartMarshal(stream);
qry.Write(writer, KeepPortable);
FinishMarshal(writer);
cursor = UU.CacheOutOpQueryCursor(Target, (int)qry.OpId, stream.SynchronizeOutput());
}
return new QueryCursor<TK, TV>(cursor, Marshaller, _flagKeepPortable);
}
/// <summary>
/// Write query arguments.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="args">Arguments.</param>
private static void WriteQueryArgs(PortableWriterImpl writer, object[] args)
{
if (args == null)
writer.WriteInt(0);
else
{
writer.WriteInt(args.Length);
foreach (var arg in args)
writer.WriteObject(arg);
}
}
/** <inheritdoc /> */
public IContinuousQueryHandle QueryContinuous(ContinuousQuery<TK, TV> qry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
return QueryContinuousImpl(qry, null);
}
/** <inheritdoc /> */
public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
IgniteArgumentCheck.NotNull(initialQry, "initialQry");
return QueryContinuousImpl(qry, initialQry);
}
/// <summary>
/// QueryContinuous implementation.
/// </summary>
private IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuousImpl(ContinuousQuery<TK, TV> qry,
QueryBase initialQry)
{
qry.Validate();
var hnd = new ContinuousQueryHandleImpl<TK, TV>(qry, Marshaller, _flagKeepPortable);
using (var stream = IgniteManager.Memory.Allocate().Stream())
{
var writer = Marshaller.StartMarshal(stream);
hnd.Start(_ignite, writer, () =>
{
if (initialQry != null)
{
writer.WriteInt((int) initialQry.OpId);
initialQry.Write(writer, KeepPortable);
}
else
writer.WriteInt(-1); // no initial query
FinishMarshal(writer);
// ReSharper disable once AccessToDisposedClosure
return UU.CacheOutOpContinuousQuery(Target, (int)CacheOp.QryContinuous, stream.SynchronizeOutput());
}, qry);
}
return hnd;
}
#endregion
#region Enumerable support
/** <inheritdoc /> */
public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(CachePeekMode[] peekModes)
{
return new CacheEnumerable<TK, TV>(this, EncodePeekModes(peekModes));
}
/** <inheritdoc /> */
public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator()
{
return new CacheEnumeratorProxy<TK, TV>(this, false, 0);
}
/** <inheritdoc /> */
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Create real cache enumerator.
/// </summary>
/// <param name="loc">Local flag.</param>
/// <param name="peekModes">Peek modes for local enumerator.</param>
/// <returns>Cache enumerator.</returns>
internal CacheEnumerator<TK, TV> CreateEnumerator(bool loc, int peekModes)
{
if (loc)
return new CacheEnumerator<TK, TV>(UU.CacheLocalIterator(Target, peekModes), Marshaller, _flagKeepPortable);
return new CacheEnumerator<TK, TV>(UU.CacheIterator(Target), Marshaller, _flagKeepPortable);
}
#endregion
/** <inheritDoc /> */
protected override T Unmarshal<T>(IPortableStream stream)
{
return Marshaller.Unmarshal<T>(stream, _flagKeepPortable);
}
/// <summary>
/// Encodes the peek modes into a single int value.
/// </summary>
private static int EncodePeekModes(CachePeekMode[] modes)
{
int modesEncoded = 0;
if (modes != null)
{
foreach (var mode in modes)
modesEncoded |= (int) mode;
}
return modesEncoded;
}
/// <summary>
/// Unwraps an exception from PortableResultHolder, if any. Otherwise does the cast.
/// </summary>
/// <typeparam name="T">Result type.</typeparam>
/// <param name="obj">Object.</param>
/// <returns>Result.</returns>
private static T GetResultOrThrow<T>(object obj)
{
var holder = obj as PortableResultWrapper;
if (holder != null)
{
var err = holder.Result as Exception;
if (err != null)
throw err as CacheEntryProcessorException ?? new CacheEntryProcessorException(err);
}
return obj == null ? default(T) : (T) obj;
}
/// <summary>
/// Reads results of InvokeAll operation.
/// </summary>
/// <typeparam name="T">The type of the result.</typeparam>
/// <param name="inStream">Stream.</param>
/// <returns>Results of InvokeAll operation.</returns>
private IDictionary<TK, ICacheEntryProcessorResult<T>> ReadInvokeAllResults<T>(IPortableStream inStream)
{
var count = inStream.ReadInt();
if (count == -1)
return null;
var results = new Dictionary<TK, ICacheEntryProcessorResult<T>>(count);
for (var i = 0; i < count; i++)
{
var key = Unmarshal<TK>(inStream);
var hasError = inStream.ReadBool();
results[key] = hasError
? new CacheEntryProcessorResult<T>(ReadException(inStream))
: new CacheEntryProcessorResult<T>(Unmarshal<T>(inStream));
}
return results;
}
/// <summary>
/// Reads the exception, either in portable wrapper form, or as a pair of strings.
/// </summary>
/// <param name="inStream">The stream.</param>
/// <returns>Exception.</returns>
private CacheEntryProcessorException ReadException(IPortableStream inStream)
{
var item = Unmarshal<object>(inStream);
var clsName = item as string;
if (clsName == null)
return new CacheEntryProcessorException((Exception) ((PortableResultWrapper) item).Result);
var msg = Unmarshal<string>(inStream);
return new CacheEntryProcessorException(ExceptionUtils.GetException(clsName, msg));
}
/// <summary>
/// Read dictionary returned by GET_ALL operation.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>Dictionary.</returns>
private static IDictionary<TK, TV> ReadGetAllDictionary(PortableReaderImpl reader)
{
IPortableStream stream = reader.Stream;
if (stream.ReadBool())
{
int size = stream.ReadInt();
IDictionary<TK, TV> res = new Dictionary<TK, TV>(size);
for (int i = 0; i < size; i++)
{
TK key = reader.ReadObject<TK>();
TV val = reader.ReadObject<TV>();
res[key] = val;
}
return res;
}
return null;
}
/// <summary>
/// Gets the future result converter based on the last operation id.
/// </summary>
/// <typeparam name="TResult">The type of the future result.</typeparam>
/// <param name="lastAsyncOpId">The last op id.</param>
/// <returns>Future result converter.</returns>
private Func<PortableReaderImpl, TResult> GetFutureResultConverter<TResult>(int lastAsyncOpId)
{
if (lastAsyncOpId == (int) CacheOp.GetAll)
return reader => (TResult)ReadGetAllDictionary(reader);
if (lastAsyncOpId == (int)CacheOp.Invoke)
return reader => { throw ReadException(reader.Stream); };
if (lastAsyncOpId == (int) CacheOp.InvokeAll)
return _invokeAllConverter.Value as Func<PortableReaderImpl, TResult>;
return null;
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using StdFormat;
namespace _4PosBackOffice.NET
{
internal partial class frmStockMultiName : System.Windows.Forms.Form
{
private ADODB.Recordset withEventsField_adoPrimaryRS;
public ADODB.Recordset adoPrimaryRS {
get { return withEventsField_adoPrimaryRS; }
set {
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord;
}
withEventsField_adoPrimaryRS = value;
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord;
}
}
}
bool mbChangedByCode;
int mvBookMark;
bool mbEditFlag;
bool mbAddNewFlag;
bool mbDataChanged;
string gFilter;
string gFilterSQL;
private void loadLanguage()
{
//frmStockMultiName = No Code [Edit Stock Item Names]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmStockMultiName.Caption = rsLang("LanguageLayoutLnk_Description"): frmStockMultiName.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//lblHeading = No Code [Using the "Stock Item Selector"...]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lblHeading.Caption = rsLang("LanguageLayoutLnk_Description"): lblHeading.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1006;
//Filter|Checked
if (modRecordSet.rsLang.RecordCount){cmdFilter.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdFilter.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1085;
//Print|Checked
if (modRecordSet.rsLang.RecordCount){cmdPrint.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdPrint.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmStockMultiName.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void cmdFilter_Click(System.Object eventSender, System.EventArgs eventArgs)
{
My.MyProject.Forms.frmFilter.loadFilter(ref gFilter);
getNamespace();
}
private void getNamespace()
{
object lString = null;
if (string.IsNullOrEmpty(gFilter)) {
this.lblHeading.Text = "";
} else {
My.MyProject.Forms.frmFilter.buildCriteria(ref gFilter);
this.lblHeading.Text = My.MyProject.Forms.frmFilter.gHeading;
}
gFilterSQL = My.MyProject.Forms.frmFilter.gCriteria;
if (string.IsNullOrEmpty(gFilterSQL)) {
//UPGRADE_WARNING: Couldn't resolve default property of object lString. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
lString = " WHERE StockItem.StockItem_Disabled=0 AND StockItem.StockItem_Discontinued=0 ";
} else {
//UPGRADE_WARNING: Couldn't resolve default property of object lString. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
lString = gFilterSQL + " AND StockItem.StockItem_Disabled=0 AND StockItem.StockItem_Discontinued=0 ";
}
//UPGRADE_WARNING: Couldn't resolve default property of object lString. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
adoPrimaryRS = modRecordSet.getRS(ref "SELECT StockItem_Name,StockItem_ReceiptName FROM StockItem " + lString + " ORDER BY StockItem_Name");
//Display the list of Titles in the DataCombo
grdDataGrid.DataSource = adoPrimaryRS;
grdDataGrid.Columns[0].HeaderText = "Stock Name";
grdDataGrid.Columns[0].DefaultCellStyle.Alignment = MSDataGridLib.AlignmentConstants.dbgLeft;
grdDataGrid.Columns[1].HeaderText = "Receipt Name";
grdDataGrid.Columns[1].DefaultCellStyle.Alignment = MSDataGridLib.AlignmentConstants.dbgLeft;
grdDataGrid.Columns[1].Width = sizeConvertors.twipsToPixels(2000, true);
frmStockMultiName_Resize(this, new System.EventArgs());
mbDataChanged = false;
}
private void cmdPrint_Click(System.Object eventSender, System.EventArgs eventArgs)
{
ADODB.Recordset rs = default(ADODB.Recordset);
bool ltype = false;
CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
Report.Load("cryStockItemName.rpt");
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
rs = modRecordSet.getRS(ref "SELECT * FROM Company");
Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
Report.SetParameterValue("txtTilte", this.Text);
Report.SetParameterValue("txtFilter", this.lblHeading.Text);
rs.Close();
//Report.Database.SetDataSource(adoPrimaryRS, 3)
Report.Database.Tables(1).SetDataSource(adoPrimaryRS);
//Report.VerifyOnEveryPrint = True
My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTilte").ToString;
My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
My.MyProject.Forms.frmReportShow.mReport = Report;
My.MyProject.Forms.frmReportShow.sMode = "0";
My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
My.MyProject.Forms.frmReportShow.ShowDialog();
}
private void frmStockMultiName_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 27) {
KeyAscii = 0;
cmdClose_Click(cmdClose, new System.EventArgs());
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmStockMultiName_Load(System.Object eventSender, System.EventArgs eventArgs)
{
var myfmt = new StdDataFormat();
myfmt.Type = FormatType.fmtCustom;
gFilter = "stockitem";
getNamespace();
mbDataChanged = false;
loadLanguage();
}
private void frmStockMultiName_Resize(System.Object eventSender, System.EventArgs eventArgs)
{
// ERROR: Not supported in C#: OnErrorStatement
//This will resize the grid when the form is resized
System.Windows.Forms.Application.DoEvents();
grdDataGrid.Height = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(this.ClientRectangle.Height, false) - 30 - sizeConvertors.pixelToTwips(picButtons.Height, false), false);
grdDataGrid.Columns[0].Width = sizeConvertors.twipsToPixels(sizeConvertors.pixelToTwips(grdDataGrid.Width, true) - 2000 - 580, true);
}
private void frmStockMultiName_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This will display the current record position for this recordset
}
private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This is where you put validation code
//This event gets called when the following actions occur
bool bCancel = false;
switch (adReason) {
case ADODB.EventReasonEnum.adRsnAddNew:
break;
case ADODB.EventReasonEnum.adRsnClose:
break;
case ADODB.EventReasonEnum.adRsnDelete:
break;
case ADODB.EventReasonEnum.adRsnFirstChange:
break;
case ADODB.EventReasonEnum.adRsnMove:
break;
case ADODB.EventReasonEnum.adRsnRequery:
break;
case ADODB.EventReasonEnum.adRsnResynch:
break;
case ADODB.EventReasonEnum.adRsnUndoAddNew:
break;
case ADODB.EventReasonEnum.adRsnUndoDelete:
break;
case ADODB.EventReasonEnum.adRsnUndoUpdate:
break;
case ADODB.EventReasonEnum.adRsnUpdate:
break;
}
if (bCancel)
adStatus = ADODB.EventStatusEnum.adStatusCancel;
}
private void cmdCancel_Click()
{
// ERROR: Not supported in C#: OnErrorStatement
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
//UPGRADE_WARNING: Couldn't resolve default property of object mvBookMark. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
if (mvBookMark > 0) {
//UPGRADE_WARNING: Couldn't resolve default property of object mvBookMark. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
mbDataChanged = false;
}
//UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
private void update_Renamed()
{
// ERROR: Not supported in C#: OnErrorStatement
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
if (mbAddNewFlag) {
adoPrimaryRS.MoveLast();
//move to the new record
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return;
UpdateErr:
Interaction.MsgBox(Err().Description);
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
update_Renamed();
this.Close();
}
private void goFirst()
{
// ERROR: Not supported in C#: OnErrorStatement
adoPrimaryRS.MoveFirst();
mbDataChanged = false;
return;
GoFirstError:
Interaction.MsgBox(Err().Description);
}
private void goLast()
{
// ERROR: Not supported in C#: OnErrorStatement
adoPrimaryRS.MoveLast();
mbDataChanged = false;
return;
GoLastError:
Interaction.MsgBox(Err().Description);
}
//Private Sub grdDataGrid_CellValueChanged(ByVal eventSender As System.Object, ByVal eventArgs As DataColumnChangeEventArgs) Handles grdDataGrid.ColumnDisplayIndexChanged
// If grdDataGrid.Columns(ColIndex).DataFormat.Format = "#,##0.00" Then
// grdDataGrid.Columns(ColIndex).DataFormat = 0
// End If
//End Sub
}
}
| |
// 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.Collections.ObjectModel;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Text;
namespace System.Data.SqlClient
{
internal enum CallbackType
{
Read = 0,
Write = 1
}
internal enum EncryptionOptions
{
OFF,
ON,
NOT_SUP,
REQ,
LOGIN
}
internal enum PreLoginHandshakeStatus
{
Successful,
InstanceFailure
}
internal enum PreLoginOptions
{
VERSION,
ENCRYPT,
INSTANCE,
THREADID,
MARS,
TRACEID,
NUMOPT,
LASTOPT = 255
}
internal enum RunBehavior
{
UntilDone = 1, // 0001 binary
ReturnImmediately = 2, // 0010 binary
Clean = 5, // 0101 binary - Clean AND UntilDone
Attention = 13 // 1101 binary - Clean AND UntilDone AND Attention
}
internal enum TdsParserState
{
Closed,
OpenNotLoggedIn,
OpenLoggedIn,
Broken,
}
sealed internal class SqlCollation
{
// First 20 bits of info field represent the lcid, bits 21-25 are compare options
private const uint IgnoreCase = 1 << 20; // bit 21 - IgnoreCase
private const uint IgnoreNonSpace = 1 << 21; // bit 22 - IgnoreNonSpace / IgnoreAccent
private const uint IgnoreWidth = 1 << 22; // bit 23 - IgnoreWidth
private const uint IgnoreKanaType = 1 << 23; // bit 24 - IgnoreKanaType
private const uint BinarySort = 1 << 24; // bit 25 - BinarySort
internal const uint MaskLcid = 0xfffff;
private const int LcidVersionBitOffset = 28;
private const uint MaskLcidVersion = unchecked((uint)(0xf << LcidVersionBitOffset));
private const uint MaskCompareOpt = IgnoreCase | IgnoreNonSpace | IgnoreWidth | IgnoreKanaType | BinarySort;
internal uint info;
internal byte sortId;
private static int FirstSupportedCollationVersion(int lcid)
{
// NOTE: switch-case works ~3 times faster in this case than search with Dictionary
switch (lcid)
{
case 1044: return 2; // Norwegian_100_BIN
case 1047: return 2; // Romansh_100_BIN
case 1056: return 2; // Urdu_100_BIN
case 1065: return 2; // Persian_100_BIN
case 1068: return 2; // Azeri_Latin_100_BIN
case 1070: return 2; // Upper_Sorbian_100_BIN
case 1071: return 1; // Macedonian_FYROM_90_BIN
case 1081: return 1; // Indic_General_90_BIN
case 1082: return 2; // Maltese_100_BIN
case 1083: return 2; // Sami_Norway_100_BIN
case 1087: return 1; // Kazakh_90_BIN
case 1090: return 2; // Turkmen_100_BIN
case 1091: return 1; // Uzbek_Latin_90_BIN
case 1092: return 1; // Tatar_90_BIN
case 1093: return 2; // Bengali_100_BIN
case 1101: return 2; // Assamese_100_BIN
case 1105: return 2; // Tibetan_100_BIN
case 1106: return 2; // Welsh_100_BIN
case 1107: return 2; // Khmer_100_BIN
case 1108: return 2; // Lao_100_BIN
case 1114: return 1; // Syriac_90_BIN
case 1121: return 2; // Nepali_100_BIN
case 1122: return 2; // Frisian_100_BIN
case 1123: return 2; // Pashto_100_BIN
case 1125: return 1; // Divehi_90_BIN
case 1133: return 2; // Bashkir_100_BIN
case 1146: return 2; // Mapudungan_100_BIN
case 1148: return 2; // Mohawk_100_BIN
case 1150: return 2; // Breton_100_BIN
case 1152: return 2; // Uighur_100_BIN
case 1153: return 2; // Maori_100_BIN
case 1155: return 2; // Corsican_100_BIN
case 1157: return 2; // Yakut_100_BIN
case 1164: return 2; // Dari_100_BIN
case 2074: return 2; // Serbian_Latin_100_BIN
case 2092: return 2; // Azeri_Cyrillic_100_BIN
case 2107: return 2; // Sami_Sweden_Finland_100_BIN
case 2143: return 2; // Tamazight_100_BIN
case 3076: return 1; // Chinese_Hong_Kong_Stroke_90_BIN
case 3098: return 2; // Serbian_Cyrillic_100_BIN
case 5124: return 2; // Chinese_Traditional_Pinyin_100_BIN
case 5146: return 2; // Bosnian_Latin_100_BIN
case 8218: return 2; // Bosnian_Cyrillic_100_BIN
default: return 0; // other LCIDs have collation with version 0
}
}
internal int LCID
{
// First 20 bits of info field represent the lcid
get
{
return unchecked((int)(info & MaskLcid));
}
set
{
int lcid = value & (int)MaskLcid;
Debug.Assert(lcid == value, "invalid set_LCID value");
// Some new Katmai LCIDs do not have collation with version = 0
// since user has no way to specify collation version, we set the first (minimal) supported version for these collations
int versionBits = FirstSupportedCollationVersion(lcid) << LcidVersionBitOffset;
Debug.Assert((versionBits & MaskLcidVersion) == versionBits, "invalid version returned by FirstSupportedCollationVersion");
// combine the current compare options with the new locale ID and its first supported version
info = (info & MaskCompareOpt) | unchecked((uint)lcid) | unchecked((uint)versionBits);
}
}
internal SqlCompareOptions SqlCompareOptions
{
get
{
SqlCompareOptions options = SqlCompareOptions.None;
if (0 != (info & IgnoreCase))
options |= SqlCompareOptions.IgnoreCase;
if (0 != (info & IgnoreNonSpace))
options |= SqlCompareOptions.IgnoreNonSpace;
if (0 != (info & IgnoreWidth))
options |= SqlCompareOptions.IgnoreWidth;
if (0 != (info & IgnoreKanaType))
options |= SqlCompareOptions.IgnoreKanaType;
if (0 != (info & BinarySort))
options |= SqlCompareOptions.BinarySort;
return options;
}
set
{
Debug.Assert((value & SqlTypeWorkarounds.SqlStringValidSqlCompareOptionMask) == value, "invalid set_SqlCompareOptions value");
uint tmp = 0;
if (0 != (value & SqlCompareOptions.IgnoreCase))
tmp |= IgnoreCase;
if (0 != (value & SqlCompareOptions.IgnoreNonSpace))
tmp |= IgnoreNonSpace;
if (0 != (value & SqlCompareOptions.IgnoreWidth))
tmp |= IgnoreWidth;
if (0 != (value & SqlCompareOptions.IgnoreKanaType))
tmp |= IgnoreKanaType;
if (0 != (value & SqlCompareOptions.BinarySort))
tmp |= BinarySort;
info = (info & MaskLcid) | tmp;
}
}
internal static bool AreSame(SqlCollation a, SqlCollation b)
{
if (a == null || b == null)
{
return a == b;
}
else
{
return a.info == b.info && a.sortId == b.sortId;
}
}
}
internal class RoutingInfo
{
internal byte Protocol { get; private set; }
internal UInt16 Port { get; private set; }
internal string ServerName { get; private set; }
internal RoutingInfo(byte protocol, UInt16 port, string servername)
{
Protocol = protocol;
Port = port;
ServerName = servername;
}
}
sealed internal class SqlEnvChange
{
internal byte type;
internal byte oldLength;
internal int newLength; // 7206 TDS changes makes this length an int
internal int length;
internal string newValue;
internal string oldValue;
internal byte[] newBinValue;
internal byte[] oldBinValue;
internal long newLongValue;
internal long oldLongValue;
internal SqlCollation newCollation;
internal SqlCollation oldCollation;
internal RoutingInfo newRoutingInfo;
}
sealed internal class SqlLogin
{
internal int timeout; // login timeout
internal bool userInstance = false; // user instance
internal string hostName = ""; // client machine name
internal string userName = ""; // user id
internal string password = ""; // password
internal string applicationName = ""; // application name
internal string serverName = ""; // server name
internal string language = ""; // initial language
internal string database = ""; // initial database
internal string attachDBFilename = ""; // DB filename to be attached
internal bool useReplication = false; // user login for replication
internal bool useSSPI = false; // use integrated security
internal int packetSize = SqlConnectionString.DEFAULT.Packet_Size; // packet size
internal bool readOnlyIntent = false; // read-only intent
}
sealed internal class SqlLoginAck
{
internal byte majorVersion;
internal byte minorVersion;
internal short buildNum;
internal UInt32 tdsVersion;
}
sealed internal class _SqlMetaData : SqlMetaDataPriv
{
internal string column;
internal MultiPartTableName multiPartTableName;
internal readonly int ordinal;
internal byte updatability; // two bit field (0 is read only, 1 is updatable, 2 is updatability unknown)
internal bool isDifferentName;
internal bool isKey;
internal bool isHidden;
internal bool isExpression;
internal bool isIdentity;
internal string baseColumn;
internal _SqlMetaData(int ordinal) : base()
{
this.ordinal = ordinal;
}
internal string serverName
{
get
{
return multiPartTableName.ServerName;
}
}
internal string catalogName
{
get
{
return multiPartTableName.CatalogName;
}
}
internal string schemaName
{
get
{
return multiPartTableName.SchemaName;
}
}
internal string tableName
{
get
{
return multiPartTableName.TableName;
}
}
internal bool IsNewKatmaiDateTimeType
{
get
{
return SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type;
}
}
internal bool IsLargeUdt
{
get
{
return type == SqlDbType.Udt && length == Int32.MaxValue;
}
}
public object Clone()
{
_SqlMetaData result = new _SqlMetaData(ordinal);
result.CopyFrom(this);
result.column = column;
result.multiPartTableName = multiPartTableName;
result.updatability = updatability;
result.isKey = isKey;
result.isHidden = isHidden;
result.isIdentity = isIdentity;
return result;
}
}
sealed internal class _SqlMetaDataSet
{
internal ushort id; // for altrow-columns only
internal int[] indexMap;
internal int visibleColumns;
private readonly _SqlMetaData[] _metaDataArray;
internal ReadOnlyCollection<DbColumn> dbColumnSchema;
internal _SqlMetaDataSet(int count)
{
_metaDataArray = new _SqlMetaData[count];
for (int i = 0; i < _metaDataArray.Length; ++i)
{
_metaDataArray[i] = new _SqlMetaData(i);
}
}
private _SqlMetaDataSet(_SqlMetaDataSet original)
{
this.id = original.id;
// although indexMap is not immutable, in practice it is initialized once and then passed around
this.indexMap = original.indexMap;
this.visibleColumns = original.visibleColumns;
this.dbColumnSchema = original.dbColumnSchema;
if (original._metaDataArray == null)
{
_metaDataArray = null;
}
else
{
_metaDataArray = new _SqlMetaData[original._metaDataArray.Length];
for (int idx = 0; idx < _metaDataArray.Length; idx++)
{
_metaDataArray[idx] = (_SqlMetaData)original._metaDataArray[idx].Clone();
}
}
}
internal int Length
{
get
{
return _metaDataArray.Length;
}
}
internal _SqlMetaData this[int index]
{
get
{
return _metaDataArray[index];
}
set
{
Debug.Assert(null == value, "used only by SqlBulkCopy");
_metaDataArray[index] = value;
}
}
public object Clone()
{
return new _SqlMetaDataSet(this);
}
}
sealed internal class _SqlMetaDataSetCollection
{
private readonly List<_SqlMetaDataSet> _altMetaDataSetArray;
internal _SqlMetaDataSet metaDataSet;
internal _SqlMetaDataSetCollection()
{
_altMetaDataSetArray = new List<_SqlMetaDataSet>();
}
internal void SetAltMetaData(_SqlMetaDataSet altMetaDataSet)
{
// If altmetadata with same id is found, override it rather than adding a new one
int newId = altMetaDataSet.id;
for (int i = 0; i < _altMetaDataSetArray.Count; i++)
{
if (_altMetaDataSetArray[i].id == newId)
{
// override the existing metadata with the same id
_altMetaDataSetArray[i] = altMetaDataSet;
return;
}
}
// if we did not find metadata to override, add as new
_altMetaDataSetArray.Add(altMetaDataSet);
}
internal _SqlMetaDataSet GetAltMetaData(int id)
{
foreach (_SqlMetaDataSet altMetaDataSet in _altMetaDataSetArray)
{
if (altMetaDataSet.id == id)
{
return altMetaDataSet;
}
}
Debug.Assert(false, "Can't match up altMetaDataSet with given id");
return null;
}
public object Clone()
{
_SqlMetaDataSetCollection result = new _SqlMetaDataSetCollection();
result.metaDataSet = metaDataSet == null ? null : (_SqlMetaDataSet)metaDataSet.Clone();
foreach (_SqlMetaDataSet set in _altMetaDataSetArray)
{
result._altMetaDataSetArray.Add((_SqlMetaDataSet)set.Clone());
}
return result;
}
}
internal class SqlMetaDataPriv
{
internal SqlDbType type; // SqlDbType enum value
internal byte tdsType; // underlying tds type
internal byte precision = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
internal byte scale = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
internal int length;
internal SqlCollation collation;
internal int codePage;
internal Encoding encoding;
internal bool isNullable;
// UDT specific metadata
// server metadata info
// additional temporary UDT meta data
internal string udtDatabaseName;
internal string udtSchemaName;
internal string udtTypeName;
internal string udtAssemblyQualifiedName;
// Xml specific metadata
internal string xmlSchemaCollectionDatabase;
internal string xmlSchemaCollectionOwningSchema;
internal string xmlSchemaCollectionName;
internal MetaType metaType; // cached metaType
internal SqlMetaDataPriv()
{
}
internal virtual void CopyFrom(SqlMetaDataPriv original)
{
this.type = original.type;
this.tdsType = original.tdsType;
this.precision = original.precision;
this.scale = original.scale;
this.length = original.length;
this.collation = original.collation;
this.codePage = original.codePage;
this.encoding = original.encoding;
this.isNullable = original.isNullable;
this.udtDatabaseName = original.udtDatabaseName;
this.udtSchemaName = original.udtSchemaName;
this.udtTypeName = original.udtTypeName;
this.udtAssemblyQualifiedName = original.udtAssemblyQualifiedName;
this.xmlSchemaCollectionDatabase = original.xmlSchemaCollectionDatabase;
this.xmlSchemaCollectionOwningSchema = original.xmlSchemaCollectionOwningSchema;
this.xmlSchemaCollectionName = original.xmlSchemaCollectionName;
this.metaType = original.metaType;
}
}
sealed internal class _SqlRPC
{
internal string rpcName;
internal ushort ProcID; // Used instead of name
internal ushort options;
internal SqlParameter[] parameters;
internal byte[] paramoptions;
}
sealed internal class SqlReturnValue : SqlMetaDataPriv
{
internal string parameter;
internal readonly SqlBuffer value;
internal SqlReturnValue() : base()
{
value = new SqlBuffer();
}
}
internal struct MultiPartTableName
{
private string _multipartName;
private string _serverName;
private string _catalogName;
private string _schemaName;
private string _tableName;
internal MultiPartTableName(string[] parts)
{
_multipartName = null;
_serverName = parts[0];
_catalogName = parts[1];
_schemaName = parts[2];
_tableName = parts[3];
}
internal MultiPartTableName(string multipartName)
{
_multipartName = multipartName;
_serverName = null;
_catalogName = null;
_schemaName = null;
_tableName = null;
}
internal string ServerName
{
get
{
ParseMultipartName();
return _serverName;
}
set { _serverName = value; }
}
internal string CatalogName
{
get
{
ParseMultipartName();
return _catalogName;
}
set { _catalogName = value; }
}
internal string SchemaName
{
get
{
ParseMultipartName();
return _schemaName;
}
set { _schemaName = value; }
}
internal string TableName
{
get
{
ParseMultipartName();
return _tableName;
}
set { _tableName = value; }
}
private void ParseMultipartName()
{
if (null != _multipartName)
{
string[] parts = MultipartIdentifier.ParseMultipartIdentifier(_multipartName, "[\"", "]\"", SR.SQL_TDSParserTableName, false);
_serverName = parts[0];
_catalogName = parts[1];
_schemaName = parts[2];
_tableName = parts[3];
_multipartName = null;
}
}
internal static readonly MultiPartTableName Null = new MultiPartTableName(new string[] { null, null, null, null });
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Models;
using OmniSharp.Models.FixUsings;
using OmniSharp.Roslyn.CSharp.Services.Refactoring;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class FixUsingsFacts : AbstractSingleRequestHandlerTestFixture<FixUsingService>
{
private const string TestFileName = "test.cs";
public FixUsingsFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
}
protected override string EndpointName => OmniSharpEndpoints.FixUsings;
[Fact]
public async Task FixUsings_AddsUsingSingle()
{
const string code = @"
namespace nsA
{
public class classX{}
}
namespace OmniSharp
{
public class class1
{
public method1()
{
var c1 = new classX();
}
}
}";
const string expectedCode = @"
using nsA;
namespace nsA
{
public class classX{}
}
namespace OmniSharp
{
public class class1
{
public method1()
{
var c1 = new classX();
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
[Fact]
public async Task FixUsings_AddsUsingSingleForFrameworkMethod()
{
const string code = @"
namespace OmniSharp
{
public class class1
{
public void method1()
{
Guid.NewGuid();
}
}
}";
string expectedCode = @"
using System;
namespace OmniSharp
{
public class class1
{
public void method1()
{
Guid.NewGuid();
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
[Fact]
public async Task FixUsings_AddsUsingSingleForFrameworkClass()
{
const string code = @"
namespace OmniSharp
{
public class class1
{
public void method1()()
{
var s = new StringBuilder();
}
}
}";
const string expectedCode = @"
using System.Text;
namespace OmniSharp
{
public class class1
{
public void method1()()
{
var s = new StringBuilder();
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
[Fact]
public async Task FixUsings_AddsUsingMultiple()
{
const string code = @"
namespace nsA
{
public class classX{}
}
namespace nsB
{
public class classY{}
}
namespace OmniSharp
{
public class class1
{
public method1()
{
var c1 = new classX();
var c2 = new classY();
}
}
}";
const string expectedCode = @"
using nsA;
using nsB;
namespace nsA
{
public class classX{}
}
namespace nsB
{
public class classY{}
}
namespace OmniSharp
{
public class class1
{
public method1()
{
var c1 = new classX();
var c2 = new classY();
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
[Fact]
public async Task FixUsings_AddsUsingMultipleForFramework()
{
const string code = @"
namespace OmniSharp
{
public class class1
{
public void method1()
{
Guid.NewGuid();
var sb = new StringBuilder();
}
}
}";
const string expectedCode = @"
using System;
using System.Text;
namespace OmniSharp
{
public class class1
{
public void method1()
{
Guid.NewGuid();
var sb = new StringBuilder();
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
[Fact]
public async Task FixUsings_ReturnsAmbiguousResult()
{
const string code = @"
namespace nsA
{
public class classX{}
}
namespace nsB
{
public class classX{}
}
namespace OmniSharp
{
public class class1
{
public method1()
{
var c1 = new $$classX();
}
}
}";
var content = TestContent.Parse(code);
var point = content.GetPointFromPosition();
var expectedUnresolved = new[]
{
new QuickFix()
{
Line = point.Line,
Column = point.Offset,
FileName = TestFileName,
Text = "`classX` is ambiguous. Namespaces: using nsA; using nsB;",
}
};
await AssertUnresolvedReferencesAsync(content.Code, expectedUnresolved);
}
[Fact]
public async Task FixUsings_ReturnsNoUsingsForAmbiguousResult()
{
const string code = @"
namespace nsA {
public class classX{}
}
namespace nsB {
public class classX{}
}
namespace OmniSharp {
public class class1
{
public method1()
{
var c1 = new classX();
}
}
}";
await AssertBufferContentsAsync(code, expectedCode: code);
}
[Fact]
public async Task FixUsings_AddsUsingForExtension()
{
const string code = @"
namespace nsA {
public static class StringExtension {
public static void Whatever(this string astring) {}
}
}
namespace OmniSharp {
public class class1
{
public method1()
{
""string"".Whatever();
}
}
}";
const string expectedCode = @"
using nsA;
namespace nsA {
public static class StringExtension {
public static void Whatever(this string astring) {}
}
}
namespace OmniSharp {
public class class1
{
public method1()
{
""string"".Whatever();
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
[Fact]
public async Task FixUsings_AddsUsingLinqMethodSyntax()
{
const string code = @"namespace OmniSharp
{
public class class1
{
public void method1()
{
List<string> first = new List<string>();
var testing = first.Where(s => s == ""abc"");
}
}
}";
const string expectedCode = @"using System.Collections.Generic;
using System.Linq;
namespace OmniSharp
{
public class class1
{
public void method1()
{
List<string> first = new List<string>();
var testing = first.Where(s => s == ""abc"");
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
[Fact]
public async Task FixUsings_AddsUsingLinqQuerySyntax()
{
const string code = @"namespace OmniSharp
{
public class class1
{
public void method1()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from n in numbers
where n < 5
select n;
}
}
}";
const string expectedCode = @"using System.Linq;
namespace OmniSharp
{
public class class1
{
public void method1()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from n in numbers
where n < 5
select n;
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
[Fact]
public async Task FixUsings_RemoveDuplicateUsing()
{
const string code = @"
using System;
using System;
namespace OmniSharp
{
public class class1
{
public void method1()
{
Guid.NewGuid();
}
}
}";
const string expectedCode = @"
using System;
namespace OmniSharp
{
public class class1
{
public void method1()
{
Guid.NewGuid();
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
[Fact]
public async Task FixUsings_RemoveUnusedUsing()
{
const string code = @"
using System;
using System.Linq;
namespace OmniSharp
{
public class class1
{
public void method1()
{
Guid.NewGuid();
}
}
}";
const string expectedCode = @"
using System;
namespace OmniSharp
{
public class class1
{
public void method1()
{
Guid.NewGuid();
}
}
}";
await AssertBufferContentsAsync(code, expectedCode);
}
private async Task AssertBufferContentsAsync(string code, string expectedCode)
{
var response = await RunFixUsingsAsync(code);
Assert.Equal(FlattenNewLines(expectedCode), FlattenNewLines(response.Buffer));
}
private static string FlattenNewLines(string input)
{
return input.Replace("\r\n", "\n");
}
private async Task AssertUnresolvedReferencesAsync(string code, QuickFix[] expectedResults)
{
var response = await RunFixUsingsAsync(code);
var results = response.AmbiguousResults.ToArray();
Assert.Equal(results.Length, expectedResults.Length);
for (var i = 0; i < results.Length; i++)
{
var result = results[i];
var expectedResult = expectedResults[i];
Assert.Equal(expectedResult.Line, result.Line);
Assert.Equal(expectedResult.Column, result.Column);
Assert.Equal(expectedResult.FileName, result.FileName);
Assert.Equal(expectedResult.Text, result.Text);
}
}
private async Task<FixUsingsResponse> RunFixUsingsAsync(string code)
{
SharedOmniSharpTestHost.AddFilesToWorkspace(new TestFile(TestFileName, code));
var requestHandler = GetRequestHandler(SharedOmniSharpTestHost);
var request = new FixUsingsRequest
{
FileName = TestFileName
};
return await requestHandler.Handle(request);
}
}
}
| |
using System;
using System.Linq;
using System.Configuration;
using System.Collections.Generic;
using System.Threading;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using ServiceStack.ServiceHost;
using ServiceStackBenchmark.Model;
namespace ServiceStackBenchmark
{
public static class AppHostConfigHelper
{
public static bool InitMongoDB(this Funq.Container container)
{
try
{
// Register the MySql Database Connection Factory
var mongoDbConnectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
var client = new MongoClient(mongoDbConnectionString);
var server = client.GetServer();
var database = server.GetDatabase("hello_world");
container.Register<MongoDatabase>(c => database);
BsonClassMap.RegisterClassMap<World>(cm => {
cm.MapProperty(c => c.id);
cm.MapProperty(c => c.randomNumber);
});
BsonClassMap.RegisterClassMap<Fortune>(cm => {
cm.MapProperty(c => c.id);
cm.MapProperty(c => c.message);
});
// Create needed tables in MySql Server if they do not exist
return database.CreateWorldTable() && database.CreateFortuneTable();
}
catch
{
// Unregister failed database connection factory
container.Register<MongoDatabase>(c => null);
return false;
}
}
public static bool InitMySQL(this Funq.Container container)
{
try
{
// Register the MySql Database Connection Factory
var mySqlConnectionString = ConfigurationManager.ConnectionStrings["MySQL"];
var mySqlFactory = new MySqlOrmLiteConnectionFactory(mySqlConnectionString.ConnectionString);
mySqlFactory.DialectProvider.UseUnicode = true;
container.Register<IMySqlOrmLiteConnectionFactory>(c => mySqlFactory);
// Create needed tables in MySql Server if they do not exist
using (var conn = mySqlFactory.OpenDbConnection())
{
return conn.CreateWorldTable() && conn.CreateFortuneTable();
}
}
catch (Exception ex)
{
// Unregister failed database connection factory
container.Register<IMySqlOrmLiteConnectionFactory>(c => null);
return false;
}
}
public static bool InitPostgreSQL(this Funq.Container container)
{
try
{
// Register the PostgreSQL Database Connection Factory
var postgreSqlConnectionString = ConfigurationManager.ConnectionStrings["PostgreSQL"];
var postgreSqlFactory = new PostgreSqlOrmLiteConnectionFactory(postgreSqlConnectionString.ConnectionString);
postgreSqlFactory.DialectProvider.UseUnicode = true;
container.Register<IPostgreSqlOrmLiteConnectionFactory>(c => postgreSqlFactory);
// Create needed tables in PostgreSql Server if they do not exist
using (var conn = postgreSqlFactory.OpenDbConnection())
{
return conn.CreateWorldTable() && conn.CreateFortuneTable();
}
}
catch (Exception ex)
{
// Unregister failed database connection factory
container.Register<IPostgreSqlOrmLiteConnectionFactory>(c => null);
return false;
}
}
public static bool InitSQLServer(this Funq.Container container)
{
try
{
// Register the Microsoft Sql Server Database Connection Factory
var sqlServerConnectionString = ConfigurationManager.ConnectionStrings["SQLServer"];
var sqlServerFactory = new SqlServerOrmLiteConnectionFactory(sqlServerConnectionString.ConnectionString);
sqlServerFactory.DialectProvider.UseUnicode = true;
container.Register<ISqlServerOrmLiteConnectionFactory>(c => sqlServerFactory);
// Create needed tables in Microsoft Sql Server if they do not exist
using (var conn = sqlServerFactory.OpenDbConnection())
{
return conn.CreateWorldTable() && conn.CreateFortuneTable();
}
}
catch (Exception ex)
{
// Unregister failed database connection factory
container.Register<ISqlServerOrmLiteConnectionFactory>(c => null);
return false;
}
}
public static void InitDatabaseRoutes(this Funq.Container container, IServiceRoutes routes)
{
if (container.InitMongoDB())
{
routes.Add<MongoDBDbRequest>("/mongodb/db", "GET");
routes.Add<MongoDBQueriesRequest>("/mongodb/queries/{queries}", "GET");
routes.Add<MongoDBFortunesRequest>("/mongodb/fortunes", "GET");
routes.Add<MongoDBUpdatesRequest>("/mongodb/updates/{queries}", "GET");
routes.Add<MongoDBCachedDbRequest>("/mongodb/cached/db", "GET");
}
if (container.InitMySQL())
{
routes.Add<MySqlDbRequest>("/mysql/db", "GET");
routes.Add<MySqlQueriesRequest>("/mysql/queries/{queries}", "GET");
routes.Add<MySqlFortunesRequest>("/mysql/fortunes", "GET");
routes.Add<MySqlUpdatesRequest>("/mysql/updates/{queries}", "GET");
routes.Add<MySqlCachedDbRequest>("/mysql/cached/db", "GET");
}
if (container.InitPostgreSQL())
{
routes.Add<PostgreSqlDbRequest>("/postgresql/db", "GET");
routes.Add<PostgreSqlQueriesRequest>("/postgresql/queries/{queries}", "GET");
routes.Add<PostgreSqlFortunesRequest>("/postgresql/fortunes", "GET");
routes.Add<PostgreSqlUpdatesRequest>("/postgresql/updates/{queries}", "GET");
routes.Add<PostgreSqlCachedDbRequest>("/postgresql/cached/db", "GET");
}
if (container.InitSQLServer())
{
routes.Add<SqlServerDbRequest>("/sqlserver/db", "GET");
routes.Add<SqlServerQueriesRequest>("/sqlserver/queries/{queries}", "GET");
routes.Add<SqlServerFortunesRequest>("/sqlserver/fortunes", "GET");
routes.Add<SqlServerUpdatesRequest>("/sqlserver/updates/{queries}", "GET");
routes.Add<SqlServerCachedDbRequest>("/sqlserver/cached/db", "GET");
}
}
public static Feature GetDisabledFeatures()
{
try
{
var disabled = ConfigurationManager.AppSettings.Get("DisabledFeatures");
Feature d;
if (Enum.TryParse(disabled, true, out d))
return d;
return Feature.None;
}
catch
{
return Feature.None;
}
}
/// <summary>
/// Method to config the Minimum number of Worker Threads per Logical Processor Count.
/// </summary>
/// <remarks>the Completion Port Threads are set to their defaults as there is no IO concerrency in our app</remarks>
public static void ConfigThreadPool()
{
string minTPLPSetting = ConfigurationManager.AppSettings["minWorkerThreadsPerLogicalProcessor"];
if (minTPLPSetting == null)
return;
int sysMinWorkerThreads, sysMinCompletionPortThreads;
ThreadPool.GetMinThreads(out sysMinWorkerThreads, out sysMinCompletionPortThreads);
int newMinWorkerThreadsPerCPU = Math.Max(1, Convert.ToInt32(minTPLPSetting));
var minWorkerThreads = Environment.ProcessorCount * newMinWorkerThreadsPerCPU;
ThreadPool.SetMinThreads(minWorkerThreads, sysMinCompletionPortThreads);
}
}
}
| |
using System;
using Shouldly;
using Xunit;
namespace AutoMapper.UnitTests.BeforeAfterMapping
{
using Bug;
public class When_configuring_before_and_after_methods
{
public class Source
{
}
public class Destination
{
}
[Fact]
public void Before_and_After_should_be_called()
{
var beforeMapCalled = false;
var afterMapCalled = false;
var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>()
.BeforeMap((src, dest) => beforeMapCalled = true)
.AfterMap((src, dest) => afterMapCalled = true));
var mapper = config.CreateMapper();
mapper.Map<Source, Destination>(new Source());
beforeMapCalled.ShouldBeTrue();
afterMapCalled.ShouldBeTrue();
}
[Fact]
public void Before_and_After_overrides_should_be_called()
{
var beforeMapCalled = false;
var afterMapCalled = false;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.ForAllMaps((map, expression) =>
{
expression.BeforeMap((src, dest, context) => beforeMapCalled = true);
expression.AfterMap((src, dest, context) => afterMapCalled = true);
});
});
var mapper = config.CreateMapper();
mapper.Map<Source, Destination>(new Source());
beforeMapCalled.ShouldBeTrue();
afterMapCalled.ShouldBeTrue();
}
}
public class When_configuring_before_and_after_methods_multiple_times
{
public class Source
{
}
public class Destination
{
}
[Fact]
public void Before_and_After_should_be_called()
{
var beforeMapCount = 0;
var afterMapCount = 0;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.BeforeMap((src, dest) => beforeMapCount++)
.BeforeMap((src, dest) => beforeMapCount++)
.AfterMap((src, dest) => afterMapCount++)
.AfterMap((src, dest) => afterMapCount++);
});
var mapper = config.CreateMapper();
mapper.Map<Source, Destination>(new Source());
beforeMapCount.ShouldBe(2);
afterMapCount.ShouldBe(2);
}
[Fact]
public void Before_and_After_overrides_should_be_called()
{
var beforeMapCount = 0;
var afterMapCount = 0;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.ForAllMaps((map, expression) =>
{
expression.BeforeMap((src, dest, context) => beforeMapCount++)
.BeforeMap((src, dest, context) => beforeMapCount++);
expression.AfterMap((src, dest, context) => afterMapCount++)
.AfterMap((src, dest, context) => afterMapCount++);
});
});
var mapper = config.CreateMapper();
mapper.Map<Source, Destination>(new Source());
beforeMapCount.ShouldBe(2);
afterMapCount.ShouldBe(2);
}
}
public class When_using_a_class_to_do_before_after_mappings : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
public class BeforeMapAction : IMappingAction<Source, Destination>
{
private readonly int _decrement;
public BeforeMapAction(int decrement)
{
_decrement = decrement;
}
public void Process(Source source, Destination destination, ResolutionContext context)
{
source.Value -= _decrement * 2;
}
}
public class AfterMapAction : IMappingAction<Source, Destination>
{
private readonly int _increment;
public AfterMapAction(int increment)
{
_increment = increment;
}
public void Process(Source source, Destination destination, ResolutionContext context)
{
destination.Value += _increment * 5;
}
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.ConstructServicesUsing(t => Activator.CreateInstance(t, 2));
cfg.CreateMap<Source, Destination>()
.BeforeMap<BeforeMapAction>()
.AfterMap<AfterMapAction>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {Value = 4});
}
[Fact]
public void Should_use_global_constructor_for_building_mapping_actions()
{
_destination.Value.ShouldBe(10);
}
}
public class When_using_a_class_to_do_before_after_mappings_with_resolutioncontext : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
public class BeforeMapAction : IMappingAction<Source, Destination>
{
private readonly int _decrement;
public BeforeMapAction(int decrement)
{
_decrement = decrement;
}
public void Process(Source source, Destination destination, ResolutionContext context)
{
var customMultiplier = (int)context.Items["CustomMultiplier"];
source.Value -= _decrement * 2 * customMultiplier;
}
}
public class AfterMapAction : IMappingAction<Source, Destination>
{
private readonly int _increment;
public AfterMapAction(int increment)
{
_increment = increment;
}
public void Process(Source source, Destination destination, ResolutionContext context)
{
var customMultiplier = (int)context.Items["CustomMultiplier"];
destination.Value += _increment * 5 * customMultiplier;
}
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.ConstructServicesUsing(t => Activator.CreateInstance(t, 2));
cfg.CreateMap<Source, Destination>()
.BeforeMap<BeforeMapAction>()
.AfterMap<AfterMapAction>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Value = 4 }, opt => opt.Items["CustomMultiplier"] = 10);
}
[Fact]
public void Should_use_global_constructor_for_building_mapping_actions()
{
_destination.Value.ShouldBe(64);
}
}
public class MappingSpecificBeforeMapping : AutoMapperSpecBase
{
private Dest _dest;
public class Source
{
public int Value { get; set; }
}
public class Dest
{
public int Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Dest>()
.BeforeMap((src, dest) => src.Value += 10);
});
protected override void Because_of()
{
_dest = Mapper.Map<Source, Dest>(new Source
{
Value = 5
}, opt => opt.BeforeMap((src, dest) => src.Value += 10));
}
[Fact]
public void Should_execute_typemap_and_scoped_beforemap()
{
_dest.Value.ShouldBe(25);
}
}
public class MappingSpecificAfterMapping : AutoMapperSpecBase
{
private Dest _dest;
public class Source
{
public int Value { get; set; }
}
public class Dest
{
public int Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Dest>()
.AfterMap((src, dest) => dest.Value += 10);
});
protected override void Because_of()
{
_dest = Mapper.Map<Source, Dest>(new Source
{
Value = 5
}, opt => opt.AfterMap((src, dest) => dest.Value += 10));
}
[Fact]
public void Should_execute_typemap_and_scoped_aftermap()
{
_dest.Value.ShouldBe(25);
}
}
}
| |
namespace Fixtures.SwaggerBatHttp
{
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 HttpClientFailureExtensions
{
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Head400(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head400Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Head400Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Head400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Get400(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get400Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Get400Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Get400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Put400(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Put400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Put400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Patch400(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Patch400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Patch400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Post400(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Post400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Post400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Delete400(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 400 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Delete400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Delete400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 401 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Head401(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head401Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 401 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Head401Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Head401WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 402 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Get402(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get402Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 402 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Get402Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Get402WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 403 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Get403(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get403Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 403 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Get403Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Get403WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 404 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Put404(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put404Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 404 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Put404Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Put404WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 405 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Patch405(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch405Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 405 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Patch405Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Patch405WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 406 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Post406(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post406Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 406 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Post406Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Post406WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 407 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Delete407(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete407Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 407 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Delete407Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Delete407WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 409 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Put409(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put409Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 409 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Put409Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Put409WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 410 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Head410(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head410Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 410 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Head410Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Head410WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 411 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Get411(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get411Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 411 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Get411Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Get411WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 412 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Get412(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get412Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 412 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Get412Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Get412WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 413 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Put413(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put413Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 413 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Put413Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Put413WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 414 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Patch414(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch414Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 414 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Patch414Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Patch414WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 415 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Post415(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post415Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 415 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Post415Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Post415WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 416 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Get416(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get416Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 416 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Get416Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Get416WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 417 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static Error Delete417(this IHttpClientFailure operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete417Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 417 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Delete417Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Delete417WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Return 429 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static Error Head429(this IHttpClientFailure operations)
{
return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head429Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 429 status code - should be represented in the client as an error
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<Error> Head429Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<Error> result = await operations.Head429WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using AxiomCoders.PdfTemplateEditor.EditorStuff;
using System.Drawing;
using System.Windows.Forms;
namespace AxiomCoders.PdfTemplateEditor.EditorStuff
{
/// <summary>
/// some positions for commands
/// </summary>
public enum CommandPosition
{
TopLeft,
TopCenter,
TopRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
BottomLeft,
BottomCenter,
BottomRight
}
/// <summary>
/// Item used to store command information
/// </summary>
public class CommandItem
{
private CommandPosition commandPosition;
public AxiomCoders.PdfTemplateEditor.EditorStuff.CommandPosition CommandPosition
{
get { return commandPosition; }
}
private EditorItem owner;
public AxiomCoders.PdfTemplateEditor.EditorStuff.EditorItem Owner
{
get { return owner; }
set { owner = value; }
}
protected CommandItem()
{
}
public virtual void Draw(float zoomLevel, System.Drawing.Graphics gc)
{
System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
mat.Multiply(this.TransformationMatrix, System.Drawing.Drawing2D.MatrixOrder.Append);
mat.Multiply(this.Owner.DrawMatrix, System.Drawing.Drawing2D.MatrixOrder.Append);
mat.Multiply(this.Owner.ViewMatrix, System.Drawing.Drawing2D.MatrixOrder.Append);
gc.Transform = mat;
float w = (float)this.WidthInPixels / this.Owner.ViewMatrix.Elements[0];
float h = (float)this.HeightInPixels / this.Owner.ViewMatrix.Elements[3];
Pen p = new Pen(Color.Gray, 1.0f / zoomLevel);
gc.DrawRectangle(p, 0, 0, w, h);
}
protected int commandSize = 6;
protected float widthInPixels;
public float WidthInPixels
{
get { return widthInPixels; }
}
protected float heightInPixels;
public float HeightInPixels
{
get { return heightInPixels; }
}
public CommandItem(CommandPosition position, EditorItem owner)
{
this.Owner = owner;
this.commandPosition = position;
this.widthInPixels = commandSize;
this.heightInPixels = commandSize;
}
protected int GetDisplaceX()
{
switch (commandPosition)
{
case CommandPosition.TopCenter:
return (int)(this.Owner.WidthInPixels/2) + (this.commandSize / 2);
}
return 0;
}
protected int GetDisplaceY()
{
switch (commandPosition)
{
case CommandPosition.TopCenter:
return -this.commandSize / 2;
}
return 0;
}
/// <summary>
/// Current cursor for this command item
/// </summary>
protected Cursor cursor = Cursors.Default;
protected float locationInPixelsX;
public float LocationInPixelsX
{
get { return locationInPixelsX; }
set { locationInPixelsX = value; }
}
protected float locationInPixelsY;
public float LocationInPixelsY
{
get { return locationInPixelsY; }
set { locationInPixelsY = value; }
}
protected System.Drawing.Drawing2D.Matrix transformationMatrix = new System.Drawing.Drawing2D.Matrix();
public System.Drawing.Drawing2D.Matrix TransformationMatrix
{
get
{
System.Drawing.Drawing2D.Matrix offsetTrans;
offsetTrans = new System.Drawing.Drawing2D.Matrix();
offsetTrans.Translate((float)this.LocationInPixelsX, (float)this.LocationInPixelsY);
// first we scale than rotate and then transform
this.transformationMatrix.Reset();
this.transformationMatrix.Multiply(offsetTrans, System.Drawing.Drawing2D.MatrixOrder.Append);
return this.transformationMatrix;
}
}
public virtual void StartMoving()
{
}
public virtual void StopMoving()
{
}
public virtual void Move(float dx, float dy)
{
}
/// <summary>
/// Check if this command can be selected and return true in case it can
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public bool CanBeSelected(float x, float y, System.Drawing.Drawing2D.Matrix viewMatrix)
{
// transform x,y back to object coordinates to check for selection
System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
mat.Multiply(this.TransformationMatrix, System.Drawing.Drawing2D.MatrixOrder.Append);
mat.Multiply(this.Owner.DrawMatrix, System.Drawing.Drawing2D.MatrixOrder.Append);
mat.Multiply(viewMatrix, System.Drawing.Drawing2D.MatrixOrder.Append);
mat.Invert();
PointF tmpPoint = new PointF(x, y);
PointF[] points = new PointF[1];
points[0] = tmpPoint;
mat.TransformPoints(points);
tmpPoint = points[0];
// check if this item should be selected
//float tmpX = LocationInPixelsX * zoomLevel;
//float tmpY = LocationInPixelsY * zoomLevel;
//float w = widthInPixels; //** zoomLevel;
//float h = heightInPixels; //* zoomLevel;
float w = (float)this.WidthInPixels / this.Owner.ViewMatrix.Elements[0];
float h = (float)this.HeightInPixels / this.Owner.ViewMatrix.Elements[3];
// if starting coordinate fall inside this component rect
if (tmpPoint.X >= 0 && tmpPoint.X <= w && tmpPoint.Y >= 0 && tmpPoint.Y <= h)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Return cursor for command
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="zoomLevel"></param>
/// <returns>null if coordinates are not fine</returns>
public Cursor GetCursor(float x, float y, System.Drawing.Drawing2D.Matrix viewMatrix)
{
// transform x,y back to object coordinates to check for selection
System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
mat.Multiply(this.TransformationMatrix, System.Drawing.Drawing2D.MatrixOrder.Append);
mat.Multiply(this.Owner.DrawMatrix, System.Drawing.Drawing2D.MatrixOrder.Append);
mat.Multiply(viewMatrix, System.Drawing.Drawing2D.MatrixOrder.Append);
mat.Invert();
PointF tmpPoint = new PointF(x, y);
PointF[] points = new PointF[1];
points[0] = tmpPoint;
mat.TransformPoints(points);
tmpPoint = points[0];
// check if this item should be selected
float w = (float)this.WidthInPixels / this.Owner.ViewMatrix.Elements[0];
float h = (float)this.HeightInPixels / this.Owner.ViewMatrix.Elements[3];
// if starting coordinate fall inside this component rect
if (tmpPoint.X >= 0 && tmpPoint.X <= w && tmpPoint.Y >= 0 && tmpPoint.Y <= h)
{
return this.cursor;
}
else
{
return null;
}
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Xml.Serialization;
using System.Reflection;
using NUnit.Framework;
using Boo.Lang.Compiler.Ast;
namespace Boo.Lang.Parser.Tests
{
/// <summary>
/// Test cases for the BooParser class.
/// </summary>
[TestFixture]
public class BooParserTestCase : AbstractParserTestFixture
{
[Test]
public void TestEndSourceLocationForInlineClosures()
{
string code = @"foo = { a = 3;
return a; }";
EnsureClosureEndSourceLocation(code, 2, 11);
}
[Test]
public void TestEndSourceLocationForBlockClosures()
{
string code = @"
foo = def():
return a
";
EnsureClosureEndSourceLocation(code, 3, 13);
}
void EnsureClosureEndSourceLocation(string code, int line, int column)
{
CompileUnit cu = BooParser.ParseString("closures", code);
Expression e = ((ExpressionStatement)cu.Modules[0].Globals.Statements[0]).Expression;
BlockExpression cbe = (BlockExpression)((BinaryExpression)e).Right;
SourceLocation esl = cbe.Body.EndSourceLocation;
Assert.AreEqual(line, esl.Line);
Assert.AreEqual(column, esl.Column);
}
[Test]
public void TestParseExpression()
{
string code = @"3 + 2 * 5";
Expression e = BooParser.ParseExpression("test", code);
Assert.AreEqual("3 + (2 * 5)", e.ToString());
}
[Test]
public void TestSimple()
{
string fname = GetTestCasePath("simple.boo");
CompileUnit cu = BooParser.ParseFile(fname);
Assert.IsNotNull(cu);
Boo.Lang.Compiler.Ast.Module module = cu.Modules[0];
Assert.IsNotNull(module);
Assert.AreEqual("simple", module.Name);
Assert.AreEqual("module doc string", module.Documentation);
Assert.AreEqual("Empty.simple", module.FullName);
Assert.AreEqual(fname, module.LexicalInfo.FileName);
Assert.IsNotNull(module.Namespace);
Assert.AreEqual("Empty", module.Namespace.Name);
Assert.AreEqual(4, module.Namespace.LexicalInfo.Line);
Assert.AreEqual(1, module.Namespace.LexicalInfo.Column);
Assert.AreEqual(fname, module.Namespace.LexicalInfo.FileName);
}
[Test]
public void TestSimpleClasses()
{
string fname = GetTestCasePath("simple_classes.boo");
Boo.Lang.Compiler.Ast.Module module = BooParser.ParseFile(fname).Modules[0];
Assert.AreEqual("Foo.Bar", module.Namespace.Name);
Assert.IsNotNull(module.Members);
Assert.AreEqual(2, module.Members.Count);
TypeMember cd = module.Members[0];
Assert.IsTrue(cd is ClassDefinition);
Assert.AreEqual("Customer", cd.Name);
Assert.AreEqual("Foo.Bar.Customer", ((TypeDefinition)cd).FullName);
Assert.AreSame(module.Namespace, ((TypeDefinition)cd).EnclosingNamespace);
cd = module.Members[1];
Assert.AreEqual("Person", cd.Name);
}
[Test]
public void TestSimpleClassMethods()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("simple_class_methods.boo");
Assert.AreEqual("ITL.Content", module.Namespace.Name);
Assert.AreEqual(1, module.Imports.Count);
Import i = module.Imports[0];
Assert.AreEqual("System", i.Namespace);
Assert.AreEqual(3, i.LexicalInfo.Line);
Assert.AreEqual(1, module.Members.Count);
ClassDefinition cd = (ClassDefinition)module.Members[0];
Assert.AreEqual("Article", cd.Name);
Assert.AreEqual(3, cd.Members.Count);
Method m = (Method)cd.Members[0];
Assert.AreEqual("getTitle", m.Name);
Assert.IsNotNull(m.ReturnType, "ReturnType");
Assert.AreEqual("string", ((SimpleTypeReference)m.ReturnType).Name);
m = (Method)cd.Members[1];
Assert.AreEqual("getBody", m.Name);
Assert.IsNotNull(m.ReturnType, "ReturnType");
Assert.AreEqual("string", ((SimpleTypeReference)m.ReturnType).Name);
m = (Method)cd.Members[2];
Assert.AreEqual("getTag", m.Name);
Assert.IsNull(m.ReturnType, "methods without a return type must have ReturnType set to null!");
}
[Test]
public void TestSimpleClassFields()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("simple_class_fields.boo");
Assert.AreEqual(1, module.Members.Count);
ClassDefinition cd = (ClassDefinition)module.Members[0];
Assert.AreEqual(3, cd.Members.Count, "Members");
Field f = (Field)cd.Members[0];
Assert.AreEqual("_name", f.Name);
Assert.IsNotNull(f.Type, "Field.Type");
Assert.AreEqual("string", ((SimpleTypeReference)f.Type).Name);
Constructor c = (Constructor)cd.Members[1];
Assert.AreEqual("constructor", c.Name);
Assert.IsNull(c.ReturnType);
Assert.AreEqual(1, c.Parameters.Count, "Parameters.Count");
Assert.AreEqual("name", c.Parameters[0].Name);
Assert.AreEqual("string", ((SimpleTypeReference)c.Parameters[0].Type).Name);
Method m = (Method)cd.Members[2];
Assert.AreEqual("getName", m.Name);
Assert.IsNull(m.ReturnType);
Assert.AreEqual(0, m.Parameters.Count);
Assert.IsNotNull(m.Body, "Body");
Assert.AreEqual(1, m.Body.Statements.Count);
ReturnStatement rs = (ReturnStatement)m.Body.Statements[0];
ReferenceExpression i = (ReferenceExpression)rs.Expression;
Assert.AreEqual("_name", i.Name);
}
[Test]
public void TestSimpleGlobalDefs()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("simple_global_defs.boo");
Assert.AreEqual("Math", module.Namespace.Name);
Assert.AreEqual(3, module.Members.Count);
Assert.AreEqual("Rational", module.Members[0].Name);
Assert.AreEqual("pi", module.Members[1].Name);
Assert.AreEqual("rationalPI", module.Members[2].Name);
Assert.AreEqual(0, module.Globals.Statements.Count);
}
[Test]
public void StatementModifiersOnUnpackStatement()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("stmt_modifiers_3.boo");
Block body = module.Globals;
Assert.AreEqual(2, body.Statements.Count);
UnpackStatement stmt = (UnpackStatement)body.Statements[0];
Assert.IsNotNull(stmt.Modifier, "Modifier");
Assert.AreEqual(StatementModifierType.If, stmt.Modifier.Type);
Assert.IsTrue(stmt.Modifier.Condition is BoolLiteralExpression);
Assert.AreEqual(true, ((BoolLiteralExpression)stmt.Modifier.Condition).Value);
RunParserTestCase("stmt_modifiers_3.boo");
}
[Test]
public void TestStmtModifiers1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("stmt_modifiers_1.boo");
Method m = (Method)module.Members[0];
ReturnStatement rs = (ReturnStatement)m.Body.Statements[0];
Assert.IsNotNull(rs.Modifier, "Modifier");
Assert.AreEqual(StatementModifierType.If, rs.Modifier.Type);
BinaryExpression be = (BinaryExpression)rs.Modifier.Condition;
Assert.AreEqual(BinaryOperatorType.LessThan, be.Operator);
Assert.AreEqual("n", ((ReferenceExpression)be.Left).Name);
Assert.AreEqual(2, ((IntegerLiteralExpression)be.Right).Value);
}
[Test]
public void TestStmtModifiers2()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("stmt_modifiers_2.boo");
ExpressionStatement s = (ExpressionStatement)module.Globals.Statements[0];
BinaryExpression a = (BinaryExpression)s.Expression;
Assert.AreEqual(BinaryOperatorType.Assign, a.Operator);
Assert.AreEqual("f", ((ReferenceExpression)a.Left).Name);
Assert.AreEqual(BinaryOperatorType.Division, ((BinaryExpression)a.Right).Operator);
}
[Test]
public void TestStaticMethod()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("static_method.boo");
Assert.AreEqual(1, module.Members.Count);
ClassDefinition cd = (ClassDefinition)module.Members[0];
Assert.AreEqual("Math", cd.Name);
Assert.AreEqual(1, cd.Members.Count);
Method m = (Method)cd.Members[0];
Assert.AreEqual(TypeMemberModifiers.Static, m.Modifiers);
Assert.AreEqual("square", m.Name);
Assert.AreEqual("int", ((SimpleTypeReference)m.ReturnType).Name);
}
[Test]
public void TestClass2()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("class_2.boo");
ClassDefinition cd = (ClassDefinition)module.Members[0];
Assert.AreEqual(6, cd.Members.Count);
for (int i=0; i<5; ++i)
{
Assert.AreEqual(TypeMemberModifiers.None, cd.Members[i].Modifiers);
}
Assert.AreEqual(TypeMemberModifiers.Public | TypeMemberModifiers.Static, cd.Members[5].Modifiers);
}
[Test]
public void TestForStmt1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("for_stmt_1.boo");
ForStatement fs = (ForStatement)module.Globals.Statements[0];
Assert.AreEqual(1, fs.Declarations.Count);
Declaration d = fs.Declarations[0];
Assert.AreEqual("i", d.Name);
Assert.IsNull(d.Type);
ListLiteralExpression lle = (ListLiteralExpression)fs.Iterator;
Assert.AreEqual(3, lle.Items.Count);
for (int i=0; i<3; ++i)
{
Assert.AreEqual(i+1, ((IntegerLiteralExpression)lle.Items[i]).Value);
}
Assert.AreEqual(1, fs.Block.Statements.Count);
Assert.AreEqual("print", ((ReferenceExpression)((MethodInvocationExpression)((ExpressionStatement)fs.Block.Statements[0]).Expression).Target).Name);
}
[Test]
public void TestRELiteral1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("re_literal_1.boo");
Assert.AreEqual(2, module.Globals.Statements.Count);
ExpressionStatement es = (ExpressionStatement)module.Globals.Statements[1];
Assert.AreEqual("print", ((ReferenceExpression)((MethodInvocationExpression)es.Expression).Target).Name);
Assert.AreEqual(StatementModifierType.If, es.Modifier.Type);
BinaryExpression be = (BinaryExpression)es.Modifier.Condition;
Assert.AreEqual(BinaryOperatorType.Match, be.Operator);
Assert.AreEqual("s", ((ReferenceExpression)be.Left).Name);
Assert.AreEqual("/foo/", ((RELiteralExpression)be.Right).Value);
}
[Test]
public void TestRELiteral2()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("re_literal_2.boo");
StatementCollection stmts = module.Globals.Statements;
Assert.AreEqual(2, stmts.Count);
BinaryExpression ae = (BinaryExpression)((ExpressionStatement)stmts[0]).Expression;
Assert.AreEqual(BinaryOperatorType.Assign, ae.Operator);
Assert.AreEqual("\"Bamboo\"\n", ((StringLiteralExpression)ae.Right).Value);
ae = (BinaryExpression)((ExpressionStatement)stmts[1]).Expression;
Assert.AreEqual(BinaryOperatorType.Assign, ae.Operator);
Assert.AreEqual("/foo\\(bar\\)/", ((RELiteralExpression)ae.Right).Value);
}
[Test]
public void TestRELiteral3()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("re_literal_3.boo");
StatementCollection stmts = module.Globals.Statements;
Assert.AreEqual(2, stmts.Count);
BinaryExpression ae = (BinaryExpression)((ExpressionStatement)stmts[0]).Expression;
Assert.AreEqual(BinaryOperatorType.Assign, ae.Operator);
Assert.AreEqual("/\\x2f\\u002f/", ((RELiteralExpression)ae.Right).Value);
}
[Test]
public void TestIfElse1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("if_else_1.boo");
StatementCollection stmts = module.Globals.Statements;
Assert.AreEqual(1, stmts.Count);
IfStatement s = (IfStatement)stmts[0];
BinaryExpression be = (BinaryExpression)s.Condition;
Assert.AreEqual(BinaryOperatorType.Match, be.Operator);
Assert.AreEqual("gets", ((ReferenceExpression)((MethodInvocationExpression)be.Left).Target).Name);
Assert.AreEqual("/foo/", ((RELiteralExpression)be.Right).Value);
Assert.AreEqual(3, s.TrueBlock.Statements.Count);
Assert.IsNull(s.FalseBlock);
s = (IfStatement)s.TrueBlock.Statements[2];
be = (BinaryExpression)s.Condition;
Assert.AreEqual("/bar/", ((RELiteralExpression)be.Right).Value);
Assert.AreEqual(1, s.TrueBlock.Statements.Count);
Assert.IsNotNull(s.FalseBlock);
Assert.AreEqual(1, s.FalseBlock.Statements.Count);
Assert.AreEqual("foobar, eh?", ((StringLiteralExpression)((MethodInvocationExpression)((ExpressionStatement)s.TrueBlock.Statements[0]).Expression).Arguments[0]).Value);
Assert.AreEqual("nah?", ((StringLiteralExpression)((MethodInvocationExpression)((ExpressionStatement)s.FalseBlock.Statements[0]).Expression).Arguments[0]).Value);
}
[Test]
public void TestInterface1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("interface_1.boo");
Assert.AreEqual(1, module.Members.Count);
InterfaceDefinition id = (InterfaceDefinition)module.Members[0];
Assert.AreEqual("IContentItem", id.Name);
Assert.AreEqual(5, id.Members.Count);
Property p = (Property)id.Members[0];
Assert.AreEqual("Parent", p.Name);
Assert.AreEqual("IContentItem", ((SimpleTypeReference)p.Type).Name);
Assert.IsNotNull(p.Getter, "Getter");
Assert.IsNull(p.Setter, "Setter");
p = (Property)id.Members[1];
Assert.AreEqual("Name", p.Name);
Assert.AreEqual("string", ((SimpleTypeReference)p.Type).Name);
Assert.IsNotNull(p.Getter, "Getter");
Assert.IsNotNull(p.Setter, "Setter");
Method m = (Method)id.Members[2];
Assert.AreEqual("SelectItem", m.Name);
Assert.AreEqual("IContentItem", ((SimpleTypeReference)m.ReturnType).Name);
Assert.AreEqual("expression", m.Parameters[0].Name);
Assert.AreEqual("string", ((SimpleTypeReference)m.Parameters[0].Type).Name);
Assert.AreEqual("Validate", ((Method)id.Members[3]).Name);
Assert.AreEqual("OnRemove", ((Method)id.Members[4]).Name);
}
[Test]
public void TestEnum1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("enum_1.boo");
Assert.AreEqual(2, module.Members.Count);
EnumDefinition ed = (EnumDefinition)module.Members[0];
Assert.AreEqual("Priority", ed.Name);
Assert.AreEqual(3, ed.Members.Count);
Assert.AreEqual("Low", ed.Members[0].Name);
Assert.AreEqual("Normal", ed.Members[1].Name);
Assert.AreEqual("High", ed.Members[2].Name);
ed = (EnumDefinition)module.Members[1];
Assert.AreEqual(3, ed.Members.Count);
Assert.AreEqual("Easy", ed.Members[0].Name);
Assert.AreEqual(0, ((EnumMember)ed.Members[0]).Initializer.Value);
Assert.AreEqual("Normal", ed.Members[1].Name);
Assert.AreEqual(5, ((EnumMember)ed.Members[1]).Initializer.Value);
Assert.AreEqual("Hard", ed.Members[2].Name);
Assert.IsNull(((EnumMember)ed.Members[2]).Initializer, "Initializer");
}
[Test]
public void TestProperties1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("properties_1.boo");
ClassDefinition cd = (ClassDefinition)module.Members[0];
Assert.AreEqual("Person", cd.Name);
Assert.AreEqual("_id", cd.Members[0].Name);
Assert.AreEqual("_name", cd.Members[1].Name);
Property p = (Property)cd.Members[3];
Assert.AreEqual("ID", p.Name);
Assert.AreEqual("string", ((SimpleTypeReference)p.Type).Name);
Assert.IsNotNull(p.Getter, "Getter");
Assert.AreEqual(1, p.Getter.Body.Statements.Count);
Assert.AreEqual("_id", ((ReferenceExpression)((ReturnStatement)p.Getter.Body.Statements[0]).Expression).Name);
Assert.IsNull(p.Setter, "Setter");
p = (Property)cd.Members[4];
Assert.AreEqual("Name", p.Name);
Assert.AreEqual("string", ((SimpleTypeReference)p.Type).Name);
Assert.IsNotNull(p.Getter, "Getter ");
Assert.AreEqual(1, p.Getter.Body.Statements.Count);
Assert.AreEqual("_name", ((ReferenceExpression)((ReturnStatement)p.Getter.Body.Statements[0]).Expression).Name);
Assert.IsNotNull(p.Setter, "Setter");
Assert.AreEqual(1, p.Setter.Body.Statements.Count);
BinaryExpression a = (BinaryExpression)((ExpressionStatement)p.Setter.Body.Statements[0]).Expression;
Assert.AreEqual(BinaryOperatorType.Assign, a.Operator);
Assert.AreEqual("_name", ((ReferenceExpression)a.Left).Name);
Assert.AreEqual("value", ((ReferenceExpression)a.Right).Name);
}
[Test]
public void TestWhileStmt1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("while_stmt_1.boo");
WhileStatement ws = (WhileStatement)module.Globals.Statements[3];
Assert.AreEqual(true, ((BoolLiteralExpression)ws.Condition).Value);
Assert.AreEqual(4, ws.Block.Statements.Count);
BreakStatement bs = (BreakStatement)ws.Block.Statements[3];
BinaryExpression condition = (BinaryExpression)bs.Modifier.Condition;
Assert.AreEqual(BinaryOperatorType.Equality, condition.Operator);
}
[Test]
public void TestUnpackStmt1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("unpack_stmt_1.boo");
UnpackStatement us = (UnpackStatement)module.Globals.Statements[0];
Assert.AreEqual(2, us.Declarations.Count);
Assert.AreEqual("arg0", us.Declarations[0].Name);
Assert.AreEqual("arg1", us.Declarations[1].Name);
MethodInvocationExpression mce = (MethodInvocationExpression)us.Expression;
MemberReferenceExpression mre = ((MemberReferenceExpression)mce.Target);
Assert.AreEqual("GetCommandLineArgs", mre.Name);
Assert.AreEqual("Environment", ((ReferenceExpression)mre.Target).Name);
}
[Test]
public void TestYieldStmt1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("yield_stmt_1.boo");
Method m = (Method)module.Members[0];
ForStatement fs = (ForStatement)m.Body.Statements[0];
YieldStatement ys = (YieldStatement)fs.Block.Statements[0];
Assert.AreEqual("i", ((ReferenceExpression)ys.Expression).Name);
Assert.AreEqual(StatementModifierType.If, ys.Modifier.Type);
}
[Test]
public void TestNonSignificantWhitespaceRegions1()
{
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("nonsignificant_ws_regions_1.boo");
StatementCollection stmts = module.Globals.Statements;
Assert.AreEqual(2, stmts.Count);
ExpressionStatement es = (ExpressionStatement)stmts[0];
BinaryExpression ae = (BinaryExpression)es.Expression;
Assert.AreEqual(BinaryOperatorType.Assign, ae.Operator);
Assert.AreEqual("a", ((ReferenceExpression)ae.Left).Name);
Assert.AreEqual(2, ((ListLiteralExpression)ae.Right).Items.Count);
ForStatement fs = (ForStatement)stmts[1];
MethodInvocationExpression mce = (MethodInvocationExpression)fs.Iterator;
Assert.AreEqual("map", ((ReferenceExpression)mce.Target).Name);
Assert.AreEqual(2, mce.Arguments.Count);
Assert.AreEqual(1, fs.Block.Statements.Count);
}
[Test]
public void Docstrings()
{
/*
"""
A module can have a docstring.
"""
namespace Foo.Bar
"""
And so can the namespace declaration.
"""
class Person:
"""
A class can have it.
With multiple lines.
"""
_fname as string
"""Fields can have one."""
def constructor([required] fname as string):
"""
And so can a method or constructor.
"""
_fname = fname
FirstName as string:
"""And why couldn't a property?"""
get:
return _fname
interface ICustomer:
"""an interface."""
def Initialize()
"""interface method"""
Name as string:
"""interface property"""
get
enum AnEnum:
"""and so can an enum"""
AnItem
"""and its items"""
AnotherItem
*/
Boo.Lang.Compiler.Ast.Module module = ParseTestCase("docstrings_1.boo");
Assert.AreEqual("A module can have a docstring.", module.Documentation);
Assert.AreEqual("And so can the namespace declaration.", module.Namespace.Documentation);
ClassDefinition person = (ClassDefinition)module.Members[0];
Assert.AreEqual("A class can have it.\nWith multiple lines.", person.Documentation);
Assert.AreEqual("Fields can have one.", person.Members[0].Documentation);
Assert.AreEqual("\tAnd so can a method or constructor.\n\t", person.Members[1].Documentation);
Assert.AreEqual("And why couldn't a property?", person.Members[2].Documentation);
InterfaceDefinition customer = (InterfaceDefinition)module.Members[1];
Assert.AreEqual("an interface.", customer.Documentation);
Assert.AreEqual("interface method", customer.Members[0].Documentation);
Assert.AreEqual("interface property", customer.Members[1].Documentation);
EnumDefinition anEnum = (EnumDefinition)module.Members[2];
Assert.AreEqual("and so can an enum", anEnum.Documentation);
Assert.AreEqual("and its items", anEnum.Members[0].Documentation);
}
}
}
| |
// Copyright 2017 Google 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 UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/// A class that manages the room effects to be applied to spatial audio sources in the scene.
public static class ResonanceAudioRoomManager {
/// Material type that determines the acoustic properties of a room surface.
public enum SurfaceMaterial {
Transparent = 0, ///< Transparent
AcousticCeilingTiles = 1, ///< Acoustic ceiling tiles
BrickBare = 2, ///< Brick, bare
BrickPainted = 3, ///< Brick, painted
ConcreteBlockCoarse = 4, ///< Concrete block, coarse
ConcreteBlockPainted = 5, ///< Concrete block, painted
CurtainHeavy = 6, ///< Curtain, heavy
FiberglassInsulation = 7, ///< Fiberglass insulation
GlassThin = 8, ///< Glass, thin
GlassThick = 9, ///< Glass, thick
Grass = 10, ///< Grass
LinoleumOnConcrete = 11, ///< Linoleum on concrete
Marble = 12, ///< Marble
Metal = 13, ///< Galvanized sheet metal
ParquetOnConcrete = 14, ///< Parquet on concrete
PlasterRough = 15, ///< Plaster, rough
PlasterSmooth = 16, ///< Plaster, smooth
PlywoodPanel = 17, ///< Plywood panel
PolishedConcreteOrTile = 18, ///< Polished concrete or tile
Sheetrock = 19, ///< Sheetrock
WaterOrIceSurface = 20, ///< Water or ice surface
WoodCeiling = 21, ///< Wood ceiling
WoodPanel = 22 ///< Wood panel
}
/// A serializable dictionary class that maps surface materials from GUIDs. The dictionary is
/// serialized to two lists, one for the keys (GUIDs) and one for the values (surface materials).
[Serializable]
public class SurfaceMaterialDictionary
: Dictionary<string, SurfaceMaterial>, ISerializationCallbackReceiver {
public SurfaceMaterialDictionary() {
guids = new List<string>();
surfaceMaterials = new List<SurfaceMaterial>();
}
/// Serializes the dictionary to two lists.
public void OnBeforeSerialize() {
guids.Clear();
surfaceMaterials.Clear();
foreach (var keyValuePair in this) {
guids.Add(keyValuePair.Key);
surfaceMaterials.Add(keyValuePair.Value);
}
}
/// Deserializes the two lists and fills the dictionary.
public void OnAfterDeserialize() {
this.Clear();
for (int i = 0; i < guids.Count; ++i) {
this.Add(guids[i], surfaceMaterials[i]);
}
}
// List of keys.
[SerializeField]
private List<string> guids;
// List of values.
[SerializeField]
private List<SurfaceMaterial> surfaceMaterials;
}
/// Returns the room effects gain of the current room region for the given |sourcePosition|.
public static float ComputeRoomEffectsGain(Vector3 sourcePosition) {
if (roomEffectsRegions.Count == 0) {
// No room effects present, return default value.
return 1.0f;
}
float distanceToRoom = 0.0f;
var lastRoomEffectsRegion = roomEffectsRegions[roomEffectsRegions.Count - 1];
if (lastRoomEffectsRegion.room != null) {
var room = lastRoomEffectsRegion.room;
bounds.size = Vector3.Scale(room.transform.lossyScale, room.size);
Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation);
Vector3 relativePosition = rotationInverse * (sourcePosition - room.transform.position);
Vector3 closestPosition = bounds.ClosestPoint(relativePosition);
distanceToRoom = Vector3.Distance(relativePosition, closestPosition);
} else {
var reverbProbe = lastRoomEffectsRegion.reverbProbe;
Vector3 relativePosition = sourcePosition - reverbProbe.transform.position;
if (reverbProbe.regionShape == ResonanceAudioReverbProbe.RegionShape.Box) {
bounds.size = reverbProbe.GetScaledBoxRegionSize();
Quaternion rotationInverse = Quaternion.Inverse(reverbProbe.transform.rotation);
relativePosition = rotationInverse * relativePosition;
Vector3 closestPosition = bounds.ClosestPoint(relativePosition);
distanceToRoom = Vector3.Distance(relativePosition, closestPosition);
} else {
float radius = reverbProbe.GetScaledSphericalRegionRadius();
distanceToRoom = Mathf.Max(0.0f, relativePosition.magnitude - radius);
}
}
return ComputeRoomEffectsAttenuation(distanceToRoom);
}
/// Adds or removes a Resonance Audio room depending on whether the listener is inside |room|.
public static void UpdateRoom(ResonanceAudioRoom room) {
UpdateRoomEffectsRegions(room, IsListenerInsideRoom(room));
UpdateRoomEffects();
}
/// Removes a Resonance Audio room.
public static void RemoveRoom(ResonanceAudioRoom room) {
UpdateRoomEffectsRegions(room, false);
UpdateRoomEffects();
}
/// Adds or removes a Resonance Audio reverb probe depending on whether the listener is inside
/// |reverbProbe|.
public static void UpdateReverbProbe(ResonanceAudioReverbProbe reverbProbe) {
UpdateRoomEffectsRegions(reverbProbe, IsListenerInsideVisibleReverbProbe(reverbProbe));
UpdateRoomEffects();
}
/// Removes a Resonance Audio reverb probe.
public static void RemoveReverbProbe(ResonanceAudioReverbProbe reverbProbe) {
UpdateRoomEffectsRegions(reverbProbe, false);
UpdateRoomEffects();
}
// A struct to encapsulate either a ResonanceAudioRoom or a ResonanceAudioReverbProbe. Only one of
// |room| and |reverbProbe| is not null.
private struct RoomEffectsRegion {
/// Currently active room/reverb probe.
public ResonanceAudioRoom room;
public ResonanceAudioReverbProbe reverbProbe;
public RoomEffectsRegion(ResonanceAudioRoom room, ResonanceAudioReverbProbe reverbProbe) {
this.room = room;
this.reverbProbe = reverbProbe;
}
}
// Container to store the candidate room effects regions in the scene.
private static List<RoomEffectsRegion> roomEffectsRegions = new List<RoomEffectsRegion>();
// Boundaries instance to be used in room detection logic.
private static Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
// Updates the list of room effects regions with the given |room|.
private static void UpdateRoomEffectsRegions(ResonanceAudioRoom room, bool isEnabled) {
int regionIndex = -1;
for (int i = 0; i < roomEffectsRegions.Count; ++i) {
if (roomEffectsRegions[i].room == room) {
regionIndex = i;
break;
}
}
if (isEnabled && regionIndex == -1) {
roomEffectsRegions.Add(new RoomEffectsRegion(room ,null));
} else if (!isEnabled && regionIndex != -1) {
roomEffectsRegions.RemoveAt(regionIndex);
}
}
// Updates the list of room effects regions with the given |reverbProbe|.
private static void UpdateRoomEffectsRegions(ResonanceAudioReverbProbe reverbProbe,
bool isEnabled) {
int regionIndex = -1;
for (int i = 0; i < roomEffectsRegions.Count; ++i) {
if (roomEffectsRegions[i].reverbProbe == reverbProbe) {
regionIndex = i;
break;
}
}
if (isEnabled && regionIndex == -1) {
roomEffectsRegions.Add(new RoomEffectsRegion(null, reverbProbe));
} else if (!isEnabled && regionIndex != -1) {
roomEffectsRegions.RemoveAt(regionIndex);
}
}
// Updates the room effects of the environment with respect to the current room configuration.
private static void UpdateRoomEffects() {
if (roomEffectsRegions.Count == 0) {
ResonanceAudio.DisableRoomEffects();
return;
}
var lastRoomEffectsRegion = roomEffectsRegions[roomEffectsRegions.Count - 1];
if (lastRoomEffectsRegion.room != null) {
ResonanceAudio.UpdateRoom(lastRoomEffectsRegion.room);
} else {
ResonanceAudio.UpdateReverbProbe(lastRoomEffectsRegion.reverbProbe);
}
}
// Returns the room effects attenuation with respect to the given |distance| to a room region.
private static float ComputeRoomEffectsAttenuation(float distanceToRoom) {
// Shift the attenuation curve by 1.0f to avoid zero division.
float distance = 1.0f + distanceToRoom;
return 1.0f / Mathf.Pow(distance, 2.0f);
}
// Returns whether the listener is currently inside the given |room| boundaries.
private static bool IsListenerInsideRoom(ResonanceAudioRoom room) {
bool isInside = false;
Transform listenerTransform = ResonanceAudio.ListenerTransform;
if (listenerTransform != null) {
Vector3 relativePosition = listenerTransform.position - room.transform.position;
Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation);
bounds.size = Vector3.Scale(room.transform.lossyScale, room.size);
isInside = bounds.Contains(rotationInverse * relativePosition);
}
return isInside;
}
// Returns whether the listener is currently inside the application region of the given
// |reverb_probe|, subject to the visibility test if |reverbProbe.onlyWhenVisible| is true.
private static bool IsListenerInsideVisibleReverbProbe(ResonanceAudioReverbProbe reverbProbe) {
Transform listenerTransform = ResonanceAudio.ListenerTransform;
if (listenerTransform == null) {
return false;
}
Vector3 relativePosition = listenerTransform.position - reverbProbe.transform.position;
// First the containing test.
if (reverbProbe.regionShape == ResonanceAudioReverbProbe.RegionShape.Sphere) {
if (relativePosition.magnitude > reverbProbe.GetScaledSphericalRegionRadius()) {
return false;
}
} else {
Quaternion rotationInverse = Quaternion.Inverse(reverbProbe.transform.rotation);
bounds.size = reverbProbe.GetScaledBoxRegionSize();
if (!bounds.Contains(rotationInverse * relativePosition)) {
return false;
}
}
// Then the visibility test.
if (reverbProbe.onlyApplyWhenVisible &&
ResonanceAudio.ComputeOcclusion(reverbProbe.transform) > 0.0f) {
return false;
}
return true;
}
}
| |
#region BSD License
/*
Copyright (c) 2004 - 2008
Matthew Holmes (matthew@wildfiregames.com),
Dan Moorehead (dan05a@gmail.com),
Dave Hudson (jendave@yahoo.com),
C.J. Adams-Collier (cjac@colliertech.org),
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.
* The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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
#region MIT X11 license
/*
Portions of this file authored by Lluis Sanchez Gual
Copyright (C) 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.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Xsl;
using System.Net;
using System.Diagnostics;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Parse;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Targets
{
public enum ClrVersion
{
Default,
Net_1_1,
Net_2_0
}
public class SystemPackage
{
string name;
string version;
string description;
string[] assemblies;
bool isInternal;
ClrVersion targetVersion;
public void Initialize(string name,
string version,
string description,
string[] assemblies,
ClrVersion targetVersion,
bool isInternal)
{
this.isInternal = isInternal;
this.name = name;
this.version = version;
this.assemblies = assemblies;
this.description = description;
this.targetVersion = targetVersion;
}
public string Name
{
get { return name; }
}
public string Version
{
get { return version; }
}
public string Description
{
get { return description; }
}
public ClrVersion TargetVersion
{
get { return targetVersion; }
}
// The package is part of the mono SDK
public bool IsCorePackage
{
get { return name == "mono"; }
}
// The package has been registered by an add-in, and is not installed
// in the system.
public bool IsInternalPackage
{
get { return isInternal; }
}
public string[] Assemblies
{
get { return assemblies; }
}
}
/// <summary>
///
/// </summary>
[Target("autotools")]
public class AutotoolsTarget : ITarget
{
#region Fields
Kernel m_Kernel;
XmlDocument autotoolsDoc;
XmlUrlResolver xr;
System.Security.Policy.Evidence e;
Hashtable assemblyPathToPackage = new Hashtable();
Hashtable assemblyFullNameToPath = new Hashtable();
Hashtable packagesHash = new Hashtable();
readonly List<SystemPackage> packages = new List<SystemPackage>();
#endregion
#region Private Methods
private void mkdirDashP(string dirName)
{
DirectoryInfo di = new DirectoryInfo(dirName);
if (di.Exists)
return;
string parentDirName = System.IO.Path.GetDirectoryName(dirName);
DirectoryInfo parentDi = new DirectoryInfo(parentDirName);
if (!parentDi.Exists)
mkdirDashP(parentDirName);
di.Create();
}
private void chkMkDir(string dirName)
{
System.IO.DirectoryInfo di =
new System.IO.DirectoryInfo(dirName);
if (!di.Exists)
di.Create();
}
private void transformToFile(string filename, XsltArgumentList argList, string nodeName)
{
// Create an XslTransform for this file
XslTransform templateTransformer =
new XslTransform();
// Load up the template
XmlNode templateNode =
autotoolsDoc.SelectSingleNode(nodeName + "/*");
templateTransformer.Load(templateNode.CreateNavigator(), xr, e);
// Create a writer for the transformed template
XmlTextWriter templateWriter =
new XmlTextWriter(filename, null);
// Perform transformation, writing the file
templateTransformer.Transform
(m_Kernel.CurrentDoc, argList, templateWriter, xr);
}
string NormalizeAsmName(string name)
{
int i = name.IndexOf(", PublicKeyToken=null");
if (i != -1)
return name.Substring(0, i).Trim();
else
return name;
}
private void AddAssembly(string assemblyfile, SystemPackage package)
{
if (!File.Exists(assemblyfile))
return;
try
{
System.Reflection.AssemblyName an = System.Reflection.AssemblyName.GetAssemblyName(assemblyfile);
assemblyFullNameToPath[NormalizeAsmName(an.FullName)] = assemblyfile;
assemblyPathToPackage[assemblyfile] = package;
}
catch
{
}
}
private List<string> GetAssembliesWithLibInfo(string line, string file)
{
List<string> references = new List<string>();
List<string> libdirs = new List<string>();
List<string> retval = new List<string>();
foreach (string piece in line.Split(' '))
{
if (piece.ToLower().Trim().StartsWith("/r:") || piece.ToLower().Trim().StartsWith("-r:"))
{
references.Add(ProcessPiece(piece.Substring(3).Trim(), file));
}
else if (piece.ToLower().Trim().StartsWith("/lib:") || piece.ToLower().Trim().StartsWith("-lib:"))
{
libdirs.Add(ProcessPiece(piece.Substring(5).Trim(), file));
}
}
foreach (string refrnc in references)
{
foreach (string libdir in libdirs)
{
if (File.Exists(libdir + Path.DirectorySeparatorChar + refrnc))
{
retval.Add(libdir + Path.DirectorySeparatorChar + refrnc);
}
}
}
return retval;
}
private List<string> GetAssembliesWithoutLibInfo(string line, string file)
{
List<string> references = new List<string>();
foreach (string reference in line.Split(' '))
{
if (reference.ToLower().Trim().StartsWith("/r:") || reference.ToLower().Trim().StartsWith("-r:"))
{
string final_ref = reference.Substring(3).Trim();
references.Add(ProcessPiece(final_ref, file));
}
}
return references;
}
private string ProcessPiece(string piece, string pcfile)
{
int start = piece.IndexOf("${");
if (start == -1)
return piece;
int end = piece.IndexOf("}");
if (end == -1)
return piece;
string variable = piece.Substring(start + 2, end - start - 2);
string interp = GetVariableFromPkgConfig(variable, Path.GetFileNameWithoutExtension(pcfile));
return ProcessPiece(piece.Replace("${" + variable + "}", interp), pcfile);
}
private string GetVariableFromPkgConfig(string var, string pcfile)
{
ProcessStartInfo psi = new ProcessStartInfo("pkg-config");
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.Arguments = String.Format("--variable={0} {1}", var, pcfile);
Process p = new Process();
p.StartInfo = psi;
p.Start();
string ret = p.StandardOutput.ReadToEnd().Trim();
p.WaitForExit();
if (String.IsNullOrEmpty(ret))
return String.Empty;
return ret;
}
private void ParsePCFile(string pcfile)
{
// Don't register the package twice
string pname = Path.GetFileNameWithoutExtension(pcfile);
if (packagesHash.Contains(pname))
return;
List<string> fullassemblies = null;
string version = "";
string desc = "";
SystemPackage package = new SystemPackage();
using (StreamReader reader = new StreamReader(pcfile))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string lowerLine = line.ToLower();
if (lowerLine.StartsWith("libs:") && lowerLine.IndexOf(".dll") != -1)
{
string choppedLine = line.Substring(5).Trim();
if (choppedLine.IndexOf("-lib:") != -1 || choppedLine.IndexOf("/lib:") != -1)
{
fullassemblies = GetAssembliesWithLibInfo(choppedLine, pcfile);
}
else
{
fullassemblies = GetAssembliesWithoutLibInfo(choppedLine, pcfile);
}
}
else if (lowerLine.StartsWith("version:"))
{
// "version:".Length == 8
version = line.Substring(8).Trim();
}
else if (lowerLine.StartsWith("description:"))
{
// "description:".Length == 12
desc = line.Substring(12).Trim();
}
}
}
if (fullassemblies == null)
return;
foreach (string assembly in fullassemblies)
{
AddAssembly(assembly, package);
}
package.Initialize(pname,
version,
desc,
fullassemblies.ToArray(),
ClrVersion.Default,
false);
packages.Add(package);
packagesHash[pname] = package;
}
void RegisterSystemAssemblies(string prefix, string version, ClrVersion ver)
{
SystemPackage package = new SystemPackage();
List<string> list = new List<string>();
string dir = Path.Combine(prefix, version);
if (!Directory.Exists(dir))
{
return;
}
foreach (string assembly in Directory.GetFiles(dir, "*.dll"))
{
AddAssembly(assembly, package);
list.Add(assembly);
}
package.Initialize("mono",
version,
"The Mono runtime",
list.ToArray(),
ver,
false);
packages.Add(package);
}
void RunInitialization()
{
string versionDir;
if (Environment.Version.Major == 1)
{
versionDir = "1.0";
}
else
{
versionDir = "2.0";
}
//Pull up assemblies from the installed mono system.
string prefix = Path.GetDirectoryName(typeof(int).Assembly.Location);
if (prefix.IndexOf(Path.Combine("mono", versionDir)) == -1)
prefix = Path.Combine(prefix, "mono");
else
prefix = Path.GetDirectoryName(prefix);
RegisterSystemAssemblies(prefix, "1.0", ClrVersion.Net_1_1);
RegisterSystemAssemblies(prefix, "2.0", ClrVersion.Net_2_0);
string search_dirs = Environment.GetEnvironmentVariable("PKG_CONFIG_PATH");
string libpath = Environment.GetEnvironmentVariable("PKG_CONFIG_LIBPATH");
if (String.IsNullOrEmpty(libpath))
{
string path_dirs = Environment.GetEnvironmentVariable("PATH");
foreach (string pathdir in path_dirs.Split(Path.PathSeparator))
{
if (pathdir == null)
continue;
if (File.Exists(pathdir + Path.DirectorySeparatorChar + "pkg-config"))
{
libpath = Path.Combine(pathdir, "..");
libpath = Path.Combine(libpath, "lib");
libpath = Path.Combine(libpath, "pkgconfig");
break;
}
}
}
search_dirs += Path.PathSeparator + libpath;
if (!string.IsNullOrEmpty(search_dirs))
{
List<string> scanDirs = new List<string>();
foreach (string potentialDir in search_dirs.Split(Path.PathSeparator))
{
if (!scanDirs.Contains(potentialDir))
scanDirs.Add(potentialDir);
}
foreach (string pcdir in scanDirs)
{
if (pcdir == null)
continue;
if (Directory.Exists(pcdir))
{
foreach (string pcfile in Directory.GetFiles(pcdir, "*.pc"))
{
ParsePCFile(pcfile);
}
}
}
}
}
private void WriteCombine(SolutionNode solution)
{
#region "Create Solution directory if it doesn't exist"
string solutionDir = Path.Combine(solution.FullPath,
Path.Combine("autotools",
solution.Name));
chkMkDir(solutionDir);
#endregion
#region "Write Solution-level files"
XsltArgumentList argList = new XsltArgumentList();
argList.AddParam("solutionName", "", solution.Name);
// $solutionDir is $rootDir/$solutionName/
transformToFile(Path.Combine(solutionDir, "configure.ac"),
argList, "/Autotools/SolutionConfigureAc");
transformToFile(Path.Combine(solutionDir, "Makefile.am"),
argList, "/Autotools/SolutionMakefileAm");
transformToFile(Path.Combine(solutionDir, "autogen.sh"),
argList, "/Autotools/SolutionAutogenSh");
#endregion
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
m_Kernel.Log.Write(String.Format("Writing project: {0}",
project.Name));
WriteProject(solution, project);
}
}
private static string PrependPath(string path)
{
string tmpPath = Helper.NormalizePath(path, '/');
Regex regex = new Regex(@"(\w):/(\w+)");
Match match = regex.Match(tmpPath);
if (match.Success || tmpPath[0] == '.' || tmpPath[0] == '/')
{
tmpPath = Helper.NormalizePath(tmpPath);
}
else
{
tmpPath = Helper.NormalizePath("./" + tmpPath);
}
return tmpPath;
}
private static string BuildReference(SolutionNode solution,
ReferenceNode refr)
{
string ret = "";
if (solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode project =
(ProjectNode)solution.ProjectsTable[refr.Name];
string fileRef = FindFileReference(refr.Name, project);
string finalPath =
Helper.NormalizePath(Helper.MakeFilePath(project.FullPath +
"/$(BUILD_DIR)/$(CONFIG)/",
refr.Name, "dll"),
'/');
ret += finalPath;
return ret;
}
else
{
ProjectNode project = (ProjectNode)refr.Parent;
string fileRef = FindFileReference(refr.Name, project);
if (refr.Path != null || fileRef != null)
{
string finalPath = ((refr.Path != null) ?
Helper.NormalizePath(refr.Path + "/" +
refr.Name + ".dll",
'/') :
fileRef
);
ret += Path.Combine(project.Path, finalPath);
return ret;
}
try
{
//Assembly assem = Assembly.Load(refr.Name);
//if (assem != null)
//{
// int index = refr.Name.IndexOf(",");
// if ( index > 0)
// {
// ret += assem.Location;
// //Console.WriteLine("Location1: " + assem.Location);
// }
// else
// {
// ret += (refr.Name + ".dll");
// //Console.WriteLine("Location2: " + assem.Location);
// }
//}
//else
//{
int index = refr.Name.IndexOf(",");
if (index > 0)
{
ret += refr.Name.Substring(0, index) + ".dll";
//Console.WriteLine("Location3: " + assem.Location);
}
else
{
ret += (refr.Name + ".dll");
//Console.WriteLine("Location4: " + assem.Location);
}
//}
}
catch (System.NullReferenceException e)
{
e.ToString();
int index = refr.Name.IndexOf(",");
if (index > 0)
{
ret += refr.Name.Substring(0, index) + ".dll";
//Console.WriteLine("Location5: " + assem.Location);
}
else
{
ret += (refr.Name + ".dll");
//Console.WriteLine("Location6: " + assem.Location);
}
}
}
return ret;
}
private static string BuildReferencePath(SolutionNode solution,
ReferenceNode refr)
{
string ret = "";
if (solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode project =
(ProjectNode)solution.ProjectsTable[refr.Name];
string finalPath =
Helper.NormalizePath(Helper.MakeReferencePath(project.FullPath +
"/${build.dir}/"),
'/');
ret += finalPath;
return ret;
}
else
{
ProjectNode project = (ProjectNode)refr.Parent;
string fileRef = FindFileReference(refr.Name, project);
if (refr.Path != null || fileRef != null)
{
string finalPath = ((refr.Path != null) ?
Helper.NormalizePath(refr.Path, '/') :
fileRef
);
ret += finalPath;
return ret;
}
try
{
Assembly assem = Assembly.Load(refr.Name);
if (assem != null)
{
ret += "";
}
else
{
ret += "";
}
}
catch (System.NullReferenceException e)
{
e.ToString();
ret += "";
}
}
return ret;
}
private static string FindFileReference(string refName,
ProjectNode project)
{
foreach (ReferencePathNode refPath in project.ReferencePaths)
{
string fullPath =
Helper.MakeFilePath(refPath.Path, refName, "dll");
if (File.Exists(fullPath)) {
return fullPath;
}
}
return null;
}
/// <summary>
/// Gets the XML doc file.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="conf">The conf.</param>
/// <returns></returns>
public static string GetXmlDocFile(ProjectNode project, ConfigurationNode conf)
{
if (conf == null)
{
throw new ArgumentNullException("conf");
}
if (project == null)
{
throw new ArgumentNullException("project");
}
string docFile = (string)conf.Options["XmlDocFile"];
// if(docFile != null && docFile.Length == 0)//default to assembly name if not specified
// {
// return Path.GetFileNameWithoutExtension(project.AssemblyName) + ".xml";
// }
return docFile;
}
/// <summary>
/// Normalizes the path.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
public static string NormalizePath(string path)
{
if (path == null)
{
return "";
}
StringBuilder tmpPath;
if (Core.Parse.Preprocessor.GetOS() == "Win32")
{
tmpPath = new StringBuilder(path.Replace('\\', '/'));
tmpPath.Replace("/", @"\\");
}
else
{
tmpPath = new StringBuilder(path.Replace('\\', '/'));
tmpPath = tmpPath.Replace('/', Path.DirectorySeparatorChar);
}
return tmpPath.ToString();
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
string solutionDir = Path.Combine(solution.FullPath, Path.Combine("autotools", solution.Name));
string projectDir = Path.Combine(solutionDir, project.Name);
string projectVersion = project.Version;
bool hasAssemblyConfig = false;
chkMkDir(projectDir);
List<string>
compiledFiles = new List<string>(),
contentFiles = new List<string>(),
embeddedFiles = new List<string>(),
binaryLibs = new List<string>(),
pkgLibs = new List<string>(),
systemLibs = new List<string>(),
runtimeLibs = new List<string>(),
extraDistFiles = new List<string>(),
localCopyTargets = new List<string>();
// If there exists a .config file for this assembly, copy
// it to the project folder
// TODO: Support copying .config.osx files
// TODO: support processing the .config file for native library deps
string projectAssemblyName = project.Name;
if (project.AssemblyName != null)
projectAssemblyName = project.AssemblyName;
if (File.Exists(Path.Combine(project.FullPath, projectAssemblyName) + ".dll.config"))
{
hasAssemblyConfig = true;
System.IO.File.Copy(Path.Combine(project.FullPath, projectAssemblyName + ".dll.config"), Path.Combine(projectDir, projectAssemblyName + ".dll.config"), true);
extraDistFiles.Add(project.AssemblyName + ".dll.config");
}
foreach (ConfigurationNode conf in project.Configurations)
{
if (conf.Options.KeyFile != string.Empty)
{
// Copy snk file into the project's directory
// Use the snk from the project directory directly
string source = Path.Combine(project.FullPath, conf.Options.KeyFile);
string keyFile = conf.Options.KeyFile;
Regex re = new Regex(".*/");
keyFile = re.Replace(keyFile, "");
string dest = Path.Combine(projectDir, keyFile);
// Tell the user if there's a problem copying the file
try
{
mkdirDashP(System.IO.Path.GetDirectoryName(dest));
System.IO.File.Copy(source, dest, true);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}
}
// Copy compiled, embedded and content files into the project's directory
foreach (string filename in project.Files)
{
string source = Path.Combine(project.FullPath, filename);
string dest = Path.Combine(projectDir, filename);
if (filename.Contains("AssemblyInfo.cs"))
{
// If we've got an AssemblyInfo.cs, pull the version number from it
string[] sources = { source };
string[] args = { "" };
Microsoft.CSharp.CSharpCodeProvider cscp =
new Microsoft.CSharp.CSharpCodeProvider();
string tempAssemblyFile = Path.Combine(Path.GetTempPath(), project.Name + "-temp.dll");
System.CodeDom.Compiler.CompilerParameters cparam =
new System.CodeDom.Compiler.CompilerParameters(args, tempAssemblyFile);
System.CodeDom.Compiler.CompilerResults cr =
cscp.CompileAssemblyFromFile(cparam, sources);
foreach (System.CodeDom.Compiler.CompilerError error in cr.Errors)
Console.WriteLine("Error! '{0}'", error.ErrorText);
try {
string projectFullName = cr.CompiledAssembly.FullName;
Regex verRegex = new Regex("Version=([\\d\\.]+)");
Match verMatch = verRegex.Match(projectFullName);
if (verMatch.Success)
projectVersion = verMatch.Groups[1].Value;
}catch{
Console.WriteLine("Couldn't compile AssemblyInfo.cs");
}
// Clean up the temp file
try
{
if (File.Exists(tempAssemblyFile))
File.Delete(tempAssemblyFile);
}
catch
{
Console.WriteLine("Error! '{0}'", e.ToString());
}
}
// Tell the user if there's a problem copying the file
try
{
mkdirDashP(System.IO.Path.GetDirectoryName(dest));
System.IO.File.Copy(source, dest, true);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
switch (project.Files.GetBuildAction(filename))
{
case BuildAction.Compile:
compiledFiles.Add(filename);
break;
case BuildAction.Content:
contentFiles.Add(filename);
extraDistFiles.Add(filename);
break;
case BuildAction.EmbeddedResource:
embeddedFiles.Add(filename);
break;
}
}
// Set up references
for (int refNum = 0; refNum < project.References.Count; refNum++)
{
ReferenceNode refr = (ReferenceNode)project.References[refNum];
Assembly refAssembly = Assembly.LoadWithPartialName(refr.Name);
/* Determine which pkg-config (.pc) file refers to
this assembly */
SystemPackage package = null;
if (packagesHash.Contains(refr.Name)){
package = (SystemPackage)packagesHash[refr.Name];
}else{
string assemblyFullName = string.Empty;
if (refAssembly != null)
assemblyFullName = refAssembly.FullName;
string assemblyFileName = string.Empty;
if (assemblyFullName != string.Empty &&
assemblyFullNameToPath.Contains(assemblyFullName)
)
assemblyFileName =
(string)assemblyFullNameToPath[assemblyFullName];
if (assemblyFileName != string.Empty &&
assemblyPathToPackage.Contains(assemblyFileName)
)
package = (SystemPackage)assemblyPathToPackage[assemblyFileName];
}
/* If we know the .pc file and it is not "mono"
(already in the path), add a -pkg: argument */
if (package != null &&
package.Name != "mono" &&
!pkgLibs.Contains(package.Name)
)
pkgLibs.Add(package.Name);
string fileRef =
FindFileReference(refr.Name, (ProjectNode)refr.Parent);
if (refr.LocalCopy ||
solution.ProjectsTable.ContainsKey(refr.Name) ||
fileRef != null ||
refr.Path != null
)
{
/* Attempt to copy the referenced lib to the
project's directory */
string filename = refr.Name + ".dll";
string source = filename;
if (refr.Path != null)
source = Path.Combine(refr.Path, source);
source = Path.Combine(project.FullPath, source);
string dest = Path.Combine(projectDir, filename);
/* Since we depend on this binary dll to build, we
* will add a compile- time dependency on the
* copied dll, and add the dll to the list of
* files distributed with this package
*/
binaryLibs.Add(refr.Name + ".dll");
extraDistFiles.Add(refr.Name + ".dll");
// TODO: Support copying .config.osx files
// TODO: Support for determining native dependencies
if (File.Exists(source + ".config"))
{
System.IO.File.Copy(source + ".config", Path.GetDirectoryName(dest), true);
extraDistFiles.Add(refr.Name + ".dll.config");
}
try
{
System.IO.File.Copy(source, dest, true);
}
catch (System.IO.IOException)
{
if (solution.ProjectsTable.ContainsKey(refr.Name)){
/* If an assembly is referenced, marked for
* local copy, in the list of projects for
* this solution, but does not exist, put a
* target into the Makefile.am to build the
* assembly and copy it to this project's
* directory
*/
ProjectNode sourcePrj =
((ProjectNode)(solution.ProjectsTable[refr.Name]));
string target =
String.Format("{0}:\n" +
"\t$(MAKE) -C ../{1}\n" +
"\tln ../{2}/$@ $@\n",
filename,
sourcePrj.Name,
sourcePrj.Name );
localCopyTargets.Add(target);
}
}
}
else if( !pkgLibs.Contains(refr.Name) )
{
// Else, let's assume it's in the GAC or the lib path
string assemName = string.Empty;
int index = refr.Name.IndexOf(",");
if (index > 0)
assemName = refr.Name.Substring(0, index);
else
assemName = refr.Name;
m_Kernel.Log.Write(String.Format(
"Warning: Couldn't find an appropriate assembly " +
"for reference:\n'{0}'", refr.Name
));
systemLibs.Add(assemName);
}
}
const string lineSep = " \\\n\t";
string compiledFilesString = string.Empty;
if (compiledFiles.Count > 0)
compiledFilesString =
lineSep + string.Join(lineSep, compiledFiles.ToArray());
string embeddedFilesString = "";
if (embeddedFiles.Count > 0)
embeddedFilesString =
lineSep + string.Join(lineSep, embeddedFiles.ToArray());
string contentFilesString = "";
if (contentFiles.Count > 0)
contentFilesString =
lineSep + string.Join(lineSep, contentFiles.ToArray());
string extraDistFilesString = "";
if (extraDistFiles.Count > 0)
extraDistFilesString =
lineSep + string.Join(lineSep, extraDistFiles.ToArray());
string pkgLibsString = "";
if (pkgLibs.Count > 0)
pkgLibsString =
lineSep + string.Join(lineSep, pkgLibs.ToArray());
string binaryLibsString = "";
if (binaryLibs.Count > 0)
binaryLibsString =
lineSep + string.Join(lineSep, binaryLibs.ToArray());
string systemLibsString = "";
if (systemLibs.Count > 0)
systemLibsString =
lineSep + string.Join(lineSep, systemLibs.ToArray());
string localCopyTargetsString = "";
if (localCopyTargets.Count > 0)
localCopyTargetsString =
string.Join("\n", localCopyTargets.ToArray());
string monoPath = "";
foreach (string runtimeLib in runtimeLibs)
{
monoPath += ":`pkg-config --variable=libdir " + runtimeLib + "`";
}
// Add the project name to the list of transformation
// parameters
XsltArgumentList argList = new XsltArgumentList();
argList.AddParam("projectName", "", project.Name);
argList.AddParam("solutionName", "", solution.Name);
argList.AddParam("assemblyName", "", projectAssemblyName);
argList.AddParam("compiledFiles", "", compiledFilesString);
argList.AddParam("embeddedFiles", "", embeddedFilesString);
argList.AddParam("contentFiles", "", contentFilesString);
argList.AddParam("extraDistFiles", "", extraDistFilesString);
argList.AddParam("pkgLibs", "", pkgLibsString);
argList.AddParam("binaryLibs", "", binaryLibsString);
argList.AddParam("systemLibs", "", systemLibsString);
argList.AddParam("monoPath", "", monoPath);
argList.AddParam("localCopyTargets", "", localCopyTargetsString);
argList.AddParam("projectVersion", "", projectVersion);
argList.AddParam("hasAssemblyConfig", "", hasAssemblyConfig ? "true" : "");
// Transform the templates
transformToFile(Path.Combine(projectDir, "configure.ac"), argList, "/Autotools/ProjectConfigureAc");
transformToFile(Path.Combine(projectDir, "Makefile.am"), argList, "/Autotools/ProjectMakefileAm");
transformToFile(Path.Combine(projectDir, "autogen.sh"), argList, "/Autotools/ProjectAutogenSh");
if (project.Type == Core.Nodes.ProjectType.Library)
transformToFile(Path.Combine(projectDir, project.Name + ".pc.in"), argList, "/Autotools/ProjectPcIn");
if (project.Type == Core.Nodes.ProjectType.Exe || project.Type == Core.Nodes.ProjectType.WinExe)
transformToFile(Path.Combine(projectDir, project.Name.ToLower() + ".in"), argList, "/Autotools/ProjectWrapperScriptIn");
}
private void WriteProjectOld(SolutionNode solution, ProjectNode project)
{
string projFile = Helper.MakeFilePath(project.FullPath, "Include", "am");
StreamWriter ss = new StreamWriter(projFile);
ss.NewLine = "\n";
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projFile));
using (ss)
{
ss.WriteLine(Helper.AssemblyFullName(project.AssemblyName, project.Type) + ":");
ss.WriteLine("\tmkdir -p " + Helper.MakePathRelativeTo(solution.FullPath, project.Path) + "/$(BUILD_DIR)/$(CONFIG)/");
foreach (string file in project.Files)
{
if (project.Files.GetSubType(file) != SubType.Code && project.Files.GetSubType(file) != SubType.Settings)
{
ss.Write("\tresgen ");
ss.Write(Helper.NormalizePath(Path.Combine(project.Path, file.Substring(0, file.LastIndexOf('.')) + ".resx "), '/'));
if (project.Files.GetResourceName(file) != "")
{
ss.WriteLine(Helper.NormalizePath(Path.Combine(project.Path, project.RootNamespace + "." + project.Files.GetResourceName(file) + ".resources"), '/'));
}
else
{
ss.WriteLine(Helper.NormalizePath(Path.Combine(project.Path, project.RootNamespace + "." + file.Substring(0, file.LastIndexOf('.')) + ".resources"), '/'));
}
}
}
ss.WriteLine("\t$(CSC)\t/out:" + Helper.MakePathRelativeTo(solution.FullPath, project.Path) + "/$(BUILD_DIR)/$(CONFIG)/" + Helper.AssemblyFullName(project.AssemblyName, project.Type) + " \\");
ss.WriteLine("\t\t/target:" + project.Type.ToString().ToLower() + " \\");
if (project.References.Count > 0)
{
ss.Write("\t\t/reference:");
bool firstref = true;
foreach (ReferenceNode refr in project.References)
{
if (firstref)
{
firstref = false;
}
else
{
ss.Write(",");
}
ss.Write("{0}", Helper.NormalizePath(Helper.MakePathRelativeTo(solution.FullPath, BuildReference(solution, refr)), '/'));
}
ss.WriteLine(" \\");
}
//ss.WriteLine("\t\tProperties/AssemblyInfo.cs \\");
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.EmbeddedResource:
ss.Write("\t\t/resource:");
ss.WriteLine(Helper.NormalizePath(Path.Combine(project.Path, file), '/') + " \\");
break;
default:
if (project.Files.GetSubType(file) != SubType.Code && project.Files.GetSubType(file) != SubType.Settings)
{
ss.Write("\t\t/resource:");
if (project.Files.GetResourceName(file) != "")
{
ss.WriteLine(Helper.NormalizePath(Path.Combine(project.Path, project.RootNamespace + "." + project.Files.GetResourceName(file) + ".resources"), '/') + "," + project.RootNamespace + "." + project.Files.GetResourceName(file) + ".resources" + " \\");
}
else
{
ss.WriteLine(Helper.NormalizePath(Path.Combine(project.Path, project.RootNamespace + "." + file.Substring(0, file.LastIndexOf('.')) + ".resources"), '/') + "," + project.RootNamespace + "." + file.Substring(0, file.LastIndexOf('.')) + ".resources" + " \\");
}
}
break;
}
}
foreach (ConfigurationNode conf in project.Configurations)
{
if (conf.Options.KeyFile != "")
{
ss.WriteLine("\t\t/keyfile:" + Helper.NormalizePath(Path.Combine(project.Path, conf.Options.KeyFile), '/') + " \\");
break;
}
}
foreach (ConfigurationNode conf in project.Configurations)
{
if (conf.Options.AllowUnsafe)
{
ss.WriteLine("\t\t/unsafe \\");
break;
}
}
if (project.AppIcon != "")
{
ss.WriteLine("\t\t/win32icon:" + Helper.NormalizePath(Path.Combine(project.Path, project.AppIcon), '/') + " \\");
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.WriteLine("\t\t/define:{0}", conf.Options.CompilerDefines.Replace(';', ',') + " \\");
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
if (GetXmlDocFile(project, conf) != "")
{
ss.WriteLine("\t\t/doc:" + Helper.MakePathRelativeTo(solution.FullPath, project.Path) + "/$(BUILD_DIR)/$(CONFIG)/" + project.Name + ".xml \\");
break;
}
}
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.Compile:
ss.WriteLine("\t\t\\");
ss.Write("\t\t" + NormalizePath(Path.Combine(Helper.MakePathRelativeTo(solution.FullPath, project.Path), file)));
break;
default:
break;
}
}
ss.WriteLine();
ss.WriteLine();
if (project.Type == ProjectType.Library)
{
ss.WriteLine("install-data-local:");
ss.WriteLine(" echo \"$(GACUTIL) /i bin/Release/" + project.Name + ".dll /f $(GACUTIL_FLAGS)\"; \\");
ss.WriteLine(" $(GACUTIL) /i bin/Release/" + project.Name + ".dll /f $(GACUTIL_FLAGS) || exit 1;");
ss.WriteLine();
ss.WriteLine("uninstall-local:");
ss.WriteLine(" echo \"$(GACUTIL) /u " + project.Name + " $(GACUTIL_FLAGS)\"; \\");
ss.WriteLine(" $(GACUTIL) /u " + project.Name + " $(GACUTIL_FLAGS) || exit 1;");
ss.WriteLine();
}
ss.WriteLine("CLEANFILES = $(BUILD_DIR)/$(CONFIG)/" + Helper.AssemblyFullName(project.AssemblyName, project.Type) + " $(BUILD_DIR)/$(CONFIG)/" + project.AssemblyName + ".mdb $(BUILD_DIR)/$(CONFIG)/" + project.AssemblyName + ".pdb " + project.AssemblyName + ".xml");
ss.WriteLine("EXTRA_DIST = \\");
ss.Write(" $(FILES)");
foreach (ConfigurationNode conf in project.Configurations)
{
if (conf.Options.KeyFile != "")
{
ss.Write(" \\");
ss.WriteLine("\t" + conf.Options.KeyFile);
}
break;
}
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
bool hasLibrary = false;
private void WriteCombineOld(SolutionNode solution)
{
/* TODO: These vars should be pulled from the prebuild.xml file */
string releaseVersion = "2.0.0";
string assemblyVersion = "2.1.0.0";
string description =
"Tao Framework " + solution.Name + " Binding For .NET";
hasLibrary = false;
m_Kernel.Log.Write("Creating Autotools make files");
foreach (ProjectNode project in solution.Projects)
{
if (m_Kernel.AllowProject(project.FilterGroups))
{
m_Kernel.Log.Write("...Creating makefile: {0}", project.Name);
WriteProject(solution, project);
}
}
m_Kernel.Log.Write("");
string combFile = Helper.MakeFilePath(solution.FullPath, "Makefile", "am");
StreamWriter ss = new StreamWriter(combFile);
ss.NewLine = "\n";
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(combFile));
using (ss)
{
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
if (project.Type == ProjectType.Library)
{
hasLibrary = true;
break;
}
}
if (hasLibrary)
{
ss.Write("pkgconfig_in_files = ");
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
if (project.Type == ProjectType.Library)
{
string combFilepc = Helper.MakeFilePath(solution.FullPath, project.Name, "pc.in");
ss.Write(" " + project.Name + ".pc.in ");
StreamWriter sspc = new StreamWriter(combFilepc);
sspc.NewLine = "\n";
using (sspc)
{
sspc.WriteLine("prefix=@prefix@");
sspc.WriteLine("exec_prefix=${prefix}");
sspc.WriteLine("libdir=${exec_prefix}/lib");
sspc.WriteLine();
sspc.WriteLine("Name: @PACKAGE_NAME@");
sspc.WriteLine("Description: @DESCRIPTION@");
sspc.WriteLine("Version: @ASSEMBLY_VERSION@");
sspc.WriteLine("Libs: -r:${libdir}/mono/gac/@PACKAGE_NAME@/@ASSEMBLY_VERSION@__@PUBKEY@/@PACKAGE_NAME@.dll");
}
}
}
ss.WriteLine();
ss.WriteLine("pkgconfigdir=$(prefix)/lib/pkgconfig");
ss.WriteLine("pkgconfig_DATA=$(pkgconfig_in_files:.pc.in=.pc)");
}
ss.WriteLine();
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.WriteLine("-include x {0}",
Helper.NormalizePath(Helper.MakeFilePath(path, "Include", "am"), '/'));
}
ss.WriteLine();
ss.WriteLine("all: \\");
ss.Write("\t");
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(Helper.AssemblyFullName(project.AssemblyName, project.Type) + " ");
}
ss.WriteLine();
if (hasLibrary)
{
ss.WriteLine("EXTRA_DIST = \\");
ss.WriteLine("\t$(pkgconfig_in_files)");
}
else
{
ss.WriteLine("EXTRA_DIST = ");
}
ss.WriteLine();
ss.WriteLine("DISTCLEANFILES = \\");
ss.WriteLine("\tconfigure \\");
ss.WriteLine("\tMakefile.in \\");
ss.WriteLine("\taclocal.m4");
}
combFile = Helper.MakeFilePath(solution.FullPath, "configure", "ac");
StreamWriter ts = new StreamWriter(combFile);
ts.NewLine = "\n";
using (ts)
{
if (this.hasLibrary)
{
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
if (project.Type == ProjectType.Library)
{
ts.WriteLine("AC_INIT(" + project.Name + ".pc.in)");
break;
}
}
}
else
{
ts.WriteLine("AC_INIT(Makefile.am)");
}
ts.WriteLine("AC_PREREQ(2.53)");
ts.WriteLine("AC_CANONICAL_SYSTEM");
ts.WriteLine("PACKAGE_NAME={0}", solution.Name);
ts.WriteLine("PACKAGE_VERSION={0}", releaseVersion);
ts.WriteLine("DESCRIPTION=\"{0}\"", description);
ts.WriteLine("AC_SUBST(DESCRIPTION)");
ts.WriteLine("AM_INIT_AUTOMAKE([$PACKAGE_NAME],[$PACKAGE_VERSION],[$DESCRIPTION])");
ts.WriteLine("ASSEMBLY_VERSION={0}", assemblyVersion);
ts.WriteLine("AC_SUBST(ASSEMBLY_VERSION)");
ts.WriteLine("PUBKEY=`sn -t $PACKAGE_NAME.snk | grep 'Public Key Token' | awk -F: '{print $2}' | sed -e 's/^ //'`");
ts.WriteLine("AC_SUBST(PUBKEY)");
ts.WriteLine();
ts.WriteLine("AM_MAINTAINER_MODE");
ts.WriteLine();
ts.WriteLine("dnl AC_PROG_INTLTOOL([0.25])");
ts.WriteLine();
ts.WriteLine("AC_PROG_INSTALL");
ts.WriteLine();
ts.WriteLine("MONO_REQUIRED_VERSION=1.1");
ts.WriteLine();
ts.WriteLine("AC_MSG_CHECKING([whether we're compiling from CVS])");
ts.WriteLine("if test -f \"$srcdir/.cvs_version\" ; then");
ts.WriteLine(" from_cvs=yes");
ts.WriteLine("else");
ts.WriteLine(" if test -f \"$srcdir/.svn\" ; then");
ts.WriteLine(" from_cvs=yes");
ts.WriteLine(" else");
ts.WriteLine(" from_cvs=no");
ts.WriteLine(" fi");
ts.WriteLine("fi");
ts.WriteLine();
ts.WriteLine("AC_MSG_RESULT($from_cvs)");
ts.WriteLine();
ts.WriteLine("AC_PATH_PROG(MONO, mono)");
ts.WriteLine("AC_PATH_PROG(GMCS, gmcs)");
ts.WriteLine("AC_PATH_PROG(GACUTIL, gacutil)");
ts.WriteLine();
ts.WriteLine("AC_MSG_CHECKING([for mono])");
ts.WriteLine("dnl if test \"x$MONO\" = \"x\" ; then");
ts.WriteLine("dnl AC_MSG_ERROR([Can't find \"mono\" in your PATH])");
ts.WriteLine("dnl else");
ts.WriteLine(" AC_MSG_RESULT([found])");
ts.WriteLine("dnl fi");
ts.WriteLine();
ts.WriteLine("AC_MSG_CHECKING([for gmcs])");
ts.WriteLine("dnl if test \"x$GMCS\" = \"x\" ; then");
ts.WriteLine("dnl AC_MSG_ERROR([Can't find \"gmcs\" in your PATH])");
ts.WriteLine("dnl else");
ts.WriteLine(" AC_MSG_RESULT([found])");
ts.WriteLine("dnl fi");
ts.WriteLine();
//ts.WriteLine("AC_MSG_CHECKING([for gacutil])");
//ts.WriteLine("if test \"x$GACUTIL\" = \"x\" ; then");
//ts.WriteLine(" AC_MSG_ERROR([Can't find \"gacutil\" in your PATH])");
//ts.WriteLine("else");
//ts.WriteLine(" AC_MSG_RESULT([found])");
//ts.WriteLine("fi");
ts.WriteLine();
ts.WriteLine("AC_SUBST(PATH)");
ts.WriteLine("AC_SUBST(LD_LIBRARY_PATH)");
ts.WriteLine();
ts.WriteLine("dnl CSFLAGS=\"-debug -nowarn:1574\"");
ts.WriteLine("CSFLAGS=\"\"");
ts.WriteLine("AC_SUBST(CSFLAGS)");
ts.WriteLine();
// ts.WriteLine("AC_MSG_CHECKING(--disable-sdl argument)");
// ts.WriteLine("AC_ARG_ENABLE(sdl,");
// ts.WriteLine(" [ --disable-sdl Disable Sdl interface.],");
// ts.WriteLine(" [disable_sdl=$disableval],");
// ts.WriteLine(" [disable_sdl=\"no\"])");
// ts.WriteLine("AC_MSG_RESULT($disable_sdl)");
// ts.WriteLine("if test \"$disable_sdl\" = \"yes\"; then");
// ts.WriteLine(" AC_DEFINE(FEAT_SDL)");
// ts.WriteLine("fi");
ts.WriteLine();
ts.WriteLine("dnl Find pkg-config");
ts.WriteLine("AC_PATH_PROG(PKGCONFIG, pkg-config, no)");
ts.WriteLine("if test \"x$PKG_CONFIG\" = \"xno\"; then");
ts.WriteLine(" AC_MSG_ERROR([You need to install pkg-config])");
ts.WriteLine("fi");
ts.WriteLine();
ts.WriteLine("PKG_CHECK_MODULES(MONO_DEPENDENCY, mono >= $MONO_REQUIRED_VERSION, has_mono=true, has_mono=false)");
ts.WriteLine("BUILD_DIR=\"bin\"");
ts.WriteLine("AC_SUBST(BUILD_DIR)");
ts.WriteLine("CONFIG=\"Release\"");
ts.WriteLine("AC_SUBST(CONFIG)");
ts.WriteLine();
ts.WriteLine("if test \"x$has_mono\" = \"xtrue\"; then");
ts.WriteLine(" AC_PATH_PROG(RUNTIME, mono, no)");
ts.WriteLine(" AC_PATH_PROG(CSC, gmcs, no)");
ts.WriteLine(" if test `uname -s` = \"Darwin\"; then");
ts.WriteLine(" LIB_PREFIX=");
ts.WriteLine(" LIB_SUFFIX=.dylib");
ts.WriteLine(" else");
ts.WriteLine(" LIB_PREFIX=.so");
ts.WriteLine(" LIB_SUFFIX=");
ts.WriteLine(" fi");
ts.WriteLine("else");
ts.WriteLine(" AC_PATH_PROG(CSC, csc.exe, no)");
ts.WriteLine(" if test x$CSC = \"xno\"; then");
ts.WriteLine(" AC_MSG_ERROR([You need to install either mono or .Net])");
ts.WriteLine(" else");
ts.WriteLine(" RUNTIME=");
ts.WriteLine(" LIB_PREFIX=");
ts.WriteLine(" LIB_SUFFIX=.dylib");
ts.WriteLine(" fi");
ts.WriteLine("fi");
ts.WriteLine();
ts.WriteLine("AC_SUBST(LIB_PREFIX)");
ts.WriteLine("AC_SUBST(LIB_SUFFIX)");
ts.WriteLine();
ts.WriteLine("AC_SUBST(BASE_DEPENDENCIES_CFLAGS)");
ts.WriteLine("AC_SUBST(BASE_DEPENDENCIES_LIBS)");
ts.WriteLine();
ts.WriteLine("dnl Find monodoc");
ts.WriteLine("MONODOC_REQUIRED_VERSION=1.0");
ts.WriteLine("AC_SUBST(MONODOC_REQUIRED_VERSION)");
ts.WriteLine("PKG_CHECK_MODULES(MONODOC_DEPENDENCY, monodoc >= $MONODOC_REQUIRED_VERSION, enable_monodoc=yes, enable_monodoc=no)");
ts.WriteLine();
ts.WriteLine("if test \"x$enable_monodoc\" = \"xyes\"; then");
ts.WriteLine(" AC_PATH_PROG(MONODOC, monodoc, no)");
ts.WriteLine(" if test x$MONODOC = xno; then");
ts.WriteLine(" enable_monodoc=no");
ts.WriteLine(" fi");
ts.WriteLine("else");
ts.WriteLine(" MONODOC=");
ts.WriteLine("fi");
ts.WriteLine();
ts.WriteLine("AC_SUBST(MONODOC)");
ts.WriteLine("AM_CONDITIONAL(ENABLE_MONODOC, test \"x$enable_monodoc\" = \"xyes\")");
ts.WriteLine();
ts.WriteLine("AC_PATH_PROG(GACUTIL, gacutil, no)");
ts.WriteLine("if test \"x$GACUTIL\" = \"xno\" ; then");
ts.WriteLine(" AC_MSG_ERROR([No gacutil tool found])");
ts.WriteLine("fi");
ts.WriteLine();
// foreach(ProjectNode project in solution.ProjectsTableOrder)
// {
// if (project.Type == ProjectType.Library)
// {
// }
// }
ts.WriteLine("GACUTIL_FLAGS='/package $(PACKAGE_NAME) /gacdir $(DESTDIR)$(prefix)'");
ts.WriteLine("AC_SUBST(GACUTIL_FLAGS)");
ts.WriteLine();
ts.WriteLine("winbuild=no");
ts.WriteLine("case \"$host\" in");
ts.WriteLine(" *-*-mingw*|*-*-cygwin*)");
ts.WriteLine(" winbuild=yes");
ts.WriteLine(" ;;");
ts.WriteLine("esac");
ts.WriteLine("AM_CONDITIONAL(WINBUILD, test x$winbuild = xyes)");
ts.WriteLine();
// ts.WriteLine("dnl Check for SDL");
// ts.WriteLine();
// ts.WriteLine("AC_PATH_PROG([SDL_CONFIG], [sdl-config])");
// ts.WriteLine("have_sdl=no");
// ts.WriteLine("if test -n \"${SDL_CONFIG}\"; then");
// ts.WriteLine(" have_sdl=yes");
// ts.WriteLine(" SDL_CFLAGS=`$SDL_CONFIG --cflags`");
// ts.WriteLine(" SDL_LIBS=`$SDL_CONFIG --libs`");
// ts.WriteLine(" #");
// ts.WriteLine(" # sdl-config sometimes emits an rpath flag pointing at its library");
// ts.WriteLine(" # installation directory. We don't want this, as it prevents users from");
// ts.WriteLine(" # linking sdl-viewer against, for example, a locally compiled libGL when a");
// ts.WriteLine(" # version of the library also exists in SDL's library installation");
// ts.WriteLine(" # directory, typically /usr/lib.");
// ts.WriteLine(" #");
// ts.WriteLine(" SDL_LIBS=`echo $SDL_LIBS | sed 's/-Wl,-rpath,[[^ ]]* //'`");
// ts.WriteLine("fi");
// ts.WriteLine("AC_SUBST([SDL_CFLAGS])");
// ts.WriteLine("AC_SUBST([SDL_LIBS])");
ts.WriteLine();
ts.WriteLine("AC_OUTPUT([");
ts.WriteLine("Makefile");
// TODO: this does not work quite right.
//ts.WriteLine("Properties/AssemblyInfo.cs");
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
if (project.Type == ProjectType.Library)
{
ts.WriteLine(project.Name + ".pc");
}
// string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
// ts.WriteLine(Helper.NormalizePath(Helper.MakeFilePath(path, "Include"),'/'));
}
ts.WriteLine("])");
ts.WriteLine();
ts.WriteLine("#po/Makefile.in");
ts.WriteLine();
ts.WriteLine("echo \"---\"");
ts.WriteLine("echo \"Configuration summary\"");
ts.WriteLine("echo \"\"");
ts.WriteLine("echo \" * Installation prefix: $prefix\"");
ts.WriteLine("echo \" * compiler: $CSC\"");
ts.WriteLine("echo \" * Documentation: $enable_monodoc ($MONODOC)\"");
ts.WriteLine("echo \" * Package Name: $PACKAGE_NAME\"");
ts.WriteLine("echo \" * Version: $PACKAGE_VERSION\"");
ts.WriteLine("echo \" * Public Key: $PUBKEY\"");
ts.WriteLine("echo \"\"");
ts.WriteLine("echo \"---\"");
ts.WriteLine();
}
ts.NewLine = "\n";
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
if (project.GenerateAssemblyInfoFile)
{
GenerateAssemblyInfoFile(solution, combFile);
}
}
}
private static void GenerateAssemblyInfoFile(SolutionNode solution, string combFile)
{
System.IO.Directory.CreateDirectory(Helper.MakePathRelativeTo(solution.FullPath, "Properties"));
combFile = Helper.MakeFilePath(solution.FullPath + "/Properties/", "AssemblyInfo.cs", "in");
StreamWriter ai = new StreamWriter(combFile);
using (ai)
{
ai.WriteLine("#region License");
ai.WriteLine("/*");
ai.WriteLine("MIT License");
ai.WriteLine("Copyright (c)2003-2006 Tao Framework Team");
ai.WriteLine("http://www.taoframework.com");
ai.WriteLine("All rights reserved.");
ai.WriteLine("");
ai.WriteLine("Permission is hereby granted, free of charge, to any person obtaining a copy");
ai.WriteLine("of this software and associated documentation files (the \"Software\"), to deal");
ai.WriteLine("in the Software without restriction, including without limitation the rights");
ai.WriteLine("to use, copy, modify, merge, publish, distribute, sublicense, and/or sell");
ai.WriteLine("copies of the Software, and to permit persons to whom the Software is");
ai.WriteLine("furnished to do so, subject to the following conditions:");
ai.WriteLine("");
ai.WriteLine("The above copyright notice and this permission notice shall be included in all");
ai.WriteLine("copies or substantial portions of the Software.");
ai.WriteLine("");
ai.WriteLine("THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR");
ai.WriteLine("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,");
ai.WriteLine("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE");
ai.WriteLine("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER");
ai.WriteLine("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,");
ai.WriteLine("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE");
ai.WriteLine("SOFTWARE.");
ai.WriteLine("*/");
ai.WriteLine("#endregion License");
ai.WriteLine("");
ai.WriteLine("using System;");
ai.WriteLine("using System.Reflection;");
ai.WriteLine("using System.Runtime.InteropServices;");
ai.WriteLine("using System.Security;");
ai.WriteLine("using System.Security.Permissions;");
ai.WriteLine("");
ai.WriteLine("[assembly: AllowPartiallyTrustedCallers]");
ai.WriteLine("[assembly: AssemblyCompany(\"Tao Framework -- http://www.taoframework.com\")]");
ai.WriteLine("[assembly: AssemblyConfiguration(\"Retail\")]");
ai.WriteLine("[assembly: AssemblyCopyright(\"Copyright (c)2003-2006 Tao Framework Team. All rights reserved.\")]");
ai.WriteLine("[assembly: AssemblyCulture(\"\")]");
ai.WriteLine("[assembly: AssemblyDefaultAlias(\"@PACKAGE_NAME@\")]");
ai.WriteLine("[assembly: AssemblyDelaySign(false)]");
ai.WriteLine("[assembly: AssemblyDescription(\"@DESCRIPTION@\")]");
ai.WriteLine("[assembly: AssemblyFileVersion(\"@ASSEMBLY_VERSION@\")]");
ai.WriteLine("[assembly: AssemblyInformationalVersion(\"@ASSEMBLY_VERSION@\")]");
ai.WriteLine("[assembly: AssemblyKeyName(\"\")]");
ai.WriteLine("[assembly: AssemblyProduct(\"@PACKAGE_NAME@.dll\")]");
ai.WriteLine("[assembly: AssemblyTitle(\"@DESCRIPTION@\")]");
ai.WriteLine("[assembly: AssemblyTrademark(\"Tao Framework -- http://www.taoframework.com\")]");
ai.WriteLine("[assembly: AssemblyVersion(\"@ASSEMBLY_VERSION@\")]");
ai.WriteLine("[assembly: CLSCompliant(true)]");
ai.WriteLine("[assembly: ComVisible(false)]");
ai.WriteLine("[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)]");
ai.WriteLine("[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.SkipVerification)]");
ai.WriteLine("[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]");
}
//return combFile;
}
private void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
string projectFile = Helper.MakeFilePath(project.FullPath, "Include", "am");
Helper.DeleteIfExists(projectFile);
}
private void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning Autotools make files for", solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, "Makefile", "am");
Helper.DeleteIfExists(slnFile);
slnFile = Helper.MakeFilePath(solution.FullPath, "Makefile", "in");
Helper.DeleteIfExists(slnFile);
slnFile = Helper.MakeFilePath(solution.FullPath, "configure", "ac");
Helper.DeleteIfExists(slnFile);
slnFile = Helper.MakeFilePath(solution.FullPath, "configure");
Helper.DeleteIfExists(slnFile);
slnFile = Helper.MakeFilePath(solution.FullPath, "Makefile");
Helper.DeleteIfExists(slnFile);
foreach (ProjectNode project in solution.Projects)
{
CleanProject(project);
}
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
/// <summary>
/// Writes the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public void Write(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
m_Kernel.Log.Write("Parsing system pkg-config files");
RunInitialization();
string streamName = "autotools.xml";
string fqStreamName = String.Format("Prebuild.data.{0}",
streamName
);
// Retrieve stream for the autotools template XML
Stream autotoolsStream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(fqStreamName);
if(autotoolsStream == null) {
/*
* try without the default namespace prepended, in
* case prebuild.exe assembly was compiled with
* something other than Visual Studio .NET
*/
autotoolsStream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(streamName);
if(autotoolsStream == null){
string errStr =
String.Format("Could not find embedded resource file:\n" +
"'{0}' or '{1}'",
streamName, fqStreamName
);
m_Kernel.Log.Write(errStr);
throw new System.Reflection.TargetException(errStr);
}
}
// Create an XML URL Resolver with default credentials
xr = new System.Xml.XmlUrlResolver();
xr.Credentials = CredentialCache.DefaultCredentials;
// Create a default evidence - no need to limit access
e = new System.Security.Policy.Evidence();
// Load the autotools XML
autotoolsDoc = new XmlDocument();
autotoolsDoc.Load(autotoolsStream);
/* rootDir is the filesystem location where the Autotools
* build tree will be created - for now we'll make it
* $PWD/autotools
*/
string pwd = Directory.GetCurrentDirectory();
//string pwd = System.Environment.GetEnvironmentVariable("PWD");
string rootDir = "";
//if (pwd.Length != 0)
//{
rootDir = Path.Combine(pwd, "autotools");
//}
//else
//{
// pwd = Assembly.GetExecutingAssembly()
//}
chkMkDir(rootDir);
foreach (SolutionNode solution in kern.Solutions)
{
m_Kernel.Log.Write(String.Format("Writing solution: {0}",
solution.Name));
WriteCombine(solution);
}
m_Kernel = null;
}
/// <summary>
/// Cleans the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Clean(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach (SolutionNode sol in kern.Solutions)
{
CleanSolution(sol);
}
m_Kernel = null;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return "autotools";
}
}
#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.
/*============================================================
**
** Classes: Object Security family of classes
**
**
===========================================================*/
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
namespace System.Security.AccessControl
{
public enum AccessControlModification
{
Add = 0,
Set = 1,
Reset = 2,
Remove = 3,
RemoveAll = 4,
RemoveSpecific = 5,
}
public abstract class ObjectSecurity
{
#region Private Members
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
internal readonly CommonSecurityDescriptor _securityDescriptor;
private bool _ownerModified = false;
private bool _groupModified = false;
private bool _saclModified = false;
private bool _daclModified = false;
// only these SACL control flags will be automatically carry forward
// when update with new security descriptor.
private const ControlFlags SACL_CONTROL_FLAGS =
ControlFlags.SystemAclPresent |
ControlFlags.SystemAclAutoInherited |
ControlFlags.SystemAclProtected;
// only these DACL control flags will be automatically carry forward
// when update with new security descriptor
private const ControlFlags DACL_CONTROL_FLAGS =
ControlFlags.DiscretionaryAclPresent |
ControlFlags.DiscretionaryAclAutoInherited |
ControlFlags.DiscretionaryAclProtected;
#endregion
#region Constructors
protected ObjectSecurity()
{
}
protected ObjectSecurity(bool isContainer, bool isDS)
: this()
{
// we will create an empty DACL, denying anyone any access as the default. 5 is the capacity.
DiscretionaryAcl dacl = new DiscretionaryAcl(isContainer, isDS, 5);
_securityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, ControlFlags.None, null, null, null, dacl);
}
protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor)
: this()
{
if (securityDescriptor == null)
{
throw new ArgumentNullException(nameof(securityDescriptor));
}
_securityDescriptor = securityDescriptor;
}
#endregion
#region Private methods
private void UpdateWithNewSecurityDescriptor(RawSecurityDescriptor newOne, AccessControlSections includeSections)
{
Debug.Assert(newOne != null, "Must not supply a null parameter here");
if ((includeSections & AccessControlSections.Owner) != 0)
{
_ownerModified = true;
_securityDescriptor.Owner = newOne.Owner;
}
if ((includeSections & AccessControlSections.Group) != 0)
{
_groupModified = true;
_securityDescriptor.Group = newOne.Group;
}
if ((includeSections & AccessControlSections.Audit) != 0)
{
_saclModified = true;
if (newOne.SystemAcl != null)
{
_securityDescriptor.SystemAcl = new SystemAcl(IsContainer, IsDS, newOne.SystemAcl, true);
}
else
{
_securityDescriptor.SystemAcl = null;
}
// carry forward the SACL related control flags
_securityDescriptor.UpdateControlFlags(SACL_CONTROL_FLAGS, (ControlFlags)(newOne.ControlFlags & SACL_CONTROL_FLAGS));
}
if ((includeSections & AccessControlSections.Access) != 0)
{
_daclModified = true;
if (newOne.DiscretionaryAcl != null)
{
_securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl(IsContainer, IsDS, newOne.DiscretionaryAcl, true);
}
else
{
_securityDescriptor.DiscretionaryAcl = null;
}
// by the following property set, the _securityDescriptor's control flags
// may contains DACL present flag. That needs to be carried forward! Therefore, we OR
// the current _securityDescriptor.s DACL present flag.
ControlFlags daclFlag = (_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent);
_securityDescriptor.UpdateControlFlags(DACL_CONTROL_FLAGS,
(ControlFlags)((newOne.ControlFlags | daclFlag) & DACL_CONTROL_FLAGS));
}
}
#endregion
#region Protected Properties and Methods
/// <summary>
/// Gets the security descriptor for this instance.
/// </summary>
protected CommonSecurityDescriptor SecurityDescriptor => _securityDescriptor;
protected void ReadLock()
{
_lock.EnterReadLock();
}
protected void ReadUnlock()
{
_lock.ExitReadLock();
}
protected void WriteLock()
{
_lock.EnterWriteLock();
}
protected void WriteUnlock()
{
_lock.ExitWriteLock();
}
protected bool OwnerModified
{
get
{
if (!(_lock.IsReadLockHeld || _lock.IsWriteLockHeld))
{
throw new InvalidOperationException(SR.InvalidOperation_MustLockForReadOrWrite);
}
return _ownerModified;
}
set
{
if (!_lock.IsWriteLockHeld)
{
throw new InvalidOperationException(SR.InvalidOperation_MustLockForWrite);
}
_ownerModified = value;
}
}
protected bool GroupModified
{
get
{
if (!(_lock.IsReadLockHeld || _lock.IsWriteLockHeld))
{
throw new InvalidOperationException(SR.InvalidOperation_MustLockForReadOrWrite);
}
return _groupModified;
}
set
{
if (!_lock.IsWriteLockHeld)
{
throw new InvalidOperationException(SR.InvalidOperation_MustLockForWrite);
}
_groupModified = value;
}
}
protected bool AuditRulesModified
{
get
{
if (!(_lock.IsReadLockHeld || _lock.IsWriteLockHeld))
{
throw new InvalidOperationException(SR.InvalidOperation_MustLockForReadOrWrite);
}
return _saclModified;
}
set
{
if (!_lock.IsWriteLockHeld)
{
throw new InvalidOperationException(SR.InvalidOperation_MustLockForWrite);
}
_saclModified = value;
}
}
protected bool AccessRulesModified
{
get
{
if (!(_lock.IsReadLockHeld || _lock.IsWriteLockHeld))
{
throw new InvalidOperationException(SR.InvalidOperation_MustLockForReadOrWrite);
}
return _daclModified;
}
set
{
if (!_lock.IsWriteLockHeld)
{
throw new InvalidOperationException(SR.InvalidOperation_MustLockForWrite);
}
_daclModified = value;
}
}
protected bool IsContainer
{
get { return _securityDescriptor.IsContainer; }
}
protected bool IsDS
{
get { return _securityDescriptor.IsDS; }
}
//
// Persists the changes made to the object
//
// This overloaded method takes a name of an existing object
//
protected virtual void Persist(string name, AccessControlSections includeSections)
{
throw NotImplemented.ByDesign;
}
//
// if Persist (by name) is implemented, then this function will also try to enable take ownership
// privilege while persisting if the enableOwnershipPrivilege is true.
// Integrators can override it if this is not desired.
//
protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections)
{
Privilege ownerPrivilege = null;
try
{
if (enableOwnershipPrivilege)
{
ownerPrivilege = new Privilege(Privilege.TakeOwnership);
try
{
ownerPrivilege.Enable();
}
catch (PrivilegeNotHeldException)
{
// we will ignore this exception and press on just in case this is a remote resource
}
}
Persist(name, includeSections);
}
catch
{
// protection against exception filter-based luring attacks
if (ownerPrivilege != null)
{
ownerPrivilege.Revert();
}
throw;
}
finally
{
if (ownerPrivilege != null)
{
ownerPrivilege.Revert();
}
}
}
//
// Persists the changes made to the object
//
// This overloaded method takes a handle to an existing object
//
protected virtual void Persist(SafeHandle handle, AccessControlSections includeSections)
{
throw NotImplemented.ByDesign;
}
#endregion
#region Public Methods
//
// Sets and retrieves the owner of this object
//
public IdentityReference GetOwner(System.Type targetType)
{
ReadLock();
try
{
if (_securityDescriptor.Owner == null)
{
return null;
}
return _securityDescriptor.Owner.Translate(targetType);
}
finally
{
ReadUnlock();
}
}
public void SetOwner(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
WriteLock();
try
{
_securityDescriptor.Owner = identity.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
_ownerModified = true;
}
finally
{
WriteUnlock();
}
}
//
// Sets and retrieves the group of this object
//
public IdentityReference GetGroup(System.Type targetType)
{
ReadLock();
try
{
if (_securityDescriptor.Group == null)
{
return null;
}
return _securityDescriptor.Group.Translate(targetType);
}
finally
{
ReadUnlock();
}
}
public void SetGroup(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
WriteLock();
try
{
_securityDescriptor.Group = identity.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
_groupModified = true;
}
finally
{
WriteUnlock();
}
}
public virtual void PurgeAccessRules(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
WriteLock();
try
{
_securityDescriptor.PurgeAccessControl(identity.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier);
_daclModified = true;
}
finally
{
WriteUnlock();
}
}
public virtual void PurgeAuditRules(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
WriteLock();
try
{
_securityDescriptor.PurgeAudit(identity.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier);
_saclModified = true;
}
finally
{
WriteUnlock();
}
}
public bool AreAccessRulesProtected
{
get
{
ReadLock();
try
{
return ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0);
}
finally
{
ReadUnlock();
}
}
}
public void SetAccessRuleProtection(bool isProtected, bool preserveInheritance)
{
WriteLock();
try
{
_securityDescriptor.SetDiscretionaryAclProtection(isProtected, preserveInheritance);
_daclModified = true;
}
finally
{
WriteUnlock();
}
}
public bool AreAuditRulesProtected
{
get
{
ReadLock();
try
{
return ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0);
}
finally
{
ReadUnlock();
}
}
}
public void SetAuditRuleProtection(bool isProtected, bool preserveInheritance)
{
WriteLock();
try
{
_securityDescriptor.SetSystemAclProtection(isProtected, preserveInheritance);
_saclModified = true;
}
finally
{
WriteUnlock();
}
}
public bool AreAccessRulesCanonical
{
get
{
ReadLock();
try
{
return _securityDescriptor.IsDiscretionaryAclCanonical;
}
finally
{
ReadUnlock();
}
}
}
public bool AreAuditRulesCanonical
{
get
{
ReadLock();
try
{
return _securityDescriptor.IsSystemAclCanonical;
}
finally
{
ReadUnlock();
}
}
}
public static bool IsSddlConversionSupported()
{
return true; // SDDL to binary conversions are supported on Windows 2000 and higher
}
public string GetSecurityDescriptorSddlForm(AccessControlSections includeSections)
{
ReadLock();
try
{
return _securityDescriptor.GetSddlForm(includeSections);
}
finally
{
ReadUnlock();
}
}
public void SetSecurityDescriptorSddlForm(string sddlForm)
{
SetSecurityDescriptorSddlForm(sddlForm, AccessControlSections.All);
}
public void SetSecurityDescriptorSddlForm(string sddlForm, AccessControlSections includeSections)
{
if (sddlForm == null)
{
throw new ArgumentNullException(nameof(sddlForm));
}
if ((includeSections & AccessControlSections.All) == 0)
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
nameof(includeSections));
}
WriteLock();
try
{
UpdateWithNewSecurityDescriptor(new RawSecurityDescriptor(sddlForm), includeSections);
}
finally
{
WriteUnlock();
}
}
public byte[] GetSecurityDescriptorBinaryForm()
{
ReadLock();
try
{
byte[] result = new byte[_securityDescriptor.BinaryLength];
_securityDescriptor.GetBinaryForm(result, 0);
return result;
}
finally
{
ReadUnlock();
}
}
public void SetSecurityDescriptorBinaryForm(byte[] binaryForm)
{
SetSecurityDescriptorBinaryForm(binaryForm, AccessControlSections.All);
}
public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSections includeSections)
{
if (binaryForm == null)
{
throw new ArgumentNullException(nameof(binaryForm));
}
if ((includeSections & AccessControlSections.All) == 0)
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
nameof(includeSections));
}
WriteLock();
try
{
UpdateWithNewSecurityDescriptor(new RawSecurityDescriptor(binaryForm, 0), includeSections);
}
finally
{
WriteUnlock();
}
}
public abstract Type AccessRightType { get; }
public abstract Type AccessRuleType { get; }
public abstract Type AuditRuleType { get; }
protected abstract bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified);
protected abstract bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified);
public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified)
{
if (rule == null)
{
throw new ArgumentNullException(nameof(rule));
}
if (!this.AccessRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()))
{
throw new ArgumentException(
SR.AccessControl_InvalidAccessRuleType,
nameof(rule));
}
WriteLock();
try
{
return ModifyAccess(modification, rule, out modified);
}
finally
{
WriteUnlock();
}
}
public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified)
{
if (rule == null)
{
throw new ArgumentNullException(nameof(rule));
}
if (!this.AuditRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()))
{
throw new ArgumentException(
SR.AccessControl_InvalidAuditRuleType,
nameof(rule));
}
WriteLock();
try
{
return ModifyAudit(modification, rule, out modified);
}
finally
{
WriteUnlock();
}
}
public abstract AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type);
public abstract AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags);
#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.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Internal.DeveloperExperience;
using Internal.Runtime.Augments;
namespace System
{
internal class PreallocatedOutOfMemoryException
{
public static OutOfMemoryException Instance { get; private set; }
// Eagerly preallocate instance of out of memory exception to avoid infinite recursion once we run out of memory
internal static void Initialize()
{
Instance = new OutOfMemoryException(message: null); // Cannot call the nullary constructor as that triggers non-trivial resource manager logic.
}
}
[ReflectionBlocked]
public class RuntimeExceptionHelpers
{
//------------------------------------------------------------------------------------------------------------
// @TODO: this function is related to throwing exceptions out of Rtm. If we did not have to throw
// out of Rtm, then we would note have to have the code below to get a classlib exception object given
// an exception id, or the special functions to back up the MDIL THROW_* instructions, or the allocation
// failure helper. If we could move to a world where we never throw out of Rtm, perhaps by moving parts
// of Rtm that do need to throw out to Bartok- or Binder-generated functions, then we could remove all of this.
//------------------------------------------------------------------------------------------------------------
[ThreadStatic]
private static bool t_allocatingOutOfMemoryException;
// This is the classlib-provided "get exception" function that will be invoked whenever the runtime
// needs to throw an exception back to a method in a non-runtime module. The classlib is expected
// to convert every code in the ExceptionIDs enum to an exception object.
[RuntimeExport("GetRuntimeException")]
public static Exception GetRuntimeException(ExceptionIDs id)
{
if (!SafeToPerformRichExceptionSupport)
return null;
// This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions
// back into the dispatcher.
try
{
// @TODO: this function should return pre-allocated exception objects, either frozen in the image
// or preallocated during DllMain(). In particular, this function will be called when out of memory,
// and failure to create an exception will result in infinite recursion and therefore a stack overflow.
switch (id)
{
case ExceptionIDs.OutOfMemory:
Exception outOfMemoryException = PreallocatedOutOfMemoryException.Instance;
// If possible, try to allocate proper out-of-memory exception with error message and stack trace
if (!t_allocatingOutOfMemoryException)
{
t_allocatingOutOfMemoryException = true;
try
{
outOfMemoryException = new OutOfMemoryException();
}
catch
{
}
t_allocatingOutOfMemoryException = false;
}
return outOfMemoryException;
case ExceptionIDs.Arithmetic:
return new ArithmeticException();
case ExceptionIDs.ArrayTypeMismatch:
return new ArrayTypeMismatchException();
case ExceptionIDs.DivideByZero:
return new DivideByZeroException();
case ExceptionIDs.IndexOutOfRange:
return new IndexOutOfRangeException();
case ExceptionIDs.InvalidCast:
return new InvalidCastException();
case ExceptionIDs.Overflow:
return new OverflowException();
case ExceptionIDs.NullReference:
return new NullReferenceException();
case ExceptionIDs.AccessViolation:
FailFast("Access Violation: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. The application will be terminated since this platform does not support throwing an AccessViolationException.");
return null;
case ExceptionIDs.DataMisaligned:
return new DataMisalignedException();
default:
FailFast("The runtime requires an exception for a case that this class library does not understand.");
return null;
}
}
catch
{
return null; // returning null will cause the runtime to FailFast via the class library.
}
}
public enum RhFailFastReason
{
Unknown = 0,
InternalError = 1, // "Runtime internal error"
UnhandledException_ExceptionDispatchNotAllowed = 2, // "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope."
UnhandledException_CallerDidNotHandle = 3, // "Unhandled exception: no handler found in calling method."
ClassLibDidNotTranslateExceptionID = 4, // "Unable to translate failure into a classlib-specific exception object."
IllegalNativeCallableEntry = 5, // "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code."
PN_UnhandledException = 6, // ProjectN: "Unhandled exception: a managed exception was not handled before reaching unmanaged code"
PN_UnhandledExceptionFromPInvoke = 7, // ProjectN: "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition."
Max
}
private static string GetStringForFailFastReason(RhFailFastReason reason)
{
switch (reason)
{
case RhFailFastReason.InternalError:
return "Runtime internal error";
case RhFailFastReason.UnhandledException_ExceptionDispatchNotAllowed:
return "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope.";
case RhFailFastReason.UnhandledException_CallerDidNotHandle:
return "Unhandled exception: no handler found in calling method.";
case RhFailFastReason.ClassLibDidNotTranslateExceptionID:
return "Unable to translate failure into a classlib-specific exception object.";
case RhFailFastReason.IllegalNativeCallableEntry:
return "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code.";
case RhFailFastReason.PN_UnhandledException:
return "Unhandled exception: a managed exception was not handled before reaching unmanaged code.";
case RhFailFastReason.PN_UnhandledExceptionFromPInvoke:
return "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition.";
default:
return "Unknown reason.";
}
}
public static void FailFast(string message)
{
FailFast(message, null, RhFailFastReason.Unknown, IntPtr.Zero, IntPtr.Zero);
}
public static unsafe void FailFast(string message, Exception exception)
{
FailFast(message, exception, RhFailFastReason.Unknown, IntPtr.Zero, IntPtr.Zero);
}
// Used to report exceptions that *logically* go unhandled in the Fx code. For example, an
// exception that escapes from a ThreadPool workitem, or from a void-returning async method.
public static void ReportUnhandledException(Exception exception)
{
// ReportUnhandledError will also call this in APPX scenarios,
// but WinRT can failfast before we get another chance
// (in APPX scenarios, this one will get overwritten by the one with the CCW pointer)
GenerateExceptionInformationForDump(exception, IntPtr.Zero);
#if ENABLE_WINRT
// If possible report the exception to GEH, if not fail fast.
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks == null || !callbacks.ReportUnhandledError(exception))
FailFast(GetStringForFailFastReason(RhFailFastReason.PN_UnhandledException), exception);
#else
FailFast(GetStringForFailFastReason(RhFailFastReason.PN_UnhandledException), exception);
#endif
}
// This is the classlib-provided fail-fast function that will be invoked whenever the runtime
// needs to cause the process to exit. It is the classlib's opprotunity to customize the
// termination behavior in whatever way necessary.
[RuntimeExport("FailFast")]
public static void RuntimeFailFast(RhFailFastReason reason, Exception exception, IntPtr pExAddress, IntPtr pExContext)
{
if (!SafeToPerformRichExceptionSupport)
return;
// This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions
// back into the dispatcher.
try
{
// Avoid complex processing and allocations if we are already in failfast or recursive out of memory.
// We do not set InFailFast.Value here, because we want rich diagnostics in the FailFast
// call below and reentrancy is not possible for this method (all exceptions are ignored).
bool minimalFailFast = InFailFast.Value || (exception == PreallocatedOutOfMemoryException.Instance);
string failFastMessage = "";
if (!minimalFailFast)
{
if ((reason == RhFailFastReason.PN_UnhandledException) && (exception != null))
{
Debug.WriteLine("Unhandled Exception: " + exception.ToString());
}
failFastMessage = string.Format("Runtime-generated FailFast: ({0}): {1}{2}",
reason.ToString(), // Explicit call to ToString() to avoid MissingMetadataException inside String.Format()
GetStringForFailFastReason(reason),
exception != null ? " [exception object available]" : "");
}
FailFast(failFastMessage, exception, reason, pExAddress, pExContext);
}
catch
{
// Returning from this callback will cause the runtime to FailFast without involving the class
// library.
}
}
internal static void FailFast(string message, Exception exception, RhFailFastReason reason, IntPtr pExAddress, IntPtr pExContext)
{
// If this a recursive call to FailFast, avoid all unnecessary and complex activity the second time around to avoid the recursion
// that got us here the first time (Some judgement is required as to what activity is "unnecessary and complex".)
bool minimalFailFast = InFailFast.Value || (exception == PreallocatedOutOfMemoryException.Instance);
InFailFast.Value = true;
if (!minimalFailFast)
{
string output = (exception != null) ?
"Unhandled Exception: " + exception.ToString()
: message;
DeveloperExperience.Default.WriteLine(output);
GenerateExceptionInformationForDump(exception, IntPtr.Zero);
}
#if PLATFORM_WINDOWS
uint errorCode = 0x80004005; // E_FAIL
// To help enable testing to bucket the failures we choose one of the following as errorCode:
// * hashcode of EETypePtr if it is an unhandled managed exception
// * HRESULT, if available
// * RhFailFastReason, if it is one of the known reasons
if (exception != null)
{
if (reason == RhFailFastReason.PN_UnhandledException)
errorCode = (uint)(exception.EETypePtr.GetHashCode());
else if (exception.HResult != 0)
errorCode = (uint)exception.HResult;
}
else if (reason != RhFailFastReason.Unknown)
{
errorCode = (uint)reason + 0x1000; // Add something to avoid common low level exit codes
}
Interop.mincore.RaiseFailFastException(errorCode, pExAddress, pExContext);
#else
Interop.Sys.Abort();
#endif
}
// Use a nested class to avoid running the class constructor of the outer class when
// accessing this flag.
private static class InFailFast
{
// This boolean is used to stop runaway FailFast recursions. Though this is technically a concurrently set field, it only gets set during
// fatal process shutdowns and it's only purpose is a reasonable-case effort to make a bad situation a little less bad.
// Trying to use locks or other concurrent access apis would actually defeat the purpose of making FailFast as robust as possible.
public static bool Value;
}
#pragma warning disable 414 // field is assigned, but never used -- This is because C# doesn't realize that we
// copy the field into a buffer.
/// <summary>
/// This is the header that describes our 'error report' buffer to the minidump auxiliary provider.
/// Its format is know to that system-wide DLL, so do not change it. The remainder of the buffer is
/// opaque to the minidump auxiliary provider, so it'll have its own format that is more easily
/// changed.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct ERROR_REPORT_BUFFER_HEADER
{
private int _headerSignature;
private int _bufferByteCount;
public void WriteHeader(int cbBuffer)
{
_headerSignature = 0x31304244; // 'DB01'
_bufferByteCount = cbBuffer;
}
}
/// <summary>
/// This header describes the contents of the serialized error report to DAC, which can deserialize it
/// from a dump file or live debugging session. This format is easier to change than the
/// ERROR_REPORT_BUFFER_HEADER, but it is still well-known to DAC, so any changes must update the
/// version number and also have corresponding changes made to DAC.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct SERIALIZED_ERROR_REPORT_HEADER
{
private int _errorReportSignature; // This is the version of the 'container format'.
private int _exceptionSerializationVersion; // This is the version of the Exception format. It is
// separate from the 'container format' version since the
// implementation of the Exception serialization is owned by
// the Exception class.
private int _exceptionCount; // We just contain a logical array of exceptions.
private int _loadedModuleCount; // Number of loaded modules. present when signature >= ER02.
// {ExceptionCount} serialized Exceptions follow.
// {LoadedModuleCount} module handles follow. present when signature >= ER02.
public void WriteHeader(int nExceptions, int nLoadedModules)
{
_errorReportSignature = 0x32305245; // 'ER02'
_exceptionSerializationVersion = Exception.CurrentSerializationSignature;
_exceptionCount = nExceptions;
_loadedModuleCount = nLoadedModules;
}
}
/// <summary>
/// Holds metadata about an exception in flight. Class because ConditionalWeakTable only accepts reference types
/// </summary>
private class ExceptionData
{
public ExceptionData()
{
// Set this to a non-zero value so that logic mapping entries to threads
// doesn't think an uninitialized ExceptionData is on thread 0
ExceptionMetadata.ThreadId = 0xFFFFFFFF;
}
public struct ExceptionMetadataStruct
{
public uint ExceptionId { get; set; } // Id assigned to the exception. May not be contiguous or start at 0.
public uint InnerExceptionId { get; set; } // ID of the inner exception or 0xFFFFFFFF for 'no inner exception'
public uint ThreadId { get; set; } // Managed thread ID the eception was thrown on
public int NestingLevel { get; set; } // If multiple exceptions are currently active on a thread, this gives the ordering for them.
// The highest number is the most recent exception. -1 means the exception is not currently in flight
// (but it may still be an InnerException).
public IntPtr ExceptionCCWPtr { get; set; } // If the exception was thrown in an interop scenario, this contains the CCW pointer, otherwise, IntPtr.Zero
}
public ExceptionMetadataStruct ExceptionMetadata;
/// <summary>
/// Data created by Exception.SerializeForDump()
/// </summary>
public byte[] SerializedExceptionData { get; set; }
/// <summary>
/// Serializes the exception metadata and SerializedExceptionData
/// </summary>
public unsafe byte[] Serialize()
{
checked
{
byte[] serializedData = new byte[sizeof(ExceptionMetadataStruct) + SerializedExceptionData.Length];
fixed (byte* pSerializedData = &serializedData[0])
{
ExceptionMetadataStruct* pMetadata = (ExceptionMetadataStruct*)pSerializedData;
pMetadata->ExceptionId = ExceptionMetadata.ExceptionId;
pMetadata->InnerExceptionId = ExceptionMetadata.InnerExceptionId;
pMetadata->ThreadId = ExceptionMetadata.ThreadId;
pMetadata->NestingLevel = ExceptionMetadata.NestingLevel;
pMetadata->ExceptionCCWPtr = ExceptionMetadata.ExceptionCCWPtr;
PInvokeMarshal.CopyToNative(SerializedExceptionData, 0, (IntPtr)(pSerializedData + sizeof(ExceptionMetadataStruct)), SerializedExceptionData.Length);
}
return serializedData;
}
}
}
/// <summary>
/// Table of exceptions that were on stacks triggering GenerateExceptionInformationForDump
/// </summary>
private static readonly ConditionalWeakTable<Exception, ExceptionData> s_exceptionDataTable = new ConditionalWeakTable<Exception, ExceptionData>();
/// <summary>
/// Counter for exception ID assignment
/// </summary>
private static int s_currentExceptionId = 0;
/// <summary>
/// This method will call the runtime to gather the Exception objects from every exception dispatch in
/// progress on the current thread. It will then serialize them into a new buffer and pass that
/// buffer back to the runtime, which will publish it to a place where a global "minidump auxiliary
/// provider" will be able to save the buffer's contents into triage dumps.
///
/// Thread safety information: The guarantee of this method is that the buffer it produces will have
/// complete and correct information for all live exceptions on the current thread (as long as the same exception object
/// is not thrown simultaneously on multiple threads). It will do a best-effort attempt to serialize information about exceptions
/// already recorded on other threads, but that data can be lost or corrupted. The restrictions are:
/// 1. Only exceptions active or recorded on the current thread have their table data modified.
/// 2. After updating data in the table, we serialize a snapshot of the table (provided by ConditionalWeakTable.Values),
/// regardless of what other threads might do to the table before or after. However, because of #1, this thread's
/// exception data should stay stable
/// 3. There is a dependency on the fact that ConditionalWeakTable's members are all threadsafe and that .Values returns a snapshot
/// </summary>
public static void GenerateExceptionInformationForDump(Exception currentException, IntPtr exceptionCCWPtr)
{
LowLevelList<byte[]> serializedExceptions = new LowLevelList<byte[]>();
// If currentException is null, there's a state corrupting exception in flight and we can't serialize it
if (currentException != null)
{
SerializeExceptionsForDump(currentException, exceptionCCWPtr, serializedExceptions);
}
GenerateErrorReportForDump(serializedExceptions);
}
private static void SerializeExceptionsForDump(Exception currentException, IntPtr exceptionCCWPtr, LowLevelList<byte[]> serializedExceptions)
{
const uint NoInnerExceptionValue = 0xFFFFFFFF;
// Approximate upper size limit for the serialized exceptions (but we'll always serialize currentException)
// If we hit the limit, because we serialize in arbitrary order, there may be missing InnerExceptions or nested exceptions.
const int MaxBufferSize = 20000;
int nExceptions;
RuntimeImports.RhGetExceptionsForCurrentThread(null, out nExceptions);
Exception[] curThreadExceptions = new Exception[nExceptions];
RuntimeImports.RhGetExceptionsForCurrentThread(curThreadExceptions, out nExceptions);
LowLevelList<Exception> exceptions = new LowLevelList<Exception>(curThreadExceptions);
LowLevelList<Exception> nonThrownInnerExceptions = new LowLevelList<Exception>();
uint currentThreadId = (uint)Environment.CurrentNativeThreadId;
// Reset nesting levels for exceptions on this thread that might not be currently in flight
foreach (KeyValuePair<Exception, ExceptionData> item in s_exceptionDataTable)
{
ExceptionData exceptionData = item.Value;
if (exceptionData.ExceptionMetadata.ThreadId == currentThreadId)
{
exceptionData.ExceptionMetadata.NestingLevel = -1;
}
}
// Find all inner exceptions, even if they're not currently being handled
for (int i = 0; i < exceptions.Count; i++)
{
if (exceptions[i].InnerException != null && !exceptions.Contains(exceptions[i].InnerException))
{
exceptions.Add(exceptions[i].InnerException);
nonThrownInnerExceptions.Add(exceptions[i].InnerException);
}
}
int currentNestingLevel = curThreadExceptions.Length - 1;
// Make sure we serialize currentException
if (!exceptions.Contains(currentException))
{
// When this happens, currentException is probably passed to this function through System.Environment.FailFast(), we
// would want to treat as if this exception is last thrown in the current thread.
exceptions.Insert(0, currentException);
currentNestingLevel++;
}
// Populate exception data for all exceptions interesting to this thread.
// Whether or not there was previously data for that object, it might have changed.
for (int i = 0; i < exceptions.Count; i++)
{
ExceptionData exceptionData = s_exceptionDataTable.GetOrCreateValue(exceptions[i]);
exceptionData.ExceptionMetadata.ExceptionId = (uint)System.Threading.Interlocked.Increment(ref s_currentExceptionId);
if (exceptionData.ExceptionMetadata.ExceptionId == NoInnerExceptionValue)
{
exceptionData.ExceptionMetadata.ExceptionId = (uint)System.Threading.Interlocked.Increment(ref s_currentExceptionId);
}
exceptionData.ExceptionMetadata.ThreadId = currentThreadId;
// Only include nesting information for exceptions that were thrown on this thread
if (!nonThrownInnerExceptions.Contains(exceptions[i]))
{
exceptionData.ExceptionMetadata.NestingLevel = currentNestingLevel;
currentNestingLevel--;
}
else
{
exceptionData.ExceptionMetadata.NestingLevel = -1;
}
// Only match the CCW pointer up to the current exception
if (object.ReferenceEquals(exceptions[i], currentException))
{
exceptionData.ExceptionMetadata.ExceptionCCWPtr = exceptionCCWPtr;
}
byte[] serializedEx = exceptions[i].SerializeForDump();
exceptionData.SerializedExceptionData = serializedEx;
}
// Populate inner exception ids now that we have all of them in the table
for (int i = 0; i < exceptions.Count; i++)
{
ExceptionData exceptionData;
if (!s_exceptionDataTable.TryGetValue(exceptions[i], out exceptionData))
{
// This shouldn't happen, but we can't meaningfully throw here
continue;
}
if (exceptions[i].InnerException != null)
{
ExceptionData innerExceptionData;
if (s_exceptionDataTable.TryGetValue(exceptions[i].InnerException, out innerExceptionData))
{
exceptionData.ExceptionMetadata.InnerExceptionId = innerExceptionData.ExceptionMetadata.ExceptionId;
}
}
else
{
exceptionData.ExceptionMetadata.InnerExceptionId = NoInnerExceptionValue;
}
}
int totalSerializedExceptionSize = 0;
// Make sure we include the current exception, regardless of buffer size
ExceptionData currentExceptionData = null;
if (s_exceptionDataTable.TryGetValue(currentException, out currentExceptionData))
{
byte[] serializedExceptionData = currentExceptionData.Serialize();
serializedExceptions.Add(serializedExceptionData);
totalSerializedExceptionSize = serializedExceptionData.Length;
}
checked
{
foreach (KeyValuePair<Exception, ExceptionData> item in s_exceptionDataTable)
{
ExceptionData exceptionData = item.Value;
// Already serialized currentException
if (currentExceptionData != null && exceptionData.ExceptionMetadata.ExceptionId == currentExceptionData.ExceptionMetadata.ExceptionId)
{
continue;
}
byte[] serializedExceptionData = exceptionData.Serialize();
if (totalSerializedExceptionSize + serializedExceptionData.Length >= MaxBufferSize)
{
break;
}
serializedExceptions.Add(serializedExceptionData);
totalSerializedExceptionSize += serializedExceptionData.Length;
}
}
}
private static unsafe void GenerateErrorReportForDump(LowLevelList<byte[]> serializedExceptions)
{
checked
{
int loadedModuleCount = (int)RuntimeImports.RhGetLoadedOSModules(null);
int cbModuleHandles = sizeof(System.IntPtr) * loadedModuleCount;
int cbFinalBuffer = sizeof(ERROR_REPORT_BUFFER_HEADER) + sizeof(SERIALIZED_ERROR_REPORT_HEADER) + cbModuleHandles;
for (int i = 0; i < serializedExceptions.Count; i++)
{
cbFinalBuffer += serializedExceptions[i].Length;
}
byte[] finalBuffer = new byte[cbFinalBuffer];
fixed (byte* pBuffer = &finalBuffer[0])
{
byte* pCursor = pBuffer;
int cbRemaining = cbFinalBuffer;
ERROR_REPORT_BUFFER_HEADER* pDacHeader = (ERROR_REPORT_BUFFER_HEADER*)pCursor;
pDacHeader->WriteHeader(cbFinalBuffer);
pCursor += sizeof(ERROR_REPORT_BUFFER_HEADER);
cbRemaining -= sizeof(ERROR_REPORT_BUFFER_HEADER);
SERIALIZED_ERROR_REPORT_HEADER* pPayloadHeader = (SERIALIZED_ERROR_REPORT_HEADER*)pCursor;
pPayloadHeader->WriteHeader(serializedExceptions.Count, loadedModuleCount);
pCursor += sizeof(SERIALIZED_ERROR_REPORT_HEADER);
cbRemaining -= sizeof(SERIALIZED_ERROR_REPORT_HEADER);
// copy the serialized exceptions to report buffer
for (int i = 0; i < serializedExceptions.Count; i++)
{
int cbChunk = serializedExceptions[i].Length;
PInvokeMarshal.CopyToNative(serializedExceptions[i], 0, (IntPtr)pCursor, cbChunk);
cbRemaining -= cbChunk;
pCursor += cbChunk;
}
// copy the module-handle array to report buffer
IntPtr[] loadedModuleHandles = new IntPtr[loadedModuleCount];
RuntimeImports.RhGetLoadedOSModules(loadedModuleHandles);
PInvokeMarshal.CopyToNative(loadedModuleHandles, 0, (IntPtr)pCursor, loadedModuleHandles.Length);
cbRemaining -= cbModuleHandles;
pCursor += cbModuleHandles;
Debug.Assert(cbRemaining == 0);
}
UpdateErrorReportBuffer(finalBuffer);
}
}
// This returns "true" once enough of the framework has been initialized to safely perform operations
// such as filling in the stack frame and generating diagnostic support.
public static bool SafeToPerformRichExceptionSupport
{
get
{
// Reflection needs to work as the exception code calls GetType() and GetType().ToString()
if (RuntimeAugments.CallbacksIfAvailable == null)
return false;
return true;
}
}
private static GCHandle s_ExceptionInfoBufferPinningHandle;
private static Lock s_ExceptionInfoBufferLock = new Lock();
private static unsafe void UpdateErrorReportBuffer(byte[] finalBuffer)
{
Debug.Assert(finalBuffer?.Length > 0);
using (LockHolder.Hold(s_ExceptionInfoBufferLock))
{
fixed (byte* pBuffer = &finalBuffer[0])
{
byte* pPrevBuffer = (byte*)RuntimeImports.RhSetErrorInfoBuffer(pBuffer);
Debug.Assert(s_ExceptionInfoBufferPinningHandle.IsAllocated == (pPrevBuffer != null));
if (pPrevBuffer != null)
{
byte[] currentExceptionInfoBuffer = (byte[])s_ExceptionInfoBufferPinningHandle.Target;
Debug.Assert(currentExceptionInfoBuffer?.Length > 0);
fixed (byte* pPrev = ¤tExceptionInfoBuffer[0])
Debug.Assert(pPrev == pPrevBuffer);
}
if (!s_ExceptionInfoBufferPinningHandle.IsAllocated)
{
// We allocate a pinning GC handle because we are logically giving the runtime 'unmanaged memory'.
s_ExceptionInfoBufferPinningHandle = GCHandle.Alloc(finalBuffer, GCHandleType.Pinned);
}
else
{
s_ExceptionInfoBufferPinningHandle.Target = finalBuffer;
}
}
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// RoleResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.IpMessaging.V2.Service
{
public class RoleResource : Resource
{
public sealed class RoleTypeEnum : StringEnum
{
private RoleTypeEnum(string value) : base(value) {}
public RoleTypeEnum() {}
public static implicit operator RoleTypeEnum(string value)
{
return new RoleTypeEnum(value);
}
public static readonly RoleTypeEnum Channel = new RoleTypeEnum("channel");
public static readonly RoleTypeEnum Deployment = new RoleTypeEnum("deployment");
}
private static Request BuildFetchRequest(FetchRoleOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Roles/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static RoleResource Fetch(FetchRoleOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<RoleResource> FetchAsync(FetchRoleOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static RoleResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchRoleOptions(pathServiceSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<RoleResource> FetchAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchRoleOptions(pathServiceSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteRoleOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Roles/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static bool Delete(DeleteRoleOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteRoleOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteRoleOptions(pathServiceSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteRoleOptions(pathServiceSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateRoleOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Roles",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static RoleResource Create(CreateRoleOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<RoleResource> CreateAsync(CreateRoleOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="friendlyName"> The friendly_name </param>
/// <param name="type"> The type </param>
/// <param name="permission"> The permission </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static RoleResource Create(string pathServiceSid,
string friendlyName,
RoleResource.RoleTypeEnum type,
List<string> permission,
ITwilioRestClient client = null)
{
var options = new CreateRoleOptions(pathServiceSid, friendlyName, type, permission);
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="friendlyName"> The friendly_name </param>
/// <param name="type"> The type </param>
/// <param name="permission"> The permission </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<RoleResource> CreateAsync(string pathServiceSid,
string friendlyName,
RoleResource.RoleTypeEnum type,
List<string> permission,
ITwilioRestClient client = null)
{
var options = new CreateRoleOptions(pathServiceSid, friendlyName, type, permission);
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadRoleOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Roles",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static ResourceSet<RoleResource> Read(ReadRoleOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<RoleResource>.FromJson("roles", response.Content);
return new ResourceSet<RoleResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<ResourceSet<RoleResource>> ReadAsync(ReadRoleOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<RoleResource>.FromJson("roles", response.Content);
return new ResourceSet<RoleResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static ResourceSet<RoleResource> Read(string pathServiceSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadRoleOptions(pathServiceSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<ResourceSet<RoleResource>> ReadAsync(string pathServiceSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadRoleOptions(pathServiceSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<RoleResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<RoleResource>.FromJson("roles", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<RoleResource> NextPage(Page<RoleResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<RoleResource>.FromJson("roles", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<RoleResource> PreviousPage(Page<RoleResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<RoleResource>.FromJson("roles", response.Content);
}
private static Request BuildUpdateRequest(UpdateRoleOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Roles/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static RoleResource Update(UpdateRoleOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Role parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<RoleResource> UpdateAsync(UpdateRoleOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="permission"> The permission </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Role </returns>
public static RoleResource Update(string pathServiceSid,
string pathSid,
List<string> permission,
ITwilioRestClient client = null)
{
var options = new UpdateRoleOptions(pathServiceSid, pathSid, permission);
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="permission"> The permission </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Role </returns>
public static async System.Threading.Tasks.Task<RoleResource> UpdateAsync(string pathServiceSid,
string pathSid,
List<string> permission,
ITwilioRestClient client = null)
{
var options = new UpdateRoleOptions(pathServiceSid, pathSid, permission);
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a RoleResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> RoleResource object represented by the provided JSON </returns>
public static RoleResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<RoleResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The sid
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The account_sid
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The service_sid
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The friendly_name
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The type
/// </summary>
[JsonProperty("type")]
[JsonConverter(typeof(StringEnumConverter))]
public RoleResource.RoleTypeEnum Type { get; private set; }
/// <summary>
/// The permissions
/// </summary>
[JsonProperty("permissions")]
public List<string> Permissions { get; private set; }
/// <summary>
/// The date_created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The date_updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private RoleResource()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using ProtoCore.DSASM;
using ProtoCore.Utils;
namespace ProtoCore
{
namespace RuntimeData
{
public enum WarningID
{
kDefault,
kAccessViolation,
kAmbiguousMethodDispatch,
kAurgumentIsNotExpected,
kCallingConstructorOnInstance,
kConversionNotPossible,
kDereferencingNonPointer,
kFileNotExist,
kIndexOutOfRange,
kInvalidRecursion,
kInvalidArguments,
kCyclicDependency,
kMethodResolutionFailure,
kOverIndexing,
kTypeConvertionCauseInfoLoss,
kTypeMismatch,
kReplicationWarning
}
public struct WarningMessage
{
public const string kArrayOverIndexed = "Variable is over indexed.";
public const string kIndexOutOfRange = "Index is out of range.";
public const string kSymbolOverIndexed = "'{0}' is over indexed.";
public const string kStringOverIndexed = "String is over indexed.";
public const string kStringIndexOutOfRange = "The index to string is out of range";
public const string kAssignNonCharacterToString = "Only character can be assigned to a position in a string.";
public const string KCallingConstructorOnInstance = "Cannot call constructor '{0}()' on instance.";
public const string kInvokeMethodOnInvalidObject = "Method '{0}()' is invoked on invalid object.";
public const string kMethodStackOverflow = "Stack overflow caused by calling method '{0}()' recursively.";
public const string kCyclicDependency = "Cyclic dependency detected at '{0}' and '{1}'.";
public const string kFFIFailedToObtainThisObject = "Failed to obtain this object for '{0}.{1}'.";
public const string kFFIFailedToObtainObject = "Failed to obtain object '{0}' for '{1}.{2}'.";
public const string kFFIInvalidCast = "'{0}' is being cast to '{1}', but the allowed range is [{2}..{3}].";
public const string kDeferencingNonPointer = "Deferencing a non-pointer.";
public const string kFailToConverToPointer = "Converting other things to pointer is not allowed.";
public const string kFailToConverToNull = "Converting other things to null is not allowed.";
public const string kFailToConverToFunction = "Converting other things to function pointer is not allowed.";
public const string kConvertDoubleToInt = "Converting double to int will cause possible information loss.";
public const string kArrayRankReduction = "Type conversion would cause array rank reduction. This is not permitted outside of replication. {511ED65F-FB66-4709-BDDA-DCD5E053B87F}";
public const string kConvertArrayToNonArray = "Converting an array to {0} would cause array rank reduction and is not permitted.";
public const string kConvertNonConvertibleTypes = "Asked to convert non-convertible types.";
public const string kFunctionNotFound = "No candidate function could be found.";
public const string kAmbigousMethodDispatch = "Candidate function could not be located on final replicated dispatch GUARD {FDD1F347-A9A6-43FB-A08E-A5E793EC3920}.";
public const string kInvalidArguments = "Argument is invalid.";
public const string kInvalidArgumentsInRangeExpression = "The value that used in range expression should be either interger or double.";
public const string kFileNotFound = "'{0}' doesn't exist.";
public const string kPropertyNotFound = "Object does not have a property '{0}'.";
public const string kPropertyOfClassNotFound = "Class '{0}' does not have a property '{1}'.";
public const string kPropertyInaccessible = "Property '{0}' is inaccessible.";
public const string kMethodResolutionFailure = "Method resolution failure on: {0}() - 0CD069F4-6C8A-42B6-86B1-B5C17072751B.";
public const string kMethodResolutionFailureForOperator = "Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'.";
}
public struct WarningEntry
{
public RuntimeData.WarningID id;
public string message;
public int Line;
public int Col;
public string Filename;
}
}
public class RuntimeStatus
{
private ProtoCore.Core core;
private bool warningAsError;
private System.IO.TextWriter output = System.Console.Out;
private readonly List<RuntimeData.WarningEntry> warnings;
public IOutputStream MessageHandler { get; set; }
public IOutputStream WebMsgHandler { get; set; }
public List<RuntimeData.WarningEntry> Warnings { get { return warnings; } }
//public CodeModel.CodePoint CodePoint { get; private set; }
public RuntimeStatus(Core core,bool warningAsError = false, System.IO.TextWriter writer = null)
{
warnings = new List<RuntimeData.WarningEntry>();
this.warningAsError = warningAsError;
this.core = core;
if (core.Options.WebRunner)
{
//this.WebMsgHandler = new WebOutputStream(core);
}
if (writer != null)
{
output = System.Console.Out;
System.Console.SetOut(writer);
}
}
public void LogWarning(RuntimeData.WarningID id, string msg, string path, int line, int col)
{
string filename = string.IsNullOrEmpty(path) ? string.Empty : path;
if (string.IsNullOrEmpty(filename) || line == -1 || col == -1)
{
ProtoCore.CodeGen.AuditCodeLocation(core, ref filename, ref line, ref col);
}
OutputMessage outputMsg = new OutputMessage(string.Format("> Runtime warning: {0}\n - \"{1}\" <line: {2}, col: {3}>", msg, filename, line, col));
System.Console.WriteLine(string.Format("> Runtime warning: {0}\n - \"{1}\" <line: {2}, col: {3}>", msg, filename, line, col));
if (WebMsgHandler != null)
{
WebMsgHandler.Write(outputMsg);
}
warnings.Add(new RuntimeData.WarningEntry { id = id, message = msg, Col = col, Line = line, Filename = filename });
if (core.Options.IsDeltaExecution)
{
core.LogErrorInGlobalMap(Core.ErrorType.Warning, msg, filename, line, col, BuildData.WarningID.kDefault, id);
}
if (null != MessageHandler)
{
OutputMessage.MessageType type = OutputMessage.MessageType.Warning;
MessageHandler.Write(new OutputMessage(type, msg.Trim(), filename, line, col));
}
CodeModel.CodeFile cf = new CodeModel.CodeFile { FilePath = path };
/*CodePoint = new CodeModel.CodePoint
{
SourceLocation = cf,
LineNo = line,
CharNo = col
};*/
}
public void LogWarning(RuntimeData.WarningID id, string msg)
{
LogWarning(id, msg, string.Empty, -1, -1);
}
public void LogWarning(RuntimeData.WarningID id, string msg, int blockID)
{
LogWarning(id, msg, string.Empty, -1, -1);
}
public bool ContainsWarning(RuntimeData.WarningID warnId)
{
foreach (RuntimeData.WarningEntry warn in warnings)
{
if (warnId == warn.id)
return true;
}
return false;
}
public void LogMethodResolutionWarning(Core core, string methodName, int classScope = ProtoCore.DSASM.Constants.kInvalidIndex, List<StackValue> arguments = null)
{
string message;
string propertyName;
Operator op;
if (CoreUtils.TryGetPropertyName(methodName, out propertyName))
{
if (classScope != Constants.kGlobalScope)
{
string classname = core.DSExecutable.classTable.ClassNodes[classScope].name;
message = string.Format(RuntimeData.WarningMessage.kPropertyOfClassNotFound, classname, propertyName);
}
else
{
message = string.Format(RuntimeData.WarningMessage.kPropertyNotFound, propertyName);
}
}
else if (CoreUtils.TryGetOperator(methodName, out op))
{
string strOp = Op.GetOpSymbol(op);
message = String.Format(RuntimeData.WarningMessage.kMethodResolutionFailureForOperator,
strOp,
core.TypeSystem.GetType((int)arguments[0].metaData.type),
core.TypeSystem.GetType((int)arguments[1].metaData.type));
}
else
{
message = string.Format(ProtoCore.RuntimeData.WarningMessage.kMethodResolutionFailure, methodName);
}
LogWarning(ProtoCore.RuntimeData.WarningID.kMethodResolutionFailure, message);
}
public void LogMethodNotAccessibleWarning(Core core, string methodName)
{
string message;
string propertyName;
if (CoreUtils.TryGetPropertyName(methodName, out propertyName))
{
message = String.Format(RuntimeData.WarningMessage.kPropertyInaccessible, propertyName);
}
else
{
message = String.Format(RuntimeData.WarningMessage.kMethodResolutionFailure, methodName);
}
LogWarning(ProtoCore.RuntimeData.WarningID.kMethodResolutionFailure, message);
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using Autodesk;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.CurvedBeam.CS
{
/// <summary>
/// This class inherits from IExternalCommand interface, and implements the Execute method to create Arc, BSpline beams.
/// </summary>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.UsingCommandData)]
public class Command : IExternalCommand
{
#region Class memeber variables
Autodesk.Revit.UI.UIApplication m_revit = null;
ArrayList m_beamMaps = new ArrayList(); // list of beams' type
ArrayList m_levels = new ArrayList(); // list of levels
#endregion
#region Command class properties
/// <summary>
/// list of all type of beams
/// </summary>
public ArrayList BeamMaps
{
get
{
return m_beamMaps;
}
}
/// <summary>
/// list of all levels
/// </summary>
public ArrayList LevelMaps
{
get
{
return m_levels;
}
}
#endregion
#region IExternalCommand interface implementation
///<summary>
/// Implement this method as an external command for Revit.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
/// <param name="message">A message that can be set by the external application
/// which will be displayed if a failure or cancellation is returned by
/// the external command.</param>
/// <param name="elements">A set of elements to which the external application
/// can add elements that are to be highlighted in case of failure or cancellation.</param>
/// <returns>Return the status of the external command.
/// A result of Succeeded means that the API external method functioned as expected.
/// Cancelled can be used to signify that the user cancelled the external operation
/// at some point. Failure should be returned if the application is unable to proceed with
/// the operation.</returns>
public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
{
m_revit = commandData.Application;
Transaction tran = new Transaction(m_revit.ActiveUIDocument.Document, "CurvedBeam");
tran.Start();
// if initialize failed return Result.Failed
bool initializeOK = Initialize();
if (!initializeOK)
{
return Autodesk.Revit.UI.Result.Failed;
}
// pop up new beam form
CurvedBeamForm displayForm = new CurvedBeamForm(this);
displayForm.ShowDialog();
tran.Commit();
return Autodesk.Revit.UI.Result.Succeeded;
}
#endregion
/// <summary>
/// iterate all the symbols of levels and beams
/// </summary>
/// <returns>A value that signifies if the initialization was successful for true or failed for false</returns>
private bool Initialize()
{
try
{
ElementClassFilter levelFilter = new ElementClassFilter(typeof(Level));
ElementClassFilter famFilter = new ElementClassFilter(typeof(Family));
LogicalOrFilter orFilter = new LogicalOrFilter(levelFilter, famFilter);
FilteredElementCollector collector = new FilteredElementCollector(m_revit.ActiveUIDocument.Document);
FilteredElementIterator i = collector.WherePasses(orFilter).GetElementIterator();
i.Reset();
bool moreElement = i.MoveNext();
while (moreElement)
{
object o = i.Current;
// add level to list
Level level = o as Level;
if (null != level)
{
m_levels.Add(new LevelMap(level));
goto nextLoop;
}
// get
Family f = o as Family;
if (null == f)
{
goto nextLoop;
}
foreach (object symbol in f.Symbols)
{
FamilySymbol familyType = symbol as FamilySymbol;
if (null == familyType)
{
goto nextLoop;
}
if (null == familyType.Category)
{
goto nextLoop;
}
// add symbols of beams and braces to lists
string categoryName = familyType.Category.Name;
if ("Structural Framing" == categoryName)
{
m_beamMaps.Add(new SymbolMap(familyType));
}
}
nextLoop:
moreElement = i.MoveNext();
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
return true;
}
/// <summary>
/// create an horizontal arc instance with specified z coordinate value
/// </summary>
public Arc CreateArc(double z)
{
Autodesk.Revit.DB.XYZ center = new Autodesk.Revit.DB.XYZ (0, 0, z);
double radius = 20.0;
double startAngle = 0.0;
double endAngle = 5.0;
Autodesk.Revit.DB.XYZ xAxis = new Autodesk.Revit.DB.XYZ (1, 0, 0);
Autodesk.Revit.DB.XYZ yAxis = new Autodesk.Revit.DB.XYZ (0, 1, 0);
return m_revit.Application.Create.NewArc(center, radius, startAngle, endAngle, xAxis, yAxis);
}
/// <summary>
/// create a horizontal partial ellipse instance with specified z coordinate value
/// </summary>
public Ellipse CreateEllipse(double z)
{
Autodesk.Revit.DB.XYZ center = new Autodesk.Revit.DB.XYZ (0, 0, z);
double radX = 30;
double radY = 50;
Autodesk.Revit.DB.XYZ xVec = new Autodesk.Revit.DB.XYZ (1, 0, 0);
Autodesk.Revit.DB.XYZ yVec = new Autodesk.Revit.DB.XYZ (0, 1, 0);
double param0 = 0.0;
double param1 = 3.1415;
Ellipse ellpise = m_revit.Application.Create.NewEllipse(center, radX, radY, xVec, yVec, param0, param1);
m_revit.ActiveUIDocument.Document.Regenerate();
return ellpise;
}
/// <summary>
/// create a horizontal nurbspline instance with specified z coordinate value
/// </summary>
public NurbSpline CreateNurbSpline(double z)
{
// create control points with same z value
List<XYZ> ctrPoints = new List<XYZ>();
Autodesk.Revit.DB.XYZ xyz1 = new Autodesk.Revit.DB.XYZ (-41.887503610431267, -9.0290629129782189, z);
Autodesk.Revit.DB.XYZ xyz2 = new Autodesk.Revit.DB.XYZ (-9.27600019217055, 0.32213521486563046, z);
Autodesk.Revit.DB.XYZ xyz3 = new Autodesk.Revit.DB.XYZ (9.27600019217055, 0.32213521486563046, z);
Autodesk.Revit.DB.XYZ xyz4 = new Autodesk.Revit.DB.XYZ (41.887503610431267, 9.0290629129782189, z);
ctrPoints.Add(xyz1); ctrPoints.Add(xyz2); ctrPoints.Add(xyz3);
ctrPoints.Add(xyz4);
DoubleArray weights = new DoubleArray();
double w1 = 1, w2 = 1, w3 = 1, w4 = 1;
weights.Append(ref w1); weights.Append(ref w2); weights.Append(ref w3);
weights.Append(ref w4);
DoubleArray knots = new DoubleArray();
double k0 = 0, k1 = 0, k2 = 0, k3 = 0, k4 = 34.425128, k5 = 34.425128, k6 = 34.425128, k7 = 34.425128;
knots.Append(ref k0); knots.Append(ref k1); knots.Append(ref k2); knots.Append(ref k3);
knots.Append(ref k4); knots.Append(ref k5); knots.Append(ref k6);
knots.Append(ref k7);
NurbSpline detailNurbSpline = m_revit.Application.Create.NewNurbSpline(ctrPoints, weights, knots, 3, false, true);
m_revit.ActiveUIDocument.Document.Regenerate();
return detailNurbSpline;
}
/// <summary>
/// create a curved beam
/// </summary>
/// <param name="fsBeam">beam type</param>
/// <param name="curve">Curve of this beam.</param>
/// <param name="level">beam's reference level</param>
/// <returns></returns>
public bool CreateCurvedBeam(FamilySymbol fsBeam, Curve curve, Level level)
{
FamilyInstance beam;
try
{
beam = m_revit.ActiveUIDocument.Document.Create.NewFamilyInstance(curve, fsBeam, level, StructuralType.Beam);
if (null == beam)
{
return false;
}
// get beam location curve
LocationCurve beamCurve = beam.Location as LocationCurve;
if (null == beamCurve)
{
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Revit");
return false;
}
// regenerate document
m_revit.ActiveUIDocument.Document.Regenerate();
return true;
}
}
/// <summary>
/// assistant class contains symbol and it's name
/// </summary>
public class SymbolMap
{
#region SymbolMap class member variables
string m_symbolName = "";
FamilySymbol m_symbol = null;
#endregion
/// <summary>
/// constructor without parameter is forbidden
/// </summary>
private SymbolMap()
{
// no operation
}
/// <summary>
/// constructor
/// </summary>
/// <param name="symbol">family symbol</param>
public SymbolMap(FamilySymbol symbol)
{
m_symbol = symbol;
string familyName = "";
if (null != symbol.Family)
{
familyName = symbol.Family.Name;
}
m_symbolName = familyName + " : " + symbol.Name;
}
/// <summary>
/// SymbolName property
/// </summary>
public string SymbolName
{
get
{
return m_symbolName;
}
}
/// <summary>
/// ElementType property
/// </summary>
public FamilySymbol ElementType
{
get
{
return m_symbol;
}
}
}
/// <summary>
/// assistant class contains level and it's name
/// </summary>
public class LevelMap
{
#region LevelMap class member variable
string m_levelName = "";
Level m_level = null;
#endregion
#region LevelMap Constructors
/// <summary>
/// constructor without parameter is forbidden
/// </summary>
private LevelMap()
{
// no operation
}
/// <summary>
/// constructor
/// </summary>
/// <param name="level">level</param>
public LevelMap(Level level)
{
m_level = level;
m_levelName = level.Name;
}
#endregion
#region LevelMap properties
/// <summary>
/// LevelName property
/// </summary>
public string LevelName
{
get
{
return m_levelName;
}
}
/// <summary>
/// Level property
/// </summary>
public Level Level
{
get
{
return m_level;
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using FileHelpers.Converters;
using FileHelpers.Core;
using FileHelpers.Options;
namespace FileHelpers
{
/// <summary>
/// Base class for all Field Types.
/// Implements all the basic functionality of a field in a typed file.
/// </summary>
public abstract class FieldBase
{
#region " Private & Internal Fields "
// --------------------------------------------------------------
// WARNING !!!
// Remember to add each of these fields to the clone method !!
// --------------------------------------------------------------
/// <summary>
/// type of object to be created, eg DateTime
/// </summary>
public Type FieldType { get; private set; }
/// <summary>
/// Provider to convert to and from text
/// </summary>
public ConverterBase Converter { get; private set; }
/// <summary>
/// Number of extra characters used, delimiters and quote characters
/// </summary>
internal virtual int CharsToDiscard => 0;
/// <summary>
/// Field type of an array or it is just fieldType.
/// What actual object will be created
/// </summary>
internal Type FieldTypeInternal { get; private set; }
/// <summary>
/// Is this field an array?
/// </summary>
public bool IsArray { get; private set; }
/// <summary>
/// Array must have this many entries
/// </summary>
public int ArrayMinLength { get; set; }
/// <summary>
/// Array may have this many entries, if equal to ArrayMinLength then
/// it is a fixed length array
/// </summary>
public int ArrayMaxLength { get; set; }
/// <summary>
/// Seems to be duplicate of FieldTypeInternal except it is ONLY set
/// for an array
/// </summary>
private Type ArrayType { get; set; }
/// <summary>
/// Do we process this field but not store the value
/// </summary>
public bool Discarded { get; set; }
/// <summary>
/// Value to use if input is null or empty
/// </summary>
internal object NullValue { get; private set; }
/// <summary>
/// Are we a simple string field we can just assign to
/// </summary>
private bool IsStringField { get; set; }
/// <summary>
/// Details about the extraction criteria
/// </summary>
internal FieldInfo FieldInfo { get; private set; }
/// <summary>
/// indicates whether we trim leading and/or trailing whitespace
/// </summary>
public TrimMode TrimMode { get; set; }
/// <summary>
/// Character to chop off front and / rear of the string
/// </summary>
internal char[] TrimChars { get; set; }
/// <summary>
/// The field may not be present on the input data (line not long enough)
/// </summary>
public bool IsOptional
{
get; set;
}
/// <summary>
/// The next field along is optional, optimise processing next records
/// </summary>
internal bool NextIsOptional
{
get
{
if (Parent.FieldCount > ParentIndex + 1)
return Parent.Fields[ParentIndex + 1].IsOptional;
return false;
}
}
/// <summary>
/// Am I the first field in an array list
/// </summary>
internal bool IsFirst => ParentIndex == 0;
/// <summary>
/// Am I the last field in the array list
/// </summary>
internal bool IsLast => ParentIndex == Parent.FieldCount - 1;
/// <summary>
/// Set from the FieldInNewLIneAtribute. This field begins on a new
/// line of the file
/// </summary>
internal bool InNewLine { get; private set; }
/// <summary>
/// Order of the field in the file layout
/// </summary>
internal int? FieldOrder { get; private set; }
/// <summary>
/// Can null be assigned to this value type, for example not int or
/// DateTime
/// </summary>
internal bool IsNullableType { get; private set; }
/// <summary>
/// Name of the field without extra characters (eg property)
/// </summary>
internal string FieldFriendlyName { get; private set; }
/// <summary>
/// The field must be not be empty
/// </summary>
public bool IsNotEmpty { get; set; }
/// <summary>
/// Caption of the field displayed in header row (see EngineBase.GetFileHeader)
/// </summary>
internal string FieldCaption { get; private set; }
// --------------------------------------------------------------
// WARNING !!!
// Remember to add each of these fields to the clone method !!
// --------------------------------------------------------------
/// <summary>
/// Fieldname of the field we are storing
/// </summary>
internal string FieldName => FieldInfo.Name;
#endregion
#region " CreateField "
/// <summary>
/// Check the Attributes on the field and return a structure containing
/// the settings for this file.
/// </summary>
/// <param name="fi">Information about this field</param>
/// <param name="recordAttribute">Type of record we are reading</param>
/// <returns>Null if not used</returns>
public static FieldBase CreateField(FieldInfo fi, TypedRecordAttribute recordAttribute)
{
FieldBase res = null;
MemberInfo mi = fi;
var memberName = "The field: '" + fi.Name;
Type fieldType = fi.FieldType;
string fieldFriendlyName = AutoPropertyName(fi);
if (string.IsNullOrEmpty(fieldFriendlyName) == false)
{
var prop = fi.DeclaringType.GetProperty(fieldFriendlyName);
if (prop != null)
{
memberName = "The property: '" + prop.Name;
mi = prop;
}
else
{
fieldFriendlyName = null;
}
}
// If ignored, return null
#pragma warning disable 612,618 // disable obsolete warning
if (mi.IsDefined(typeof(FieldNotInFileAttribute), true) ||
mi.IsDefined(typeof(FieldIgnoredAttribute), true) ||
mi.IsDefined(typeof(FieldHiddenAttribute), true))
#pragma warning restore 612,618
return null;
var attributes = (FieldAttribute[])mi.GetCustomAttributes(typeof(FieldAttribute), true);
// CHECK USAGE ERRORS !!!
// Fixed length record and no attributes at all
if (recordAttribute is FixedLengthRecordAttribute &&
attributes.Length == 0)
{
throw new BadUsageException(memberName +
"' must be marked with the FieldFixedLength attribute because the record class is marked with FixedLengthRecord.");
}
if (attributes.Length > 1)
{
throw new BadUsageException(memberName +
"' has a FieldFixedLength and a FieldDelimiter attribute.");
}
if (recordAttribute is DelimitedRecordAttribute &&
mi.IsDefined(typeof(FieldAlignAttribute), false))
{
throw new BadUsageException(memberName +
"' can't be marked with the FieldAlign attribute - it is only valid for fixed length records and are used only for writing.");
}
if (fieldType.IsArray == false &&
mi.IsDefined(typeof(FieldArrayLengthAttribute), false))
{
throw new BadUsageException(memberName +
"' can't be marked with the FieldArrayLength attribute - it is only valid for array fields.");
}
// PROCESS IN NORMAL CONDITIONS
if (attributes.Length > 0)
{
FieldAttribute fieldAttb = attributes[0];
if (fieldAttb is FieldFixedLengthAttribute)
{
// Fixed Field
if (recordAttribute is DelimitedRecordAttribute)
{
throw new BadUsageException(memberName +
"' can't be marked with FieldFixedLength attribute, it is only for the FixedLengthRecords not for delimited ones.");
}
var attbFixedLength = (FieldFixedLengthAttribute)fieldAttb;
var attbAlign = Attributes.GetFirst<FieldAlignAttribute>(mi);
res = new FixedLengthField(fi,
attbFixedLength.Length,
attbFixedLength.OverflowMode,
attbAlign,
recordAttribute.DefaultCultureName);
((FixedLengthField)res).FixedMode = ((FixedLengthRecordAttribute)recordAttribute).FixedMode;
}
else if (fieldAttb is FieldDelimiterAttribute)
{
// Delimited Field
if (recordAttribute is FixedLengthRecordAttribute)
{
throw new BadUsageException(memberName +
"' can't be marked with FieldDelimiter attribute, it is only for DelimitedRecords not for fixed ones.");
}
res = new DelimitedField(fi,
((FieldDelimiterAttribute)fieldAttb).Delimiter,
recordAttribute.DefaultCultureName);
}
else
{
throw new BadUsageException(
"Custom field attributes are not currently supported. Unknown attribute: " +
fieldAttb.GetType().Name + " on field: " + fi.Name);
}
}
else // attributes.Length == 0
{
var delimitedRecordAttribute = recordAttribute as DelimitedRecordAttribute;
if (delimitedRecordAttribute != null)
{
res = new DelimitedField(fi,
delimitedRecordAttribute.Separator,
recordAttribute.DefaultCultureName);
}
}
if (res != null)
{
// FieldDiscarded
res.Discarded = mi.IsDefined(typeof(FieldValueDiscardedAttribute), false);
// FieldTrim
Attributes.WorkWithFirst<FieldTrimAttribute>(mi,
(x) =>
{
res.TrimMode = x.TrimMode;
res.TrimChars = x.TrimChars;
});
// FieldQuoted
Attributes.WorkWithFirst<FieldQuotedAttribute>(mi,
(x) =>
{
if (res is FixedLengthField)
{
throw new BadUsageException(
memberName +
"' can't be marked with FieldQuoted attribute, it is only for delimited records.");
}
((DelimitedField)res).QuoteChar =
x.QuoteChar;
((DelimitedField)res).QuoteMode =
x.QuoteMode;
((DelimitedField)res).QuoteMultiline =
x.QuoteMultiline;
});
// FieldOrder
Attributes.WorkWithFirst<FieldOrderAttribute>(mi, x => res.FieldOrder = x.Order);
// FieldCaption
Attributes.WorkWithFirst<FieldCaptionAttribute>(mi, x => res.FieldCaption = x.Caption);
// FieldOptional
res.IsOptional = mi.IsDefined(typeof(FieldOptionalAttribute), false);
// FieldInNewLine
res.InNewLine = mi.IsDefined(typeof(FieldInNewLineAttribute), false);
// FieldNotEmpty
res.IsNotEmpty = mi.IsDefined(typeof(FieldNotEmptyAttribute), false);
// FieldArrayLength
if (fieldType.IsArray)
{
res.IsArray = true;
res.ArrayType = fieldType.GetElementType();
// MinValue indicates that there is no FieldArrayLength in the array
res.ArrayMinLength = int.MinValue;
res.ArrayMaxLength = int.MaxValue;
Attributes.WorkWithFirst<FieldArrayLengthAttribute>(mi,
(x) =>
{
res.ArrayMinLength = x.MinLength;
res.ArrayMaxLength = x.MaxLength;
if (res.ArrayMaxLength < res.ArrayMinLength ||
res.ArrayMinLength < 0 ||
res.ArrayMaxLength <= 0)
{
throw new BadUsageException(memberName +
" has invalid length values in the [FieldArrayLength] attribute.");
}
});
}
}
if (string.IsNullOrEmpty(res.FieldFriendlyName))
res.FieldFriendlyName = res.FieldName;
return res;
}
internal RecordOptions Parent { private get; set; }
internal int ParentIndex { private get; set; }
internal static string AutoPropertyName(FieldInfo fi)
{
if (fi.IsDefined(typeof(CompilerGeneratedAttribute), false))
{
if (fi.Name.EndsWith("__BackingField") &&
fi.Name.StartsWith("<") &&
fi.Name.Contains(">"))
return fi.Name.Substring(1, fi.Name.IndexOf(">") - 1);
}
if (fi.IsDefined(typeof(DebuggerBrowsableAttribute), false))
{
if (fi.Name.EndsWith("@") && !fi.IsPublic)
{
var name = fi.Name.Substring(0, fi.Name.Length - 1);
if (fi.DeclaringType?.GetProperty(name) != null)
return name;
}
}
return "";
}
#endregion
#region " Constructor "
/// <summary>
/// Create a field base without any configuration
/// </summary>
internal FieldBase()
{
IsNullableType = false;
TrimMode = TrimMode.None;
FieldOrder = null;
InNewLine = false;
IsOptional = false;
TrimChars = null;
NullValue = null;
IsArray = false;
IsNotEmpty = false;
}
/// <summary>
/// Create a field base from a fieldinfo object
/// Verify the settings against the actual field to ensure it will work.
/// </summary>
/// <param name="fi">Field Info Object</param>
/// <param name="defaultCultureName">Default culture name used for each properties if no converter is specified otherwise. If null, the default decimal separator (".") will be used.</param>
internal FieldBase(FieldInfo fi, string defaultCultureName = null)
: this()
{
FieldInfo = fi;
FieldType = FieldInfo.FieldType;
MemberInfo attibuteTarget = fi;
FieldFriendlyName = AutoPropertyName(fi);
if (string.IsNullOrEmpty(FieldFriendlyName) == false)
{
var prop = fi.DeclaringType.GetProperty(FieldFriendlyName);
if (prop == null)
{
FieldFriendlyName = null;
}
else
{
attibuteTarget = prop;
}
}
if (FieldType.IsArray)
FieldTypeInternal = FieldType.GetElementType();
else
FieldTypeInternal = FieldType;
IsStringField = FieldTypeInternal == typeof(string);
object[] attribs = attibuteTarget.GetCustomAttributes(typeof(FieldConverterAttribute), true);
if (attribs.Length > 0)
{
var conv = (FieldConverterAttribute)attribs[0];
Converter = conv.Converter;
conv.ValidateTypes(FieldInfo);
}
else
Converter = ConvertHelpers.GetDefaultConverter(FieldFriendlyName ?? fi.Name,
FieldType,
defaultCultureName: defaultCultureName);
if (Converter != null)
Converter.mDestinationType = FieldTypeInternal;
attribs = attibuteTarget.GetCustomAttributes(typeof(FieldNullValueAttribute), true);
if (attribs.Length > 0)
{
NullValue = ((FieldNullValueAttribute)attribs[0]).NullValue;
if (NullValue != null)
{
if (!FieldTypeInternal.IsAssignableFrom(NullValue.GetType()))
{
throw new BadUsageException("The NullValue is of type: " + NullValue.GetType().Name +
" that is not asignable to the field " + FieldInfo.Name +
" of type: " +
FieldTypeInternal.Name);
}
}
}
IsNullableType = FieldTypeInternal.IsValueType &&
FieldTypeInternal.IsGenericType &&
FieldTypeInternal.GetGenericTypeDefinition() == typeof(Nullable<>);
}
#endregion
#region " MustOverride (String Handling) "
/// <summary>
/// Extract the string from the underlying data, removes quotes
/// characters for example
/// </summary>
/// <param name="line">Line to parse data from</param>
/// <returns>Slightly processed string from the data</returns>
internal abstract ExtractedInfo ExtractFieldString(LineInfo line);
private void CreateFieldString(StringBuilder sb, object fieldValue, bool isLast)
{
string field = ConvertToString(fieldValue);
CreateFieldString(sb, field, isLast);
}
/// <summary>
/// Create a text block containing the field from definition
/// </summary>
/// <param name="sb">Append string to output</param>
/// <param name="field">Field we are adding</param>
/// <param name="isLast">Indicates if we are processing last field</param>
protected abstract void CreateFieldString(StringBuilder sb, string field, bool isLast);
private string ConvertToString(object fieldValue)
{
if (Converter == null)
{
if (fieldValue == null)
return string.Empty;
else
return fieldValue.ToString();
}
else
return Converter.FieldToString(fieldValue);
}
#endregion
#region " ExtractValue "
/// <summary>
/// Get the data out of the records
/// </summary>
/// <param name="line">Line handler containing text</param>
/// <returns></returns>
internal object ExtractFieldValue(LineInfo line)
{
//-> extract only what I need
if (InNewLine)
{
// Any trailing characters, terminate
if (line.EmptyFromPos() == false)
{
throw new BadUsageException(line,
"Text '" + line.CurrentString +
"' found before the new line of the field: " + FieldInfo.Name +
" (this is not allowed when you use [FieldInNewLine])");
}
line.ReLoad(line.mReader.ReadNextLine());
if (line.mLineStr == null)
{
throw new BadUsageException(line,
"End of stream found parsing the field " + FieldInfo.Name +
". Please check the class record.");
}
}
if (IsArray == false)
{
ExtractedInfo info = ExtractFieldString(line);
if (info.mCustomExtractedString == null)
line.mCurrentPos = info.ExtractedTo + 1;
line.mCurrentPos += CharsToDiscard; //total;
if (Discarded)
return GetDiscardedNullValue();
else
return AssignFromString(info, line).Value;
}
else
{
if (ArrayMinLength <= 0)
ArrayMinLength = 0;
int i = 0;
var res = new ArrayList(Math.Max(ArrayMinLength, 10));
while (line.mCurrentPos - CharsToDiscard < line.mLineStr.Length &&
i < ArrayMaxLength)
{
ExtractedInfo info = ExtractFieldString(line);
if (info.mCustomExtractedString == null)
line.mCurrentPos = info.ExtractedTo + 1;
line.mCurrentPos += CharsToDiscard;
try
{
var value = AssignFromString(info, line);
if (value.NullValueUsed &&
i == 0 &&
line.IsEOL())
break;
res.Add(value.Value);
}
catch (NullValueNotFoundException)
{
if (i == 0)
break;
else
throw;
}
i++;
}
if (res.Count < ArrayMinLength)
{
throw new InvalidOperationException(
$"Line: {line.mReader.LineNumber.ToString()} Column: {line.mCurrentPos.ToString()} Field: {FieldInfo.Name}. The array has only {res.Count} values, less than the minimum length of {ArrayMinLength}");
}
else if (IsLast && line.IsEOL() == false)
{
throw new InvalidOperationException(
$"Line: {line.mReader.LineNumber} Column: {line.mCurrentPos} Field: {FieldInfo.Name}. The array has more values than the maximum length of {ArrayMaxLength}");
}
// TODO: is there a reason we go through all the array processing then discard it
if (Discarded)
return null;
else
return res.ToArray(ArrayType);
}
}
#region " AssignFromString "
private struct AssignResult
{
public object Value;
public bool NullValueUsed;
}
/// <summary>
/// Create field object after extracting the string from the underlying
/// input data
/// </summary>
/// <param name="fieldString">Information extracted?</param>
/// <param name="line">Underlying input data</param>
/// <returns>Object to assign to field</returns>
private AssignResult AssignFromString(ExtractedInfo fieldString, LineInfo line)
{
var extractedString = fieldString.ExtractedString();
try
{
object val;
if (IsNotEmpty && string.IsNullOrEmpty(extractedString))
{
throw new InvalidOperationException("The value is empty and must be populated.");
}
else if (Converter == null)
{
if (IsStringField)
val = TrimString(extractedString);
else
{
extractedString = extractedString.Trim();
if (extractedString.Length == 0)
{
return new AssignResult
{
Value = GetNullValue(line),
NullValueUsed = true
};
}
else
val = Convert.ChangeType(extractedString, FieldTypeInternal, null);
}
}
else
{
var trimmedString = extractedString.Trim();
if (Converter.CustomNullHandling == false &&
trimmedString.Length == 0)
{
return new AssignResult
{
Value = GetNullValue(line),
NullValueUsed = true
};
}
else
{
if (TrimMode == TrimMode.Both)
val = Converter.StringToField(trimmedString);
else
val = Converter.StringToField(TrimString(extractedString));
if (val == null)
{
return new AssignResult
{
Value = GetNullValue(line),
NullValueUsed = true
};
}
}
}
return new AssignResult
{
Value = val
};
}
catch (ConvertException ex)
{
ex.FieldName = FieldInfo.Name;
ex.LineNumber = line.mReader.LineNumber;
ex.ColumnNumber = fieldString.ExtractedFrom + 1;
throw;
}
catch (BadUsageException)
{
throw;
}
catch (Exception ex)
{
if (Converter == null ||
Converter.GetType().Assembly == typeof(FieldBase).Assembly)
{
throw new ConvertException(extractedString,
FieldTypeInternal,
FieldInfo.Name,
line.mReader.LineNumber,
fieldString.ExtractedFrom + 1,
ex.Message,
ex);
}
else
{
throw new ConvertException(extractedString,
FieldTypeInternal,
FieldInfo.Name,
line.mReader.LineNumber,
fieldString.ExtractedFrom + 1,
"Your custom converter: " + Converter.GetType().Name + " throws an " + ex.GetType().Name +
" with the message: " + ex.Message,
ex);
}
}
}
private string TrimString(string extractedString)
{
switch (TrimMode)
{
case TrimMode.None:
return extractedString;
case TrimMode.Both:
return extractedString.Trim();
case TrimMode.Left:
return extractedString.TrimStart();
case TrimMode.Right:
return extractedString.TrimEnd();
default:
throw new Exception("Trim mode invalid in FieldBase.TrimString -> " + TrimMode.ToString());
}
}
/// <summary>
/// Convert a null value into a representation,
/// allows for a null value override
/// </summary>
/// <param name="line">input line to read, used for error messages</param>
/// <returns>Null value for object</returns>
private object GetNullValue(LineInfo line)
{
if (NullValue == null)
{
if (FieldTypeInternal.IsValueType)
{
if (IsNullableType)
return null;
string msg = "No value found for the value type field: '" + FieldInfo.Name + "' Class: '" +
FieldInfo.DeclaringType.Name + "'. " + Environment.NewLine
+
"You must use the [FieldNullValue] attribute because this is a value type and can't be null or use a Nullable Type instead of the current type.";
throw new NullValueNotFoundException(line, msg);
}
else
return null;
}
else
return NullValue;
}
/// <summary>
/// Get the null value that represent a discarded value
/// </summary>
/// <returns>null value of discard?</returns>
private object GetDiscardedNullValue()
{
if (NullValue == null)
{
if (FieldTypeInternal.IsValueType)
{
if (IsNullableType)
return null;
string msg = "The field: '" + FieldInfo.Name + "' Class: '" +
FieldInfo.DeclaringType.Name +
"' is from a value type: " + FieldInfo.FieldType.Name +
" and is discarded (null) you must provide a [FieldNullValue] attribute.";
throw new BadUsageException(msg);
}
else
return null;
}
else
return NullValue;
}
#endregion
#region " CreateValueForField "
/// <summary>
/// Convert a field value into a write able value
/// </summary>
/// <param name="fieldValue">object value to convert</param>
/// <returns>converted value</returns>
public object CreateValueForField(object fieldValue)
{
object val;
if (fieldValue == null)
{
if (NullValue == null)
{
if (FieldTypeInternal.IsValueType &&
Nullable.GetUnderlyingType(FieldTypeInternal) == null)
{
throw new BadUsageException(
"Null Value found. You must specify a FieldNullValueAttribute in the " + FieldInfo.Name +
" field of type " + FieldTypeInternal.Name + ", because this is a ValueType.");
}
else
val = null;
}
else
val = NullValue;
}
else if (FieldTypeInternal == fieldValue.GetType())
val = fieldValue;
else
{
if (Converter == null)
val = Convert.ChangeType(fieldValue, FieldTypeInternal, null);
else
{
try
{
if (Nullable.GetUnderlyingType(FieldTypeInternal) != null &&
Nullable.GetUnderlyingType(FieldTypeInternal) == fieldValue.GetType())
val = fieldValue;
else
val = Convert.ChangeType(fieldValue, FieldTypeInternal, null);
}
catch
{
val = Converter.StringToField(fieldValue.ToString());
}
}
}
return val;
}
#endregion
#endregion
#region " AssignToString "
/// <summary>
/// convert field to string value and assign to a string builder
/// buffer for output
/// </summary>
/// <param name="sb">buffer to collect record</param>
/// <param name="fieldValue">value to convert</param>
internal void AssignToString(StringBuilder sb, object fieldValue)
{
if (InNewLine)
sb.Append(Environment.NewLine);
if (IsArray)
{
if (fieldValue == null)
{
if (0 < ArrayMinLength)
{
throw new InvalidOperationException(
$"Field: {FieldInfo.Name}. The array is null, but the minimum length is {ArrayMinLength}");
}
return;
}
var array = (IList)fieldValue;
if (array.Count < ArrayMinLength)
{
throw new InvalidOperationException(
$"Field: {FieldInfo.Name}. The array has {array.Count} values, but the minimum length is {ArrayMinLength}");
}
if (array.Count > ArrayMaxLength)
{
throw new InvalidOperationException(
$"Field: {FieldInfo.Name}. The array has {array.Count} values, but the maximum length is {ArrayMaxLength}");
}
for (int i = 0; i < array.Count; i++)
{
object val = array[i];
CreateFieldString(sb, val, IsLast && i == array.Count - 1);
}
}
else
CreateFieldString(sb, fieldValue, IsLast);
}
#endregion
/// <summary>
/// Copy the field object
/// </summary>
/// <returns>a complete copy of the Field object</returns>
internal FieldBase Clone()
{
var res = CreateClone();
res.FieldType = FieldType;
res.Converter = Converter;
res.FieldTypeInternal = FieldTypeInternal;
res.IsArray = IsArray;
res.ArrayType = ArrayType;
res.ArrayMinLength = ArrayMinLength;
res.ArrayMaxLength = ArrayMaxLength;
res.NullValue = NullValue;
res.IsStringField = IsStringField;
res.FieldInfo = FieldInfo;
res.TrimMode = TrimMode;
res.TrimChars = TrimChars;
res.IsOptional = IsOptional;
res.InNewLine = InNewLine;
res.FieldOrder = FieldOrder;
res.IsNullableType = IsNullableType;
res.Discarded = Discarded;
res.FieldFriendlyName = FieldFriendlyName;
res.IsNotEmpty = IsNotEmpty;
res.FieldCaption = FieldCaption;
res.Parent = Parent;
res.ParentIndex = ParentIndex;
return res;
}
/// <summary>
/// Add the extra details that derived classes create
/// </summary>
/// <returns>field clone of right type</returns>
protected abstract FieldBase CreateClone();
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
namespace Microsoft.PowerShell.Telemetry
{
/// <summary>
/// The category of telemetry.
/// </summary>
internal enum TelemetryType
{
/// <summary>
/// Telemetry of the application type (cmdlet, script, etc).
/// </summary>
ApplicationType,
/// <summary>
/// Send telemetry when we load a module, only module names in the s_knownModules list
/// will be reported, otherwise it will be "anonymous".
/// </summary>
ModuleLoad,
/// <summary>
/// Send telemetry when we load a module using Windows compatibility feature, only module names in the s_knownModules list
/// will be reported, otherwise it will be "anonymous".
/// </summary>
WinCompatModuleLoad,
/// <summary>
/// Send telemetry for experimental module feature activation.
/// All experimental engine features will be have telemetry.
/// </summary>
ExperimentalEngineFeatureActivation,
/// <summary>
/// Send telemetry for experimental module feature activation.
/// Experimental module features will send telemetry based on the module it is in.
/// If we send telemetry for the module, we will also do so for any experimental feature
/// in that module.
/// </summary>
ExperimentalModuleFeatureActivation,
/// <summary>
/// Send telemetry for each PowerShell.Create API.
/// </summary>
PowerShellCreate,
/// <summary>
/// Remote session creation.
/// </summary>
RemoteSessionOpen,
}
/// <summary>
/// Send up telemetry for startup.
/// </summary>
public static class ApplicationInsightsTelemetry
{
// If this env var is true, yes, or 1, telemetry will NOT be sent.
private const string _telemetryOptoutEnvVar = "POWERSHELL_TELEMETRY_OPTOUT";
// PSCoreInsight2 telemetry key
// private const string _psCoreTelemetryKey = "ee4b2115-d347-47b0-adb6-b19c2c763808"; // Production
private const string _psCoreTelemetryKey = "d26a5ef4-d608-452c-a6b8-a4a55935f70d"; // V7 Preview 3
// Use "anonymous" as the string to return when you can't report a name
private const string _anonymous = "anonymous";
// the telemetry failure string
private const string _telemetryFailure = "TELEMETRY_FAILURE";
// Telemetry client to be reused when we start sending more telemetry
private static TelemetryClient s_telemetryClient { get; }
// the unique identifier for the user, when we start we
private static string s_uniqueUserIdentifier { get; }
// the session identifier
private static string s_sessionId { get; }
// private semaphore to determine whether we sent the startup telemetry event
private static int s_startupEventSent = 0;
/// Use a hashset for quick lookups.
/// We send telemetry only a known set of modules.
/// If it's not in the list (initialized in the static constructor), then we report anonymous.
private static readonly HashSet<string> s_knownModules;
/// <summary>Gets a value indicating whether telemetry can be sent.</summary>
public static bool CanSendTelemetry { get; private set; }
/// <summary>
/// Initializes static members of the <see cref="ApplicationInsightsTelemetry"/> class.
/// Static constructor determines whether telemetry is to be sent, and then
/// sets the telemetry key and set the telemetry delivery mode.
/// Creates the session ID and initializes the HashSet of known module names.
/// Gets or constructs the unique identifier.
/// </summary>
static ApplicationInsightsTelemetry()
{
// If we can't send telemetry, there's no reason to do any of this
CanSendTelemetry = !GetEnvironmentVariableAsBool(name: _telemetryOptoutEnvVar, defaultValue: false);
if (CanSendTelemetry)
{
TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
configuration.InstrumentationKey = _psCoreTelemetryKey;
// Set this to true to reduce latency during development
configuration.TelemetryChannel.DeveloperMode = false;
s_telemetryClient = new TelemetryClient(configuration);
// Be sure to obscure any information about the client node.
s_telemetryClient.Context.Cloud.RoleInstance = string.Empty;
s_telemetryClient.Context.GetInternalContext().NodeName = string.Empty;
s_sessionId = Guid.NewGuid().ToString();
// use a hashset when looking for module names, it should be quicker than a string comparison
s_knownModules = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"AADRM",
"activedirectory",
"adcsadministration",
"adcsdeployment",
"addsadministration",
"addsdeployment",
"adfs",
"adrms",
"adrmsadmin",
"agpm",
"appbackgroundtask",
"applocker",
"appv",
"appvclient",
"appvsequencer",
"appvserver",
"appx",
"assignedaccess",
"Az",
"Az.Accounts",
"Az.Advisor",
"Az.Aks",
"Az.AlertsManagement",
"Az.AnalysisServices",
"Az.ApiManagement",
"Az.ApplicationInsights",
"Az.Attestation",
"Az.Automation",
"Az.Batch",
"Az.Billing",
"Az.Blueprint",
"Az.Cdn",
"Az.CognitiveServices",
"Az.Compute",
"Az.ContainerInstance",
"Az.ContainerRegistry",
"Az.DataBox",
"Az.DataFactory",
"Az.DataLakeAnalytics",
"Az.DataLakeStore",
"Az.DataMigration",
"Az.DataShare",
"Az.DeploymentManager",
"Az.DeviceProvisioningServices",
"Az.DevSpaces",
"Az.DevTestLabs",
"Az.Dns",
"Az.EventGrid",
"Az.EventHub",
"Az.FrontDoor",
"Az.GuestConfiguration",
"Az.HDInsight",
"Az.HealthcareApis",
"Az.IotCentral",
"Az.IotHub",
"Az.KeyVault",
"Az.Kusto",
"Az.LogicApp",
"Az.MachineLearning",
"Az.ManagedServiceIdentity",
"Az.ManagedServices",
"Az.ManagementPartner",
"Az.Maps",
"Az.MarketplaceOrdering",
"Az.Media",
"Az.MixedReality",
"Az.Monitor",
"Az.NetAppFiles",
"Az.Network",
"Az.NotificationHubs",
"Az.OperationalInsights",
"Az.Peering",
"Az.PolicyInsights",
"Az.PowerBIEmbedded",
"Az.PrivateDns",
"Az.RecoveryServices",
"Az.RedisCache",
"Az.Relay",
"Az.Reservations",
"Az.ResourceGraph",
"Az.Resources",
"Az.Search",
"Az.Security",
"Az.ServiceBus",
"Az.ServiceFabric",
"Az.SignalR",
"Az.Sql",
"Az.Storage",
"Az.StorageSync",
"Az.StorageTable",
"Az.StreamAnalytics",
"Az.Subscription",
"Az.TrafficManager",
"Az.Websites",
"Azs.Azurebridge.Admin",
"Azs.Backup.Admin",
"Azs.Commerce.Admin",
"Azs.Compute.Admin",
"Azs.Fabric.Admin",
"Azs.Gallery.Admin",
"Azs.Infrastructureinsights.Admin",
"Azs.Keyvault.Admin",
"Azs.Network.Admin",
"Azs.Storage.Admin",
"Azs.Subscriptions",
"Azs.Subscriptions.Admin",
"Azs.Update.Admin",
"AzStorageTable",
"Azure",
"Azure.AnalysisServices",
"Azure.Storage",
"AzureAD",
"AzureInformationProtection",
"AzureRM.Aks",
"AzureRM.AnalysisServices",
"AzureRM.ApiManagement",
"AzureRM.ApplicationInsights",
"AzureRM.Automation",
"AzureRM.Backup",
"AzureRM.Batch",
"AzureRM.Billing",
"AzureRM.Cdn",
"AzureRM.CognitiveServices",
"AzureRm.Compute",
"AzureRM.Compute.ManagedService",
"AzureRM.Consumption",
"AzureRM.ContainerInstance",
"AzureRM.ContainerRegistry",
"AzureRM.DataFactories",
"AzureRM.DataFactoryV2",
"AzureRM.DataLakeAnalytics",
"AzureRM.DataLakeStore",
"AzureRM.DataMigration",
"AzureRM.DeploymentManager",
"AzureRM.DeviceProvisioningServices",
"AzureRM.DevSpaces",
"AzureRM.DevTestLabs",
"AzureRm.Dns",
"AzureRM.EventGrid",
"AzureRM.EventHub",
"AzureRM.FrontDoor",
"AzureRM.HDInsight",
"AzureRm.Insights",
"AzureRM.IotCentral",
"AzureRM.IotHub",
"AzureRm.Keyvault",
"AzureRM.LocationBasedServices",
"AzureRM.LogicApp",
"AzureRM.MachineLearning",
"AzureRM.MachineLearningCompute",
"AzureRM.ManagedServiceIdentity",
"AzureRM.ManagementPartner",
"AzureRM.Maps",
"AzureRM.MarketplaceOrdering",
"AzureRM.Media",
"AzureRM.Network",
"AzureRM.NotificationHubs",
"AzureRM.OperationalInsights",
"AzureRM.PolicyInsights",
"AzureRM.PowerBIEmbedded",
"AzureRM.Profile",
"AzureRM.RecoveryServices",
"AzureRM.RecoveryServices.Backup",
"AzureRM.RecoveryServices.SiteRecovery",
"AzureRM.RedisCache",
"AzureRM.Relay",
"AzureRM.Reservations",
"AzureRM.ResourceGraph",
"AzureRM.Resources",
"AzureRM.Scheduler",
"AzureRM.Search",
"AzureRM.Security",
"AzureRM.ServerManagement",
"AzureRM.ServiceBus",
"AzureRM.ServiceFabric",
"AzureRM.SignalR",
"AzureRM.SiteRecovery",
"AzureRM.Sql",
"AzureRm.Storage",
"AzureRM.StorageSync",
"AzureRM.StreamAnalytics",
"AzureRM.Subscription",
"AzureRM.Subscription.Preview",
"AzureRM.Tags",
"AzureRM.TrafficManager",
"AzureRm.UsageAggregates",
"AzureRm.Websites",
"AzureRmStorageTable",
"bestpractices",
"bitlocker",
"bitstransfer",
"booteventcollector",
"branchcache",
"CimCmdlets",
"clusterawareupdating",
"CompatPowerShellGet",
"configci",
"ConfigurationManager",
"DataProtectionManager",
"dcbqos",
"deduplication",
"defender",
"devicehealthattestation",
"dfsn",
"dfsr",
"dhcpserver",
"directaccessclient",
"directaccessclientcomponent",
"directaccessclientcomponents",
"dism",
"dnsclient",
"dnsserver",
"ElasticDatabaseJobs",
"EventTracingManagement",
"failoverclusters",
"fileserverresourcemanager",
"FIMAutomation",
"GPRegistryPolicy",
"grouppolicy",
"hardwarecertification",
"hcs",
"hgsattestation",
"hgsclient",
"hgsdiagnostics",
"hgskeyprotection",
"hgsserver",
"hnvdiagnostics",
"hostcomputeservice",
"hpc",
"HPC.ACM",
"HPC.ACM.API.PS",
"HPCPack2016",
"hyper-v",
"IISAdministration",
"international",
"ipamserver",
"iscsi",
"iscsitarget",
"ISE",
"kds",
"Microsoft.MBAM",
"Microsoft.MEDV",
"MgmtSvcAdmin",
"MgmtSvcConfig",
"MgmtSvcMySql",
"MgmtSvcSqlServer",
"Microsoft.AzureStack.ReadinessChecker",
"Microsoft.Crm.PowerShell",
"Microsoft.DiagnosticDataViewer",
"Microsoft.DirectoryServices.MetadirectoryServices.Config",
"Microsoft.Dynamics.Nav.Apps.Management",
"Microsoft.Dynamics.Nav.Apps.Tools",
"Microsoft.Dynamics.Nav.Ide",
"Microsoft.Dynamics.Nav.Management",
"Microsoft.Dynamics.Nav.Model.Tools",
"Microsoft.Dynamics.Nav.Model.Tools.Crm",
"Microsoft.EnterpriseManagement.Warehouse.Cmdlets",
"Microsoft.Medv.Administration.Commands.WorkspacePackager",
"Microsoft.PowerApps.Checker.PowerShell",
"Microsoft.PowerShell.Archive",
"Microsoft.PowerShell.Core",
"Microsoft.PowerShell.Crescendo",
"Microsoft.PowerShell.Diagnostics",
"Microsoft.PowerShell.Host",
"Microsoft.PowerShell.LocalAccounts",
"Microsoft.PowerShell.Management",
"Microsoft.PowerShell.ODataUtils",
"Microsoft.PowerShell.Operation.Validation",
"Microsoft.PowerShell.RemotingTools",
"Microsoft.PowerShell.SecretManagement",
"Microsoft.PowerShell.SecretStore",
"Microsoft.PowerShell.Security",
"Microsoft.PowerShell.TextUtility",
"Microsoft.PowerShell.Utility",
"Microsoft.SharePoint.Powershell",
"Microsoft.SystemCenter.ServiceManagementAutomation",
"Microsoft.Windows.ServerManager.Migration",
"Microsoft.WSMan.Management",
"Microsoft.Xrm.OnlineManagementAPI",
"Microsoft.Xrm.Tooling.CrmConnector.PowerShell",
"Microsoft.Xrm.Tooling.PackageDeployment",
"Microsoft.Xrm.Tooling.PackageDeployment.Powershell",
"Microsoft.Xrm.Tooling.Testing",
"MicrosoftPowerBIMgmt",
"MicrosoftPowerBIMgmt.Data",
"MicrosoftPowerBIMgmt.Profile",
"MicrosoftPowerBIMgmt.Reports",
"MicrosoftPowerBIMgmt.Workspaces",
"MicrosoftStaffHub",
"MicrosoftTeams",
"MIMPAM",
"mlSqlPs",
"MMAgent",
"MPIO",
"MsDtc",
"MSMQ",
"MSOnline",
"MSOnlineBackup",
"WmsCmdlets",
"WmsCmdlets3",
"NanoServerImageGenerator",
"NAVWebClientManagement",
"NetAdapter",
"NetConnection",
"NetEventPacketCapture",
"Netlbfo",
"Netldpagent",
"NetNat",
"Netqos",
"NetSecurity",
"NetSwitchtTeam",
"Nettcpip",
"Netwnv",
"NetworkConnectivity",
"NetworkConnectivityStatus",
"NetworkController",
"NetworkControllerDiagnostics",
"NetworkloadBalancingClusters",
"NetworkSwitchManager",
"NetworkTransition",
"NFS",
"NPS",
"OfficeWebapps",
"OperationsManager",
"PackageManagement",
"PartnerCenter",
"pcsvdevice",
"pef",
"Pester",
"pkiclient",
"platformidentifier",
"pnpdevice",
"PowerShellEditorServices",
"PowerShellGet",
"powershellwebaccess",
"printmanagement",
"ProcessMitigations",
"provisioning",
"PSDesiredStateConfiguration",
"PSDiagnostics",
"PSReadLine",
"PSScheduledJob",
"PSScriptAnalyzer",
"PSWorkflow",
"PSWorkflowUtility",
"RemoteAccess",
"RemoteDesktop",
"RemoteDesktopServices",
"ScheduledTasks",
"Secureboot",
"ServerCore",
"ServerManager",
"ServerManagerTasks",
"ServerMigrationcmdlets",
"ServiceFabric",
"Microsoft.Online.SharePoint.PowerShell",
"shieldedvmdatafile",
"shieldedvmprovisioning",
"shieldedvmtemplate",
"SkypeOnlineConnector",
"SkypeForBusinessHybridHealth",
"smbshare",
"smbwitness",
"smisconfig",
"softwareinventorylogging",
"SPFAdmin",
"Microsoft.SharePoint.MigrationTool.PowerShell",
"sqlps",
"SqlServer",
"StartLayout",
"StartScreen",
"Storage",
"StorageDsc",
"storageqos",
"Storagereplica",
"Storagespaces",
"Syncshare",
"System.Center.Service.Manager",
"TLS",
"TroubleshootingPack",
"TrustedPlatformModule",
"UEV",
"UpdateServices",
"UserAccessLogging",
"vamt",
"VirtualMachineManager",
"vpnclient",
"WasPSExt",
"WDAC",
"WDS",
"WebAdministration",
"WebAdministrationDsc",
"WebApplicationProxy",
"WebSites",
"Whea",
"WhiteboardAdmin",
"WindowsDefender",
"WindowsDefenderDsc",
"WindowsDeveloperLicense",
"WindowsDiagnosticData",
"WindowsErrorReporting",
"WindowServerRackup",
"WindowsSearch",
"WindowsServerBackup",
"WindowsUpdate",
"wsscmdlets",
"wsssetup",
"wsus",
"xActiveDirectory",
"xBitLocker",
"xDefender",
"xDhcpServer",
"xDismFeature",
"xDnsServer",
"xHyper-V",
"xHyper-VBackup",
"xPSDesiredStateConfiguration",
"xSmbShare",
"xSqlPs",
"xStorage",
"xWebAdministration",
"xWindowsUpdate",
};
s_uniqueUserIdentifier = GetUniqueIdentifier().ToString();
}
}
/// <summary>
/// Determine whether the environment variable is set and how.
/// </summary>
/// <param name="name">The name of the environment variable.</param>
/// <param name="defaultValue">If the environment variable is not set, use this as the default value.</param>
/// <returns>A boolean representing the value of the environment variable.</returns>
private static bool GetEnvironmentVariableAsBool(string name, bool defaultValue)
{
var str = Environment.GetEnvironmentVariable(name);
if (string.IsNullOrEmpty(str))
{
return defaultValue;
}
var boolStr = str.AsSpan();
if (boolStr.Length == 1)
{
if (boolStr[0] == '1')
{
return true;
}
if (boolStr[0] == '0')
{
return false;
}
}
if (boolStr.Length == 3 &&
(boolStr[0] == 'y' || boolStr[0] == 'Y') &&
(boolStr[1] == 'e' || boolStr[1] == 'E') &&
(boolStr[2] == 's' || boolStr[2] == 'S'))
{
return true;
}
if (boolStr.Length == 2 &&
(boolStr[0] == 'n' || boolStr[0] == 'N') &&
(boolStr[1] == 'o' || boolStr[1] == 'O'))
{
return false;
}
if (boolStr.Length == 4 &&
(boolStr[0] == 't' || boolStr[0] == 'T') &&
(boolStr[1] == 'r' || boolStr[1] == 'R') &&
(boolStr[2] == 'u' || boolStr[2] == 'U') &&
(boolStr[3] == 'e' || boolStr[3] == 'E'))
{
return true;
}
if (boolStr.Length == 5 &&
(boolStr[0] == 'f' || boolStr[0] == 'F') &&
(boolStr[1] == 'a' || boolStr[1] == 'A') &&
(boolStr[2] == 'l' || boolStr[2] == 'L') &&
(boolStr[3] == 's' || boolStr[3] == 'S') &&
(boolStr[4] == 'e' || boolStr[4] == 'E'))
{
return false;
}
return defaultValue;
}
/// <summary>
/// Send telemetry as a metric.
/// </summary>
/// <param name="metricId">The type of telemetry that we'll be sending.</param>
/// <param name="data">The specific details about the telemetry.</param>
internal static void SendTelemetryMetric(TelemetryType metricId, string data)
{
if (!CanSendTelemetry)
{
return;
}
SendPSCoreStartupTelemetry("hosted");
string metricName = metricId.ToString();
try
{
switch (metricId)
{
case TelemetryType.ApplicationType:
case TelemetryType.PowerShellCreate:
case TelemetryType.RemoteSessionOpen:
case TelemetryType.ExperimentalEngineFeatureActivation:
s_telemetryClient.GetMetric(metricName, "uuid", "SessionId", "Detail").TrackValue(metricValue: 1.0, s_uniqueUserIdentifier, s_sessionId, data);
break;
case TelemetryType.ExperimentalModuleFeatureActivation:
string experimentalFeatureName = GetExperimentalFeatureName(data);
s_telemetryClient.GetMetric(metricName, "uuid", "SessionId", "Detail").TrackValue(metricValue: 1.0, s_uniqueUserIdentifier, s_sessionId, experimentalFeatureName);
break;
case TelemetryType.ModuleLoad:
case TelemetryType.WinCompatModuleLoad:
string moduleName = GetModuleName(data); // This will return anonymous if the modulename is not on the report list
s_telemetryClient.GetMetric(metricName, "uuid", "SessionId", "Detail").TrackValue(metricValue: 1.0, s_uniqueUserIdentifier, s_sessionId, moduleName);
break;
}
}
catch
{
// do nothing, telemetry can't be sent
// don't send the panic telemetry as if we have failed above, it will likely fail here.
}
}
// Get the experimental feature name. If we can report it, we'll return the name of the feature, otherwise, we'll return "anonymous"
private static string GetExperimentalFeatureName(string featureNameToValidate)
{
// An experimental feature in a module is guaranteed to start with the module name
// we can strip out the text past the last '.' as the text before that will be the ModuleName
int lastDotIndex = featureNameToValidate.LastIndexOf('.');
string moduleName = featureNameToValidate.Substring(0, lastDotIndex);
if (s_knownModules.Contains(moduleName))
{
return featureNameToValidate;
}
return _anonymous;
}
// Get the module name. If we can report it, we'll return the name, otherwise, we'll return "anonymous"
private static string GetModuleName(string moduleNameToValidate)
{
if (s_knownModules.Contains(moduleNameToValidate))
{
return moduleNameToValidate;
}
return _anonymous;
}
/// <summary>
/// Create the startup payload and send it up.
/// This is done only once during for the console host.
/// </summary>
/// <param name="mode">The "mode" of the startup.</param>
internal static void SendPSCoreStartupTelemetry(string mode)
{
// Check if we already sent startup telemetry
if (Interlocked.CompareExchange(ref s_startupEventSent, 1, 0) == 1)
{
return;
}
if (!CanSendTelemetry)
{
return;
}
var properties = new Dictionary<string, string>();
// The variable POWERSHELL_DISTRIBUTION_CHANNEL is set in our docker images.
// This allows us to track the actual docker OS as OSDescription provides only "linuxkit"
// which has limited usefulness
var channel = Environment.GetEnvironmentVariable("POWERSHELL_DISTRIBUTION_CHANNEL");
properties.Add("SessionId", s_sessionId);
properties.Add("UUID", s_uniqueUserIdentifier);
properties.Add("GitCommitID", PSVersionInfo.GitCommitId);
properties.Add("OSDescription", RuntimeInformation.OSDescription);
properties.Add("OSChannel", string.IsNullOrEmpty(channel) ? "unknown" : channel);
properties.Add("StartMode", string.IsNullOrEmpty(mode) ? "unknown" : mode);
try
{
s_telemetryClient.TrackEvent("ConsoleHostStartup", properties, null);
}
catch
{
// do nothing, telemetry cannot be sent
}
}
/// <summary>
/// Try to read the file and collect the guid.
/// </summary>
/// <param name="telemetryFilePath">The path to the telemetry file.</param>
/// <param name="id">The newly created id.</param>
/// <returns>
/// The method returns a bool indicating success or failure of creating the id.
/// </returns>
private static bool TryGetIdentifier(string telemetryFilePath, out Guid id)
{
if (File.Exists(telemetryFilePath))
{
// attempt to read the persisted identifier
const int GuidSize = 16;
byte[] buffer = new byte[GuidSize];
try
{
using (FileStream fs = new FileStream(telemetryFilePath, FileMode.Open, FileAccess.Read))
{
// if the read is invalid, or wrong size, we return it
int n = fs.Read(buffer, 0, GuidSize);
if (n == GuidSize)
{
// it's possible this could through
id = new Guid(buffer);
if (id != Guid.Empty)
{
return true;
}
}
}
}
catch
{
// something went wrong, the file may not exist or not have enough bytes, so return false
}
}
id = Guid.Empty;
return false;
}
/// <summary>
/// Try to create a unique identifier and persist it to the telemetry.uuid file.
/// </summary>
/// <param name="telemetryFilePath">The path to the persisted telemetry.uuid file.</param>
/// <param name="id">The created identifier.</param>
/// <returns>
/// The method returns a bool indicating success or failure of creating the id.
/// </returns>
private static bool TryCreateUniqueIdentifierAndFile(string telemetryFilePath, out Guid id)
{
// one last attempt to retrieve before creating incase we have a lot of simultaneous entry into the mutex.
id = Guid.Empty;
if (TryGetIdentifier(telemetryFilePath, out id))
{
return true;
}
// The directory may not exist, so attempt to create it
// CreateDirectory will simply return the directory if exists
try
{
Directory.CreateDirectory(Path.GetDirectoryName(telemetryFilePath));
}
catch
{
// send a telemetry indicating a problem with the cache dir
// it's likely something is seriously wrong so we should at least report it.
// We don't want to provide reasons here, that's not the point, but we
// would like to know if we're having a generalized problem which we can trace statistically
CanSendTelemetry = false;
s_telemetryClient.GetMetric(_telemetryFailure, "Detail").TrackValue(1, "cachedir");
return false;
}
// Create and save the new identifier, and if there's a problem, disable telemetry
try
{
id = Guid.NewGuid();
File.WriteAllBytes(telemetryFilePath, id.ToByteArray());
return true;
}
catch
{
// another bit of telemetry to notify us about a problem with saving the unique id.
s_telemetryClient.GetMetric(_telemetryFailure, "Detail").TrackValue(1, "saveuuid");
}
return false;
}
/// <summary>
/// Retrieve the unique identifier from the persisted file, if it doesn't exist create it.
/// Generate a guid which will be used as the UUID.
/// </summary>
/// <returns>A guid which represents the unique identifier.</returns>
private static Guid GetUniqueIdentifier()
{
// Try to get the unique id. If this returns false, we'll
// create/recreate the telemetry.uuid file to persist for next startup.
Guid id = Guid.Empty;
string uuidPath = Path.Join(Platform.CacheDirectory, "telemetry.uuid");
if (TryGetIdentifier(uuidPath, out id))
{
return id;
}
// Multiple processes may start simultaneously so we need a system wide
// way to control access to the file in the case (although remote) when we have
// simultaneous shell starts without the persisted file which attempt to create the file.
try
{
// TryCreateUniqueIdentifierAndFile shouldn't throw, but the mutex might
using var m = new Mutex(true, "CreateUniqueUserId");
m.WaitOne();
try
{
if (TryCreateUniqueIdentifierAndFile(uuidPath, out id))
{
return id;
}
}
finally
{
m.ReleaseMutex();
}
}
catch (Exception)
{
// Any problem in generating a uuid will result in no telemetry being sent.
// Try to send the failure in telemetry, but it will have no unique id.
s_telemetryClient.GetMetric(_telemetryFailure, "Detail").TrackValue(1, "mutex");
}
// something bad happened, turn off telemetry since the unique id wasn't set.
CanSendTelemetry = false;
return id;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.Versioning;
using Cake.Core;
using Cake.Core.Configuration;
using Cake.Core.Diagnostics;
using Cake.Core.IO;
using Cake.Core.Tooling;
using CK.Globbing;
using NUnit.Framework;
using static CK.Testing.BasicTestHelper;
namespace Cake.CK.Pack.Tests
{
[TestFixture]
public class Tests
{
ICakeContext _context;
readonly string _testDirectory = System.IO.Path.Combine( TestHelper.TestProjectFolder, "FileTests");
readonly string _outputDirectory = System.IO.Path.Combine( TestHelper.TestProjectFolder, "Output" );
[SetUp]
public void Setup()
{
_context = new CakeContext();
_context.Environment.WorkingDirectory = _testDirectory;
Directory.CreateDirectory( _outputDirectory );
}
private class CakeEnvironment : ICakeEnvironment
{
private Core.IO.DirectoryPath _workingDir;
public Core.IO.DirectoryPath WorkingDirectory
{
get
{
return _workingDir;
}
set
{
_workingDir = value;
}
}
public DirectoryPath ApplicationRoot => throw new NotImplementedException();
public ICakePlatform Platform => throw new NotImplementedException();
public ICakeRuntime Runtime => throw new NotImplementedException();
public Core.IO.DirectoryPath GetApplicationRoot()
{
throw new NotImplementedException();
}
public string GetEnvironmentVariable( string variable )
{
throw new NotImplementedException();
}
public IDictionary<string, string> GetEnvironmentVariables()
{
throw new NotImplementedException();
}
public Core.IO.DirectoryPath GetSpecialPath( Core.IO.SpecialPath path )
{
throw new NotImplementedException();
}
public FrameworkName GetTargetFramework()
{
throw new NotImplementedException();
}
public bool Is64BitOperativeSystem()
{
throw new NotImplementedException();
}
public bool IsUnix()
{
throw new NotImplementedException();
}
}
private class CakeContext : ICakeContext
{
private ICakeEnvironment _env = new CakeEnvironment();
public ICakeArguments Arguments => throw new NotImplementedException();
public ICakeEnvironment Environment => _env;
public Core.IO.IFileSystem FileSystem => throw new NotImplementedException();
public Core.IO.IGlobber Globber => throw new NotImplementedException();
public ICakeLog Log
{
get
{
throw new NotImplementedException();
}
}
public Core.IO.IProcessRunner ProcessRunner
{
get
{
throw new NotImplementedException();
}
}
public Core.IO.IRegistry Registry
{
get
{
throw new NotImplementedException();
}
}
public IToolLocator Tools { get; }
public ICakeDataResolver Data => throw new NotImplementedException();
public ICakeConfiguration Configuration => throw new NotImplementedException();
}
private void CheckZipContent( string zipFilePath, IEnumerable<string> includedFiles )
{
using( var zipFile = ZipFile.OpenRead( zipFilePath ) )
{
var expectedFilesCount = includedFiles.Count();
var foundFilesCount = zipFile.Entries.Count;
Assert.AreEqual( expectedFilesCount, foundFilesCount, String.Format( "Created zip - {0} files expected, {1} found", expectedFilesCount, foundFilesCount ) );
foreach( var f in includedFiles )
{
var entry = zipFile.GetEntry(f);
Assert.IsNotNull( entry, String.Format( "Created zip - {0}: not found", f ) );
Assert.AreEqual( f, entry.FullName, String.Format( "Created zip - Expected file: {0}, found: {1}", f, entry.FullName ) );
}
}
}
[Test]
public void ExploreZip()
{
var config = System.IO.Path.Combine(_testDirectory, "configuration_zip.xml");
var outputFile = System.IO.Path.Combine(_outputDirectory, "ExploreZip.zip");
var targets = CKPackAliases.GetTargetsFromConfigurationFile(_context, config);
CKPackAliases.Pack( _context, targets, outputFile, true );
CheckZipContent( outputFile, new[] {
@"Sub1\ZipFileSub1.txt",
@"Sub1\Sub2\ZipFileSub2.txt",
@"Sub1\Sub2\ZipFileSub2-2.txt"
} );
}
[Test]
public void PackFromConfigurationFile()
{
var config = System.IO.Path.Combine(_testDirectory, "configuration.xml");
var outputFile = System.IO.Path.Combine(_outputDirectory, "PackFromConfigurationFile.zip");
var targets = CKPackAliases.GetTargetsFromConfigurationFile(_context, config);
CKPackAliases.Pack( _context, targets, outputFile );
Assert.IsTrue( File.Exists( outputFile ), "Created zip - Output file not found" );
CheckZipContent( outputFile, new[] {
"RootFile.txt",
@"Target1\File1.txt",
@"Target1\File2.txt",
@"Target1\ZipContent.zip",
@"Target3\File5.txt"
} );
}
[Test]
public void PackFromList()
{
var t1 = new FileGroupTarget() { Target = "/Target1" };
var fn1 = new FileNameFilter() { Root = "ForTarget1" };
var pf1 = new PathFilter(true, "/**.txt");
t1.Filters.Add( fn1 );
fn1.Filters.Add( pf1 );
var t2 = new FileGroupTarget() { Target = "/Target2" };
var fn2 = new FileNameFilter() { Root = "ForTarget2" };
var pf2 = new PathFilter(false, "/**.txt");
t2.Filters.Add( fn2 );
fn2.Filters.Add( pf2 );
var t3 = new FileGroupTarget() { Target = "/Target3" };
var fn3 = new FileNameFilter() { Root = "ForTarget3" };
var pf3e = new PathFilter(false, "/File6.txt");
var pf3i = new PathFilter(true, "/**.txt");
t3.Filters.Add( fn3 );
fn3.Filters.Add( pf3e );
fn3.Filters.Add( pf3i );
var t4 = new FileGroupTarget() { Target = "/" };
var fn4 = new FileNameFilter() { Root = "/" };
var pf4 = new PathFilter(true, "/RootFile.txt");
t4.Filters.Add( fn4 );
fn4.Filters.Add( pf4 );
var targets = new[] { t1, t2, t3, t4 };
var outputFile = System.IO.Path.Combine(_outputDirectory, "PackFromList.zip");
CKPackAliases.Pack( _context, targets, outputFile );
Assert.IsTrue( File.Exists( outputFile ), "Created zip - Output file not found" );
CheckZipContent( outputFile, new[] {
"RootFile.txt",
@"Target1\File1.txt",
@"Target1\File2.txt",
@"Target3\File5.txt"
} );
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region Using directives
using System;
using System.Collections;
using System.Text;
using System.Xml;
using Google.GData.Client;
#endregion
namespace Google.GData.GoogleBase {
///////////////////////////////////////////////////////////////////////
/// <summary>A range with a start time and an end time.
///
/// Empty ranges are considered as one single DateTime object
/// by the Google Base framework.</summary>
///////////////////////////////////////////////////////////////////////
public class DateTimeRange
{
private readonly DateTime start;
private readonly DateTime end;
///////////////////////////////////////////////////////////////////////
/// <summary>Creates a DateTimeRange given a string representation.
///
/// The string representation should be
/// <c><date/datetime> [" " <date/datetime>]</c>
///
/// String representations for dates and date/time are accepted. In
/// this case, the start and end dates will be the same and
/// <see cref="IsDateTimeOnly">IsDateTimeOnly()</see> will be
/// true.
/// </summary>
///////////////////////////////////////////////////////////////////////
public DateTimeRange(string stringrep)
: this(ParseDateTime(ExtractStart(stringrep)),
ParseDateTime(ExtractEnd(stringrep)))
{
}
///////////////////////////////////////////////////////////////////////
/// <summary>Creates a DateTimeRange with a start and end date/time</summary>
/// <param name="start">start date</param>
/// <param name="end">end date</param>
///////////////////////////////////////////////////////////////////////
public DateTimeRange(DateTime start, DateTime end)
{
AssertArgumentNotNull(start, "start");
AssertArgumentNotNull(end, "end");
this.start = start;
this.end = end;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Creates an empty range, equivalent to a single
/// DateTime.
///
/// Use <see cref="ToDateTime">ToDateTime()</see> to convert it
/// back to a DateTime, if needed.</summary>
/// <param name="dateTime">a single date/time</param>
///////////////////////////////////////////////////////////////////////
public DateTimeRange(DateTime dateTime)
: this(dateTime, dateTime)
{
}
///////////////////////////////////////////////////////////////////////
/// <summary>Checks whether the range is empty and should be considered
/// as a single DateTime.</summary>
/// <seealso cref="ToDateTime"/>
///////////////////////////////////////////////////////////////////////
public bool IsDateTimeOnly()
{
return start.Equals(end);
}
///////////////////////////////////////////////////////////////////////
/// <summary>Converts an empty range to a single DateTime object.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the range
/// is not empty.</exception>
/// <seealso cref="IsDateTimeOnly"/>
///////////////////////////////////////////////////////////////////////
public DateTime ToDateTime()
{
if (!IsDateTimeOnly())
{
throw new InvalidOperationException("This is a real range, with start < end");
}
return start;
}
private void AssertArgumentNotNull(object arg, string name)
{
if (arg == null)
{
throw new ArgumentNullException(name);
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Start time.</summary>
///////////////////////////////////////////////////////////////////////
public DateTime Start
{
get
{
return start;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>End time</summary>
///////////////////////////////////////////////////////////////////////
public DateTime End
{
get
{
return end;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Generates a valid string representation for the DateTimeRange
/// that can later be parsed by its constructor.</summary>
///////////////////////////////////////////////////////////////////////
public override string ToString()
{
return Utilities.LocalDateTimeInUTC(start) + " " +
Utilities.LocalDateTimeInUTC(end);
}
///////////////////////////////////////////////////////////////////////
/// <summary>Generates a hash code for this element that is
/// consistent with its Equals() method.</summary>
///////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return 49 * ( 17 + start.GetHashCode() ) + end.GetHashCode();
}
///////////////////////////////////////////////////////////////////////
/// <summary>Two ranges are equal if their start and end DateTime
/// are equal.</summary>
///////////////////////////////////////////////////////////////////////
public override bool Equals(object o)
{
if (Object.ReferenceEquals(this, o))
{
return true;
}
if (!(o is DateTimeRange))
{
return false;
}
DateTimeRange other = o as DateTimeRange;
return other.start == start && other.end == end;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Comparison based on Equals()</summary>
///////////////////////////////////////////////////////////////////////
public static bool operator ==(DateTimeRange a, DateTimeRange b)
{
if (Object.ReferenceEquals(a, b))
{
return true;
}
if ((object)a == null || (object)b == null)
{
return false;
}
return a.Equals(b);
}
///////////////////////////////////////////////////////////////////////
/// <summary>Comparison based on Equals()</summary>
///////////////////////////////////////////////////////////////////////
public static bool operator !=(DateTimeRange a, DateTimeRange b)
{
return !(a == b);
}
private static string ExtractStart(string startEnd)
{
int space = startEnd.IndexOf(' ');
if (space == -1)
{
// There's only one date (start == end)
return startEnd;
}
return startEnd.Substring(0, space);
}
private static string ExtractEnd(string startEnd)
{
int space = startEnd.IndexOf(' ');
if (space == -1)
{
// There's only one date (start == end)
return startEnd;
}
return startEnd.Substring(space + 1);
}
private static DateTime ParseDateTime(string stringValue)
{
// Make the error message more explicit
try
{
return DateTime.Parse(stringValue);
}
catch(FormatException e)
{
throw new FormatException(e.Message + " (" + stringValue + ")", e);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Reflection.Runtime.General;
using Internal.TypeSystem;
using Internal.Runtime.Augments;
using Internal.TypeSystem.NativeFormat;
using Internal.NativeFormat;
namespace Internal.Runtime.TypeLoader
{
internal class SerializedDebugData
{
//
// SerializedDebugData represents the logical buffer where all debug information is serialized.
//
// DBGVISIBLE_serializedDataHeader is the blob of memory that describes the contents of
// the logical buffer. This blob is allocated on the unmanaged heap using MemoryHelpers.AllocateMemory
//
// byte[0-3] in DBGVISIBLE_serializedDataHeader represents the version of serialization format.
// In our current format, we use multiple physical memory buffers (on unmanaged heap) to hold
// the actual serialized data and DBGVISIBLE_serializedDataHeader contains a list of pointers
// to these physical buffers.
// byte[4-7] in DBGVISIBLE_serializedDataHeader is the number of currently allocated physical
// buffers.
// byte[8-...] is a list of pointers to these physical buffers.
//
// Note that type-loader must ensure that all debug data serialization is done in a thread-safe manner.
//
/// <summary>
/// Types of records in the serialized debug data. To maintain compatibility with previous
/// version of the diagnostic stream which used just the two bottom bits for entry type
/// information, we cannibalize entry #3, StepThroughStubAddress, which has only one bit flag
/// (IsTailCallStub shared with StepThroughStubSize), to encode additional entry types
/// in the higher-order bits. When the bits 0-1 contain 1-1 (i.e. the 'old-style' entry type
/// is StepThroughStubAddress) and bits 3-7 are non-zero, they get split such that
/// bits 3-4 are shifted right 3 times and increased by 3 to form the final blob kind,
/// bits 5-7 are shifted right 5 times to form the flags for the new blob kinds.
/// This creates space for 3 more entry types with 3 bits for flags which should hopefully suffice.
/// </summary>
internal enum SerializedDataBlobKind : byte
{
SharedType = 0,
SharedMethod = 1,
StepThroughStubSize = 2,
StepThroughStubAddress = 3,
NativeFormatType = 4,
Limit,
};
[Flags]
internal enum SharedTypeFlags : byte
{
HasGCStaticFieldRegion = 0x01,
HasNonGCStaticFieldRegion = 0x02,
HasThreadStaticFieldRegion = 0x04,
HasStaticFields = 0x08,
HasInstanceFields = 0x10,
HasTypeSize = 0x20
};
[Flags]
internal enum SharedMethodFlags : byte
{
HasDeclaringTypeHandle = 0x01
};
[Flags]
internal enum StepThroughStubFlags : byte
{
IsTailCallStub = 0x01
};
private static IntPtr DBGVISIBLE_serializedDataHeader;
// version of the serialization format
private const int SerializationFormatVersion = 2;
// size by which the list of pointers to physical buffers is grown
private const int HeaderBufferListSize = 100;
// offset in DBGVISIBLE_serializedDataHeader where the list of pointers to physical buffers starts
private const int HeaderBufferListOffset = sizeof(int) * 2;
// size of each physical buffer
private const int PhysicalBufferSize = 10 * 1024; // 10 KB
// offset in physical buffer where the actual data blobs start
private const int PhysicalBufferDataOffset = sizeof(int);
// the instance of SerializedDebugData via which runtime updates the debug data buffer
internal static SerializedDebugData Instance = new SerializedDebugData();
private IntPtr _activePhysicalBuffer;
private int _activePhysicalBufferIdx = -1;
private int _activePhysicalBufferOffset;
private int _activePhysicalBufferAvailableSize;
private int _serializedDataHeaderSize;
private unsafe void InitializeHeader(int physicalBufferListSize)
{
int headerSize = HeaderBufferListOffset + IntPtr.Size * physicalBufferListSize;
IntPtr header = MemoryHelpers.AllocateMemory(headerSize);
IntPtr oldHeader = IntPtr.Zero;
MemoryHelpers.Memset(header, headerSize, 0);
// check if an older header exists and copy all data from it to the newly
// allocated header.
if (_serializedDataHeaderSize > 0)
{
Debug.Assert(headerSize > _serializedDataHeaderSize);
Buffer.MemoryCopy((byte*)DBGVISIBLE_serializedDataHeader, (byte*)header, headerSize, _serializedDataHeaderSize);
// mark the older header for deletion
oldHeader = DBGVISIBLE_serializedDataHeader;
}
else
{
// write the serialization format version
*(int*)header = SerializationFormatVersion;
// write the total allocated number of physical buffers (0)
*(int*)(header + sizeof(int)) = 0;
Debug.Assert(_activePhysicalBufferIdx == 0);
}
DBGVISIBLE_serializedDataHeader = header;
_serializedDataHeaderSize = headerSize;
// delete the older header if a new one was allocated
if (oldHeader != IntPtr.Zero)
{
MemoryHelpers.FreeMemory(oldHeader);
}
}
private unsafe int GetAllocatedPhysicalBufferCount()
{
if (_serializedDataHeaderSize < HeaderBufferListOffset)
return 0;
return *(int*)(DBGVISIBLE_serializedDataHeader + sizeof(int));
}
private unsafe void AddAllocatedBufferToHeader(IntPtr buffer, int insertIdx)
{
Debug.Assert(insertIdx >= 0);
int currentPhysicalBufferListSize = _serializedDataHeaderSize == 0 ? 0 :
(_serializedDataHeaderSize - HeaderBufferListOffset) / IntPtr.Size;
if (currentPhysicalBufferListSize <= insertIdx)
{
// not enough space in the header, grow it
InitializeHeader(currentPhysicalBufferListSize + HeaderBufferListSize);
}
Debug.Assert(GetAllocatedPhysicalBufferCount() == insertIdx);
*(void**)(DBGVISIBLE_serializedDataHeader + HeaderBufferListOffset + IntPtr.Size * insertIdx) = buffer.ToPointer();
*(int*)(DBGVISIBLE_serializedDataHeader + sizeof(int)) = insertIdx + 1; // update the buffer count
}
//
// Allocates a new physical buffer and returns the first offset where data can be written into buffer
// First few bytes of the physical buffer are used to describe it.
//
// buffer[0-3] = Used buffer size
//
private unsafe int AllocatePhysicalBuffer(out IntPtr buffer)
{
// Allocate a new physical buffer.
IntPtr newPhysicalBuffer = MemoryHelpers.AllocateMemory(PhysicalBufferSize);
*(int*)newPhysicalBuffer = 0; // write the used buffer size, currently 0
// Add the pointer to new physical buffer to DBGVISIBLE_serializedDataHeader
AddAllocatedBufferToHeader(newPhysicalBuffer, ++_activePhysicalBufferIdx);
buffer = newPhysicalBuffer;
return PhysicalBufferDataOffset;
}
//
// GetPhysicalBuffer returns a physical buffer of a given size.
//
// Given a requested buffer size, this method gives back a buffer pointer
// and available usable size.
// It is the caller's responsibility to update the used buffer size after writing
// to the buffer.
//
private int GetPhysicalBuffer(int requestedSize, out IntPtr bufferPtr)
{
if (_activePhysicalBufferAvailableSize == 0)
{
// no space available in active physical buffer
// allocate a new physical buffer
_activePhysicalBufferOffset = AllocatePhysicalBuffer(out _activePhysicalBuffer);
_activePhysicalBufferAvailableSize = PhysicalBufferSize - _activePhysicalBufferOffset;
}
int availableSize = (_activePhysicalBufferAvailableSize < requestedSize) ?
_activePhysicalBufferAvailableSize : requestedSize;
_activePhysicalBufferAvailableSize -= availableSize;
bufferPtr = new IntPtr(_activePhysicalBuffer.ToInt64() + _activePhysicalBufferOffset);
_activePhysicalBufferOffset += availableSize;
return availableSize;
}
// Helper used to update the used buffer size in buffer[0-3]
private unsafe void UpdatePhysicalBufferUsedSize()
{
Debug.Assert(_activePhysicalBufferOffset >= PhysicalBufferDataOffset);
*(int*)_activePhysicalBuffer = _activePhysicalBufferOffset;
}
// Write the given byte array to the logical buffer in a thread-safe manner
private void ThreadSafeWriteBytes(byte[] src)
{
lock (Instance)
{
IntPtr dst;
int requiredSize = src.Length;
int availableSize = GetPhysicalBuffer(requiredSize, out dst);
if (availableSize < requiredSize)
{
// if current physical buffer doesn't have enough space, try
// and allocate a new one
availableSize = GetPhysicalBuffer(requiredSize, out dst);
if (availableSize < requiredSize)
throw new OutOfMemoryException();
}
InteropExtensions.CopyToNative(src, 0, dst, src.Length);
UpdatePhysicalBufferUsedSize(); // make sure that used physical buffer size is updated
}
}
// Helper method to serialize the data-blob type and flags
public void SerializeDataBlobTypeAndFlags(ref NativePrimitiveEncoder encoder, SerializedDataBlobKind blobType, byte flags)
{
// make sure that blobType fits in 2 bits and flags fits in 6 bits
Debug.Assert(blobType < SerializedDataBlobKind.Limit);
Debug.Assert((byte)blobType <= 2 && flags <= 0x3F ||
(byte)blobType == 3 && flags <= 1 ||
(byte)blobType > 3 && flags <= 7);
byte encodedKindAndFlags;
if (blobType <= (SerializedDataBlobKind)3)
{
encodedKindAndFlags = (byte)((byte)blobType | (flags << 2));
}
else
{
encodedKindAndFlags = (byte)(3 | (((byte)blobType - 3) << 3) | (flags << 5));
}
encoder.WriteByte(encodedKindAndFlags);
}
public static void RegisterDebugDataForType(TypeBuilder typeBuilder, DefType defType, TypeBuilderState state)
{
if (!defType.IsGeneric())
{
RegisterDebugDataForNativeFormatType(typeBuilder, defType, state);
return;
}
if (defType.IsGenericDefinition)
{
// We don't yet have an encoding for open generic types
// TODO! fill this in
return;
}
NativePrimitiveEncoder encoder = new NativePrimitiveEncoder();
encoder.Init();
IntPtr gcStaticFieldData = TypeLoaderEnvironment.Instance.TryGetGcStaticFieldData(typeBuilder.GetRuntimeTypeHandle(defType));
IntPtr nonGcStaticFieldData = TypeLoaderEnvironment.Instance.TryGetNonGcStaticFieldData(typeBuilder.GetRuntimeTypeHandle(defType));
bool isUniversalGenericType = state.TemplateType != null && state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal);
bool embeddedTypeSizeAndFieldOffsets = isUniversalGenericType || (state.TemplateType == null);
uint instanceFieldCount = 0;
uint staticFieldCount = 0;
// GetDiagnosticFields only returns the fields that are of interest for diagnostic reporting. So it doesn't
// return a meaningful list for non-universal canonical templates
IEnumerable<FieldDesc> diagnosticFields = defType.GetDiagnosticFields();
foreach (var f in diagnosticFields)
{
if (f.IsLiteral)
continue;
if (f.IsStatic)
{
++staticFieldCount;
}
else
{
++instanceFieldCount;
}
}
SharedTypeFlags sharedTypeFlags = 0;
if (gcStaticFieldData != IntPtr.Zero) sharedTypeFlags |= SharedTypeFlags.HasGCStaticFieldRegion;
if (nonGcStaticFieldData != IntPtr.Zero) sharedTypeFlags |= SharedTypeFlags.HasNonGCStaticFieldRegion;
if (state.ThreadDataSize != 0) sharedTypeFlags |= SharedTypeFlags.HasThreadStaticFieldRegion;
if (embeddedTypeSizeAndFieldOffsets)
{
sharedTypeFlags |= SerializedDebugData.SharedTypeFlags.HasTypeSize;
if (instanceFieldCount > 0)
sharedTypeFlags |= SerializedDebugData.SharedTypeFlags.HasInstanceFields;
if (staticFieldCount > 0)
sharedTypeFlags |= SerializedDebugData.SharedTypeFlags.HasStaticFields;
}
Instance.SerializeDataBlobTypeAndFlags(ref encoder, SerializedDataBlobKind.SharedType, (byte)sharedTypeFlags);
//
// The order of these writes is a contract shared between the runtime and debugger engine.
// Changes here must also be updated in the debugger reader code
//
encoder.WriteUnsignedLong((ulong)typeBuilder.GetRuntimeTypeHandle(defType).ToIntPtr().ToInt64());
encoder.WriteUnsigned((uint)defType.Instantiation.Length);
foreach (var instParam in defType.Instantiation)
{
encoder.WriteUnsignedLong((ulong)typeBuilder.GetRuntimeTypeHandle(instParam).ToIntPtr().ToInt64());
}
if (gcStaticFieldData != IntPtr.Zero)
{
encoder.WriteUnsignedLong((ulong)gcStaticFieldData.ToInt64());
}
if (nonGcStaticFieldData != IntPtr.Zero)
{
encoder.WriteUnsignedLong((ulong)nonGcStaticFieldData.ToInt64());
}
// Write the TLS offset into the native thread's TLS buffer. That index de-referenced is the thread static
// data region for this type
if (state.ThreadDataSize != 0)
{
encoder.WriteUnsigned(state.ThreadStaticOffset);
}
// Collect information debugger only requires for universal generics and dynamically loaded types
if (embeddedTypeSizeAndFieldOffsets)
{
Debug.Assert(state.TypeSize != null);
encoder.WriteUnsigned((uint)state.TypeSize);
if (instanceFieldCount > 0)
{
encoder.WriteUnsigned(instanceFieldCount);
uint i = 0;
foreach (FieldDesc f in diagnosticFields)
{
if (f.IsLiteral)
continue;
if (f.IsStatic)
continue;
encoder.WriteUnsigned(i);
encoder.WriteUnsigned((uint)f.Offset.AsInt);
i++;
}
}
if (staticFieldCount > 0)
{
encoder.WriteUnsigned(staticFieldCount);
uint i = 0;
foreach (FieldDesc f in diagnosticFields)
{
if (f.IsLiteral)
continue;
if (!f.IsStatic)
continue;
NativeLayoutFieldDesc nlfd = f as NativeLayoutFieldDesc;
FieldStorage fieldStorage;
if (nlfd != null)
{
// NativeLayoutFieldDesc's have the field storage information directly embedded in them
fieldStorage = nlfd.FieldStorage;
}
else
{
// Metadata based types do not, but the api's to get the info are available
if (f.IsThreadStatic)
{
fieldStorage = FieldStorage.TLSStatic;
}
else if (f.HasGCStaticBase)
{
fieldStorage = FieldStorage.GCStatic;
}
else
{
fieldStorage = FieldStorage.NonGCStatic;
}
}
encoder.WriteUnsigned(i);
encoder.WriteUnsigned((uint)fieldStorage);
encoder.WriteUnsigned((uint)f.Offset.AsInt);
i++;
}
}
}
Instance.ThreadSafeWriteBytes(encoder.GetBytes());
}
/// <summary>
/// Add information about dynamically created non-generic native format type
/// to the diagnostic stream in form of a NativeFormatType blob.
/// </summary>
/// <param name="typeBuilder">TypeBuilder is used to query runtime type handle for the type</param>
/// <param name="defType">Type to emit to the diagnostic stream</param>
/// <param name="state"></param>
public static void RegisterDebugDataForNativeFormatType(TypeBuilder typeBuilder, DefType defType, TypeBuilderState state)
{
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
NativeFormatType nativeFormatType = defType as NativeFormatType;
if (nativeFormatType == null)
{
return;
}
NativePrimitiveEncoder encoder = new NativePrimitiveEncoder();
encoder.Init();
byte nativeFormatTypeFlags = 0;
Instance.SerializeDataBlobTypeAndFlags(
ref encoder,
SerializedDataBlobKind.NativeFormatType,
nativeFormatTypeFlags);
TypeManagerHandle moduleHandle = ModuleList.Instance.GetModuleForMetadataReader(nativeFormatType.MetadataReader);
encoder.WriteUnsignedLong(unchecked((ulong)typeBuilder.GetRuntimeTypeHandle(defType).ToIntPtr().ToInt64()));
encoder.WriteUnsigned(nativeFormatType.Handle.ToHandle(nativeFormatType.MetadataReader).AsUInt());
encoder.WriteUnsignedLong(unchecked((ulong)moduleHandle.GetIntPtrUNSAFE().ToInt64()));
Instance.ThreadSafeWriteBytes(encoder.GetBytes());
#else
return;
#endif
}
public static void RegisterDebugDataForMethod(TypeBuilder typeBuilder, InstantiatedMethod method)
{
NativePrimitiveEncoder encoder = new NativePrimitiveEncoder();
encoder.Init();
byte sharedMethodFlags = 0;
sharedMethodFlags |= (byte)(method.OwningType.IsGeneric() ? SharedMethodFlags.HasDeclaringTypeHandle : 0);
Instance.SerializeDataBlobTypeAndFlags(ref encoder, SerializedDataBlobKind.SharedMethod, sharedMethodFlags);
encoder.WriteUnsignedLong((ulong)method.RuntimeMethodDictionary.ToInt64());
encoder.WriteUnsigned((uint)method.Instantiation.Length);
foreach (var instParam in method.Instantiation)
{
encoder.WriteUnsignedLong((ulong)typeBuilder.GetRuntimeTypeHandle(instParam).ToIntPtr().ToInt64());
}
if (method.OwningType.IsGeneric())
{
encoder.WriteUnsignedLong((ulong)typeBuilder.GetRuntimeTypeHandle(method.OwningType).ToIntPtr().ToInt64());
}
Instance.ThreadSafeWriteBytes(encoder.GetBytes());
}
// This method is called whenever a new thunk is allocated, to capture the thunk's code address
// in the serialized stream.
// This information is used by the debugger to detect thunk frames on the callstack.
private static bool s_tailCallThunkSizeRegistered = false;
public static void RegisterTailCallThunk(IntPtr thunk)
{
NativePrimitiveEncoder encoder = new NativePrimitiveEncoder();
if (!s_tailCallThunkSizeRegistered)
{
lock (Instance)
{
if (!s_tailCallThunkSizeRegistered)
{
// Write out the size of thunks used by the calling convention converter
// Make sure that this is called only once
encoder.Init();
Instance.SerializeDataBlobTypeAndFlags(ref encoder,
SerializedDataBlobKind.StepThroughStubSize,
(byte)StepThroughStubFlags.IsTailCallStub);
encoder.WriteUnsigned((uint)RuntimeAugments.GetThunkSize());
Instance.ThreadSafeWriteBytes(encoder.GetBytes());
s_tailCallThunkSizeRegistered = true;
}
}
}
encoder.Init();
Instance.SerializeDataBlobTypeAndFlags(ref encoder,
SerializedDataBlobKind.StepThroughStubAddress,
(byte)StepThroughStubFlags.IsTailCallStub);
encoder.WriteUnsignedLong((ulong)thunk.ToInt64());
Instance.ThreadSafeWriteBytes(encoder.GetBytes());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using MahApps.Metro;
using MetroDemo.Models;
using System.Windows.Input;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
namespace MetroDemo
{
public class AccentColorMenuData
{
public string Name { get; set; }
public Brush BorderColorBrush { get; set; }
public Brush ColorBrush { get; set; }
private ICommand changeAccentCommand;
public ICommand ChangeAccentCommand
{
get { return this.changeAccentCommand ?? (changeAccentCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = x => this.DoChangeTheme(x) }); }
}
protected virtual void DoChangeTheme(object sender)
{
var theme = ThemeManager.DetectAppStyle(Application.Current);
var accent = ThemeManager.GetAccent(this.Name);
ThemeManager.ChangeAppStyle(Application.Current, accent, theme.Item1);
}
}
public class AppThemeMenuData : AccentColorMenuData
{
protected override void DoChangeTheme(object sender)
{
var theme = ThemeManager.DetectAppStyle(Application.Current);
var appTheme = ThemeManager.GetAppTheme(this.Name);
ThemeManager.ChangeAppStyle(Application.Current, theme.Item2, appTheme);
}
}
public class MainWindowViewModel : INotifyPropertyChanged, IDataErrorInfo
{
private readonly IDialogCoordinator _dialogCoordinator;
int? _integerGreater10Property;
private bool _animateOnPositionChange = true;
public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
{
_dialogCoordinator = dialogCoordinator;
SampleData.Seed();
// create accent color menu items for the demo
this.AccentColors = ThemeManager.Accents
.Select(a => new AccentColorMenuData() { Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush })
.ToList();
// create metro theme color menu items for the demo
this.AppThemes = ThemeManager.AppThemes
.Select(a => new AppThemeMenuData() { Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush })
.ToList();
Albums = SampleData.Albums;
Artists = SampleData.Artists;
FlipViewTemplateSelector = new RandomDataTemplateSelector();
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(Image));
spFactory.SetBinding(Image.SourceProperty, new System.Windows.Data.Binding("."));
spFactory.SetValue(Image.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);
spFactory.SetValue(Image.StretchProperty, Stretch.Fill);
FlipViewTemplateSelector.TemplateOne = new DataTemplate()
{
VisualTree = spFactory
};
FlipViewImages = new string[] { "http://trinities.org/blog/wp-content/uploads/red-ball.jpg", "http://savingwithsisters.files.wordpress.com/2012/05/ball.gif" };
RaisePropertyChanged("FlipViewTemplateSelector");
BrushResources = FindBrushResources();
CultureInfos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures).ToList();
}
public string Title { get; set; }
public int SelectedIndex { get; set; }
public List<Album> Albums { get; set; }
public List<Artist> Artists { get; set; }
public List<AccentColorMenuData> AccentColors { get; set; }
public List<AppThemeMenuData> AppThemes { get; set; }
public List<CultureInfo> CultureInfos { get; set; }
public int? IntegerGreater10Property
{
get { return this._integerGreater10Property; }
set
{
if (Equals(value, _integerGreater10Property))
{
return;
}
_integerGreater10Property = value;
RaisePropertyChanged("IntegerGreater10Property");
}
}
DateTime? _datePickerDate;
public DateTime? DatePickerDate
{
get { return this._datePickerDate; }
set
{
if (Equals(value, _datePickerDate))
{
return;
}
_datePickerDate = value;
RaisePropertyChanged("DatePickerDate");
}
}
bool _magicToggleButtonIsChecked = true;
public bool MagicToggleButtonIsChecked
{
get { return this._magicToggleButtonIsChecked; }
set
{
if (Equals(value, _magicToggleButtonIsChecked))
{
return;
}
_magicToggleButtonIsChecked = value;
RaisePropertyChanged("MagicToggleButtonIsChecked");
}
}
private bool _quitConfirmationEnabled;
public bool QuitConfirmationEnabled
{
get { return _quitConfirmationEnabled; }
set
{
if (value.Equals(_quitConfirmationEnabled)) return;
_quitConfirmationEnabled = value;
RaisePropertyChanged("QuitConfirmationEnabled");
}
}
private ICommand textBoxButtonCmd;
public ICommand TextBoxButtonCmd
{
get
{
return this.textBoxButtonCmd ?? (this.textBoxButtonCmd = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = async x =>
{
if (x is TextBox)
{
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("TextBox Button was clicked!",
string.Format("Text: {0}", ((TextBox) x).Text));
}
else if (x is PasswordBox)
{
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("PasswordBox Button was clicked!",
string.Format("Password: {0}", ((PasswordBox) x).Password));
}
}
});
}
}
private ICommand textBoxButtonCmdWithParameter;
public ICommand TextBoxButtonCmdWithParameter
{
get
{
return this.textBoxButtonCmdWithParameter ?? (this.textBoxButtonCmdWithParameter = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = async x =>
{
if (x is String)
{
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("TextBox Button with parameter was clicked!",
string.Format("Parameter: {0}", x));
}
}
});
}
}
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises the PropertyChanged event if needed.
/// </summary>
/// <param name="propertyName">The name of the property that changed.</param>
protected virtual void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string this[string columnName]
{
get
{
if (columnName == "IntegerGreater10Property" && this.IntegerGreater10Property < 10)
{
return "Number is not greater than 10!";
}
if (columnName == "DatePickerDate" && this.DatePickerDate == null)
{
return "No date given!";
}
return null;
}
}
public string Error { get { return string.Empty; } }
private ICommand singleCloseTabCommand;
public ICommand SingleCloseTabCommand
{
get
{
return this.singleCloseTabCommand ?? (this.singleCloseTabCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = async x =>
{
await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("Closing tab!", string.Format("You are now closing the '{0}' tab", x));
}
});
}
}
private ICommand neverCloseTabCommand;
public ICommand NeverCloseTabCommand
{
get { return this.neverCloseTabCommand ?? (this.neverCloseTabCommand = new SimpleCommand { CanExecuteDelegate = x => false }); }
}
private ICommand showInputDialogCommand;
public ICommand ShowInputDialogCommand
{
get
{
return this.showInputDialogCommand ?? (this.showInputDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x =>
{
_dialogCoordinator.ShowInputAsync(this, "From a VM", "This dialog was shown from a VM, without knowledge of Window").ContinueWith(t => Console.WriteLine(t.Result));
}
});
}
}
private ICommand showLoginDialogCommand;
public ICommand ShowLoginDialogCommand
{
get
{
return this.showLoginDialogCommand ?? (this.showLoginDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x =>
{
_dialogCoordinator.ShowLoginAsync(this, "Login from a VM", "This login dialog was shown from a VM, so you can be all MVVM.").ContinueWith(t => Console.WriteLine(t.Result));
}
});
}
}
private ICommand showMessageDialogCommand;
public ICommand ShowMessageDialogCommand
{
get
{
return this.showMessageDialogCommand ?? (this.showMessageDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x =>
{
_dialogCoordinator.ShowMessageAsync(this, "Message from VM", "MVVM based messages!").ContinueWith(t => Console.WriteLine(t.Result));
}
});
}
}
private ICommand showProgressDialogCommand;
public ICommand ShowProgressDialogCommand
{
get
{
return this.showProgressDialogCommand ?? (this.showProgressDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x => RunProgressFromVm()
});
}
}
private async void RunProgressFromVm()
{
var controller = await _dialogCoordinator.ShowProgressAsync(this, "Progress from VM", "Progressing all the things, wait 3 seconds");
controller.SetIndeterminate();
await TaskEx.Delay(3000);
await controller.CloseAsync();
}
private ICommand showCustomDialogCommand;
public ICommand ShowCustomDialogCommand
{
get
{
return this.showCustomDialogCommand ?? (this.showCustomDialogCommand = new SimpleCommand
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x => RunCustomFromVm()
});
}
}
private async void RunCustomFromVm()
{
var customDialog = new CustomDialog() { Title = "Custom, wait 3 seconds" };
await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog);
await TaskEx.Delay(3000);
await _dialogCoordinator.HideMetroDialogAsync(this, customDialog);
}
public IEnumerable<string> BrushResources { get; private set; }
public bool AnimateOnPositionChange
{
get
{
return _animateOnPositionChange;
}
set
{
if (Equals(_animateOnPositionChange, value)) return;
_animateOnPositionChange = value;
RaisePropertyChanged("AnimateOnPositionChange");
}
}
private IEnumerable<string> FindBrushResources()
{
var rd = new ResourceDictionary
{
Source = new Uri(@"/MahApps.Metro;component/Styles/Colors.xaml", UriKind.RelativeOrAbsolute)
};
var resources = rd.Keys.Cast<object>()
.Where(key => rd[key] is Brush)
.Select(key => key.ToString())
.OrderBy(s => s)
.ToList();
return resources;
}
public RandomDataTemplateSelector FlipViewTemplateSelector
{
get;
set;
}
public string[] FlipViewImages
{
get;
set;
}
public class RandomDataTemplateSelector : DataTemplateSelector
{
public DataTemplate TemplateOne { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
return TemplateOne;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using Xunit;
namespace System.ComponentModel.Tests
{
public class TypeDescriptorTests
{
[Fact]
public void AddAndRemoveProvider()
{
var provider = new InvocationRecordingTypeDescriptionProvider();
var component = new DescriptorTestComponent();
TypeDescriptor.AddProvider(provider, component);
var retrievedProvider = TypeDescriptor.GetProvider(component);
retrievedProvider.GetCache(component);
Assert.True(provider.ReceivedCall);
provider.Reset();
TypeDescriptor.RemoveProvider(provider, component);
retrievedProvider = TypeDescriptor.GetProvider(component);
retrievedProvider.GetCache(component);
Assert.False(provider.ReceivedCall);
}
[Fact]
public void AddAttribute()
{
var component = new DescriptorTestComponent();
var addedAttribute = new DescriptorTestAttribute("expected string");
TypeDescriptor.AddAttributes(component.GetType(), addedAttribute);
AttributeCollection attributes = TypeDescriptor.GetAttributes(component);
Assert.True(attributes.Contains(addedAttribute));
}
[Fact]
public void CreateInstancePassesCtorParameters()
{
var expectedString = "expected string";
var component = TypeDescriptor.CreateInstance(null, typeof(DescriptorTestComponent), new[] { expectedString.GetType() }, new[] { expectedString });
Assert.NotNull(component);
Assert.IsType(typeof(DescriptorTestComponent), component);
Assert.Equal(expectedString, (component as DescriptorTestComponent).StringProperty);
}
[Fact]
public void GetAssociationReturnsExpectedObject()
{
var primaryObject = new DescriptorTestComponent();
var secondaryObject = new MockEventDescriptor();
TypeDescriptor.CreateAssociation(primaryObject, secondaryObject);
var associatedObject = TypeDescriptor.GetAssociation(secondaryObject.GetType(), primaryObject);
Assert.IsType(secondaryObject.GetType(), associatedObject);
Assert.Equal(secondaryObject, associatedObject);
}
[Fact]
public static void GetConverter()
{
foreach (Tuple<Type, Type> pair in s_typesWithConverters)
{
TypeConverter converter = TypeDescriptor.GetConverter(pair.Item1);
Assert.NotNull(converter);
Assert.Equal(pair.Item2, converter.GetType());
Assert.True(converter.CanConvertTo(typeof(string)));
}
}
[Fact]
public static void GetConverter_null()
{
Assert.Throws<ArgumentNullException>(() => TypeDescriptor.GetConverter(null));
}
[Fact]
public static void GetConverter_NotAvailable()
{
Assert.Throws<MissingMethodException>(
() => TypeDescriptor.GetConverter(typeof(ClassWithInvalidConverter)));
// GetConverter should throw MissingMethodException because parameterless constructor is missing in the InvalidConverter class.
}
[Fact]
public void GetEvents()
{
var component = new DescriptorTestComponent();
EventDescriptorCollection events = TypeDescriptor.GetEvents(component);
Assert.Equal(2, events.Count);
}
[Fact]
public void GetEventsFiltersByAttribute()
{
var defaultValueAttribute = new DefaultValueAttribute(null);
EventDescriptorCollection events = TypeDescriptor.GetEvents(typeof(DescriptorTestComponent), new[] { defaultValueAttribute });
Assert.Equal(1, events.Count);
}
[Fact]
public void GetPropertiesFiltersByAttribute()
{
var defaultValueAttribute = new DefaultValueAttribute(DescriptorTestComponent.DefaultPropertyValue);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(DescriptorTestComponent), new[] { defaultValueAttribute });
Assert.Equal(1, properties.Count);
}
[Fact]
public void RemoveAssociationsRemovesAllAssociations()
{
var primaryObject = new DescriptorTestComponent();
var firstAssociatedObject = new MockEventDescriptor();
var secondAssociatedObject = new MockPropertyDescriptor();
TypeDescriptor.CreateAssociation(primaryObject, firstAssociatedObject);
TypeDescriptor.CreateAssociation(primaryObject, secondAssociatedObject);
TypeDescriptor.RemoveAssociations(primaryObject);
// GetAssociation never returns null. The default implementation returns the
// primary object when an association doesn't exist. This isn't documented,
// however, so here we only verify that the formerly associated objects aren't returned.
var firstAssociation = TypeDescriptor.GetAssociation(firstAssociatedObject.GetType(), primaryObject);
Assert.NotEqual(firstAssociatedObject, firstAssociation);
var secondAssociation = TypeDescriptor.GetAssociation(secondAssociatedObject.GetType(), primaryObject);
Assert.NotEqual(secondAssociatedObject, secondAssociation);
}
[Fact]
public void RemoveSingleAssociation()
{
var primaryObject = new DescriptorTestComponent();
var firstAssociatedObject = new MockEventDescriptor();
var secondAssociatedObject = new MockPropertyDescriptor();
TypeDescriptor.CreateAssociation(primaryObject, firstAssociatedObject);
TypeDescriptor.CreateAssociation(primaryObject, secondAssociatedObject);
TypeDescriptor.RemoveAssociation(primaryObject, firstAssociatedObject);
// the second association should remain
var secondAssociation = TypeDescriptor.GetAssociation(secondAssociatedObject.GetType(), primaryObject);
Assert.Equal(secondAssociatedObject, secondAssociation);
// the first association should not
var firstAssociation = TypeDescriptor.GetAssociation(firstAssociatedObject.GetType(), primaryObject);
Assert.NotEqual(firstAssociatedObject, firstAssociation);
}
private class InvocationRecordingTypeDescriptionProvider : TypeDescriptionProvider
{
public bool ReceivedCall { get; private set; } = false;
public void Reset() => ReceivedCall = false;
public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
{
ReceivedCall = true;
return base.CreateInstance(provider, objectType, argTypes, args);
}
public override IDictionary GetCache(object instance)
{
ReceivedCall = true;
return base.GetCache(instance);
}
public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance)
{
ReceivedCall = true;
return base.GetExtendedTypeDescriptor(instance);
}
public override string GetFullComponentName(object component)
{
ReceivedCall = true;
return base.GetFullComponentName(component);
}
public override Type GetReflectionType(Type objectType, object instance)
{
ReceivedCall = true;
return base.GetReflectionType(objectType, instance);
}
protected override IExtenderProvider[] GetExtenderProviders(object instance)
{
ReceivedCall = true;
return base.GetExtenderProviders(instance);
}
public override Type GetRuntimeType(Type reflectionType)
{
ReceivedCall = true;
return base.GetRuntimeType(reflectionType);
}
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
ReceivedCall = true;
return base.GetTypeDescriptor(objectType, instance);
}
public override bool IsSupportedType(Type type)
{
ReceivedCall = true;
return base.IsSupportedType(type);
}
}
private static Tuple<Type, Type>[] s_typesWithConverters =
{
new Tuple<Type, Type> (typeof(bool), typeof(BooleanConverter)),
new Tuple<Type, Type> (typeof(byte), typeof(ByteConverter)),
new Tuple<Type, Type> (typeof(SByte), typeof(SByteConverter)),
new Tuple<Type, Type> (typeof(char), typeof(CharConverter)),
new Tuple<Type, Type> (typeof(double), typeof(DoubleConverter)),
new Tuple<Type, Type> (typeof(string), typeof(StringConverter)),
new Tuple<Type, Type> (typeof(short), typeof(Int16Converter)),
new Tuple<Type, Type> (typeof(int), typeof(Int32Converter)),
new Tuple<Type, Type> (typeof(long), typeof(Int64Converter)),
new Tuple<Type, Type> (typeof(float), typeof(SingleConverter)),
new Tuple<Type, Type> (typeof(UInt16), typeof(UInt16Converter)),
new Tuple<Type, Type> (typeof(UInt32), typeof(UInt32Converter)),
new Tuple<Type, Type> (typeof(UInt64), typeof(UInt64Converter)),
new Tuple<Type, Type> (typeof(object), typeof(TypeConverter)),
new Tuple<Type, Type> (typeof(void), typeof(TypeConverter)),
new Tuple<Type, Type> (typeof(DateTime), typeof(DateTimeConverter)),
new Tuple<Type, Type> (typeof(DateTimeOffset), typeof(DateTimeOffsetConverter)),
new Tuple<Type, Type> (typeof(Decimal), typeof(DecimalConverter)),
new Tuple<Type, Type> (typeof(TimeSpan), typeof(TimeSpanConverter)),
new Tuple<Type, Type> (typeof(Guid), typeof(GuidConverter)),
new Tuple<Type, Type> (typeof(Array), typeof(ArrayConverter)),
new Tuple<Type, Type> (typeof(ICollection), typeof(CollectionConverter)),
new Tuple<Type, Type> (typeof(Enum), typeof(EnumConverter)),
new Tuple<Type, Type> (typeof(SomeEnum), typeof(EnumConverter)),
new Tuple<Type, Type> (typeof(SomeValueType?), typeof(NullableConverter)),
new Tuple<Type, Type> (typeof(int?), typeof(NullableConverter)),
new Tuple<Type, Type> (typeof(ClassWithNoConverter), typeof(TypeConverter)),
new Tuple<Type, Type> (typeof(BaseClass), typeof(BaseClassConverter)),
new Tuple<Type, Type> (typeof(DerivedClass), typeof(DerivedClassConverter)),
new Tuple<Type, Type> (typeof(IBase), typeof(IBaseConverter)),
new Tuple<Type, Type> (typeof(IDerived), typeof(IBaseConverter)),
new Tuple<Type, Type> (typeof(ClassIBase), typeof(IBaseConverter)),
new Tuple<Type, Type> (typeof(ClassIDerived), typeof(IBaseConverter)),
new Tuple<Type, Type> (typeof(Uri), typeof(UriTypeConverter))
};
}
}
| |
/*
Copyright 2015 Shane Lillie
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.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Views;
using Android.Widget;
using EnergonSoftware.BackpackPlanner.Core.Logging;
using EnergonSoftware.BackpackPlanner.DAL;
using EnergonSoftware.BackpackPlanner.DAL.Models;
using EnergonSoftware.BackpackPlanner.Droid.Adapters;
using EnergonSoftware.BackpackPlanner.Droid.Util;
namespace EnergonSoftware.BackpackPlanner.Droid.Fragments
{
/// <summary>
/// Helper for the data listing fragments
/// </summary>
public abstract class ListItemsFragment<T> : RecyclerFragment where T: BaseModel<T>, IBackpackPlannerItem, new()
{
private static readonly ILogger Logger = CustomLogger.GetLogger(typeof(ListItemsFragment<T>));
private sealed class ListAdapterDataObserver : Android.Support.V7.Widget.RecyclerView.AdapterDataObserver
{
private readonly ListItemsFragment<T> _fragment;
public ListAdapterDataObserver(ListItemsFragment<T> fragment)
{
_fragment = fragment;
}
public override void OnChanged()
{
base.OnChanged();
_fragment.UpdateView();
}
}
private sealed class SwipeHandler : Android.Support.V7.Widget.Helper.ItemTouchHelper.SimpleCallback
{
private readonly BaseModelRecyclerListAdapter<T> _adapter;
private readonly Paint _paint = new Paint();
private readonly Bitmap _deleteIcon;
public SwipeHandler(BaseModelRecyclerListAdapter<T> adapter, int dragDirs, int swipeDirs)
: base(dragDirs, swipeDirs)
{
_adapter = adapter;
_deleteIcon = BitmapFactory.DecodeResource(_adapter.Fragment.Context.Resources, Resource.Drawable.ic_delete);
}
public override bool OnMove(Android.Support.V7.Widget.RecyclerView recyclerView, Android.Support.V7.Widget.RecyclerView.ViewHolder viewHolder, Android.Support.V7.Widget.RecyclerView.ViewHolder target)
{
return false;
}
public override void OnSwiped(Android.Support.V7.Widget.RecyclerView.ViewHolder viewHolder, int direction)
{
// http://stackoverflow.com/questions/27293960/swipe-to-dismiss-for-recyclerview
int position = viewHolder.AdapterPosition;
// TODO: this is the remove "cancel" code just to prevent the swipe from fucking up the UI
// this still needs to be fully implemented
_adapter.NotifyItemRemoved(position /*+ 1*/);
_adapter.NotifyItemRangeChanged(position, _adapter.ItemCount);
}
public override void OnChildDraw(Canvas c, Android.Support.V7.Widget.RecyclerView recyclerView, Android.Support.V7.Widget.RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
{
// http://stackoverflow.com/questions/30820806/adding-a-colored-background-with-text-icon-under-swiped-row-when-using-androids
View itemView = viewHolder.ItemView;
if(Android.Support.V7.Widget.Helper.ItemTouchHelper.ActionStateSwipe == actionState) {
if(dX > 0) {
// background
_paint.SetARGB(255, 255, 0, 0);
c.DrawRect(itemView.Left, itemView.Top, dX, itemView.Bottom, _paint);
// icon
c.DrawBitmap(_deleteIcon, itemView.Left + DisplayUtil.DpToPx(16.0f, _adapter.Fragment.Context), itemView.Top + (itemView.Bottom - itemView.Top - itemView.Height / 2.0f), _paint);
}
}
base.OnChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
}
protected abstract int WhatIsAnItemButtonResource { get; }
protected abstract int WhatIsAnItemTitleResource { get; }
protected abstract int WhatIsAnItemTextResource { get; }
protected abstract int DeleteItemConfirmationTextResource { get; }
protected abstract int DeleteItemConfirmationTitleResource { get; }
protected abstract int NoItemsResource { get; }
protected abstract int SortItemsResource { get; }
protected abstract int AddItemResource { get; }
protected override bool HasSearchView => true;
protected override bool CanExport => true;
protected BaseModelRecyclerListAdapter<T> Adapter { get; private set; }
private TextView _noItemsTextView;
public Spinner SortItemsSpinner { get; private set; }
protected abstract Android.Support.V4.App.Fragment CreateAddItemFragment();
protected abstract BaseModelRecyclerListAdapter<T> CreateAdapter();
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
base.OnViewCreated(view, savedInstanceState);
Adapter = CreateAdapter();
Layout.SetAdapter(Adapter);
AttachSwipeHandler(new SwipeHandler(Adapter, 0, Android.Support.V7.Widget.Helper.ItemTouchHelper.Right));
Adapter.RegisterAdapterDataObserver(new ListAdapterDataObserver(this));
_noItemsTextView = View.FindViewById<TextView>(NoItemsResource);
SortItemsSpinner = View.FindViewById<Spinner>(SortItemsResource);
SortItemsSpinner.ItemSelected += Adapter.SortByItemSelectedEventHander;
Button whatIsAButton = view.FindViewById<Button>(WhatIsAnItemButtonResource);
whatIsAButton.Click += (sender, args) =>
{
DialogUtil.ShowOkAlert(Activity, WhatIsAnItemTextResource, WhatIsAnItemTitleResource);
};
Android.Support.Design.Widget.FloatingActionButton addItemButton = view.FindViewById<Android.Support.Design.Widget.FloatingActionButton>(AddItemResource);
addItemButton.Click += (sender, args) =>
{
TransitionToFragment(Resource.Id.frame_content, CreateAddItemFragment(), null);
};
}
public override void OnResume()
{
base.OnResume();
PopulateList();
}
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
base.OnCreateOptionsMenu(menu, inflater);
FilterView.QueryTextChange += Adapter.FilterItemsEventHandler;
}
protected abstract Task<IReadOnlyCollection<T>> GetItemsAsync(DatabaseContext dbContext);
protected void PopulateList()
{
ProgressDialog progressDialog = DialogUtil.ShowProgressDialog(Activity, Resource.String.label_loading_items, false, true);
Task.Run(async () =>
{
IReadOnlyCollection<T> items;
using(DatabaseContext dbContext = BaseActivity.BackpackPlannerState.DatabaseState.CreateContext()) {
try {
items = await GetItemsAsync(dbContext).ConfigureAwait(false);
} catch(Exception e) {
Logger.Error($"Error loading {typeof(T)}s: {e.Message}", e);
items = null;
}
}
Activity.RunOnUiThread(() =>
{
progressDialog.Dismiss();
if(null == items) {
DialogUtil.ShowOkAlert(Activity, Resource.String.message_error_reading_items, Resource.String.title_error_reading_items);
return;
}
Logger.Debug($"Read {items.Count} {typeof(T)}s...");
Adapter.FullListItems = items;
});
}
);
}
public void DeleteItem(T item)
{
DialogUtil.ShowOkCancelAlert(Activity, DeleteItemConfirmationTextResource, DeleteItemConfirmationTitleResource,
(sender, args) => DeleteItemEventHandler(sender, args, item));
}
private void DeleteItemEventHandler(object sender, DialogClickEventArgs args, T item)
{
ProgressDialog progressDialog = DialogUtil.ShowProgressDialog(Activity, Resource.String.label_deleting_item, false, true);
Task.Run(async () =>
{
int count;
using(DatabaseContext dbContext = BaseActivity.BackpackPlannerState.DatabaseState.CreateContext()) {
try {
item.IsDeleted = true;
count = await dbContext.SaveChangesAsync().ConfigureAwait(false);
item.OnRemove();
} catch(Exception e) {
Logger.Error($"Error deleting {typeof(T)}: {e.Message}", e);
item.IsDeleted = false;
count = -1;
}
}
Activity.RunOnUiThread(() =>
{
progressDialog.Dismiss();
if(count < 1) {
DialogUtil.ShowOkAlert(Activity, Resource.String.message_error_deleting_item, Resource.String.title_error_deleting_item);
return;
}
Adapter.RemoveItem(item);
SnackbarUtil.ShowUndoSnackbar(View, Resource.String.label_deleted_item, Android.Support.Design.Widget.Snackbar.LengthLong,
view => UndoDeleteItemEventHandler(view, item));
});
}
);
}
private void UndoDeleteItemEventHandler(View view, T item)
{
ProgressDialog progressDialog = DialogUtil.ShowProgressDialog(Activity, Resource.String.label_deleted_item_undoing, false, true);
Task.Run(async () =>
{
int count;
using(DatabaseContext dbContext = BaseActivity.BackpackPlannerState.DatabaseState.CreateContext()) {
try {
item.IsDeleted = false;
count = await dbContext.SaveChangesAsync().ConfigureAwait(false);
// TODO: re-hook any PropertyChanged listeners
} catch(Exception e) {
Logger.Error($"Error restoring {typeof(T)}: {e.Message}", e);
item.IsDeleted = true;
count = -1;
}
}
Activity.RunOnUiThread(() =>
{
progressDialog.Dismiss();
if(count < 1) {
DialogUtil.ShowOkAlert(Activity, Resource.String.message_error_restoring_item, Resource.String.title_error_restoring_item);
return;
}
Adapter.AddItem(item);
SnackbarUtil.ShowSnackbar(view, Resource.String.label_deleted_item_undone, Android.Support.Design.Widget.Snackbar.LengthShort);
});
}
);
}
protected override void UpdateView()
{
base.UpdateView();
bool hasItems = Adapter.ItemCount > 0;
_noItemsTextView.Visibility = hasItems ? ViewStates.Gone : ViewStates.Visible;
if(null != SortItemsSpinner) {
SortItemsSpinner.Visibility = hasItems ? ViewStates.Visible : ViewStates.Gone;
}
Layout.Visibility = hasItems ? ViewStates.Visible : ViewStates.Gone;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Servers. Contains operations to: Create, Retrieve, Update, and Delete
/// servers.
/// </summary>
internal partial class ServerOperations : IServiceOperations<SqlManagementClient>, IServerOperations
{
/// <summary>
/// Initializes a new instance of the ServerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServerOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates a new Azure SQL Database server.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Database request.
/// </returns>
public async Task<ServerGetResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, ServerCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Tags == null)
{
throw new ArgumentNullException("parameters.Tags");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Sql/servers/" + serverName.Trim() + "?";
url = url + "api-version=2014-04-01";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject serverCreateOrUpdateParametersValue = new JObject();
requestDoc = serverCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
serverCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Version != null)
{
propertiesValue["version"] = parameters.Properties.Version;
}
if (parameters.Properties.AdministratorLogin != null)
{
propertiesValue["administratorLogin"] = parameters.Properties.AdministratorLogin;
}
if (parameters.Properties.AdministratorLoginPassword != null)
{
propertiesValue["administratorLoginPassword"] = parameters.Properties.AdministratorLoginPassword;
}
serverCreateOrUpdateParametersValue["location"] = parameters.Location;
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
serverCreateOrUpdateParametersValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Server serverInstance = new Server();
result.Server = serverInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
ServerProperties propertiesInstance = new ServerProperties();
serverInstance.Properties = propertiesInstance;
JToken fullyQualifiedDomainNameValue = propertiesValue2["fullyQualifiedDomainName"];
if (fullyQualifiedDomainNameValue != null && fullyQualifiedDomainNameValue.Type != JTokenType.Null)
{
string fullyQualifiedDomainNameInstance = ((string)fullyQualifiedDomainNameValue);
propertiesInstance.FullyQualifiedDomainName = fullyQualifiedDomainNameInstance;
}
JToken versionValue = propertiesValue2["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
propertiesInstance.Version = versionInstance;
}
JToken administratorLoginValue = propertiesValue2["administratorLogin"];
if (administratorLoginValue != null && administratorLoginValue.Type != JTokenType.Null)
{
string administratorLoginInstance = ((string)administratorLoginValue);
propertiesInstance.AdministratorLogin = administratorLoginInstance;
}
JToken administratorLoginPasswordValue = propertiesValue2["administratorLoginPassword"];
if (administratorLoginPasswordValue != null && administratorLoginPasswordValue.Type != JTokenType.Null)
{
string administratorLoginPasswordInstance = ((string)administratorLoginPasswordValue);
propertiesInstance.AdministratorLoginPassword = administratorLoginPasswordInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverInstance.Id = idInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
serverInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about an Azure SQL Database Server.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the server to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> DeleteAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Sql/servers/" + serverName.Trim() + "?";
url = url + "api-version=2014-04-01";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about an Azure SQL Database Server.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the server to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Database request.
/// </returns>
public async Task<ServerGetResponse> GetAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Sql/servers/" + serverName.Trim() + "?";
url = url + "api-version=2014-04-01";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Server serverInstance = new Server();
result.Server = serverInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerProperties propertiesInstance = new ServerProperties();
serverInstance.Properties = propertiesInstance;
JToken fullyQualifiedDomainNameValue = propertiesValue["fullyQualifiedDomainName"];
if (fullyQualifiedDomainNameValue != null && fullyQualifiedDomainNameValue.Type != JTokenType.Null)
{
string fullyQualifiedDomainNameInstance = ((string)fullyQualifiedDomainNameValue);
propertiesInstance.FullyQualifiedDomainName = fullyQualifiedDomainNameInstance;
}
JToken versionValue = propertiesValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
propertiesInstance.Version = versionInstance;
}
JToken administratorLoginValue = propertiesValue["administratorLogin"];
if (administratorLoginValue != null && administratorLoginValue.Type != JTokenType.Null)
{
string administratorLoginInstance = ((string)administratorLoginValue);
propertiesInstance.AdministratorLogin = administratorLoginInstance;
}
JToken administratorLoginPasswordValue = propertiesValue["administratorLoginPassword"];
if (administratorLoginPasswordValue != null && administratorLoginPasswordValue.Type != JTokenType.Null)
{
string administratorLoginPasswordInstance = ((string)administratorLoginPasswordValue);
propertiesInstance.AdministratorLoginPassword = administratorLoginPasswordInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverInstance.Id = idInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about an Azure SQL Database Server.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Database request.
/// </returns>
public async Task<ServerListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Sql/servers?";
url = url + "api-version=2014-04-01";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Server serverInstance = new Server();
result.Servers.Add(serverInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerProperties propertiesInstance = new ServerProperties();
serverInstance.Properties = propertiesInstance;
JToken fullyQualifiedDomainNameValue = propertiesValue["fullyQualifiedDomainName"];
if (fullyQualifiedDomainNameValue != null && fullyQualifiedDomainNameValue.Type != JTokenType.Null)
{
string fullyQualifiedDomainNameInstance = ((string)fullyQualifiedDomainNameValue);
propertiesInstance.FullyQualifiedDomainName = fullyQualifiedDomainNameInstance;
}
JToken versionValue = propertiesValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
propertiesInstance.Version = versionInstance;
}
JToken administratorLoginValue = propertiesValue["administratorLogin"];
if (administratorLoginValue != null && administratorLoginValue.Type != JTokenType.Null)
{
string administratorLoginInstance = ((string)administratorLoginValue);
propertiesInstance.AdministratorLogin = administratorLoginInstance;
}
JToken administratorLoginPasswordValue = propertiesValue["administratorLoginPassword"];
if (administratorLoginPasswordValue != null && administratorLoginPasswordValue.Type != JTokenType.Null)
{
string administratorLoginPasswordInstance = ((string)administratorLoginPasswordValue);
propertiesInstance.AdministratorLoginPassword = administratorLoginPasswordInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverInstance.Id = idInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text; // StringBuilder
using System.Xml;
// important TODOS:
// TODO 1. Start tags: The ParseXmlElement function has been modified to be called after both the
// angle bracket < and element name have been read, instead of just the < bracket and some valid name character,
// previously the case. This change was made so that elements with optional closing tags could read a new
// element's start tag and decide whether they were required to close. However, there is a question of whether to
// handle this in the parser or lexical analyzer. It is currently handled in the parser - the lexical analyzer still
// recognizes a start tag opener as a '<' + valid name start char; it is the parser that reads the actual name.
// this is correct behavior assuming that the name is a valid html name, because the lexical analyzer should not know anything
// about optional closing tags, etc. UPDATED: 10/13/2004: I am updating this to read the whole start tag of something
// that is not an HTML, treat it as empty, and add it to the tree. That way the converter will know it's there, but
// it will hvae no content. We could also partially recover by trying to look up and match names if they are similar
// TODO 2. Invalid element names: However, it might make sense to give the lexical analyzer the ability to identify
// a valid html element name and not return something as a start tag otherwise. For example, if we type <good>, should
// the lexical analyzer return that it has found the start of an element when this is not the case in HTML? But this will
// require implementing a lookahead token in the lexical analyzer so that it can treat an invalid element name as text. One
// character of lookahead will not be enough.
// TODO 3. Attributes: The attribute recovery is poor when reading attribute values in quotes - if no closing quotes are found,
// the lexical analyzer just keeps reading and if it eventually reaches the end of file, it would have just skipped everything.
// There are a couple of ways to deal with this: 1) stop reading attributes when we encounter a '>' character - this doesn't allow
// the '>' character to be used in attribute values, but it can still be used as an entity. 2) Maintain a HTML-specific list
// of attributes and their values that each html element can take, and if we find correct attribute namesand values for an
// element we use them regardless of the quotes, this way we could just ignore something invalid. One more option: 3) Read ahead
// in the quoted value and if we find an end of file, we can return to where we were and process as text. However this requires
// a lot of lookahead and a resettable reader.
// TODO 4: elements with optional closing tags: For elements with optional closing tags, we always close the element if we find
// that one of it's ancestors has closed. This condition may be too broad and we should develop a better heuristic. We should also
// improve the heuristics for closing certain elements when the next element starts
// TODO 5. Nesting: Support for unbalanced nesting, e.g. <b> <i> </b> </i>: this is not presently supported. To support it we may need
// to maintain two xml elements, one the element that represents what has already been read and another represents what we are presently reading.
// Then if we encounter an unbalanced nesting tag we could close the element that was supposed to close, save the current element
// and store it in the list of already-read content, and then open a new element to which all tags that are currently open
// can be applied. Is there a better way to do this? Should we do it at all?
// TODO 6. Elements with optional starting tags: there are 4 such elements in the HTML 4 specification - html, tbody, body and head.
// The current recovery doesn;t do anything for any of these elements except the html element, because it's not critical - head
// and body elementscan be contained within html element, and tbody is contained within table. To extend this for XHTML
// extensions, and to recover in case other elements are missing start tags, we would need to insert an extra recursive call
// to ParseXmlElement for the missing start tag. It is suggested to do this by giving ParseXmlElement an argument that specifies
// a name to use. If this argument is null, it assumes its name is the next token from the lexical analyzer and continues
// exactly as it does now. However, if the argument contains a valid html element name then it takes that value as its name
// and continues as before. This way, if the next token is the element that should actually be its child, it will see
// the name in the next step and initiate a recursive call. We would also need to add some logic in the loop for when a start tag
// is found - if the start tag is not compatible with current context and indicates that a start tag has been missed, then we
// can initiate the extra recursive call and give it the name of the missed start tag. The issues are when to insert this logic,
// and if we want to support it over multiple missing start tags. If we insert it at the time a start tag is read in element
// text, then we can support only one missing start tag, since the extra call will read the next start tag and make a recursive
// call without checking the context. This is a conceptual problem, and the check should be made just before a recursive call,
// with the choice being whether we should supply an element name as argument, or leave it as NULL and read from the input
// TODO 7: Context: Is it appropriate to keep track of context here? For example, should we only expect td, tr elements when
// reading a table and ignore them otherwise? This may be too much of a load on the parser, I think it's better if the converter
// deals with it
namespace Memento.Core.Converter
{
/// <summary>
/// HtmlParser class accepts a string of possibly badly formed Html, parses it and returns a string
/// of well-formed Html that is as close to the original string in content as possible
/// </summary>
internal class HtmlParser
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor. Initializes the _htmlLexicalAnalayzer element with the given input string
/// </summary>
/// <param name="inputString">
/// string to parsed into well-formed Html
/// </param>
private HtmlParser(string inputString)
{
// Create an output xml document
_document = new XmlDocument();
// initialize open tag stack
_openedElements = new Stack<XmlElement>();
_pendingInlineElements = new Stack<XmlElement>();
// initialize lexical analyzer
_htmlLexicalAnalyzer = new HtmlLexicalAnalyzer(inputString);
// get first token from input, expecting text
_htmlLexicalAnalyzer.GetNextContentToken();
}
#endregion Constructors
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Instantiates an HtmlParser element and calls the parsing function on the given input string
/// </summary>
/// <param name="htmlString">
/// Input string of pssibly badly-formed Html to be parsed into well-formed Html
/// </param>
/// <returns>
/// XmlElement rep
/// </returns>
internal static XmlElement ParseHtml(string htmlString)
{
HtmlParser htmlParser = new HtmlParser(htmlString);
XmlElement htmlRootElement = htmlParser.ParseHtmlContent();
return htmlRootElement;
}
// .....................................................................
//
// Html Header on Clipboard
//
// .....................................................................
// Html header structure.
// Version:1.0
// StartHTML:000000000
// EndHTML:000000000
// StartFragment:000000000
// EndFragment:000000000
// StartSelection:000000000
// EndSelection:000000000
internal const string HtmlHeader = "Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\nStartSelection:{4:D10}\r\nEndSelection:{5:D10}\r\n";
internal const string HtmlStartFragmentComment = "<!--StartFragment-->";
internal const string HtmlEndFragmentComment = "<!--EndFragment-->";
/// <summary>
/// Extracts Html string from clipboard data by parsing header information in htmlDataString
/// </summary>
/// <param name="htmlDataString">
/// String representing Html clipboard data. This includes Html header
/// </param>
/// <returns>
/// String containing only the Html data part of htmlDataString, without header
/// </returns>
internal static string ExtractHtmlFromClipboardData(string htmlDataString)
{
int startHtmlIndex = htmlDataString.IndexOf("StartHTML:");
if (startHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
startHtmlIndex = Int32.Parse(htmlDataString.Substring(startHtmlIndex + "StartHTML:".Length, "0123456789".Length));
if (startHtmlIndex < 0 || startHtmlIndex > htmlDataString.Length)
{
return "ERROR: Urecognized html header";
}
int endHtmlIndex = htmlDataString.IndexOf("EndHTML:");
if (endHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
endHtmlIndex = Int32.Parse(htmlDataString.Substring(endHtmlIndex + "EndHTML:".Length, "0123456789".Length));
if (endHtmlIndex > htmlDataString.Length)
{
endHtmlIndex = htmlDataString.Length;
}
return htmlDataString.Substring(startHtmlIndex, endHtmlIndex - startHtmlIndex);
}
/// <summary>
/// Adds Xhtml header information to Html data string so that it can be placed on clipboard
/// </summary>
/// <param name="htmlString">
/// Html string to be placed on clipboard with appropriate header
/// </param>
/// <returns>
/// String wrapping htmlString with appropriate Html header
/// </returns>
internal static string AddHtmlClipboardHeader(string htmlString)
{
StringBuilder stringBuilder = new StringBuilder();
// each of 6 numbers is represented by "{0:D10}" in the format string
// must actually occupy 10 digit positions ("0123456789")
int startHTML = HtmlHeader.Length + 6 * ("0123456789".Length - "{0:D10}".Length);
int endHTML = startHTML + htmlString.Length;
int startFragment = htmlString.IndexOf(HtmlStartFragmentComment, 0);
if (startFragment >= 0)
{
startFragment = startHTML + startFragment + HtmlStartFragmentComment.Length;
}
else
{
startFragment = startHTML;
}
int endFragment = htmlString.IndexOf(HtmlEndFragmentComment, 0);
if (endFragment >= 0)
{
endFragment = startHTML + endFragment;
}
else
{
endFragment = endHTML;
}
// Create HTML clipboard header string
stringBuilder.AppendFormat(HtmlHeader, startHTML, endHTML, startFragment, endFragment, startFragment, endFragment);
// Append HTML body.
stringBuilder.Append(htmlString);
return stringBuilder.ToString();
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Private methods
//
// ---------------------------------------------------------------------
#region Private Methods
private void InvariantAssert(bool condition, string message)
{
if (!condition)
{
throw new Exception("Assertion error: " + message);
}
}
/// <summary>
/// Parses the stream of html tokens starting
/// from the name of top-level element.
/// Returns XmlElement representing the top-level
/// html element
/// </summary>
private XmlElement ParseHtmlContent()
{
// Create artificial root elelemt to be able to group multiple top-level elements
// We create "html" element which may be a duplicate of real HTML element, which is ok, as HtmlConverter will swallow it painlessly..
XmlElement htmlRootElement = _document.CreateElement("html", XhtmlNamespace);
OpenStructuringElement(htmlRootElement);
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF)
{
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.OpeningTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower();
_htmlLexicalAnalyzer.GetNextTagToken();
// Create an element
XmlElement htmlElement = _document.CreateElement(htmlElementName, XhtmlNamespace);
// Parse element attributes
ParseAttributes(htmlElement);
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.EmptyTagEnd || HtmlSchema.IsEmptyElement(htmlElementName))
{
// It is an element without content (because of explicit slash or based on implicit knowledge aboout html)
AddEmptyElement(htmlElement);
}
else if (HtmlSchema.IsInlineElement(htmlElementName))
{
// Elements known as formatting are pushed to some special
// pending stack, which allows them to be transferred
// over block tags - by doing this we convert
// overlapping tags into normal heirarchical element structure.
OpenInlineElement(htmlElement);
}
else if (HtmlSchema.IsBlockElement(htmlElementName) || HtmlSchema.IsKnownOpenableElement(htmlElementName))
{
// This includes no-scope elements
OpenStructuringElement(htmlElement);
}
else
{
// Do nothing. Skip the whole opening tag.
// Ignoring all unknown elements on their start tags.
// Thus we will ignore them on closinng tag as well.
// Anyway we don't know what to do withthem on conversion to Xaml.
}
}
else
{
// Note that the token following opening angle bracket must be a name - lexical analyzer must guarantee that.
// Otherwise - we skip the angle bracket and continue parsing the content as if it is just text.
// Add the following asserion here, right? or output "<" as a text run instead?:
// InvariantAssert(false, "Angle bracket without a following name is not expected");
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.ClosingTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower();
// Skip the name token. Assume that the following token is end of tag,
// but do not check this. If it is not true, we simply ignore one token
// - this is our recovery from bad xml in this case.
_htmlLexicalAnalyzer.GetNextTagToken();
CloseElement(htmlElementName);
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Text)
{
AddTextContent(_htmlLexicalAnalyzer.NextToken);
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Comment)
{
AddComment(_htmlLexicalAnalyzer.NextToken);
}
_htmlLexicalAnalyzer.GetNextContentToken();
}
// Get rid of the artificial root element
if (htmlRootElement.FirstChild is XmlElement &&
htmlRootElement.FirstChild == htmlRootElement.LastChild &&
htmlRootElement.FirstChild.LocalName.ToLower() == "html")
{
htmlRootElement = (XmlElement)htmlRootElement.FirstChild;
}
return htmlRootElement;
}
private XmlElement CreateElementCopy(XmlElement htmlElement)
{
XmlElement htmlElementCopy = _document.CreateElement(htmlElement.LocalName, XhtmlNamespace);
for (int i = 0; i < htmlElement.Attributes.Count; i++)
{
XmlAttribute attribute = htmlElement.Attributes[i];
htmlElementCopy.SetAttribute(attribute.Name, attribute.Value);
}
return htmlElementCopy;
}
private void AddEmptyElement(XmlElement htmlEmptyElement)
{
InvariantAssert(_openedElements.Count > 0, "AddEmptyElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlEmptyElement);
}
private void OpenInlineElement(XmlElement htmlInlineElement)
{
_pendingInlineElements.Push(htmlInlineElement);
}
// Opens structurig element such as Div or Table etc.
private void OpenStructuringElement(XmlElement htmlElement)
{
// Close all pending inline elements
// All block elements are considered as delimiters for inline elements
// which forces all inline elements to be closed and re-opened in the following
// structural element (if any).
// By doing that we guarantee that all inline elements appear only within most nested blocks
if (HtmlSchema.IsBlockElement(htmlElement.LocalName))
{
while (_openedElements.Count > 0 && HtmlSchema.IsInlineElement(_openedElements.Peek().LocalName))
{
XmlElement htmlInlineElement = _openedElements.Pop();
InvariantAssert(_openedElements.Count > 0, "OpenStructuringElement: stack of opened elements cannot become empty here");
_pendingInlineElements.Push(CreateElementCopy(htmlInlineElement));
}
}
// Add this block element to its parent
if (_openedElements.Count > 0)
{
XmlElement htmlParent = _openedElements.Peek();
// Check some known block elements for auto-closing (LI and P)
if (HtmlSchema.ClosesOnNextElementStart(htmlParent.LocalName, htmlElement.LocalName))
{
_openedElements.Pop();
htmlParent = _openedElements.Count > 0 ? _openedElements.Peek() : null;
}
if (htmlParent != null)
{
// NOTE:
// Actually we never expect null - it would mean two top-level P or LI (without a parent).
// In such weird case we will loose all paragraphs except the first one...
htmlParent.AppendChild(htmlElement);
}
}
// Push it onto a stack
_openedElements.Push(htmlElement);
}
private bool IsElementOpened(string htmlElementName)
{
foreach (XmlElement openedElement in _openedElements)
{
if (openedElement.LocalName == htmlElementName)
{
return true;
}
}
return false;
}
private void CloseElement(string htmlElementName)
{
// Check if the element is opened and already added to the parent
InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
// Check if the element is opened and still waiting to be added to the parent
if (_pendingInlineElements.Count > 0 && _pendingInlineElements.Peek().LocalName == htmlElementName)
{
// Closing an empty inline element.
// Note that HtmlConverter will skip empty inlines, but for completeness we keep them here on parser level.
XmlElement htmlInlineElement = _pendingInlineElements.Pop();
InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
return;
}
else if (IsElementOpened(htmlElementName))
{
while (_openedElements.Count > 1) // we never pop the last element - the artificial root
{
// Close all unbalanced elements.
XmlElement htmlOpenedElement = _openedElements.Pop();
if (htmlOpenedElement.LocalName == htmlElementName)
{
return;
}
if (HtmlSchema.IsInlineElement(htmlOpenedElement.LocalName))
{
// Unbalances Inlines will be transfered to the next element content
_pendingInlineElements.Push(CreateElementCopy(htmlOpenedElement));
}
}
}
// If element was not opened, we simply ignore the unbalanced closing tag
return;
}
private void AddTextContent(string textContent)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "AddTextContent: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
XmlText textNode = _document.CreateTextNode(textContent);
htmlParent.AppendChild(textNode);
}
private void AddComment(string comment)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "AddComment: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
XmlComment xmlComment = _document.CreateComment(comment);
htmlParent.AppendChild(xmlComment);
}
// Moves all inline elements pending for opening to actual document
// and adds them to current open stack.
private void OpenPendingInlineElements()
{
if (_pendingInlineElements.Count > 0)
{
XmlElement htmlInlineElement = _pendingInlineElements.Pop();
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "OpenPendingInlineElements: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
_openedElements.Push(htmlInlineElement);
}
}
private void ParseAttributes(XmlElement xmlElement)
{
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.TagEnd && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EmptyTagEnd)
{
// read next attribute (name=value)
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string attributeName = _htmlLexicalAnalyzer.NextToken;
_htmlLexicalAnalyzer.GetNextEqualSignToken();
_htmlLexicalAnalyzer.GetNextAtomToken();
string attributeValue = _htmlLexicalAnalyzer.NextToken;
xmlElement.SetAttribute(attributeName, attributeValue);
}
_htmlLexicalAnalyzer.GetNextTagToken();
}
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
internal const string XhtmlNamespace = "http://www.w3.org/1999/xhtml";
private HtmlLexicalAnalyzer _htmlLexicalAnalyzer;
// document from which all elements are created
private XmlDocument _document;
// stack for open elements
Stack<XmlElement> _openedElements;
Stack<XmlElement> _pendingInlineElements;
#endregion Private Fields
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// Static class that contains static glm functions
/// </summary>
public static partial class glm
{
/// <summary>
/// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy)
/// </summary>
public static swizzle_lvec2 swizzle(lvec2 v) => v.swizzle;
/// <summary>
/// Returns an array with all values
/// </summary>
public static long[] Values(lvec2 v) => v.Values;
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public static IEnumerator<long> GetEnumerator(lvec2 v) => v.GetEnumerator();
/// <summary>
/// Returns a string representation of this vector using ', ' as a seperator.
/// </summary>
public static string ToString(lvec2 v) => v.ToString();
/// <summary>
/// Returns a string representation of this vector using a provided seperator.
/// </summary>
public static string ToString(lvec2 v, string sep) => v.ToString(sep);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format provider for each component.
/// </summary>
public static string ToString(lvec2 v, string sep, IFormatProvider provider) => v.ToString(sep, provider);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format for each component.
/// </summary>
public static string ToString(lvec2 v, string sep, string format) => v.ToString(sep, format);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format and format provider for each component.
/// </summary>
public static string ToString(lvec2 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider);
/// <summary>
/// Returns the number of components (2).
/// </summary>
public static int Count(lvec2 v) => v.Count;
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool Equals(lvec2 v, lvec2 rhs) => v.Equals(rhs);
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public static bool Equals(lvec2 v, object obj) => v.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public static int GetHashCode(lvec2 v) => v.GetHashCode();
/// <summary>
/// Returns a bvec2 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec2 Equal(lvec2 lhs, lvec2 rhs) => lvec2.Equal(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec2 NotEqual(lvec2 lhs, lvec2 rhs) => lvec2.NotEqual(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec2 GreaterThan(lvec2 lhs, lvec2 rhs) => lvec2.GreaterThan(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec2 GreaterThanEqual(lvec2 lhs, lvec2 rhs) => lvec2.GreaterThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec2 LesserThan(lvec2 lhs, lvec2 rhs) => lvec2.LesserThan(lhs, rhs);
/// <summary>
/// Returns a bvec2 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec2 LesserThanEqual(lvec2 lhs, lvec2 rhs) => lvec2.LesserThanEqual(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of Abs (Math.Abs(v)).
/// </summary>
public static lvec2 Abs(lvec2 v) => lvec2.Abs(v);
/// <summary>
/// Returns a lvec2 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v).
/// </summary>
public static lvec2 HermiteInterpolationOrder3(lvec2 v) => lvec2.HermiteInterpolationOrder3(v);
/// <summary>
/// Returns a lvec2 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v).
/// </summary>
public static lvec2 HermiteInterpolationOrder5(lvec2 v) => lvec2.HermiteInterpolationOrder5(v);
/// <summary>
/// Returns a lvec2 from component-wise application of Sqr (v * v).
/// </summary>
public static lvec2 Sqr(lvec2 v) => lvec2.Sqr(v);
/// <summary>
/// Returns a lvec2 from component-wise application of Pow2 (v * v).
/// </summary>
public static lvec2 Pow2(lvec2 v) => lvec2.Pow2(v);
/// <summary>
/// Returns a lvec2 from component-wise application of Pow3 (v * v * v).
/// </summary>
public static lvec2 Pow3(lvec2 v) => lvec2.Pow3(v);
/// <summary>
/// Returns a lvec2 from component-wise application of Step (v >= 0 ? 1 : 0).
/// </summary>
public static lvec2 Step(lvec2 v) => lvec2.Step(v);
/// <summary>
/// Returns a lvec2 from component-wise application of Sqrt ((long)Math.Sqrt((double)v)).
/// </summary>
public static lvec2 Sqrt(lvec2 v) => lvec2.Sqrt(v);
/// <summary>
/// Returns a lvec2 from component-wise application of InverseSqrt ((long)(1.0 / Math.Sqrt((double)v))).
/// </summary>
public static lvec2 InverseSqrt(lvec2 v) => lvec2.InverseSqrt(v);
/// <summary>
/// Returns a ivec2 from component-wise application of Sign (Math.Sign(v)).
/// </summary>
public static ivec2 Sign(lvec2 v) => lvec2.Sign(v);
/// <summary>
/// Returns a lvec2 from component-wise application of Max (Math.Max(lhs, rhs)).
/// </summary>
public static lvec2 Max(lvec2 lhs, lvec2 rhs) => lvec2.Max(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of Min (Math.Min(lhs, rhs)).
/// </summary>
public static lvec2 Min(lvec2 lhs, lvec2 rhs) => lvec2.Min(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of Pow ((long)Math.Pow((double)lhs, (double)rhs)).
/// </summary>
public static lvec2 Pow(lvec2 lhs, lvec2 rhs) => lvec2.Pow(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of Log ((long)Math.Log((double)lhs, (double)rhs)).
/// </summary>
public static lvec2 Log(lvec2 lhs, lvec2 rhs) => lvec2.Log(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)).
/// </summary>
public static lvec2 Clamp(lvec2 v, lvec2 min, lvec2 max) => lvec2.Clamp(v, min, max);
/// <summary>
/// Returns a lvec2 from component-wise application of Mix (min * (1-a) + max * a).
/// </summary>
public static lvec2 Mix(lvec2 min, lvec2 max, lvec2 a) => lvec2.Mix(min, max, a);
/// <summary>
/// Returns a lvec2 from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static lvec2 Lerp(lvec2 min, lvec2 max, lvec2 a) => lvec2.Lerp(min, max, a);
/// <summary>
/// Returns a lvec2 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()).
/// </summary>
public static lvec2 Smoothstep(lvec2 edge0, lvec2 edge1, lvec2 v) => lvec2.Smoothstep(edge0, edge1, v);
/// <summary>
/// Returns a lvec2 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()).
/// </summary>
public static lvec2 Smootherstep(lvec2 edge0, lvec2 edge1, lvec2 v) => lvec2.Smootherstep(edge0, edge1, v);
/// <summary>
/// Returns a lvec2 from component-wise application of Fma (a * b + c).
/// </summary>
public static lvec2 Fma(lvec2 a, lvec2 b, lvec2 c) => lvec2.Fma(a, b, c);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static lmat2 OuterProduct(lvec2 c, lvec2 r) => lvec2.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static lmat3x2 OuterProduct(lvec2 c, lvec3 r) => lvec2.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static lmat4x2 OuterProduct(lvec2 c, lvec4 r) => lvec2.OuterProduct(c, r);
/// <summary>
/// Returns a lvec2 from component-wise application of Add (lhs + rhs).
/// </summary>
public static lvec2 Add(lvec2 lhs, lvec2 rhs) => lvec2.Add(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of Sub (lhs - rhs).
/// </summary>
public static lvec2 Sub(lvec2 lhs, lvec2 rhs) => lvec2.Sub(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of Mul (lhs * rhs).
/// </summary>
public static lvec2 Mul(lvec2 lhs, lvec2 rhs) => lvec2.Mul(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of Div (lhs / rhs).
/// </summary>
public static lvec2 Div(lvec2 lhs, lvec2 rhs) => lvec2.Div(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of Xor (lhs ^ rhs).
/// </summary>
public static lvec2 Xor(lvec2 lhs, lvec2 rhs) => lvec2.Xor(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of BitwiseOr (lhs | rhs).
/// </summary>
public static lvec2 BitwiseOr(lvec2 lhs, lvec2 rhs) => lvec2.BitwiseOr(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of BitwiseAnd (lhs & rhs).
/// </summary>
public static lvec2 BitwiseAnd(lvec2 lhs, lvec2 rhs) => lvec2.BitwiseAnd(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of LeftShift (lhs << rhs).
/// </summary>
public static lvec2 LeftShift(lvec2 lhs, ivec2 rhs) => lvec2.LeftShift(lhs, rhs);
/// <summary>
/// Returns a lvec2 from component-wise application of RightShift (lhs >> rhs).
/// </summary>
public static lvec2 RightShift(lvec2 lhs, ivec2 rhs) => lvec2.RightShift(lhs, rhs);
/// <summary>
/// Returns the minimal component of this vector.
/// </summary>
public static long MinElement(lvec2 v) => v.MinElement;
/// <summary>
/// Returns the maximal component of this vector.
/// </summary>
public static long MaxElement(lvec2 v) => v.MaxElement;
/// <summary>
/// Returns the euclidean length of this vector.
/// </summary>
public static double Length(lvec2 v) => v.Length;
/// <summary>
/// Returns the squared euclidean length of this vector.
/// </summary>
public static double LengthSqr(lvec2 v) => v.LengthSqr;
/// <summary>
/// Returns the sum of all components.
/// </summary>
public static long Sum(lvec2 v) => v.Sum;
/// <summary>
/// Returns the euclidean norm of this vector.
/// </summary>
public static double Norm(lvec2 v) => v.Norm;
/// <summary>
/// Returns the one-norm of this vector.
/// </summary>
public static double Norm1(lvec2 v) => v.Norm1;
/// <summary>
/// Returns the two-norm (euclidean length) of this vector.
/// </summary>
public static double Norm2(lvec2 v) => v.Norm2;
/// <summary>
/// Returns the max-norm of this vector.
/// </summary>
public static double NormMax(lvec2 v) => v.NormMax;
/// <summary>
/// Returns the p-norm of this vector.
/// </summary>
public static double NormP(lvec2 v, double p) => v.NormP(p);
/// <summary>
/// Returns the inner product (dot product, scalar product) of the two vectors.
/// </summary>
public static long Dot(lvec2 lhs, lvec2 rhs) => lvec2.Dot(lhs, rhs);
/// <summary>
/// Returns the euclidean distance between the two vectors.
/// </summary>
public static double Distance(lvec2 lhs, lvec2 rhs) => lvec2.Distance(lhs, rhs);
/// <summary>
/// Returns the squared euclidean distance between the two vectors.
/// </summary>
public static double DistanceSqr(lvec2 lhs, lvec2 rhs) => lvec2.DistanceSqr(lhs, rhs);
/// <summary>
/// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result).
/// </summary>
public static lvec2 Reflect(lvec2 I, lvec2 N) => lvec2.Reflect(I, N);
/// <summary>
/// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result).
/// </summary>
public static lvec2 Refract(lvec2 I, lvec2 N, long eta) => lvec2.Refract(I, N, eta);
/// <summary>
/// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N).
/// </summary>
public static lvec2 FaceForward(lvec2 N, lvec2 I, lvec2 Nref) => lvec2.FaceForward(N, I, Nref);
/// <summary>
/// Returns the length of the outer product (cross product, vector product) of the two vectors.
/// </summary>
public static long Cross(lvec2 l, lvec2 r) => lvec2.Cross(l, r);
/// <summary>
/// Returns a lvec2 with independent and identically distributed uniform integer values between 0 (inclusive) and maxValue (exclusive). (A maxValue of 0 is allowed and returns 0.)
/// </summary>
public static lvec2 Random(Random random, lvec2 maxValue) => lvec2.Random(random, maxValue);
/// <summary>
/// Returns a lvec2 with independent and identically distributed uniform integer values between minValue (inclusive) and maxValue (exclusive). (minValue == maxValue is allowed and returns minValue. Negative values are allowed.)
/// </summary>
public static lvec2 Random(Random random, lvec2 minValue, lvec2 maxValue) => lvec2.Random(random, minValue, maxValue);
/// <summary>
/// Returns a lvec2 with independent and identically distributed uniform integer values between minValue (inclusive) and maxValue (exclusive). (minValue == maxValue is allowed and returns minValue. Negative values are allowed.)
/// </summary>
public static lvec2 RandomUniform(Random random, lvec2 minValue, lvec2 maxValue) => lvec2.RandomUniform(random, minValue, maxValue);
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class IndexExpressionTests
{
[Fact]
public void UpdateSameTest()
{
SampleClassWithProperties instance = new SampleClassWithProperties { DefaultProperty = new List<int> { 100, 101 } };
IndexExpression expr = instance.DefaultIndexExpression;
IndexExpression exprUpdated = expr.Update(expr.Object, instance.DefaultArguments);
// Has to be the same, because everything is the same.
Assert.Same(expr, exprUpdated);
// Invoke to check expression.
IndexExpressionHelpers.AssertInvokeCorrect(100, expr);
IndexExpressionHelpers.AssertInvokeCorrect(100, exprUpdated);
}
[Fact]
public void UpdateDoesntRepeatEnumeration()
{
SampleClassWithProperties instance = new SampleClassWithProperties { DefaultProperty = new List<int> { 100, 101 } };
IndexExpression expr = instance.DefaultIndexExpression;
Assert.Same(expr, expr.Update(expr.Object, new RunOnceEnumerable<Expression>(instance.DefaultArguments)));
}
[Fact]
public void UpdateDifferentObjectTest()
{
SampleClassWithProperties instance = new SampleClassWithProperties { DefaultProperty = new List<int> { 100, 101 } };
IndexExpression expr = instance.DefaultIndexExpression;
Assert.NotSame(expr, expr.Update(instance.DefaultPropertyExpression, instance.DefaultArguments));
}
[Fact]
public void UpdateDifferentArgumentsTest()
{
SampleClassWithProperties instance = new SampleClassWithProperties { DefaultProperty = new List<int> { 100, 101 } };
IndexExpression expr = instance.DefaultIndexExpression;
Assert.NotSame(expr, expr.Update(expr.Object, new [] { Expression.Constant(0)}));
}
[Fact]
public void UpdateTest()
{
SampleClassWithProperties instance = new SampleClassWithProperties
{
DefaultProperty = new List<int> { 100, 101 },
AlternativeProperty = new List<int> { 200, 201 }
};
IndexExpression expr = instance.DefaultIndexExpression;
MemberExpression newProperty = Expression.Property(Expression.Constant(instance),
typeof(SampleClassWithProperties).GetProperty(nameof(instance.AlternativeProperty)));
ConstantExpression[] newArguments = {Expression.Constant(1)};
IndexExpression exprUpdated = expr.Update(newProperty, newArguments);
// Replace Object and Arguments of IndexExpression.
IndexExpressionHelpers.AssertEqual(
exprUpdated,
Expression.MakeIndex(newProperty, instance.DefaultIndexer, newArguments));
// Invoke to check expression.
IndexExpressionHelpers.AssertInvokeCorrect(100, expr);
IndexExpressionHelpers.AssertInvokeCorrect(201, exprUpdated);
}
[Fact]
public static void ToStringTest()
{
IndexExpression e1 = Expression.MakeIndex(Expression.Parameter(typeof(Vector1), "v"), typeof(Vector1).GetProperty("Item"), new[] { Expression.Parameter(typeof(int), "i") });
Assert.Equal("v.Item[i]", e1.ToString());
IndexExpression e2 = Expression.MakeIndex(Expression.Parameter(typeof(Vector2), "v"), typeof(Vector2).GetProperty("Item"), new[] { Expression.Parameter(typeof(int), "i"), Expression.Parameter(typeof(int), "j") });
Assert.Equal("v.Item[i, j]", e2.ToString());
IndexExpression e3 = Expression.ArrayAccess(Expression.Parameter(typeof(int[,]), "xs"), Expression.Parameter(typeof(int), "i"), Expression.Parameter(typeof(int), "j"));
Assert.Equal("xs[i, j]", e3.ToString());
}
#if FEATURE_COMPILE
private static TypeBuilder GetTestTypeBuilder() =>
AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("TestAssembly"), AssemblyBuilderAccess.RunAndCollect)
.DefineDynamicModule("TestModule")
.DefineType("TestType");
[Fact]
public void NoAccessorIndexedProperty()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
typeBuild.DefineProperty("Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = info.DeclaredProperties.First();
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void ByRefIndexedProperty()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
FieldBuilder field = typeBuild.DefineField("_value", typeof(int), FieldAttributes.Private);
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int).MakeByRefType(), new[] {typeof(int)});
MethodBuilder getter = typeBuild.DefineMethod(
"get_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(int).MakeByRefType(),
new[] {typeof(int)});
ILGenerator ilGen = getter.GetILGenerator();
ilGen.Emit(OpCodes.Ldarg_0);
ilGen.Emit(OpCodes.Ldflda, field);
ilGen.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void VoidIndexedProperty()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(void), new[] { typeof(int) });
MethodBuilder getter = typeBuild.DefineMethod(
"get_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(void),
new[] { typeof(int) });
ILGenerator ilGen = getter.GetILGenerator();
ilGen.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void IndexedPropertyGetReturnsWrongType()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
MethodBuilder getter = typeBuild.DefineMethod(
"get_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(long),
new[] { typeof(int) });
ILGenerator ilGen = getter.GetILGenerator();
ilGen.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void IndexedPropertySetterNoParams()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
MethodBuilder setter = typeBuild.DefineMethod(
"set_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(void),
Type.EmptyTypes);
ILGenerator ilGen = setter.GetILGenerator();
ilGen.Emit(OpCodes.Ret);
property.SetSetMethod(setter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void IndexedPropertySetterByrefValueType()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
MethodBuilder setter = typeBuild.DefineMethod(
"set_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(void),
new [] {typeof(int), typeof(int).MakeByRefType()});
ILGenerator ilGen = setter.GetILGenerator();
ilGen.Emit(OpCodes.Ret);
property.SetSetMethod(setter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void IndexedPropertySetterNotReturnVoid()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
MethodBuilder setter = typeBuild.DefineMethod(
"set_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(int),
new[] { typeof(int), typeof(int) });
ILGenerator ilGen = setter.GetILGenerator();
ilGen.Emit(OpCodes.Ret);
property.SetSetMethod(setter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void IndexedPropertyGetterInstanceSetterStatic()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
MethodBuilder getter = typeBuild.DefineMethod(
"get_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(int),
new[] { typeof(int) });
MethodBuilder setter = typeBuild.DefineMethod(
"set_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Static
| MethodAttributes.PrivateScope,
typeof(void),
new[] { typeof(int), typeof(int) });
ILGenerator ilGen = getter.GetILGenerator();
ilGen.Emit(OpCodes.Ldc_I4_0);
ilGen.Emit(OpCodes.Ret);
ilGen = setter.GetILGenerator();
ilGen.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
property.SetSetMethod(setter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void IndexedPropertySetterValueTypeNotMatchPropertyType()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
MethodBuilder setter = typeBuild.DefineMethod(
"set_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(void),
new[] { typeof(int), typeof(long) });
ILGenerator ilGen = setter.GetILGenerator();
ilGen.Emit(OpCodes.Ret);
property.SetSetMethod(setter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void IndexedPropertyGetterSetterArgCountMismatch()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
MethodBuilder getter = typeBuild.DefineMethod(
"get_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(int),
new[] { typeof(int) });
MethodBuilder setter = typeBuild.DefineMethod(
"set_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(void),
new[] { typeof(int), typeof(int), typeof(int) });
ILGenerator ilGen = getter.GetILGenerator();
ilGen.Emit(OpCodes.Ldc_I4_0);
ilGen.Emit(OpCodes.Ret);
ilGen = setter.GetILGenerator();
ilGen.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
property.SetSetMethod(setter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0)));
}
[Fact]
public void IndexedPropertyGetterSetterArgumentTypeMismatch()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int), typeof(int), typeof(int) });
MethodBuilder getter = typeBuild.DefineMethod(
"get_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(int),
new[] { typeof(int), typeof(int), typeof(int) });
MethodBuilder setter = typeBuild.DefineMethod(
"set_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(void),
new[] { typeof(int), typeof(int), typeof(long), typeof(int) });
ILGenerator ilGen = getter.GetILGenerator();
ilGen.Emit(OpCodes.Ldc_I4_0);
ilGen.Emit(OpCodes.Ret);
ilGen = setter.GetILGenerator();
ilGen.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
property.SetSetMethod(setter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0), Expression.Constant(0), Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0), Expression.Constant(0), Expression.Constant(0)));
}
[Fact]
public void IndexedPropertyVarArgs()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
MethodBuilder getter = typeBuild.DefineMethod(
"get_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
CallingConventions.VarArgs,
typeof(int),
Type.EmptyTypes);
ILGenerator ilGen = getter.GetILGenerator();
ilGen.Emit(OpCodes.Ldc_I4_0);
ilGen.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, Expression.Constant(0), Expression.Constant(0), Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", Expression.Constant(0), Expression.Constant(0), Expression.Constant(0)));
}
[Fact]
public void NullInstanceInstanceProperty()
{
PropertyInfo prop = typeof(Dictionary<int, int>).GetProperty("Item");
ConstantExpression index = Expression.Constant(0);
AssertExtensions.Throws<ArgumentException>("instance", () => Expression.Property(null, prop, index));
}
[Fact]
public void InstanceToStaticProperty()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int) });
MethodBuilder getter = typeBuild.DefineMethod(
"get_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Static
| MethodAttributes.PrivateScope,
typeof(int),
new[] { typeof(int) });
ILGenerator ilGen = getter.GetILGenerator();
ilGen.Emit(OpCodes.Ldc_I4_0);
ilGen.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("instance", () => Expression.Property(instance, prop, Expression.Constant(0)));
}
[Fact]
public void ByRefIndexer()
{
TypeBuilder typeBuild = GetTestTypeBuilder();
PropertyBuilder property = typeBuild.DefineProperty(
"Item", PropertyAttributes.None, typeof(int), new[] { typeof(int).MakeByRefType() });
MethodBuilder getter = typeBuild.DefineMethod(
"get_Item",
MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
| MethodAttributes.PrivateScope,
typeof(int),
new[] { typeof(int).MakeByRefType() });
ILGenerator ilGen = getter.GetILGenerator();
ilGen.Emit(OpCodes.Ldc_I4_0);
ilGen.Emit(OpCodes.Ret);
property.SetGetMethod(getter);
TypeInfo info = typeBuild.CreateTypeInfo();
Type type = info;
PropertyInfo prop = type.GetProperties()[0];
Expression instance = Expression.Default(type);
AssertExtensions.Throws<ArgumentException>("indexes[0]", () => Expression.Property(instance, prop, Expression.Constant(0)));
}
// FEATURE_COMPILE
#endif
[Fact]
public void CallWithoutIndices()
{
PropertyInfo prop = typeof(Dictionary<int, int>).GetProperty("Item");
DefaultExpression dict = Expression.Default(typeof(Dictionary<int, int>));
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(dict, prop, Array.Empty<Expression>()));
}
[Fact]
public void CallWithExcessiveIndices()
{
PropertyInfo prop = typeof(Dictionary<int, int>).GetProperty("Item");
DefaultExpression dict = Expression.Default(typeof(Dictionary<int, int>));
ConstantExpression index = Expression.Constant(0);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(dict, prop, index, index));
}
[Fact]
public void CallWithUnassignableIndex()
{
PropertyInfo prop = typeof(Dictionary<int, int>).GetProperty("Item");
DefaultExpression dict = Expression.Default(typeof(Dictionary<int, int>));
ConstantExpression index = Expression.Constant(0L);
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.Property(dict, prop, index));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void CallWithLambdaIndex(bool useInterpreter)
{
// An exception to the rule against unassignable indices, lamdba expressions
// can be automatically quoted.
PropertyInfo prop = typeof(Dictionary<Expression<Func<int>>, int>).GetProperty("Item");
Expression<Func<int>> index = () => 2;
ConstantExpression dict = Expression.Constant(new Dictionary<Expression<Func<int>>, int>{{index, 9}});
Func<int> f = Expression.Lambda<Func<int>>(Expression.Property(dict, prop, index)).Compile(useInterpreter);
Assert.Equal(9, f());
}
[Theory, ClassData(typeof(CompilationTypes))]
public void CallWithIntAndLambdaIndex(bool useInterpreter)
{
PropertyInfo prop = typeof(IntAndExpressionIndexed).GetProperty("Item");
ConstantExpression instance = Expression.Constant(new IntAndExpressionIndexed());
Expression<Action> index = Expression.Lambda<Action>(Expression.Empty());
ConstantExpression intIdx = Expression.Constant(0);
Func<bool> f = Expression.Lambda<Func<bool>>(Expression.Property(instance, prop, intIdx, index)).Compile(useInterpreter);
Assert.True(f());
}
[Fact]
public void TryIndexedAccessNonIndexedProperty()
{
ConstantExpression instance = Expression.Constant("");
PropertyInfo prop = typeof(string).GetProperty(nameof(string.Length));
ConstantExpression index = Expression.Constant(0);
AssertExtensions.Throws<ArgumentException>("indexer", () => Expression.Property(instance, prop, index));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void OverloadedIndexer(bool useInterpreter)
{
ConstantExpression instance = Expression.Constant(new OverloadedIndexers());
ConstantExpression index = Expression.Constant("");
Expression<Func<int>> exp = Expression.Lambda<Func<int>>(Expression.Property(instance, "Item", index));
Func<int> f = exp.Compile(useInterpreter);
Assert.Equal(2, f());
}
[Fact]
public void OverloadedIndexerBothMatch()
{
ConstantExpression instance = Expression.Constant(new OverloadedIndexersBothMatchString());
ConstantExpression index = Expression.Constant("");
Assert.Throws<InvalidOperationException>(() => Expression.Property(instance, "Item", index));
}
[Fact]
public void NoSuchPropertyExplicitlyNoIndices()
{
ConstantExpression instance = Expression.Constant("");
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Property(instance, "ThisDoesNotExist", Array.Empty<Expression>()));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Property(instance, "ThisDoesNotExist", null));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void NonIndexedPropertyExplicitlyNoIndices(bool useInterpreter)
{
ConstantExpression instance = Expression.Constant("123");
IndexExpression prop = Expression.Property(instance, "Length", null);
Expression<Func<int>> exp = Expression.Lambda<Func<int>>(prop);
Func<int> func = exp.Compile(useInterpreter);
Assert.Equal(3, func());
}
[Fact]
public void FindNothingForNullArgument()
{
ConstantExpression instance = Expression.Constant("123");
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Length", new Expression[] {null}));
}
[Fact]
public void NullArgument()
{
ConstantExpression instance = Expression.Constant(new Dictionary<int, int>());
PropertyInfo prop = typeof(Dictionary<int, int>).GetProperty("Item");
AssertExtensions.Throws<ArgumentException>("propertyName", () => Expression.Property(instance, "Item", new Expression[] {null}));
AssertExtensions.Throws<ArgumentNullException>("arguments[0]", () => Expression.Property(instance, prop, new Expression[] {null}));
}
[Fact]
public void UnreadableIndex()
{
ConstantExpression instance = Expression.Constant(new Dictionary<int, int>());
PropertyInfo prop = typeof(Dictionary<int, int>).GetProperty("Item");
MemberExpression index = Expression.Property(null, typeof(Unreadable<int>).GetProperty(nameof(Unreadable<int>.WriteOnly)));
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.Property(instance, "Item", index));
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.Property(instance, prop, index));
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void ConstrainedVirtualCall(bool useInterpreter)
{
// Virtual call via base declaration to valuetype.
ConstantExpression instance = Expression.Constant(new InterfaceIndexableValueType());
PropertyInfo prop = typeof(IIndexable).GetProperty("Item");
IndexExpression index = Expression.Property(instance, prop, Expression.Constant(4));
Expression<Func<int>> lambda = Expression.Lambda<Func<int>>(
index
);
Func<int> func = lambda.Compile(useInterpreter);
Assert.Equal(8, func());
}
private interface IIndexable
{
int this[int index] { get; }
}
private struct InterfaceIndexableValueType : IIndexable
{
public int this[int index] => index * 2;
}
private class IntAndExpressionIndexed
{
public bool this[int x, Expression<Action> y] => true;
}
private class OverloadedIndexers
{
public int this[int index] => 0;
public int this[int x, int y] => 1;
public int this[string index] => 2;
}
private class OverloadedIndexersBothMatchString
{
public int this[IComparable index] => 0;
public int this[ICloneable index] => 1;
}
class Vector1
{
public int this[int x]
{
get { return 0; }
}
}
class Vector2
{
public int this[int x, int y]
{
get { return 0; }
}
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
using SharpBox2D.Common;
namespace SharpBox2D.Dynamics
{
/**
* A body definition holds all the data needed to construct a rigid body. You can safely re-use body
* definitions. Shapes are added to a body after construction.
*
* @author daniel
*/
public class BodyDef
{
/**
* The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the
* mass is set to one.
*/
public BodyType type;
/**
* Use this to store application specific body data.
*/
public object userData;
/**
* The world position of the body. Avoid creating bodies at the origin since this can lead to many
* overlapping shapes.
*/
public Vec2 position;
/**
* The world angle of the body in radians.
*/
public float angle;
/**
* The linear velocity of the body in world co-ordinates.
*/
public Vec2 linearVelocity;
/**
* The angular velocity of the body.
*/
public float angularVelocity;
/**
* Linear damping is use to reduce the linear velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
public float linearDamping;
/**
* Angular damping is use to reduce the angular velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
public float angularDamping;
/**
* Set this flag to false if this body should never fall asleep. Note that this increases CPU
* usage.
*/
public bool allowSleep;
/**
* Is this body initially sleeping?
*/
public bool awake;
/**
* Should this body be prevented from rotating? Useful for characters.
*/
public bool fixedRotation;
/**
* Is this a fast moving body that should be prevented from tunneling through other moving bodies?
* Note that all bodies are prevented from tunneling through kinematic and static bodies. This
* setting is only considered on dynamic bodies.
*
* @warning You should use this flag sparingly since it increases processing time.
*/
public bool bullet;
/**
* Does this body start ref active?
*/
public bool active;
/**
* Experimental: scales the inertia tensor.
*/
public float gravityScale;
public BodyDef()
{
userData = null;
position = new Vec2();
angle = 0f;
linearVelocity = new Vec2();
angularVelocity = 0f;
linearDamping = 0f;
angularDamping = 0f;
allowSleep = true;
awake = true;
fixedRotation = false;
bullet = false;
type = BodyType.STATIC;
active = true;
gravityScale = 1.0f;
}
/**
* The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the
* mass is set to one.
*/
public BodyType getType()
{
return type;
}
/**
* The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the
* mass is set to one.
*/
public void setType(BodyType type)
{
this.type = type;
}
/**
* Use this to store application specific body data.
*/
public object getUserData()
{
return userData;
}
/**
* Use this to store application specific body data.
*/
public void setUserData(object userData)
{
this.userData = userData;
}
/**
* The world position of the body. Avoid creating bodies at the origin since this can lead to many
* overlapping shapes.
*/
public Vec2 getPosition()
{
return position;
}
/**
* The world position of the body. Avoid creating bodies at the origin since this can lead to many
* overlapping shapes.
*/
public void setPosition(Vec2 position)
{
this.position = position;
}
/**
* The world angle of the body in radians.
*/
public float getAngle()
{
return angle;
}
/**
* The world angle of the body in radians.
*/
public void setAngle(float angle)
{
this.angle = angle;
}
/**
* The linear velocity of the body in world co-ordinates.
*/
public Vec2 getLinearVelocity()
{
return linearVelocity;
}
/**
* The linear velocity of the body in world co-ordinates.
*/
public void setLinearVelocity(Vec2 linearVelocity)
{
this.linearVelocity = linearVelocity;
}
/**
* The angular velocity of the body.
*/
public float getAngularVelocity()
{
return angularVelocity;
}
/**
* The angular velocity of the body.
*/
public void setAngularVelocity(float angularVelocity)
{
this.angularVelocity = angularVelocity;
}
/**
* Linear damping is use to reduce the linear velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
public float getLinearDamping()
{
return linearDamping;
}
/**
* Linear damping is use to reduce the linear velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
public void setLinearDamping(float linearDamping)
{
this.linearDamping = linearDamping;
}
/**
* Angular damping is use to reduce the angular velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
public float getAngularDamping()
{
return angularDamping;
}
/**
* Angular damping is use to reduce the angular velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
public void setAngularDamping(float angularDamping)
{
this.angularDamping = angularDamping;
}
/**
* Set this flag to false if this body should never fall asleep. Note that this increases CPU
* usage.
*/
public bool isAllowSleep()
{
return allowSleep;
}
/**
* Set this flag to false if this body should never fall asleep. Note that this increases CPU
* usage.
*/
public void setAllowSleep(bool allowSleep)
{
this.allowSleep = allowSleep;
}
/**
* Is this body initially sleeping?
*/
public bool isAwake()
{
return awake;
}
/**
* Is this body initially sleeping?
*/
public void setAwake(bool awake)
{
this.awake = awake;
}
/**
* Should this body be prevented from rotating? Useful for characters.
*/
public bool isFixedRotation()
{
return fixedRotation;
}
/**
* Should this body be prevented from rotating? Useful for characters.
*/
public void setFixedRotation(bool fixedRotation)
{
this.fixedRotation = fixedRotation;
}
/**
* Is this a fast moving body that should be prevented from tunneling through other moving bodies?
* Note that all bodies are prevented from tunneling through kinematic and static bodies. This
* setting is only considered on dynamic bodies.
*
* @warning You should use this flag sparingly since it increases processing time.
*/
public bool isBullet()
{
return bullet;
}
/**
* Is this a fast moving body that should be prevented from tunneling through other moving bodies?
* Note that all bodies are prevented from tunneling through kinematic and static bodies. This
* setting is only considered on dynamic bodies.
*
* @warning You should use this flag sparingly since it increases processing time.
*/
public void setBullet(bool bullet)
{
this.bullet = bullet;
}
/**
* Does this body start ref active?
*/
public bool isActive()
{
return active;
}
/**
* Does this body start ref active?
*/
public void setActive(bool active)
{
this.active = active;
}
/**
* Experimental: scales the inertia tensor.
*/
public float getGravityScale()
{
return gravityScale;
}
/**
* Experimental: scales the inertia tensor.
*/
public void setGravityScale(float gravityScale)
{
this.gravityScale = gravityScale;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Utils;
using osu.Game.Extensions;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Edit;
using osu.Game.Screens.Edit.Compose.Components;
using osuTK;
namespace osu.Game.Skinning.Editor
{
public class SkinSelectionHandler : SelectionHandler<ISkinnableDrawable>
{
[Resolved]
private SkinEditor skinEditor { get; set; }
public override bool HandleRotation(float angle)
{
if (SelectedBlueprints.Count == 1)
{
// for single items, rotate around the origin rather than the selection centre.
((Drawable)SelectedBlueprints.First().Item).Rotation += angle;
}
else
{
var selectionQuad = getSelectionQuad();
foreach (var b in SelectedBlueprints)
{
var drawableItem = (Drawable)b.Item;
var rotatedPosition = RotatePointAroundOrigin(b.ScreenSpaceSelectionPoint, selectionQuad.Centre, angle);
updateDrawablePosition(drawableItem, rotatedPosition);
drawableItem.Rotation += angle;
}
}
// this isn't always the case but let's be lenient for now.
return true;
}
public override bool HandleScale(Vector2 scale, Anchor anchor)
{
// convert scale to screen space
scale = ToScreenSpace(scale) - ToScreenSpace(Vector2.Zero);
adjustScaleFromAnchor(ref scale, anchor);
// the selection quad is always upright, so use an AABB rect to make mutating the values easier.
var selectionRect = getSelectionQuad().AABBFloat;
// If the selection has no area we cannot scale it
if (selectionRect.Area == 0)
return false;
// copy to mutate, as we will need to compare to the original later on.
var adjustedRect = selectionRect;
// first, remove any scale axis we are not interested in.
if (anchor.HasFlagFast(Anchor.x1)) scale.X = 0;
if (anchor.HasFlagFast(Anchor.y1)) scale.Y = 0;
bool shouldAspectLock =
// for now aspect lock scale adjustments that occur at corners..
(!anchor.HasFlagFast(Anchor.x1) && !anchor.HasFlagFast(Anchor.y1))
// ..or if any of the selection have been rotated.
// this is to avoid requiring skew logic (which would likely not be the user's expected transform anyway).
|| SelectedBlueprints.Any(b => !Precision.AlmostEquals(((Drawable)b.Item).Rotation, 0));
if (shouldAspectLock)
{
if (anchor.HasFlagFast(Anchor.x1))
// if dragging from the horizontal centre, only a vertical component is available.
scale.X = scale.Y / selectionRect.Height * selectionRect.Width;
else
// in all other cases (arbitrarily) use the horizontal component for aspect lock.
scale.Y = scale.X / selectionRect.Width * selectionRect.Height;
}
if (anchor.HasFlagFast(Anchor.x0)) adjustedRect.X -= scale.X;
if (anchor.HasFlagFast(Anchor.y0)) adjustedRect.Y -= scale.Y;
adjustedRect.Width += scale.X;
adjustedRect.Height += scale.Y;
// scale adjust applied to each individual item should match that of the quad itself.
var scaledDelta = new Vector2(
MathF.Max(adjustedRect.Width / selectionRect.Width, 0),
MathF.Max(adjustedRect.Height / selectionRect.Height, 0)
);
foreach (var b in SelectedBlueprints)
{
var drawableItem = (Drawable)b.Item;
// each drawable's relative position should be maintained in the scaled quad.
var screenPosition = b.ScreenSpaceSelectionPoint;
var relativePositionInOriginal =
new Vector2(
(screenPosition.X - selectionRect.TopLeft.X) / selectionRect.Width,
(screenPosition.Y - selectionRect.TopLeft.Y) / selectionRect.Height
);
var newPositionInAdjusted = new Vector2(
adjustedRect.TopLeft.X + adjustedRect.Width * relativePositionInOriginal.X,
adjustedRect.TopLeft.Y + adjustedRect.Height * relativePositionInOriginal.Y
);
updateDrawablePosition(drawableItem, newPositionInAdjusted);
drawableItem.Scale *= scaledDelta;
}
return true;
}
public override bool HandleFlip(Direction direction)
{
var selectionQuad = getSelectionQuad();
Vector2 scaleFactor = direction == Direction.Horizontal ? new Vector2(-1, 1) : new Vector2(1, -1);
foreach (var b in SelectedBlueprints)
{
var drawableItem = (Drawable)b.Item;
var flippedPosition = GetFlippedPosition(direction, selectionQuad, b.ScreenSpaceSelectionPoint);
updateDrawablePosition(drawableItem, flippedPosition);
drawableItem.Scale *= scaleFactor;
drawableItem.Rotation -= drawableItem.Rotation % 180 * 2;
}
return true;
}
public override bool HandleMovement(MoveSelectionEvent<ISkinnableDrawable> moveEvent)
{
foreach (var c in SelectedBlueprints)
{
var item = c.Item;
Drawable drawable = (Drawable)item;
drawable.Position += drawable.ScreenSpaceDeltaToParentSpace(moveEvent.ScreenSpaceDelta);
if (item.UsesFixedAnchor) continue;
applyClosestAnchor(drawable);
}
return true;
}
private static void applyClosestAnchor(Drawable drawable) => applyAnchor(drawable, getClosestAnchor(drawable));
protected override void OnSelectionChanged()
{
base.OnSelectionChanged();
SelectionBox.CanRotate = true;
SelectionBox.CanScaleX = true;
SelectionBox.CanScaleY = true;
SelectionBox.CanFlipX = true;
SelectionBox.CanFlipY = true;
SelectionBox.CanReverse = false;
}
protected override void DeleteItems(IEnumerable<ISkinnableDrawable> items) =>
skinEditor.DeleteItems(items.ToArray());
protected override IEnumerable<MenuItem> GetContextMenuItemsForSelection(IEnumerable<SelectionBlueprint<ISkinnableDrawable>> selection)
{
var closestItem = new TernaryStateRadioMenuItem("Closest", MenuItemType.Standard, _ => applyClosestAnchors())
{
State = { Value = GetStateFromSelection(selection, c => !c.Item.UsesFixedAnchor) }
};
yield return new OsuMenuItem("Anchor")
{
Items = createAnchorItems((d, a) => d.UsesFixedAnchor && ((Drawable)d).Anchor == a, applyFixedAnchors)
.Prepend(closestItem)
.ToArray()
};
yield return new OsuMenuItem("Origin")
{
Items = createAnchorItems((d, o) => ((Drawable)d).Origin == o, applyOrigins).ToArray()
};
foreach (var item in base.GetContextMenuItemsForSelection(selection))
yield return item;
IEnumerable<TernaryStateMenuItem> createAnchorItems(Func<ISkinnableDrawable, Anchor, bool> checkFunction, Action<Anchor> applyFunction)
{
var displayableAnchors = new[]
{
Anchor.TopLeft,
Anchor.TopCentre,
Anchor.TopRight,
Anchor.CentreLeft,
Anchor.Centre,
Anchor.CentreRight,
Anchor.BottomLeft,
Anchor.BottomCentre,
Anchor.BottomRight,
};
return displayableAnchors.Select(a =>
{
return new TernaryStateRadioMenuItem(a.ToString(), MenuItemType.Standard, _ => applyFunction(a))
{
State = { Value = GetStateFromSelection(selection, c => checkFunction(c.Item, a)) }
};
});
}
}
private static void updateDrawablePosition(Drawable drawable, Vector2 screenSpacePosition)
{
drawable.Position =
drawable.Parent.ToLocalSpace(screenSpacePosition) - drawable.AnchorPosition;
}
private void applyOrigins(Anchor origin)
{
foreach (var item in SelectedItems)
{
var drawable = (Drawable)item;
if (origin == drawable.Origin) continue;
var previousOrigin = drawable.OriginPosition;
drawable.Origin = origin;
drawable.Position += drawable.OriginPosition - previousOrigin;
if (item.UsesFixedAnchor) continue;
applyClosestAnchor(drawable);
}
}
/// <summary>
/// A screen-space quad surrounding all selected drawables, accounting for their full displayed size.
/// </summary>
/// <returns></returns>
private Quad getSelectionQuad() =>
GetSurroundingQuad(SelectedBlueprints.SelectMany(b => b.Item.ScreenSpaceDrawQuad.GetVertices().ToArray()));
private void applyFixedAnchors(Anchor anchor)
{
foreach (var item in SelectedItems)
{
var drawable = (Drawable)item;
item.UsesFixedAnchor = true;
applyAnchor(drawable, anchor);
}
}
private void applyClosestAnchors()
{
foreach (var item in SelectedItems)
{
item.UsesFixedAnchor = false;
applyClosestAnchor((Drawable)item);
}
}
private static Anchor getClosestAnchor(Drawable drawable)
{
var parent = drawable.Parent;
if (parent == null)
return drawable.Anchor;
var screenPosition = getScreenPosition();
var absolutePosition = parent.ToLocalSpace(screenPosition);
var factor = parent.RelativeToAbsoluteFactor;
var result = default(Anchor);
static Anchor getAnchorFromPosition(float xOrY, Anchor anchor0, Anchor anchor1, Anchor anchor2)
{
if (xOrY >= 2 / 3f)
return anchor2;
if (xOrY >= 1 / 3f)
return anchor1;
return anchor0;
}
result |= getAnchorFromPosition(absolutePosition.X / factor.X, Anchor.x0, Anchor.x1, Anchor.x2);
result |= getAnchorFromPosition(absolutePosition.Y / factor.Y, Anchor.y0, Anchor.y1, Anchor.y2);
return result;
Vector2 getScreenPosition()
{
var quad = drawable.ScreenSpaceDrawQuad;
var origin = drawable.Origin;
var pos = quad.TopLeft;
if (origin.HasFlagFast(Anchor.x2))
pos.X += quad.Width;
else if (origin.HasFlagFast(Anchor.x1))
pos.X += quad.Width / 2f;
if (origin.HasFlagFast(Anchor.y2))
pos.Y += quad.Height;
else if (origin.HasFlagFast(Anchor.y1))
pos.Y += quad.Height / 2f;
return pos;
}
}
private static void applyAnchor(Drawable drawable, Anchor anchor)
{
if (anchor == drawable.Anchor) return;
var previousAnchor = drawable.AnchorPosition;
drawable.Anchor = anchor;
drawable.Position -= drawable.AnchorPosition - previousAnchor;
}
private static void adjustScaleFromAnchor(ref Vector2 scale, Anchor reference)
{
// cancel out scale in axes we don't care about (based on which drag handle was used).
if ((reference & Anchor.x1) > 0) scale.X = 0;
if ((reference & Anchor.y1) > 0) scale.Y = 0;
// reverse the scale direction if dragging from top or left.
if ((reference & Anchor.x0) > 0) scale.X = -scale.X;
if ((reference & Anchor.y0) > 0) scale.Y = -scale.Y;
}
}
}
| |
using System;
using System.Collections;
using System.IO;
namespace Andi.Libs.HexBox
{
/// <summary>
/// Byte provider for (big) files.
/// </summary>
public class FileByteProvider : IByteProvider, IDisposable
{
#region WriteCollection class
/// <summary>
/// Represents the write buffer class
/// </summary>
class WriteCollection : DictionaryBase
{
/// <summary>
/// Gets or sets a byte in the collection
/// </summary>
public byte this[long index]
{
get { return (byte)this.Dictionary[index]; }
set { Dictionary[index] = value; }
}
/// <summary>
/// Adds a byte into the collection
/// </summary>
/// <param name="index">the index of the byte</param>
/// <param name="value">the value of the byte</param>
public void Add(long index, byte value)
{ Dictionary.Add(index, value); }
/// <summary>
/// Determines if a byte with the given index exists.
/// </summary>
/// <param name="index">the index of the byte</param>
/// <returns>true, if the is in the collection</returns>
public bool Contains(long index)
{ return Dictionary.Contains(index); }
}
#endregion
/// <summary>
/// Occurs, when the write buffer contains new changes.
/// </summary>
public event EventHandler Changed;
/// <summary>
/// Contains all changes
/// </summary>
WriteCollection _writes = new WriteCollection();
/// <summary>
/// Contains the file name.
/// </summary>
string _fileName;
/// <summary>
/// Contains the file stream.
/// </summary>
FileStream _fileStream;
/// <summary>
/// Read-only access.
/// </summary>
bool _readOnly;
/// <summary>
/// Initializes a new instance of the FileByteProvider class.
/// </summary>
/// <param name="fileName"></param>
public FileByteProvider(string fileName)
{
_fileName = fileName;
try
{
// try to open in write mode
_fileStream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
}
catch
{
// write mode failed, try to open in read-only and fileshare friendly mode.
try
{
_fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
_readOnly = true;
}
catch
{
throw;
}
}
}
/// <summary>
/// Terminates the instance of the FileByteProvider class.
/// </summary>
~FileByteProvider()
{
Dispose();
}
/// <summary>
/// Raises the Changed event.
/// </summary>
/// <remarks>Never used.</remarks>
void OnChanged(EventArgs e)
{
if(Changed != null)
Changed(this, e);
}
/// <summary>
/// Gets the name of the file the byte provider is using.
/// </summary>
public string FileName
{
get { return _fileName; }
}
/// <summary>
/// Returns a value if there are some changes.
/// </summary>
/// <returns>true, if there are some changes</returns>
public bool HasChanges()
{
return (_writes.Count > 0);
}
/// <summary>
/// Updates the file with all changes the write buffer contains.
/// </summary>
public void ApplyChanges()
{
if (this._readOnly)
{
throw new Exception("File is in read-only mode.");
}
if(!HasChanges())
return;
IDictionaryEnumerator en = _writes.GetEnumerator();
while(en.MoveNext())
{
long index = (long)en.Key;
byte value = (byte)en.Value;
if(_fileStream.Position != index)
_fileStream.Position = index;
_fileStream.Write(new byte[] { value }, 0, 1);
}
_writes.Clear();
}
/// <summary>
/// Clears the write buffer and reject all changes made.
/// </summary>
public void RejectChanges()
{
_writes.Clear();
}
#region IByteProvider Members
/// <summary>
/// Never used.
/// </summary>
public event EventHandler LengthChanged;
/// <summary>
/// Reads a byte from the file.
/// </summary>
/// <param name="index">the index of the byte to read</param>
/// <returns>the byte</returns>
public byte ReadByte(long index)
{
if(_writes.Contains(index))
return _writes[index];
if(_fileStream.Position != index)
_fileStream.Position = index;
byte res = (byte)_fileStream.ReadByte();
return res;
}
/// <summary>
/// Gets the length of the file.
/// </summary>
public long Length
{
get
{
return _fileStream.Length;
}
}
/// <summary>
/// Writes a byte into write buffer
/// </summary>
public void WriteByte(long index, byte value)
{
if(_writes.Contains(index))
_writes[index] = value;
else
_writes.Add(index, value);
OnChanged(EventArgs.Empty);
}
/// <summary>
/// Not supported
/// </summary>
public void DeleteBytes(long index, long length)
{
throw new NotSupportedException("FileByteProvider.DeleteBytes");
}
/// <summary>
/// Not supported
/// </summary>
public void InsertBytes(long index, byte[] bs)
{
throw new NotSupportedException("FileByteProvider.InsertBytes");
}
/// <summary>
/// Returns true
/// </summary>
public bool SupportsWriteByte()
{
return !_readOnly;
}
/// <summary>
/// Returns false
/// </summary>
public bool SupportsInsertBytes()
{
return false;
}
/// <summary>
/// Returns false
/// </summary>
public bool SupportsDeleteBytes()
{
return false;
}
#endregion
#region IDisposable Members
/// <summary>
/// Releases the file handle used by the FileByteProvider.
/// </summary>
public void Dispose()
{
if(_fileStream != null)
{
_fileName = null;
_fileStream.Close();
_fileStream = null;
}
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.UI.WebControls;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.Providers.HostedSolution;
namespace WebsitePanel.Portal.ExchangeServer
{
public partial class Organizations : WebsitePanelModuleBase
{
private int CurrentDefaultOrgId { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
// set display preferences
gvOrgs.PageSize = UsersHelper.GetDisplayItemsPerPage();
// visibility
chkRecursive.Visible = (PanelSecurity.SelectedUser.Role != UserRole.User);
gvOrgs.Columns[2].Visible = gvOrgs.Columns[3].Visible = (PanelSecurity.SelectedUser.Role != UserRole.User) && chkRecursive.Checked;
btnSetDefaultOrganization.Enabled = !(gvOrgs.Rows.Count < 2);
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
if (cntx.Quotas.ContainsKey(Quotas.ORGANIZATIONS))
{
btnCreate.Enabled = (!(cntx.Quotas[Quotas.ORGANIZATIONS].QuotaAllocatedValue <= gvOrgs.Rows.Count) || (cntx.Quotas[Quotas.ORGANIZATIONS].QuotaAllocatedValue == -1));
}
/*
if (PanelSecurity.LoggedUser.Role == UserRole.User)
{
gvOrgs.Columns[2].Visible = gvOrgs.Columns[3].Visible = gvOrgs.Columns[5].Visible = false;
btnCreate.Enabled = false;
btnSetDefaultOrganization.Enabled = false;
}
*/
if (!Page.IsPostBack)
{
RedirectToRequiredOrg();
}
}
private List<string> GetPossibleUrlRefferers()
{
List<string> urlReferrers = new List<string>();
var queryBuilder = new StringBuilder();
queryBuilder.AppendFormat("?pid=Home&UserID={0}", PanelSecurity.SelectedUserId);
urlReferrers.Add(queryBuilder.ToString());
urlReferrers.Add("?pid=Home");
urlReferrers.Add("?");
urlReferrers.Add(string.Empty);
queryBuilder.Clear();
return urlReferrers;
}
private void RedirectToRequiredOrg()
{
if (Request.UrlReferrer != null && gvOrgs.Rows.Count > 0)
{
List<string> referrers = GetPossibleUrlRefferers();
if (PanelSecurity.SelectedUser.Role == UserRole.User)
{
if (Request.UrlReferrer.Query.Equals(referrers[0]))
{
RedirectToOrgHomePage();
}
}
if (PanelSecurity.LoggedUser.Role == UserRole.User)
{
if (referrers.Contains(Request.UrlReferrer.Query))
{
RedirectToOrgHomePage();
}
}
}
}
private void RedirectToOrgHomePage()
{
if (CurrentDefaultOrgId > 0) Response.Redirect(GetOrganizationEditUrl(CurrentDefaultOrgId.ToString()));
Response.Redirect(((HyperLink)gvOrgs.Rows[0].Cells[1].Controls[1]).NavigateUrl);
}
protected void btnCreate_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "create_organization"));
}
protected void odsOrgsPaged_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
messageBox.ShowErrorMessage("GET_ORGS", e.Exception);
e.ExceptionHandled = true;
}
}
public string GetOrganizationEditUrl(string itemId)
{
return EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "organization_home",
"ItemID=" + itemId);
}
public string GetUserHomePageUrl(int userId)
{
return PortalUtils.GetUserHomePageUrl(userId);
}
public string GetSpaceHomePageUrl(int spaceId)
{
return NavigateURL(PortalUtils.SPACE_ID_PARAM, spaceId.ToString());
}
protected void gvOrgs_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteItem")
{
// delete organization
int itemId = Utils.ParseInt(e.CommandArgument.ToString(), 0);
try
{
int result = ES.Services.Organizations.DeleteOrganization(itemId);
if (result < 0)
{
messageBox.ShowResultMessage(result);
return;
}
// rebind grid
gvOrgs.DataBind();
orgsQuota.BindQuota();
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
if (cntx.Quotas.ContainsKey(Quotas.ORGANIZATIONS))
{
btnCreate.Enabled = !(cntx.Quotas[Quotas.ORGANIZATIONS].QuotaAllocatedValue <= gvOrgs.Rows.Count);
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("DELETE_ORG", ex);
}
}
}
protected void btnSetDefaultOrganization_Click(object sender, EventArgs e)
{
// get org
int newDefaultOrgId = Utils.ParseInt(Request.Form["DefaultOrganization"], CurrentDefaultOrgId);
try
{
ES.Services.Organizations.SetDefaultOrganization(newDefaultOrgId, CurrentDefaultOrgId);
ShowSuccessMessage("REQUEST_COMPLETED_SUCCESFULLY");
}
catch (Exception ex)
{
ShowErrorMessage("ORGANIZATION_SET_DEFAULT_ORG", ex);
}
}
public string IsChecked(string val, string itemId)
{
if (!string.IsNullOrEmpty(val) && val.ToLowerInvariant() == "true")
{
CurrentDefaultOrgId = Utils.ParseInt(itemId, 0);
return "checked";
}
return "";
}
}
}
| |
#region Copyright & license notice
/*
* Copyright: Copyright (c) 2007 Amazon Technologies, Inc.
* License: Apache License, Version 2.0
*/
#endregion
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace Amazon.WebServices.MechanicalTurk.Advanced
{
/// <summary>
/// Stream used to log the soap request and response to the <see cref="ILog"/> interface
/// </summary>
internal class LogStream : Stream
{
private static string END_OF_ENVELOPE = "</soap:Envelope>";
private Stream _sink;
private StringBuilder sb = new StringBuilder();
public LogStream(Stream orgStream)
{
_sink = orgStream;
}
public override bool CanRead
{
get { return _sink.CanRead; }
}
public override bool CanSeek
{
get { return _sink.CanSeek; }
}
public override bool CanWrite
{
get { return _sink.CanWrite; }
}
public override long Length
{
get { return _sink.Length; }
}
public override long Position
{
get { return _sink.Position; }
set { _sink.Position = value; }
}
public override long Seek(long offset, System.IO.SeekOrigin direction)
{
return _sink.Seek(offset, direction);
}
public override void SetLength(long length)
{
_sink.SetLength(length);
}
public override void Close()
{
// write buffer to ILog (to the end of the soap envelope)
string s = sb.ToString().Trim();
int i = s.IndexOf(END_OF_ENVELOPE);
MTurkLog.Debug(s.Substring(0, i+END_OF_ENVELOPE.Length));
sb = null;
_sink.Close();
}
public override void Flush()
{
_sink.Flush();
}
public override void Write(byte[] buffer, int offset, int count)
{
_sink.Write(buffer, offset, count);
AppendBuffer(buffer, offset, count);
}
public override int Read(byte[] buffer, int offset, int count)
{
AppendBuffer(buffer, offset, count);
return _sink.Read(buffer, offset, count); ;
}
private void AppendBuffer(byte[] buffer, int offset, int count)
{
if (buffer.Length > 0 && buffer[0] != 0)
{
sb.Append(System.Text.Encoding.UTF8.GetChars(buffer, offset, count));
}
}
}
/// <summary>
/// WebResponse wrapper to log the soap request to the <see cref="ILog"/> interface
/// </summary>
internal class LoggedWebReqest : WebRequest
{
private WebRequest wr;
private Stream request_stream;
public LoggedWebReqest(WebRequest org)
{
wr = org;
}
public override string Method
{
get { return wr.Method; }
set { wr.Method = value; }
}
public override Uri RequestUri
{
get { return wr.RequestUri; }
}
public override WebHeaderCollection Headers
{
get { return wr.Headers; }
set { wr.Headers = value; }
}
public override long ContentLength
{
get { return wr.ContentLength; }
set { wr.ContentLength = value; }
}
public override string ContentType
{
get { return wr.ContentType; }
set { wr.ContentType = value; }
}
public override ICredentials Credentials
{
get { return wr.Credentials; }
set { wr.Credentials = value; }
}
public override bool PreAuthenticate
{
get { return wr.PreAuthenticate; }
set { wr.PreAuthenticate = value; }
}
public override System.IO.Stream GetRequestStream()
{
return WrappedRequestStream(wr.GetRequestStream());
}
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
return wr.BeginGetRequestStream(callback, state);
}
public override System.IO.Stream EndGetRequestStream(IAsyncResult asyncResult)
{
return WrappedRequestStream(wr.EndGetRequestStream(asyncResult));
}
private Stream WrappedRequestStream(Stream streamToWrap)
{
if (request_stream == null)
{
request_stream = new LogStream(streamToWrap);
}
return request_stream;
}
public override WebResponse GetResponse()
{
return new LoggedWebResponse(wr.GetResponse());
}
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
return wr.BeginGetResponse(callback, state);
}
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
return new LoggedWebResponse(wr.EndGetResponse(asyncResult));
}
}
/// <summary>
/// WebResponse wrapper to log the soap response to the <see cref="ILog"/> interface
/// </summary>
internal class LoggedWebResponse : WebResponse
{
private WebResponse wr;
private Stream response_stream;
public LoggedWebResponse(WebResponse org)
{
wr = org;
}
public override Stream GetResponseStream()
{
if (response_stream == null)
{
response_stream = new LogStream(wr.GetResponseStream());
}
return response_stream;
}
public override long ContentLength
{
get { return wr.ContentLength; }
set { wr.ContentLength = value; }
}
public override string ContentType
{
get { return wr.ContentType; }
set { wr.ContentType = value; }
}
public override Uri ResponseUri
{
get { return wr.ResponseUri; }
}
public override WebHeaderCollection Headers
{
get { return wr.Headers; }
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using org.swyn.foundation.utils;
using tdbgui;
namespace tdbadmin
{
/// <summary>
/// category Form.
/// </summary>
public class FCat : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox TDB_abgrp;
private System.Windows.Forms.Button TDB_ab_clr;
private System.Windows.Forms.Button TDB_ab_sel;
private System.Windows.Forms.Button TDB_ab_exit;
private System.Windows.Forms.Button TDB_ab_del;
private System.Windows.Forms.Button TDB_ab_upd;
private System.Windows.Forms.Button TDB_ab_ins;
private System.Windows.Forms.Label tdb_e_id;
private System.Windows.Forms.TextBox tdb_e_bez;
private System.Windows.Forms.TextBox tdb_e_text;
private System.Windows.Forms.Label tdb_l_text;
private System.Windows.Forms.Label tdb_l_bez;
private System.Windows.Forms.Label tdb_l_id;
private System.Windows.Forms.CheckBox Kat_e_ishost;
private System.Windows.Forms.Label Kat_l_dltt;
private System.Windows.Forms.ComboBox Kat_e_parent;
private System.Windows.Forms.Label Kat_l_parent;
private System.Windows.Forms.ComboBox Kat_e_dltt;
private System.Windows.Forms.Label Kat_l_ga;
private System.Windows.Forms.TextBox Kat_e_ga;
private bool ishost;
private tdbgui.GUIcat cat;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public FCat()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
cat = new tdbgui.GUIcat();
ishost = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.Kat_e_ga = new System.Windows.Forms.TextBox();
this.Kat_l_ga = new System.Windows.Forms.Label();
this.Kat_e_dltt = new System.Windows.Forms.ComboBox();
this.Kat_e_ishost = new System.Windows.Forms.CheckBox();
this.Kat_l_dltt = new System.Windows.Forms.Label();
this.Kat_e_parent = new System.Windows.Forms.ComboBox();
this.Kat_l_parent = new System.Windows.Forms.Label();
this.tdb_e_id = new System.Windows.Forms.Label();
this.tdb_e_bez = new System.Windows.Forms.TextBox();
this.tdb_e_text = new System.Windows.Forms.TextBox();
this.tdb_l_text = new System.Windows.Forms.Label();
this.tdb_l_bez = new System.Windows.Forms.Label();
this.tdb_l_id = new System.Windows.Forms.Label();
this.TDB_abgrp = new System.Windows.Forms.GroupBox();
this.TDB_ab_clr = new System.Windows.Forms.Button();
this.TDB_ab_sel = new System.Windows.Forms.Button();
this.TDB_ab_exit = new System.Windows.Forms.Button();
this.TDB_ab_del = new System.Windows.Forms.Button();
this.TDB_ab_upd = new System.Windows.Forms.Button();
this.TDB_ab_ins = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.TDB_abgrp.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.Kat_e_ga);
this.groupBox1.Controls.Add(this.Kat_l_ga);
this.groupBox1.Controls.Add(this.Kat_e_dltt);
this.groupBox1.Controls.Add(this.Kat_e_ishost);
this.groupBox1.Controls.Add(this.Kat_l_dltt);
this.groupBox1.Controls.Add(this.Kat_e_parent);
this.groupBox1.Controls.Add(this.Kat_l_parent);
this.groupBox1.Controls.Add(this.tdb_e_id);
this.groupBox1.Controls.Add(this.tdb_e_bez);
this.groupBox1.Controls.Add(this.tdb_e_text);
this.groupBox1.Controls.Add(this.tdb_l_text);
this.groupBox1.Controls.Add(this.tdb_l_bez);
this.groupBox1.Controls.Add(this.tdb_l_id);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(608, 317);
this.groupBox1.TabIndex = 13;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Description";
//
// Kat_e_ga
//
this.Kat_e_ga.Location = new System.Drawing.Point(136, 208);
this.Kat_e_ga.Name = "Kat_e_ga";
this.Kat_e_ga.Size = new System.Drawing.Size(248, 20);
this.Kat_e_ga.TabIndex = 17;
this.Kat_e_ga.Text = "";
//
// Kat_l_ga
//
this.Kat_l_ga.Location = new System.Drawing.Point(8, 208);
this.Kat_l_ga.Name = "Kat_l_ga";
this.Kat_l_ga.TabIndex = 16;
this.Kat_l_ga.Text = "Grafical attribute";
//
// Kat_e_dltt
//
this.Kat_e_dltt.Location = new System.Drawing.Point(136, 184);
this.Kat_e_dltt.Name = "Kat_e_dltt";
this.Kat_e_dltt.Size = new System.Drawing.Size(248, 21);
this.Kat_e_dltt.TabIndex = 15;
//
// Kat_e_ishost
//
this.Kat_e_ishost.Location = new System.Drawing.Point(432, 160);
this.Kat_e_ishost.Name = "Kat_e_ishost";
this.Kat_e_ishost.TabIndex = 14;
this.Kat_e_ishost.Text = "No Upgrade ?";
this.Kat_e_ishost.CheckedChanged += new System.EventHandler(this.Kat_e_ishost_CheckedChanged);
//
// Kat_l_dltt
//
this.Kat_l_dltt.Location = new System.Drawing.Point(8, 184);
this.Kat_l_dltt.Name = "Kat_l_dltt";
this.Kat_l_dltt.Size = new System.Drawing.Size(104, 23);
this.Kat_l_dltt.TabIndex = 12;
this.Kat_l_dltt.Text = "Supplier Type";
//
// Kat_e_parent
//
this.Kat_e_parent.Location = new System.Drawing.Point(136, 160);
this.Kat_e_parent.Name = "Kat_e_parent";
this.Kat_e_parent.Size = new System.Drawing.Size(248, 21);
this.Kat_e_parent.TabIndex = 11;
//
// Kat_l_parent
//
this.Kat_l_parent.Location = new System.Drawing.Point(8, 160);
this.Kat_l_parent.Name = "Kat_l_parent";
this.Kat_l_parent.TabIndex = 10;
this.Kat_l_parent.Text = "Upgrade category";
//
// tdb_e_id
//
this.tdb_e_id.Location = new System.Drawing.Point(136, 24);
this.tdb_e_id.Name = "tdb_e_id";
this.tdb_e_id.Size = new System.Drawing.Size(64, 16);
this.tdb_e_id.TabIndex = 9;
//
// tdb_e_bez
//
this.tdb_e_bez.Location = new System.Drawing.Point(136, 40);
this.tdb_e_bez.Name = "tdb_e_bez";
this.tdb_e_bez.Size = new System.Drawing.Size(456, 20);
this.tdb_e_bez.TabIndex = 0;
this.tdb_e_bez.Text = "";
//
// tdb_e_text
//
this.tdb_e_text.Location = new System.Drawing.Point(136, 64);
this.tdb_e_text.Multiline = true;
this.tdb_e_text.Name = "tdb_e_text";
this.tdb_e_text.Size = new System.Drawing.Size(456, 88);
this.tdb_e_text.TabIndex = 2;
this.tdb_e_text.Text = "";
//
// tdb_l_text
//
this.tdb_l_text.Location = new System.Drawing.Point(8, 96);
this.tdb_l_text.Name = "tdb_l_text";
this.tdb_l_text.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tdb_l_text.TabIndex = 4;
this.tdb_l_text.Text = "Description";
//
// tdb_l_bez
//
this.tdb_l_bez.Location = new System.Drawing.Point(8, 39);
this.tdb_l_bez.Name = "tdb_l_bez";
this.tdb_l_bez.TabIndex = 2;
this.tdb_l_bez.Text = "Title";
//
// tdb_l_id
//
this.tdb_l_id.Location = new System.Drawing.Point(8, 21);
this.tdb_l_id.Name = "tdb_l_id";
this.tdb_l_id.TabIndex = 1;
this.tdb_l_id.Text = "ID";
//
// TDB_abgrp
//
this.TDB_abgrp.Controls.Add(this.TDB_ab_clr);
this.TDB_abgrp.Controls.Add(this.TDB_ab_sel);
this.TDB_abgrp.Controls.Add(this.TDB_ab_exit);
this.TDB_abgrp.Controls.Add(this.TDB_ab_del);
this.TDB_abgrp.Controls.Add(this.TDB_ab_upd);
this.TDB_abgrp.Controls.Add(this.TDB_ab_ins);
this.TDB_abgrp.Dock = System.Windows.Forms.DockStyle.Bottom;
this.TDB_abgrp.Location = new System.Drawing.Point(0, 261);
this.TDB_abgrp.Name = "TDB_abgrp";
this.TDB_abgrp.Size = new System.Drawing.Size(608, 56);
this.TDB_abgrp.TabIndex = 15;
this.TDB_abgrp.TabStop = false;
this.TDB_abgrp.Text = "Actions";
//
// TDB_ab_clr
//
this.TDB_ab_clr.Dock = System.Windows.Forms.DockStyle.Right;
this.TDB_ab_clr.Location = new System.Drawing.Point(455, 16);
this.TDB_ab_clr.Name = "TDB_ab_clr";
this.TDB_ab_clr.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_clr.TabIndex = 10;
this.TDB_ab_clr.Text = "Clear";
this.TDB_ab_clr.Click += new System.EventHandler(this.TDB_ab_clr_Click);
//
// TDB_ab_sel
//
this.TDB_ab_sel.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255)));
this.TDB_ab_sel.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_sel.Location = new System.Drawing.Point(228, 16);
this.TDB_ab_sel.Name = "TDB_ab_sel";
this.TDB_ab_sel.Size = new System.Drawing.Size(80, 37);
this.TDB_ab_sel.TabIndex = 8;
this.TDB_ab_sel.Text = "Select";
this.TDB_ab_sel.Click += new System.EventHandler(this.TDB_ab_sel_Click);
//
// TDB_ab_exit
//
this.TDB_ab_exit.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(192)), ((System.Byte)(192)));
this.TDB_ab_exit.Dock = System.Windows.Forms.DockStyle.Right;
this.TDB_ab_exit.Location = new System.Drawing.Point(530, 16);
this.TDB_ab_exit.Name = "TDB_ab_exit";
this.TDB_ab_exit.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_exit.TabIndex = 9;
this.TDB_ab_exit.Text = "Exit";
this.TDB_ab_exit.Click += new System.EventHandler(this.TDB_ab_exit_Click);
//
// TDB_ab_del
//
this.TDB_ab_del.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192)));
this.TDB_ab_del.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_del.Location = new System.Drawing.Point(153, 16);
this.TDB_ab_del.Name = "TDB_ab_del";
this.TDB_ab_del.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_del.TabIndex = 7;
this.TDB_ab_del.Text = "Delete";
this.TDB_ab_del.Click += new System.EventHandler(this.TDB_ab_del_Click);
//
// TDB_ab_upd
//
this.TDB_ab_upd.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192)));
this.TDB_ab_upd.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_upd.Location = new System.Drawing.Point(78, 16);
this.TDB_ab_upd.Name = "TDB_ab_upd";
this.TDB_ab_upd.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_upd.TabIndex = 6;
this.TDB_ab_upd.Text = "Update";
this.TDB_ab_upd.Click += new System.EventHandler(this.TDB_ab_upd_Click);
//
// TDB_ab_ins
//
this.TDB_ab_ins.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192)));
this.TDB_ab_ins.Dock = System.Windows.Forms.DockStyle.Left;
this.TDB_ab_ins.Location = new System.Drawing.Point(3, 16);
this.TDB_ab_ins.Name = "TDB_ab_ins";
this.TDB_ab_ins.Size = new System.Drawing.Size(75, 37);
this.TDB_ab_ins.TabIndex = 5;
this.TDB_ab_ins.Text = "Insert";
this.TDB_ab_ins.Click += new System.EventHandler(this.TDB_ab_ins_Click);
//
// FCat
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(608, 317);
this.Controls.Add(this.TDB_abgrp);
this.Controls.Add(this.groupBox1);
this.Name = "FCat";
this.Text = "Category";
this.Load += new System.EventHandler(this.FCat_Load);
this.groupBox1.ResumeLayout(false);
this.TDB_abgrp.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region Form callbacks
private void TDB_ab_sel_Click(object sender, System.EventArgs e)
{
SelForm Fsel = new SelForm();
cat.Sel(Fsel.GetLV);
Fsel.Accept += new EventHandler(TDB_ab_sel_Click_Return);
Fsel.ShowDialog(this);
}
void TDB_ab_sel_Click_Return(object sender, EventArgs e)
{
int id = -1, rows = 0;
SelForm Fsel = (SelForm)sender;
id = Fsel.GetID;
cat.Get(id, ref rows);
tdb_e_id.Text = cat.ObjId.ToString();
tdb_e_bez.Text = cat.ObjBez;
tdb_e_text.Text = cat.ObjText;
if (cat.ObjParentId == -1)
{
this.Kat_e_parent.SelectedValue = -1;
this.Kat_e_ishost.CheckState = CheckState.Checked;
this.Kat_e_parent.Visible = false;
ishost = true;
}
else
{
this.Kat_e_parent.SelectedValue = cat.ObjParentId;
this.Kat_e_ishost.CheckState = CheckState.Unchecked;
this.Kat_e_parent.Visible = true;
ishost = false;
}
Kat_e_ga.Text = cat.ObjColor.ToString();
this.Kat_e_dltt.SelectedValue = cat.ObjSupType;
}
private void TDB_ab_exit_Click(object sender, System.EventArgs e)
{
Close();
}
private void TDB_ab_ins_Click(object sender, System.EventArgs e)
{
cat.InsUpd(true, tdb_e_bez.Text, tdb_e_text.Text, (int)this.Kat_e_parent.SelectedValue,
(int)this.Kat_e_dltt.SelectedValue, Convert.ToInt32(this.Kat_e_ga.Text), ishost);
tdb_e_id.Text = cat.ObjId.ToString();
}
private void TDB_ab_upd_Click(object sender, System.EventArgs e)
{
cat.InsUpd(false, tdb_e_bez.Text, tdb_e_text.Text, (int)this.Kat_e_parent.SelectedValue,
(int)this.Kat_e_dltt.SelectedValue, Convert.ToInt32(this.Kat_e_ga.Text), ishost);
}
private void TDB_ab_del_Click(object sender, System.EventArgs e)
{
int rows = 0;
cat.Get(Convert.ToInt32(tdb_e_id.Text), ref rows);
cat.Delete();
}
private void TDB_ab_clr_Click(object sender, System.EventArgs e)
{
tdb_e_id.Text = "";
tdb_e_bez.Text = "";
tdb_e_text.Text = "";
Kat_e_ga.Text = "1";
}
private void FCat_Load(object sender, System.EventArgs e)
{
cat.ObjOptional = true;
cat.SetCombo(this.Kat_e_parent);
tdbgui.GUIsuptype supt = new tdbgui.GUIsuptype();
supt.SetCombo(this.Kat_e_dltt);
}
private void Kat_e_ishost_CheckedChanged(object sender, System.EventArgs e)
{
if (this.Kat_e_ishost.CheckState == CheckState.Checked)
{
this.Kat_e_parent.Visible = false;
ishost = true;
}
else
{
this.Kat_e_parent.Visible = true;
ishost = false;
}
}
#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.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
namespace System.Configuration
{
internal class ClientConfigPaths
{
internal const string UserConfigFilename = "user.config";
private const string ConfigExtension = ".config";
private const int MaxLengthToUse = 25;
private const string HttpUri = "http://";
private const string StrongNameDesc = "StrongName";
private const string UrlDesc = "Url";
private const string PathDesc = "Path";
private static volatile ClientConfigPaths s_current;
private static volatile bool s_currentIncludesUserConfig;
private readonly bool _includesUserConfig;
private string _companyName;
private ClientConfigPaths(string exePath, bool includeUserConfig)
{
_includesUserConfig = includeUserConfig;
Assembly exeAssembly = null;
string applicationFilename = null;
if (exePath != null)
{
// Exe path was specified, use it
ApplicationUri = Path.GetFullPath(exePath);
if (!File.Exists(ApplicationUri))
{
throw ExceptionUtil.ParameterInvalid(nameof(exePath));
}
applicationFilename = ApplicationUri;
}
else
{
// Exe path wasn't specified, get it from the entry assembly
exeAssembly = Assembly.GetEntryAssembly();
if (exeAssembly == null)
throw new PlatformNotSupportedException();
HasEntryAssembly = true;
// The original NetFX (desktop) code tried to get the local path without using Uri.
// If we ever find a need to do this again be careful with the logic. "file:///" is
// used for local paths and "file://" for UNCs. Simply removing the prefix will make
// local paths relative on Unix (e.g. "file:///home" will become "home" instead of
// "/home").
string configBasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, exeAssembly.ManifestModule.Name);
Uri uri = new Uri(configBasePath);
if (uri.IsFile)
{
ApplicationUri = uri.LocalPath;
applicationFilename = uri.LocalPath;
}
else
{
ApplicationUri = Uri.EscapeDataString(configBasePath);
}
}
ApplicationConfigUri = ApplicationUri + ConfigExtension;
// In the case when exePath was explicitly supplied, we will not be able to
// construct user.config paths, so quit here.
if (exePath != null) return;
// Skip expensive initialization of user config file information if requested.
if (!_includesUserConfig) return;
bool isHttp = StringUtil.StartsWithOrdinalIgnoreCase(ApplicationConfigUri, HttpUri);
SetNamesAndVersion(applicationFilename, exeAssembly, isHttp);
if (isHttp) return;
// Create a directory suffix for local and roaming config of three parts:
// (1) Company name
string part1 = Validate(_companyName, limitSize: true);
// (2) Domain or product name & a application urit hash
string namePrefix = Validate(AppDomain.CurrentDomain.FriendlyName, limitSize: true);
if (string.IsNullOrEmpty(namePrefix))
namePrefix = Validate(ProductName, limitSize: true);
string applicationUriLower = !string.IsNullOrEmpty(ApplicationUri)
? ApplicationUri.ToLower(CultureInfo.InvariantCulture)
: null;
string hashSuffix = GetTypeAndHashSuffix(applicationUriLower);
string part2 = !string.IsNullOrEmpty(namePrefix) && !string.IsNullOrEmpty(hashSuffix)
? namePrefix + hashSuffix
: null;
// (3) The product version
string part3 = Validate(ProductVersion, limitSize: false);
string dirSuffix = CombineIfValid(CombineIfValid(part1, part2), part3);
string roamingFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (Path.IsPathRooted(roamingFolderPath))
{
RoamingConfigDirectory = CombineIfValid(roamingFolderPath, dirSuffix);
RoamingConfigFilename = CombineIfValid(RoamingConfigDirectory, UserConfigFilename);
}
string localFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (Path.IsPathRooted(localFolderPath))
{
LocalConfigDirectory = CombineIfValid(localFolderPath, dirSuffix);
LocalConfigFilename = CombineIfValid(LocalConfigDirectory, UserConfigFilename);
}
}
internal static ClientConfigPaths Current => GetPaths(null, true);
internal bool HasEntryAssembly { get; }
internal string ApplicationUri { get; }
internal string ApplicationConfigUri { get; }
internal string RoamingConfigFilename { get; }
internal string RoamingConfigDirectory { get; }
internal bool HasRoamingConfig => (RoamingConfigFilename != null) || !_includesUserConfig;
internal string LocalConfigFilename { get; }
internal string LocalConfigDirectory { get; }
internal bool HasLocalConfig => (LocalConfigFilename != null) || !_includesUserConfig;
internal string ProductName { get; private set; }
internal string ProductVersion { get; private set; }
internal static ClientConfigPaths GetPaths(string exePath, bool includeUserConfig)
{
ClientConfigPaths result;
if (exePath == null)
{
if ((s_current == null) || (includeUserConfig && !s_currentIncludesUserConfig))
{
s_current = new ClientConfigPaths(null, includeUserConfig);
s_currentIncludesUserConfig = includeUserConfig;
}
result = s_current;
}
else result = new ClientConfigPaths(exePath, includeUserConfig);
return result;
}
internal static void RefreshCurrent()
{
s_currentIncludesUserConfig = false;
s_current = null;
}
// Combines path2 with path1 if possible, else returns null.
private static string CombineIfValid(string path1, string path2)
{
if ((path1 == null) || (path2 == null)) return null;
try
{
return Path.Combine(path1, path2);
}
catch
{
return null;
}
}
// Returns a type and hash suffix based on what used to come from app domain evidence.
// The evidence we use, in priority order, is Strong Name, Url and Exe Path. If one of
// these is found, we compute a SHA1 hash of it and return a suffix based on that.
// If none is found, we return null.
private static string GetTypeAndHashSuffix(string exePath)
{
Assembly assembly = Assembly.GetEntryAssembly();
string suffix = null;
string typeName = null;
string hash = null;
if (assembly != null)
{
AssemblyName assemblyName = assembly.GetName();
Uri codeBase = new Uri(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assembly.ManifestModule.Name));
hash = IdentityHelper.GetNormalizedStrongNameHash(assemblyName);
if (hash != null)
{
typeName = StrongNameDesc;
}
else
{
hash = IdentityHelper.GetNormalizedUriHash(codeBase);
typeName = UrlDesc;
}
}
else if (!string.IsNullOrEmpty(exePath))
{
// Fall back on the exe name
hash = IdentityHelper.GetStrongHashSuitableForObjectName(exePath);
typeName = PathDesc;
}
if (!string.IsNullOrEmpty(hash)) suffix = "_" + typeName + "_" + hash;
return suffix;
}
private void SetNamesAndVersion(string applicationFilename, Assembly exeAssembly, bool isHttp)
{
Type mainType = null;
// Get CompanyName, ProductName, and ProductVersion
// First try custom attributes on the assembly.
if (exeAssembly != null)
{
object[] attrs = exeAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if ((attrs != null) && (attrs.Length > 0))
{
_companyName = ((AssemblyCompanyAttribute)attrs[0]).Company?.Trim();
}
attrs = exeAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);
if ((attrs != null) && (attrs.Length > 0))
{
ProductName = ((AssemblyProductAttribute)attrs[0]).Product?.Trim();
}
ProductVersion = exeAssembly.GetName().Version.ToString().Trim();
}
// If we couldn't get custom attributes, fall back on the entry type namespace
if (!isHttp &&
(string.IsNullOrEmpty(_companyName) || string.IsNullOrEmpty(ProductName) ||
string.IsNullOrEmpty(ProductVersion)))
{
if (exeAssembly != null)
{
MethodInfo entryPoint = exeAssembly.EntryPoint;
if (entryPoint != null)
{
mainType = entryPoint.ReflectedType;
}
}
string ns = null;
if (mainType != null) ns = mainType.Namespace;
if (string.IsNullOrEmpty(ProductName))
{
// Try the remainder of the namespace
if (ns != null)
{
int lastDot = ns.LastIndexOf(".", StringComparison.Ordinal);
if ((lastDot != -1) && (lastDot < ns.Length - 1)) ProductName = ns.Substring(lastDot + 1);
else ProductName = ns;
ProductName = ProductName.Trim();
}
// Try the type of the entry assembly
if (string.IsNullOrEmpty(ProductName) && (mainType != null)) ProductName = mainType.Name.Trim();
// give up, return empty string
if (ProductName == null) ProductName = string.Empty;
}
if (string.IsNullOrEmpty(_companyName))
{
// Try the first part of the namespace
if (ns != null)
{
int firstDot = ns.IndexOf(".", StringComparison.Ordinal);
_companyName = firstDot != -1 ? ns.Substring(0, firstDot) : ns;
_companyName = _companyName.Trim();
}
// If that doesn't work, use the product name
if (string.IsNullOrEmpty(_companyName)) _companyName = ProductName;
}
}
// Desperate measures for product version - assume 1.0
if (string.IsNullOrEmpty(ProductVersion)) ProductVersion = "1.0.0.0";
}
// Makes the passed in string suitable to use as a path name by replacing illegal characters
// with underscores. Additionally, we do two things - replace spaces too with underscores and
// limit the resultant string's length to MaxLengthToUse if limitSize is true.
private static string Validate(string str, bool limitSize)
{
string validated = str;
if (string.IsNullOrEmpty(validated)) return validated;
// First replace all illegal characters with underscores
foreach (char c in Path.GetInvalidFileNameChars()) validated = validated.Replace(c, '_');
// Replace all spaces with underscores
validated = validated.Replace(' ', '_');
if (limitSize)
{
validated = validated.Length > MaxLengthToUse
? validated.Substring(0, MaxLengthToUse)
: validated;
}
return validated;
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// A non-generic and generic parallel state class, used by the Parallel helper class
// for parallel loop management.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
// Prevents compiler warnings/errors regarding the use of ref params in Interlocked methods
namespace System.Threading.Tasks
{
/// <summary>
/// Enables iterations of <see cref="System.Threading.Tasks.Parallel"/> loops to interact with
/// other iterations.
/// </summary>
[DebuggerDisplay("ShouldExitCurrentIteration = {ShouldExitCurrentIteration}")]
public class ParallelLoopState
{
// Derived classes will track a ParallelStateFlags32 or ParallelStateFlags64.
// So this is slightly redundant, but it enables us to implement some
// methods in this base class.
private readonly ParallelLoopStateFlags _flagsBase;
internal ParallelLoopState(ParallelLoopStateFlags fbase)
{
_flagsBase = fbase;
}
/// <summary>
/// Internal/virtual support for ShouldExitCurrentIteration.
/// </summary>
internal virtual bool InternalShouldExitCurrentIteration
{
get
{
Debug.Fail(SR.ParallelState_NotSupportedException_UnsupportedMethod);
throw new NotSupportedException(
SR.ParallelState_NotSupportedException_UnsupportedMethod);
}
}
/// <summary>
/// Gets whether the current iteration of the loop should exit based
/// on requests made by this or other iterations.
/// </summary>
/// <remarks>
/// When an iteration of a loop calls <see cref="Break()"/> or <see cref="Stop()"/>, or
/// when one throws an exception, or when the loop is canceled, the <see cref="Parallel"/> class will proactively
/// attempt to prohibit additional iterations of the loop from starting execution.
/// However, there may be cases where it is unable to prevent additional iterations from starting.
/// It may also be the case that a long-running iteration has already begun execution. In such
/// cases, iterations may explicitly check the <see cref="ShouldExitCurrentIteration"/> property and
/// cease execution if the property returns true.
/// </remarks>
public bool ShouldExitCurrentIteration
{
get
{
return InternalShouldExitCurrentIteration;
}
}
/// <summary>
/// Gets whether any iteration of the loop has called <see cref="Stop()"/>.
/// </summary>
public bool IsStopped
{
get
{
return ((_flagsBase.LoopStateFlags & ParallelLoopStateFlags.ParallelLoopStateStopped) != 0);
}
}
/// <summary>
/// Gets whether any iteration of the loop has thrown an exception that went unhandled by that
/// iteration.
/// </summary>
public bool IsExceptional
{
get
{
return ((_flagsBase.LoopStateFlags & ParallelLoopStateFlags.ParallelLoopStateExceptional) != 0);
}
}
/// <summary>
/// Internal/virtual support for LowestBreakIteration.
/// </summary>
internal virtual long? InternalLowestBreakIteration
{
get
{
Debug.Fail(SR.ParallelState_NotSupportedException_UnsupportedMethod);
throw new NotSupportedException(
SR.ParallelState_NotSupportedException_UnsupportedMethod);
}
}
/// <summary>
/// Gets the lowest iteration of the loop from which <see cref="Break()"/> was called.
/// </summary>
/// <remarks>
/// If no iteration of the loop called <see cref="Break()"/>, this property will return null.
/// </remarks>
public long? LowestBreakIteration
{
get
{
return InternalLowestBreakIteration;
}
}
/// <summary>
/// Communicates that the <see cref="Parallel"/> loop should cease execution at the system's earliest
/// convenience.
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// The <see cref="Break()"/> method was previously called. <see cref="Break()"/> and <see
/// cref="Stop()"/> may not be used in combination by iterations of the same loop.
/// </exception>
/// <remarks>
/// <para>
/// <see cref="Stop()"/> may be used to communicate to the loop that no other iterations need be run.
/// For long-running iterations that may already be executing, <see cref="Stop()"/> causes <see cref="IsStopped"/>
/// to return true for all other iterations of the loop, such that another iteration may check <see
/// cref="IsStopped"/> and exit early if it's observed to be true.
/// </para>
/// <para>
/// <see cref="Stop()"/> is typically employed in search-based algorithms, where once a result is found,
/// no other iterations need be executed.
/// </para>
/// </remarks>
public void Stop()
{
_flagsBase.Stop();
}
// Internal/virtual support for Break().
internal virtual void InternalBreak()
{
Debug.Fail(SR.ParallelState_NotSupportedException_UnsupportedMethod);
throw new NotSupportedException(
SR.ParallelState_NotSupportedException_UnsupportedMethod);
}
/// <summary>
/// Communicates that the <see cref="Parallel"/> loop should cease execution at the system's earliest
/// convenience of iterations beyond the current iteration.
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// The <see cref="Stop()"/> method was previously called. <see cref="Break()"/> and <see cref="Stop()"/>
/// may not be used in combination by iterations of the same loop.
/// </exception>
/// <remarks>
/// <para>
/// <see cref="Break()"/> may be used to communicate to the loop that no other iterations after the
/// current iteration need be run. For example, if <see cref="Break()"/> is called from the 100th
/// iteration of a for loop iterating in parallel from 0 to 1000, all iterations less than 100 should
/// still be run, but the iterations from 101 through to 1000 are not necessary.
/// </para>
/// <para>
/// For long-running iterations that may already be executing, <see cref="Break()"/> causes <see
/// cref="LowestBreakIteration"/>
/// to be set to the current iteration's index if the current index is less than the current value of
/// <see cref="LowestBreakIteration"/>.
/// </para>
/// <para>
/// <see cref="Break()"/> is typically employed in search-based algorithms where an ordering is
/// present in the data source.
/// </para>
/// </remarks>
public void Break()
{
InternalBreak();
}
// Helper method to avoid repeating Break() logic between ParallelState32 and ParallelState32<TLocal>
internal static void Break(int iteration, ParallelLoopStateFlags32 pflags)
{
int oldValue = ParallelLoopStateFlags.ParallelLoopStateNone;
// Attempt to change state from "not stopped or broken or canceled or exceptional" to "broken".
if (!pflags.AtomicLoopStateUpdate(ParallelLoopStateFlags.ParallelLoopStateBroken,
ParallelLoopStateFlags.ParallelLoopStateStopped | ParallelLoopStateFlags.ParallelLoopStateExceptional | ParallelLoopStateFlags.ParallelLoopStateCanceled,
ref oldValue))
{
// If we were already stopped, we have a problem
if ((oldValue & ParallelLoopStateFlags.ParallelLoopStateStopped) != 0)
{
throw new InvalidOperationException(
SR.ParallelState_Break_InvalidOperationException_BreakAfterStop);
}
else
{
// Apparently we previously got cancelled or became exceptional. No action necessary
return;
}
}
// replace shared LowestBreakIteration with CurrentIteration, but only if CurrentIteration
// is less than LowestBreakIteration.
int oldLBI = pflags._lowestBreakIteration;
if (iteration < oldLBI)
{
SpinWait wait = new SpinWait();
while (Interlocked.CompareExchange(
ref pflags._lowestBreakIteration,
iteration,
oldLBI) != oldLBI)
{
wait.SpinOnce();
oldLBI = pflags._lowestBreakIteration;
if (iteration > oldLBI) break;
}
}
}
// Helper method to avoid repeating Break() logic between ParallelState64 and ParallelState64<TLocal>
internal static void Break(long iteration, ParallelLoopStateFlags64 pflags)
{
int oldValue = ParallelLoopStateFlags.ParallelLoopStateNone;
// Attempt to change state from "not stopped or broken or canceled or exceptional" to "broken".
if (!pflags.AtomicLoopStateUpdate(ParallelLoopStateFlags.ParallelLoopStateBroken,
ParallelLoopStateFlags.ParallelLoopStateStopped | ParallelLoopStateFlags.ParallelLoopStateExceptional | ParallelLoopStateFlags.ParallelLoopStateCanceled,
ref oldValue))
{
// If we were already stopped, we have a problem
if ((oldValue & ParallelLoopStateFlags.ParallelLoopStateStopped) != 0)
{
throw new InvalidOperationException(
SR.ParallelState_Break_InvalidOperationException_BreakAfterStop);
}
else
{
// Apparently we previously got cancelled or became exceptional. No action necessary
return;
}
}
// replace shared LowestBreakIteration with CurrentIteration, but only if CurrentIteration
// is less than LowestBreakIteration.
long oldLBI = pflags.LowestBreakIteration;
if (iteration < oldLBI)
{
SpinWait wait = new SpinWait();
while (Interlocked.CompareExchange(
ref pflags._lowestBreakIteration,
iteration,
oldLBI) != oldLBI)
{
wait.SpinOnce();
oldLBI = pflags.LowestBreakIteration;
if (iteration > oldLBI) break;
}
}
}
}
internal class ParallelLoopState32 : ParallelLoopState
{
private readonly ParallelLoopStateFlags32 _sharedParallelStateFlags;
private int _currentIteration = 0;
/// <summary>
/// Internal constructor to ensure an instance isn't created by users.
/// </summary>
/// <param name="sharedParallelStateFlags">A flag shared among all threads participating
/// in the execution of a certain loop.</param>
internal ParallelLoopState32(ParallelLoopStateFlags32 sharedParallelStateFlags)
: base(sharedParallelStateFlags)
{
_sharedParallelStateFlags = sharedParallelStateFlags;
}
/// <summary>
/// Tracks the current loop iteration for the owning task.
/// This is used to compute whether or not the task should
/// terminate early due to a Break() call.
/// </summary>
internal int CurrentIteration
{
get { return _currentIteration; }
set { _currentIteration = value; }
}
/// <summary>
/// Returns true if we should be exiting from the current iteration
/// due to Stop(), Break() or exception.
/// </summary>
internal override bool InternalShouldExitCurrentIteration
{
get { return _sharedParallelStateFlags.ShouldExitLoop(CurrentIteration); }
}
/// <summary>
/// Returns the lowest iteration at which Break() has been called, or
/// null if Break() has not yet been called.
/// </summary>
internal override long? InternalLowestBreakIteration
{
get { return _sharedParallelStateFlags.NullableLowestBreakIteration; }
}
/// <summary>
/// Communicates that parallel tasks should stop when they reach a specified iteration element.
/// (which is CurrentIteration of the caller).
/// </summary>
/// <exception cref="System.InvalidOperationException">Break() called after Stop().</exception>
/// <remarks>
/// This is shared with all other concurrent threads in the system which are participating in the
/// loop's execution. After calling Break(), no additional iterations will be executed on
/// the current thread, and other worker threads will execute once they get beyond the calling iteration.
/// </remarks>
internal override void InternalBreak()
{
ParallelLoopState.Break(CurrentIteration, _sharedParallelStateFlags);
}
}
/// <summary>
/// Allows independent iterations of a parallel loop to interact with other iterations.
/// </summary>
internal class ParallelLoopState64 : ParallelLoopState
{
private readonly ParallelLoopStateFlags64 _sharedParallelStateFlags;
private long _currentIteration = 0;
/// <summary>
/// Internal constructor to ensure an instance isn't created by users.
/// </summary>
/// <param name="sharedParallelStateFlags">A flag shared among all threads participating
/// in the execution of a certain loop.</param>
internal ParallelLoopState64(ParallelLoopStateFlags64 sharedParallelStateFlags)
: base(sharedParallelStateFlags)
{
_sharedParallelStateFlags = sharedParallelStateFlags;
}
/// <summary>
/// Tracks the current loop iteration for the owning task.
/// This is used to compute whether or not the task should
/// terminate early due to a Break() call.
/// </summary>
internal long CurrentIteration
{
// No interlocks needed, because this value is only accessed in a single thread.
get { return _currentIteration; }
set { _currentIteration = value; }
}
/// <summary>
/// Returns true if we should be exiting from the current iteration
/// due to Stop(), Break() or exception.
/// </summary>
internal override bool InternalShouldExitCurrentIteration
{
get { return _sharedParallelStateFlags.ShouldExitLoop(CurrentIteration); }
}
/// <summary>
/// Returns the lowest iteration at which Break() has been called, or
/// null if Break() has not yet been called.
/// </summary>
internal override long? InternalLowestBreakIteration
{
// We don't need to worry about torn read/write here because
// ParallelStateFlags64.LowestBreakIteration property is protected
// by an Interlocked.Read().
get { return _sharedParallelStateFlags.NullableLowestBreakIteration; }
}
/// <summary>
/// Communicates that parallel tasks should stop when they reach a specified iteration element.
/// (which is CurrentIteration of the caller).
/// </summary>
/// <exception cref="System.InvalidOperationException">Break() called after Stop().</exception>
/// <remarks>
/// Atomically sets shared StoppedBroken flag to BROKEN, then atomically sets shared
/// LowestBreakIteration to CurrentIteration, but only if CurrentIteration is less than
/// LowestBreakIteration.
/// </remarks>
internal override void InternalBreak()
{
ParallelLoopState.Break(CurrentIteration, _sharedParallelStateFlags);
}
}
/// <summary>
/// State information that is common between ParallelStateFlags class
/// and ParallelStateFlags64 class.
/// </summary>
internal class ParallelLoopStateFlags
{
internal const int ParallelLoopStateNone = 0;
internal const int ParallelLoopStateExceptional = 1;
internal const int ParallelLoopStateBroken = 2;
internal const int ParallelLoopStateStopped = 4;
internal const int ParallelLoopStateCanceled = 8;
private volatile int _loopStateFlags = ParallelLoopStateNone;
internal int LoopStateFlags
{
get { return _loopStateFlags; }
}
internal bool AtomicLoopStateUpdate(int newState, int illegalStates)
{
int oldState = 0;
return AtomicLoopStateUpdate(newState, illegalStates, ref oldState);
}
internal bool AtomicLoopStateUpdate(int newState, int illegalStates, ref int oldState)
{
SpinWait sw = new SpinWait();
do
{
oldState = _loopStateFlags;
if ((oldState & illegalStates) != 0) return false;
if (Interlocked.CompareExchange(ref _loopStateFlags, oldState | newState, oldState) == oldState)
{
return true;
}
sw.SpinOnce();
} while (true);
}
internal void SetExceptional()
{
// we can set the exceptional flag regardless of the state of other bits.
AtomicLoopStateUpdate(ParallelLoopStateExceptional, ParallelLoopStateNone);
}
internal void Stop()
{
// disallow setting of ParallelLoopStateStopped bit only if ParallelLoopStateBroken was already set
if (!AtomicLoopStateUpdate(ParallelLoopStateStopped, ParallelLoopStateBroken))
{
throw new InvalidOperationException(SR.ParallelState_Stop_InvalidOperationException_StopAfterBreak);
}
}
// Returns true if StoppedBroken is updated to ParallelLoopStateCanceled.
internal bool Cancel()
{
// we can set the canceled flag regardless of the state of other bits.
return (AtomicLoopStateUpdate(ParallelLoopStateCanceled, ParallelLoopStateNone));
}
}
/// <summary>
/// An internal class used to share accounting information in 32-bit versions
/// of For()/ForEach() loops.
/// </summary>
internal class ParallelLoopStateFlags32 : ParallelLoopStateFlags
{
// Records the lowest iteration at which a Break() has been called,
// or Int32.MaxValue if no break has been called. Used directly
// by Break().
internal volatile int _lowestBreakIteration = int.MaxValue;
// Not strictly necessary, but maintains consistency with ParallelStateFlags64
internal int LowestBreakIteration
{
get { return _lowestBreakIteration; }
}
// Does some processing to convert _lowestBreakIteration to a long?.
internal long? NullableLowestBreakIteration
{
get
{
if (_lowestBreakIteration == int.MaxValue) return null;
else
{
// protect against torn read of 64-bit value
long rval = _lowestBreakIteration;
if (IntPtr.Size >= 8) return rval;
else return Interlocked.Read(ref rval);
}
}
}
/// <summary>
/// Lets the caller know whether or not to prematurely exit the For/ForEach loop.
/// If this returns true, then exit the loop. Otherwise, keep going.
/// </summary>
/// <param name="CallerIteration">The caller's current iteration point
/// in the loop.</param>
/// <remarks>
/// The loop should exit on any one of the following conditions:
/// (1) Stop() has been called by one or more tasks.
/// (2) An exception has been raised by one or more tasks.
/// (3) Break() has been called by one or more tasks, and
/// CallerIteration exceeds the (lowest) iteration at which
/// Break() was called.
/// (4) The loop was canceled.
/// </remarks>
internal bool ShouldExitLoop(int CallerIteration)
{
int flags = LoopStateFlags;
return (flags != ParallelLoopStateNone && (
((flags & (ParallelLoopStateExceptional | ParallelLoopStateStopped | ParallelLoopStateCanceled)) != 0) ||
(((flags & ParallelLoopStateBroken) != 0) && (CallerIteration > LowestBreakIteration))));
}
// This lighter version of ShouldExitLoop will be used when the body type doesn't contain a state.
// Since simpler bodies cannot stop or break, we can safely skip checks for those flags here.
internal bool ShouldExitLoop()
{
int flags = LoopStateFlags;
return ((flags != ParallelLoopStateNone) && ((flags & (ParallelLoopStateExceptional | ParallelLoopStateCanceled)) != 0));
}
}
/// <summary>
/// An internal class used to share accounting information in 64-bit versions
/// of For()/ForEach() loops.
/// </summary>
internal class ParallelLoopStateFlags64 : ParallelLoopStateFlags
{
// Records the lowest iteration at which a Break() has been called,
// or Int64.MaxValue if no break has been called. Used directly
// by Break().
internal long _lowestBreakIteration = long.MaxValue;
// Performs a conditionally interlocked read of _lowestBreakIteration.
internal long LowestBreakIteration
{
get
{
if (IntPtr.Size >= 8) return _lowestBreakIteration;
else return Interlocked.Read(ref _lowestBreakIteration);
}
}
// Does some processing to convert _lowestBreakIteration to a long?.
internal long? NullableLowestBreakIteration
{
get
{
if (_lowestBreakIteration == long.MaxValue) return null;
else
{
if (IntPtr.Size >= 8) return _lowestBreakIteration;
else return Interlocked.Read(ref _lowestBreakIteration);
}
}
}
/// <summary>
/// Lets the caller know whether or not to prematurely exit the For/ForEach loop.
/// If this returns true, then exit the loop. Otherwise, keep going.
/// </summary>
/// <param name="CallerIteration">The caller's current iteration point
/// in the loop.</param>
/// <remarks>
/// The loop should exit on any one of the following conditions:
/// (1) Stop() has been called by one or more tasks.
/// (2) An exception has been raised by one or more tasks.
/// (3) Break() has been called by one or more tasks, and
/// CallerIteration exceeds the (lowest) iteration at which
/// Break() was called.
/// (4) The loop has been canceled.
/// </remarks>
internal bool ShouldExitLoop(long CallerIteration)
{
int flags = LoopStateFlags;
return (flags != ParallelLoopStateNone && (
((flags & (ParallelLoopStateExceptional | ParallelLoopStateStopped | ParallelLoopStateCanceled)) != 0) ||
(((flags & ParallelLoopStateBroken) != 0) && (CallerIteration > LowestBreakIteration))));
}
// This lighter version of ShouldExitLoop will be used when the body type doesn't contain a state.
// Since simpler bodies cannot stop or break, we can safely skip checks for those flags here.
internal bool ShouldExitLoop()
{
int flags = LoopStateFlags;
return ((flags != ParallelLoopStateNone) && ((flags & (ParallelLoopStateExceptional | ParallelLoopStateCanceled)) != 0));
}
}
/// <summary>
/// Provides completion status on the execution of a <see cref="Parallel"/> loop.
/// </summary>
/// <remarks>
/// If <see cref="IsCompleted"/> returns true, then the loop ran to completion, such that all iterations
/// of the loop were executed. If <see cref="IsCompleted"/> returns false and <see
/// cref="LowestBreakIteration"/> returns null, a call to <see
/// cref="System.Threading.Tasks.ParallelLoopState.Stop"/> was used to end the loop prematurely. If <see
/// cref="IsCompleted"/> returns false and <see cref="LowestBreakIteration"/> returns a non-null integral
/// value, <see cref="System.Threading.Tasks.ParallelLoopState.Break()"/> was used to end the loop prematurely.
/// </remarks>
public struct ParallelLoopResult
{
internal bool _completed;
internal long? _lowestBreakIteration;
/// <summary>
/// Gets whether the loop ran to completion, such that all iterations of the loop were executed
/// and the loop didn't receive a request to end prematurely.
/// </summary>
public bool IsCompleted { get { return _completed; } }
/// <summary>
/// Gets the index of the lowest iteration from which <see
/// cref="System.Threading.Tasks.ParallelLoopState.Break()"/>
/// was called.
/// </summary>
/// <remarks>
/// If <see cref="System.Threading.Tasks.ParallelLoopState.Break()"/> was not employed, this property will
/// return null.
/// </remarks>
public long? LowestBreakIteration { get { return _lowestBreakIteration; } }
}
}
| |
using System;
using System.Drawing;
using System.IO;
using Microsoft.DirectX;
using D3D = Microsoft.DirectX.Direct3D;
namespace Voyage.Terraingine.DataCore
{
/// <summary>
/// An object for storing texture data.
/// </summary>
public class Texture
{
#region Data Members
private D3D.Texture _texture;
private string _name;
private string _file;
private string _operationText;
private bool _mask;
private bool _render;
private Vector2 _shift, _scale;
private D3D.TextureOperation _operation;
#endregion
#region Properties
/// <summary>
/// Gets or sets the DirectX texture object.
/// </summary>
public D3D.Texture DXTexture
{
get { return _texture; }
set { _texture = value; }
}
/// <summary>
/// Gets or sets the name of the texture.
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// Gets or sets the filename of the texture.
/// </summary>
public string FileName
{
get { return _file; }
set { _file = value; }
}
/// <summary>
/// Gets or sets if the texture is used as a masking texture.
/// </summary>
public bool Mask
{
get { return _mask; }
set { _mask = value; }
}
/// <summary>
/// Gets or sets if the texture is to be rendered.
/// </summary>
public bool Render
{
get { return _render; }
set { _render = value; }
}
/// <summary>
/// Gets or sets the texture shift.
/// </summary>
public Vector2 Shift
{
get { return _shift; }
set { _shift = value; }
}
/// <summary>
/// Gets or sets the texture scale.
/// </summary>
public Vector2 Scale
{
get { return _scale; }
set { _scale = value; }
}
/// <summary>
/// Gets the texture blending operation used by the texture.
/// </summary>
public D3D.TextureOperation Operation
{
get { return _operation; }
set { _operation = value; }
}
/// <summary>
/// Gets or sets the text associated with the DirectX TextureOperation
/// </summary>
public string OperationText
{
get { return _operationText; }
set { _operationText = value; }
}
#endregion
#region Methods
/// <summary>
/// Creates a DirectX texture object.
/// </summary>
public Texture()
{
_texture = null;
Initialize();
}
/// <summary>
/// Creates a DirectX texture object.
/// </summary>
/// <param name="tex">Texture to contain in the object.</param>
/// <param name="filename">Filename to the original texture file.</param>
public Texture( D3D.Texture tex, string filename )
{
_texture = tex;
Initialize();
_name = filename;
_file = filename;
}
/// <summary>
/// Creates a copy of a Texture object.
/// </summary>
/// <param name="tex">Texture object to copy.</param>
public Texture( Texture tex )
{
if ( tex != null )
{
_texture = tex.DXTexture;
_name = tex._name;
_file = tex._file;
_mask = tex._mask;
_render = tex._render;
_shift = new Vector2( tex._shift.X, tex._shift.Y );
_scale = new Vector2( tex._scale.X, tex._scale.Y );
_operation = tex._operation;
_operationText = tex._operationText;
}
else
{
_texture = null;
Initialize();
}
}
/// <summary>
/// Safely disposes of the texture data.
/// </summary>
public void Dispose()
{
if ( _texture != null )
{
_texture.Dispose();
_texture = null;
}
Initialize();
}
/// <summary>
/// Initializes the additional information in the texture.
/// </summary>
public void Initialize()
{
_name = null;
_file = null;
_mask = false;
_render = true;
_shift = new Vector2( 0f, 0f );
_scale = new Vector2( 1f, 1f );
_operation = D3D.TextureOperation.SelectArg1;
_operationText = null;
}
/// <summary>
/// Gets the texture bitmap image data used by the texture.
/// </summary>
/// <returns>The bitmap used by the texture.</returns>
public Bitmap GetImage()
{
StreamReader reader = new StreamReader( _file );
Bitmap image = new Bitmap( reader.BaseStream );
reader.Close();
return image;
}
/// <summary>
/// Loads the specified image into the texture.
/// </summary>
/// <param name="device">The DirectX device to load the texture into.</param>
/// <param name="image">The image to load.</param>
/// <param name="usage">The Direct3D Usage parameter for the image.</param>
/// <param name="pool">The Direct3D Pool parameter for the image.</param>
public void SetImage( D3D.Device device, Bitmap image, D3D.Usage usage, D3D.Pool pool )
{
if ( _texture != null )
_texture.Dispose();
_texture = new D3D.Texture( device, image, usage, pool );
}
#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.
namespace System.Xml.Schema
{
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Runtime.Versioning;
#pragma warning disable 618
internal sealed class SchemaCollectionPreprocessor : BaseProcessor
{
private enum Compositor
{
Root,
Include,
Import
};
private XmlSchema _schema;
private string _targetNamespace;
private bool _buildinIncluded = false;
private XmlSchemaForm _elementFormDefault;
private XmlSchemaForm _attributeFormDefault;
private XmlSchemaDerivationMethod _blockDefault;
private XmlSchemaDerivationMethod _finalDefault;
//Dictionary<Uri, Uri> schemaLocations;
private Hashtable _schemaLocations;
private Hashtable _referenceNamespaces;
private string _xmlns;
private const XmlSchemaDerivationMethod schemaBlockDefaultAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.Substitution;
private const XmlSchemaDerivationMethod schemaFinalDefaultAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Union;
private const XmlSchemaDerivationMethod elementBlockAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.Substitution;
private const XmlSchemaDerivationMethod elementFinalAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension;
private const XmlSchemaDerivationMethod simpleTypeFinalAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Union;
private const XmlSchemaDerivationMethod complexTypeBlockAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension;
private const XmlSchemaDerivationMethod complexTypeFinalAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension;
private XmlResolver _xmlResolver = null;
public SchemaCollectionPreprocessor(XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler)
: base(nameTable, schemaNames, eventHandler)
{
}
public bool Execute(XmlSchema schema, string targetNamespace, bool loadExternals, XmlSchemaCollection xsc)
{
_schema = schema;
_xmlns = NameTable.Add("xmlns");
Cleanup(schema);
if (loadExternals && _xmlResolver != null)
{
_schemaLocations = new Hashtable(); //new Dictionary<Uri, Uri>();
if (schema.BaseUri != null)
{
_schemaLocations.Add(schema.BaseUri, schema.BaseUri);
}
LoadExternals(schema, xsc);
}
ValidateIdAttribute(schema);
Preprocess(schema, targetNamespace, Compositor.Root);
if (!HasErrors)
{
schema.IsPreprocessed = true;
for (int i = 0; i < schema.Includes.Count; ++i)
{
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
if (include.Schema != null)
{
include.Schema.IsPreprocessed = true;
}
}
}
return !HasErrors;
}
private void Cleanup(XmlSchema schema)
{
if (schema.IsProcessing)
{
return;
}
schema.IsProcessing = true;
for (int i = 0; i < schema.Includes.Count; ++i)
{
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
if (include.Schema != null)
{
Cleanup(include.Schema);
}
if (include is XmlSchemaRedefine)
{
XmlSchemaRedefine rdef = include as XmlSchemaRedefine;
rdef.AttributeGroups.Clear();
rdef.Groups.Clear();
rdef.SchemaTypes.Clear();
}
}
schema.Attributes.Clear();
schema.AttributeGroups.Clear();
schema.SchemaTypes.Clear();
schema.Elements.Clear();
schema.Groups.Clear();
schema.Notations.Clear();
schema.Ids.Clear();
schema.IdentityConstraints.Clear();
schema.IsProcessing = false;
}
internal XmlResolver XmlResolver
{
set
{
_xmlResolver = value;
}
}
// SxS: This method reads resource names from the source documents and does not return any resources to the caller
// It's fine to suppress the SxS warning
private void LoadExternals(XmlSchema schema, XmlSchemaCollection xsc)
{
if (schema.IsProcessing)
{
return;
}
schema.IsProcessing = true;
for (int i = 0; i < schema.Includes.Count; ++i)
{
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
Uri includeLocation = null;
//CASE 1: If the Schema object of the include has been set
if (include.Schema != null)
{
// already loaded
if (include is XmlSchemaImport && ((XmlSchemaImport)include).Namespace == XmlReservedNs.NsXml)
{
_buildinIncluded = true;
}
else
{
includeLocation = include.BaseUri;
if (includeLocation != null && _schemaLocations[includeLocation] == null)
{
_schemaLocations.Add(includeLocation, includeLocation);
}
LoadExternals(include.Schema, xsc);
}
continue;
}
//CASE 2: If the include has been already added to the schema collection directly
if (xsc != null && include is XmlSchemaImport)
{ //Added for SchemaCollection compatibility
XmlSchemaImport import = (XmlSchemaImport)include;
string importNS = import.Namespace != null ? import.Namespace : string.Empty;
include.Schema = xsc[importNS]; //Fetch it from the collection
if (include.Schema != null)
{
include.Schema = include.Schema.Clone();
if (include.Schema.BaseUri != null && _schemaLocations[include.Schema.BaseUri] == null)
{
_schemaLocations.Add(include.Schema.BaseUri, include.Schema.BaseUri);
}
//To avoid re-including components that were already included through a different path
Uri subUri = null;
for (int j = 0; j < include.Schema.Includes.Count; ++j)
{
XmlSchemaExternal subInc = (XmlSchemaExternal)include.Schema.Includes[j];
if (subInc is XmlSchemaImport)
{
XmlSchemaImport subImp = (XmlSchemaImport)subInc;
subUri = subImp.BaseUri != null ? subImp.BaseUri : (subImp.Schema != null && subImp.Schema.BaseUri != null ? subImp.Schema.BaseUri : null);
if (subUri != null)
{
if (_schemaLocations[subUri] != null)
{
subImp.Schema = null; //So that the components are not included again
}
else
{ //if its not there already, add it
_schemaLocations.Add(subUri, subUri); //The schema for that location is available
}
}
}
}
continue;
}
}
//CASE 3: If the imported namespace is the XML namespace, load built-in schema
if (include is XmlSchemaImport && ((XmlSchemaImport)include).Namespace == XmlReservedNs.NsXml)
{
if (!_buildinIncluded)
{
_buildinIncluded = true;
include.Schema = Preprocessor.GetBuildInSchema();
}
continue;
}
//CASE4: Parse schema from the provided location
string schemaLocation = include.SchemaLocation;
if (schemaLocation == null)
{
continue;
}
Uri ruri = ResolveSchemaLocationUri(schema, schemaLocation);
if (ruri != null && _schemaLocations[ruri] == null)
{
Stream stream = GetSchemaEntity(ruri);
if (stream != null)
{
include.BaseUri = ruri;
_schemaLocations.Add(ruri, ruri);
XmlTextReader reader = new XmlTextReader(ruri.ToString(), stream, NameTable);
reader.XmlResolver = _xmlResolver;
try
{
Parser parser = new Parser(SchemaType.XSD, NameTable, SchemaNames, EventHandler);
parser.Parse(reader, null);
while (reader.Read()) ;// wellformness check
include.Schema = parser.XmlSchema;
LoadExternals(include.Schema, xsc);
}
catch (XmlSchemaException e)
{
SendValidationEventNoThrow(new XmlSchemaException(SR.Sch_CannotLoadSchema, new string[] { schemaLocation, e.Message }, e.SourceUri, e.LineNumber, e.LinePosition), XmlSeverityType.Error);
}
catch (Exception)
{
SendValidationEvent(SR.Sch_InvalidIncludeLocation, include, XmlSeverityType.Warning);
}
finally
{
reader.Close();
}
}
else
{
SendValidationEvent(SR.Sch_InvalidIncludeLocation, include, XmlSeverityType.Warning);
}
}
}
schema.IsProcessing = false;
}
private void BuildRefNamespaces(XmlSchema schema)
{
_referenceNamespaces = new Hashtable();
XmlSchemaImport import;
string ns;
//Add XSD namespace
_referenceNamespaces.Add(XmlReservedNs.NsXs, XmlReservedNs.NsXs);
_referenceNamespaces.Add(string.Empty, string.Empty);
for (int i = 0; i < schema.Includes.Count; ++i)
{
import = schema.Includes[i] as XmlSchemaImport;
if (import != null)
{
ns = import.Namespace;
if (ns != null && _referenceNamespaces[ns] == null)
_referenceNamespaces.Add(ns, ns);
}
}
//Add the schema's targetnamespace
if (schema.TargetNamespace != null && _referenceNamespaces[schema.TargetNamespace] == null)
_referenceNamespaces.Add(schema.TargetNamespace, schema.TargetNamespace);
}
private void Preprocess(XmlSchema schema, string targetNamespace, Compositor compositor)
{
if (schema.IsProcessing)
{
return;
}
schema.IsProcessing = true;
string tns = schema.TargetNamespace;
if (tns != null)
{
schema.TargetNamespace = tns = NameTable.Add(tns);
if (tns.Length == 0)
{
SendValidationEvent(SR.Sch_InvalidTargetNamespaceAttribute, schema);
}
else
{
try
{
XmlConvert.ToUri(tns); // can throw
}
catch
{
SendValidationEvent(SR.Sch_InvalidNamespace, schema.TargetNamespace, schema);
}
}
}
if (schema.Version != null)
{
try
{
XmlConvert.VerifyTOKEN(schema.Version); // can throw
}
catch (Exception)
{
SendValidationEvent(SR.Sch_AttributeValueDataType, "version", schema);
}
}
switch (compositor)
{
case Compositor.Root:
if (targetNamespace == null && schema.TargetNamespace != null)
{ // not specified
targetNamespace = schema.TargetNamespace;
}
else if (schema.TargetNamespace == null && targetNamespace != null && targetNamespace.Length == 0)
{ // no namespace schema
targetNamespace = null;
}
if (targetNamespace != schema.TargetNamespace)
{
SendValidationEvent(SR.Sch_MismatchTargetNamespaceEx, targetNamespace, schema.TargetNamespace, schema);
}
break;
case Compositor.Import:
if (targetNamespace != schema.TargetNamespace)
{
SendValidationEvent(SR.Sch_MismatchTargetNamespaceImport, targetNamespace, schema.TargetNamespace, schema);
}
break;
case Compositor.Include:
if (schema.TargetNamespace != null)
{
if (targetNamespace != schema.TargetNamespace)
{
SendValidationEvent(SR.Sch_MismatchTargetNamespaceInclude, targetNamespace, schema.TargetNamespace, schema);
}
}
break;
}
for (int i = 0; i < schema.Includes.Count; ++i)
{
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
SetParent(include, schema);
PreprocessAnnotation(include);
string loc = include.SchemaLocation;
if (loc != null)
{
try
{
XmlConvert.ToUri(loc); // can throw
}
catch
{
SendValidationEvent(SR.Sch_InvalidSchemaLocation, loc, include);
}
}
else if ((include is XmlSchemaRedefine || include is XmlSchemaInclude) && include.Schema == null)
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "schemaLocation", include);
}
if (include.Schema != null)
{
if (include is XmlSchemaRedefine)
{
Preprocess(include.Schema, schema.TargetNamespace, Compositor.Include);
}
else if (include is XmlSchemaImport)
{
if (((XmlSchemaImport)include).Namespace == null && schema.TargetNamespace == null)
{
SendValidationEvent(SR.Sch_ImportTargetNamespaceNull, include);
}
else if (((XmlSchemaImport)include).Namespace == schema.TargetNamespace)
{
SendValidationEvent(SR.Sch_ImportTargetNamespace, include);
}
Preprocess(include.Schema, ((XmlSchemaImport)include).Namespace, Compositor.Import);
}
else
{
Preprocess(include.Schema, schema.TargetNamespace, Compositor.Include);
}
}
else if (include is XmlSchemaImport)
{
string ns = ((XmlSchemaImport)include).Namespace;
if (ns != null)
{
if (ns.Length == 0)
{
SendValidationEvent(SR.Sch_InvalidNamespaceAttribute, ns, include);
}
else
{
try
{
XmlConvert.ToUri(ns); //can throw
}
catch (FormatException)
{
SendValidationEvent(SR.Sch_InvalidNamespace, ns, include);
}
}
}
}
}
//Begin processing the current schema passed to preprocess
//Build the namespaces that can be referenced in the current schema
BuildRefNamespaces(schema);
_targetNamespace = targetNamespace == null ? string.Empty : targetNamespace;
if (schema.BlockDefault == XmlSchemaDerivationMethod.All)
{
_blockDefault = XmlSchemaDerivationMethod.All;
}
else if (schema.BlockDefault == XmlSchemaDerivationMethod.None)
{
_blockDefault = XmlSchemaDerivationMethod.Empty;
}
else
{
if ((schema.BlockDefault & ~schemaBlockDefaultAllowed) != 0)
{
SendValidationEvent(SR.Sch_InvalidBlockDefaultValue, schema);
}
_blockDefault = schema.BlockDefault & schemaBlockDefaultAllowed;
}
if (schema.FinalDefault == XmlSchemaDerivationMethod.All)
{
_finalDefault = XmlSchemaDerivationMethod.All;
}
else if (schema.FinalDefault == XmlSchemaDerivationMethod.None)
{
_finalDefault = XmlSchemaDerivationMethod.Empty;
}
else
{
if ((schema.FinalDefault & ~schemaFinalDefaultAllowed) != 0)
{
SendValidationEvent(SR.Sch_InvalidFinalDefaultValue, schema);
}
_finalDefault = schema.FinalDefault & schemaFinalDefaultAllowed;
}
_elementFormDefault = schema.ElementFormDefault;
if (_elementFormDefault == XmlSchemaForm.None)
{
_elementFormDefault = XmlSchemaForm.Unqualified;
}
_attributeFormDefault = schema.AttributeFormDefault;
if (_attributeFormDefault == XmlSchemaForm.None)
{
_attributeFormDefault = XmlSchemaForm.Unqualified;
}
for (int i = 0; i < schema.Includes.Count; ++i)
{
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
if (include is XmlSchemaRedefine)
{
XmlSchemaRedefine redefine = (XmlSchemaRedefine)include;
if (include.Schema != null)
{
PreprocessRedefine(redefine);
}
else
{
for (int j = 0; j < redefine.Items.Count; ++j)
{
if (!(redefine.Items[j] is XmlSchemaAnnotation))
{
SendValidationEvent(SR.Sch_RedefineNoSchema, redefine);
break;
}
}
}
}
XmlSchema includedSchema = include.Schema;
if (includedSchema != null)
{
foreach (XmlSchemaElement element in includedSchema.Elements.Values)
{
AddToTable(schema.Elements, element.QualifiedName, element);
}
foreach (XmlSchemaAttribute attribute in includedSchema.Attributes.Values)
{
AddToTable(schema.Attributes, attribute.QualifiedName, attribute);
}
foreach (XmlSchemaGroup group in includedSchema.Groups.Values)
{
AddToTable(schema.Groups, group.QualifiedName, group);
}
foreach (XmlSchemaAttributeGroup attributeGroup in includedSchema.AttributeGroups.Values)
{
AddToTable(schema.AttributeGroups, attributeGroup.QualifiedName, attributeGroup);
}
foreach (XmlSchemaType type in includedSchema.SchemaTypes.Values)
{
AddToTable(schema.SchemaTypes, type.QualifiedName, type);
}
foreach (XmlSchemaNotation notation in includedSchema.Notations.Values)
{
AddToTable(schema.Notations, notation.QualifiedName, notation);
}
}
ValidateIdAttribute(include);
}
List<XmlSchemaObject> removeItemsList = new List<XmlSchemaObject>();
for (int i = 0; i < schema.Items.Count; ++i)
{
SetParent(schema.Items[i], schema);
XmlSchemaAttribute attribute = schema.Items[i] as XmlSchemaAttribute;
if (attribute != null)
{
PreprocessAttribute(attribute);
AddToTable(schema.Attributes, attribute.QualifiedName, attribute);
}
else if (schema.Items[i] is XmlSchemaAttributeGroup)
{
XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)schema.Items[i];
PreprocessAttributeGroup(attributeGroup);
AddToTable(schema.AttributeGroups, attributeGroup.QualifiedName, attributeGroup);
}
else if (schema.Items[i] is XmlSchemaComplexType)
{
XmlSchemaComplexType complexType = (XmlSchemaComplexType)schema.Items[i];
PreprocessComplexType(complexType, false);
AddToTable(schema.SchemaTypes, complexType.QualifiedName, complexType);
}
else if (schema.Items[i] is XmlSchemaSimpleType)
{
XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)schema.Items[i];
PreprocessSimpleType(simpleType, false);
AddToTable(schema.SchemaTypes, simpleType.QualifiedName, simpleType);
}
else if (schema.Items[i] is XmlSchemaElement)
{
XmlSchemaElement element = (XmlSchemaElement)schema.Items[i];
PreprocessElement(element);
AddToTable(schema.Elements, element.QualifiedName, element);
}
else if (schema.Items[i] is XmlSchemaGroup)
{
XmlSchemaGroup group = (XmlSchemaGroup)schema.Items[i];
PreprocessGroup(group);
AddToTable(schema.Groups, group.QualifiedName, group);
}
else if (schema.Items[i] is XmlSchemaNotation)
{
XmlSchemaNotation notation = (XmlSchemaNotation)schema.Items[i];
PreprocessNotation(notation);
AddToTable(schema.Notations, notation.QualifiedName, notation);
}
else if (!(schema.Items[i] is XmlSchemaAnnotation))
{
SendValidationEvent(SR.Sch_InvalidCollection, schema.Items[i]);
removeItemsList.Add(schema.Items[i]);
}
}
for (int i = 0; i < removeItemsList.Count; ++i)
{
schema.Items.Remove(removeItemsList[i]);
}
schema.IsProcessing = false;
}
private void PreprocessRedefine(XmlSchemaRedefine redefine)
{
for (int i = 0; i < redefine.Items.Count; ++i)
{
SetParent(redefine.Items[i], redefine);
XmlSchemaGroup group = redefine.Items[i] as XmlSchemaGroup;
if (group != null)
{
PreprocessGroup(group);
if (redefine.Groups[group.QualifiedName] != null)
{
SendValidationEvent(SR.Sch_GroupDoubleRedefine, group);
}
else
{
AddToTable(redefine.Groups, group.QualifiedName, group);
group.Redefined = (XmlSchemaGroup)redefine.Schema.Groups[group.QualifiedName];
if (group.Redefined != null)
{
CheckRefinedGroup(group);
}
else
{
SendValidationEvent(SR.Sch_GroupRedefineNotFound, group);
}
}
}
else if (redefine.Items[i] is XmlSchemaAttributeGroup)
{
XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)redefine.Items[i];
PreprocessAttributeGroup(attributeGroup);
if (redefine.AttributeGroups[attributeGroup.QualifiedName] != null)
{
SendValidationEvent(SR.Sch_AttrGroupDoubleRedefine, attributeGroup);
}
else
{
AddToTable(redefine.AttributeGroups, attributeGroup.QualifiedName, attributeGroup);
attributeGroup.Redefined = (XmlSchemaAttributeGroup)redefine.Schema.AttributeGroups[attributeGroup.QualifiedName];
if (attributeGroup.Redefined != null)
{
CheckRefinedAttributeGroup(attributeGroup);
}
else
{
SendValidationEvent(SR.Sch_AttrGroupRedefineNotFound, attributeGroup);
}
}
}
else if (redefine.Items[i] is XmlSchemaComplexType)
{
XmlSchemaComplexType complexType = (XmlSchemaComplexType)redefine.Items[i];
PreprocessComplexType(complexType, false);
if (redefine.SchemaTypes[complexType.QualifiedName] != null)
{
SendValidationEvent(SR.Sch_ComplexTypeDoubleRedefine, complexType);
}
else
{
AddToTable(redefine.SchemaTypes, complexType.QualifiedName, complexType);
XmlSchemaType type = (XmlSchemaType)redefine.Schema.SchemaTypes[complexType.QualifiedName];
if (type != null)
{
if (type is XmlSchemaComplexType)
{
complexType.Redefined = type;
CheckRefinedComplexType(complexType);
}
else
{
SendValidationEvent(SR.Sch_SimpleToComplexTypeRedefine, complexType);
}
}
else
{
SendValidationEvent(SR.Sch_ComplexTypeRedefineNotFound, complexType);
}
}
}
else if (redefine.Items[i] is XmlSchemaSimpleType)
{
XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)redefine.Items[i];
PreprocessSimpleType(simpleType, false);
if (redefine.SchemaTypes[simpleType.QualifiedName] != null)
{
SendValidationEvent(SR.Sch_SimpleTypeDoubleRedefine, simpleType);
}
else
{
AddToTable(redefine.SchemaTypes, simpleType.QualifiedName, simpleType);
XmlSchemaType type = (XmlSchemaType)redefine.Schema.SchemaTypes[simpleType.QualifiedName];
if (type != null)
{
if (type is XmlSchemaSimpleType)
{
simpleType.Redefined = type;
CheckRefinedSimpleType(simpleType);
}
else
{
SendValidationEvent(SR.Sch_ComplexToSimpleTypeRedefine, simpleType);
}
}
else
{
SendValidationEvent(SR.Sch_SimpleTypeRedefineNotFound, simpleType);
}
}
}
}
foreach (DictionaryEntry entry in redefine.Groups)
{
redefine.Schema.Groups.Insert((XmlQualifiedName)entry.Key, (XmlSchemaObject)entry.Value);
}
foreach (DictionaryEntry entry in redefine.AttributeGroups)
{
redefine.Schema.AttributeGroups.Insert((XmlQualifiedName)entry.Key, (XmlSchemaObject)entry.Value);
}
foreach (DictionaryEntry entry in redefine.SchemaTypes)
{
redefine.Schema.SchemaTypes.Insert((XmlQualifiedName)entry.Key, (XmlSchemaObject)entry.Value);
}
}
private int CountGroupSelfReference(XmlSchemaObjectCollection items, XmlQualifiedName name)
{
int count = 0;
for (int i = 0; i < items.Count; ++i)
{
XmlSchemaGroupRef groupRef = items[i] as XmlSchemaGroupRef;
if (groupRef != null)
{
if (groupRef.RefName == name)
{
if (groupRef.MinOccurs != decimal.One || groupRef.MaxOccurs != decimal.One)
{
SendValidationEvent(SR.Sch_MinMaxGroupRedefine, groupRef);
}
count++;
}
}
else if (items[i] is XmlSchemaGroupBase)
{
count += CountGroupSelfReference(((XmlSchemaGroupBase)items[i]).Items, name);
}
if (count > 1)
{
break;
}
}
return count;
}
private void CheckRefinedGroup(XmlSchemaGroup group)
{
int count = 0;
if (group.Particle != null)
{
count = CountGroupSelfReference(group.Particle.Items, group.QualifiedName);
}
if (count > 1)
{
SendValidationEvent(SR.Sch_MultipleGroupSelfRef, group);
}
}
private void CheckRefinedAttributeGroup(XmlSchemaAttributeGroup attributeGroup)
{
int count = 0;
for (int i = 0; i < attributeGroup.Attributes.Count; ++i)
{
XmlSchemaAttributeGroupRef groupRef = attributeGroup.Attributes[i] as XmlSchemaAttributeGroupRef;
if (groupRef != null && groupRef.RefName == attributeGroup.QualifiedName)
{
count++;
}
}
if (count > 1)
{
SendValidationEvent(SR.Sch_MultipleAttrGroupSelfRef, attributeGroup);
}
}
private void CheckRefinedSimpleType(XmlSchemaSimpleType stype)
{
if (stype.Content != null && stype.Content is XmlSchemaSimpleTypeRestriction)
{
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)stype.Content;
if (restriction.BaseTypeName == stype.QualifiedName)
{
return;
}
}
SendValidationEvent(SR.Sch_InvalidTypeRedefine, stype);
}
private void CheckRefinedComplexType(XmlSchemaComplexType ctype)
{
if (ctype.ContentModel != null)
{
XmlQualifiedName baseName;
if (ctype.ContentModel is XmlSchemaComplexContent)
{
XmlSchemaComplexContent content = (XmlSchemaComplexContent)ctype.ContentModel;
if (content.Content is XmlSchemaComplexContentRestriction)
{
baseName = ((XmlSchemaComplexContentRestriction)content.Content).BaseTypeName;
}
else
{
baseName = ((XmlSchemaComplexContentExtension)content.Content).BaseTypeName;
}
}
else
{
XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)ctype.ContentModel;
if (content.Content is XmlSchemaSimpleContentRestriction)
{
baseName = ((XmlSchemaSimpleContentRestriction)content.Content).BaseTypeName;
}
else
{
baseName = ((XmlSchemaSimpleContentExtension)content.Content).BaseTypeName;
}
}
if (baseName == ctype.QualifiedName)
{
return;
}
}
SendValidationEvent(SR.Sch_InvalidTypeRedefine, ctype);
}
private void PreprocessAttribute(XmlSchemaAttribute attribute)
{
if (attribute.Name != null)
{
ValidateNameAttribute(attribute);
attribute.SetQualifiedName(new XmlQualifiedName(attribute.Name, _targetNamespace));
}
else
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "name", attribute);
}
if (attribute.Use != XmlSchemaUse.None)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "use", attribute);
}
if (attribute.Form != XmlSchemaForm.None)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "form", attribute);
}
PreprocessAttributeContent(attribute);
ValidateIdAttribute(attribute);
}
private void PreprocessLocalAttribute(XmlSchemaAttribute attribute)
{
if (attribute.Name != null)
{ // name
ValidateNameAttribute(attribute);
PreprocessAttributeContent(attribute);
attribute.SetQualifiedName(new XmlQualifiedName(attribute.Name, (attribute.Form == XmlSchemaForm.Qualified || (attribute.Form == XmlSchemaForm.None && _attributeFormDefault == XmlSchemaForm.Qualified)) ? _targetNamespace : null));
}
else
{ // ref
PreprocessAnnotation(attribute); //set parent of annotation child of ref
if (attribute.RefName.IsEmpty)
{
SendValidationEvent(SR.Sch_AttributeNameRef, "???", attribute);
}
else
{
ValidateQNameAttribute(attribute, "ref", attribute.RefName);
}
if (!attribute.SchemaTypeName.IsEmpty ||
attribute.SchemaType != null ||
attribute.Form != XmlSchemaForm.None /*||
attribute.DefaultValue != null ||
attribute.FixedValue != null*/
)
{
SendValidationEvent(SR.Sch_InvalidAttributeRef, attribute);
}
attribute.SetQualifiedName(attribute.RefName);
}
ValidateIdAttribute(attribute);
}
private void PreprocessAttributeContent(XmlSchemaAttribute attribute)
{
PreprocessAnnotation(attribute);
if (_schema.TargetNamespace == XmlReservedNs.NsXsi)
{
SendValidationEvent(SR.Sch_TargetNamespaceXsi, attribute);
}
if (!attribute.RefName.IsEmpty)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "ref", attribute);
}
if (attribute.DefaultValue != null && attribute.FixedValue != null)
{
SendValidationEvent(SR.Sch_DefaultFixedAttributes, attribute);
}
if (attribute.DefaultValue != null && attribute.Use != XmlSchemaUse.Optional && attribute.Use != XmlSchemaUse.None)
{
SendValidationEvent(SR.Sch_OptionalDefaultAttribute, attribute);
}
if (attribute.Name == _xmlns)
{
SendValidationEvent(SR.Sch_XmlNsAttribute, attribute);
}
if (attribute.SchemaType != null)
{
SetParent(attribute.SchemaType, attribute);
if (!attribute.SchemaTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_TypeMutualExclusive, attribute);
}
PreprocessSimpleType(attribute.SchemaType, true);
}
if (!attribute.SchemaTypeName.IsEmpty)
{
ValidateQNameAttribute(attribute, "type", attribute.SchemaTypeName);
}
}
private void PreprocessAttributeGroup(XmlSchemaAttributeGroup attributeGroup)
{
if (attributeGroup.Name != null)
{
ValidateNameAttribute(attributeGroup);
attributeGroup.SetQualifiedName(new XmlQualifiedName(attributeGroup.Name, _targetNamespace));
}
else
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "name", attributeGroup);
}
PreprocessAttributes(attributeGroup.Attributes, attributeGroup.AnyAttribute, attributeGroup);
PreprocessAnnotation(attributeGroup);
ValidateIdAttribute(attributeGroup);
}
private void PreprocessElement(XmlSchemaElement element)
{
if (element.Name != null)
{
ValidateNameAttribute(element);
element.SetQualifiedName(new XmlQualifiedName(element.Name, _targetNamespace));
}
else
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "name", element);
}
PreprocessElementContent(element);
if (element.Final == XmlSchemaDerivationMethod.All)
{
element.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else if (element.Final == XmlSchemaDerivationMethod.None)
{
if (_finalDefault == XmlSchemaDerivationMethod.All)
{
element.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else
{
element.SetFinalResolved(_finalDefault & elementFinalAllowed);
}
}
else
{
if ((element.Final & ~elementFinalAllowed) != 0)
{
SendValidationEvent(SR.Sch_InvalidElementFinalValue, element);
}
element.SetFinalResolved(element.Final & elementFinalAllowed);
}
if (element.Form != XmlSchemaForm.None)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "form", element);
}
if (element.MinOccursString != null)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "minOccurs", element);
}
if (element.MaxOccursString != null)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "maxOccurs", element);
}
if (!element.SubstitutionGroup.IsEmpty)
{
ValidateQNameAttribute(element, "type", element.SubstitutionGroup);
}
ValidateIdAttribute(element);
}
private void PreprocessLocalElement(XmlSchemaElement element)
{
if (element.Name != null)
{ // name
ValidateNameAttribute(element);
PreprocessElementContent(element);
element.SetQualifiedName(new XmlQualifiedName(element.Name, (element.Form == XmlSchemaForm.Qualified || (element.Form == XmlSchemaForm.None && _elementFormDefault == XmlSchemaForm.Qualified)) ? _targetNamespace : null));
}
else
{ // ref
PreprocessAnnotation(element); //Check annotation child for ref and set parent
if (element.RefName.IsEmpty)
{
SendValidationEvent(SR.Sch_ElementNameRef, element);
}
else
{
ValidateQNameAttribute(element, "ref", element.RefName);
}
if (!element.SchemaTypeName.IsEmpty ||
element.IsAbstract ||
element.Block != XmlSchemaDerivationMethod.None ||
element.SchemaType != null ||
element.HasConstraints ||
element.DefaultValue != null ||
element.Form != XmlSchemaForm.None ||
element.FixedValue != null ||
element.HasNillableAttribute)
{
SendValidationEvent(SR.Sch_InvalidElementRef, element);
}
if (element.DefaultValue != null && element.FixedValue != null)
{
SendValidationEvent(SR.Sch_DefaultFixedAttributes, element);
}
element.SetQualifiedName(element.RefName);
}
if (element.MinOccurs > element.MaxOccurs)
{
element.MinOccurs = decimal.Zero;
SendValidationEvent(SR.Sch_MinGtMax, element);
}
if (element.IsAbstract)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "abstract", element);
}
if (element.Final != XmlSchemaDerivationMethod.None)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "final", element);
}
if (!element.SubstitutionGroup.IsEmpty)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "substitutionGroup", element);
}
ValidateIdAttribute(element);
}
private void PreprocessElementContent(XmlSchemaElement element)
{
PreprocessAnnotation(element); //Set parent for Annotation child of element
if (!element.RefName.IsEmpty)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "ref", element);
}
if (element.Block == XmlSchemaDerivationMethod.All)
{
element.SetBlockResolved(XmlSchemaDerivationMethod.All);
}
else if (element.Block == XmlSchemaDerivationMethod.None)
{
if (_blockDefault == XmlSchemaDerivationMethod.All)
{
element.SetBlockResolved(XmlSchemaDerivationMethod.All);
}
else
{
element.SetBlockResolved(_blockDefault & elementBlockAllowed);
}
}
else
{
if ((element.Block & ~elementBlockAllowed) != 0)
{
SendValidationEvent(SR.Sch_InvalidElementBlockValue, element);
}
element.SetBlockResolved(element.Block & elementBlockAllowed);
}
if (element.SchemaType != null)
{
SetParent(element.SchemaType, element); //Set parent for simple / complex type child of element
if (!element.SchemaTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_TypeMutualExclusive, element);
}
if (element.SchemaType is XmlSchemaComplexType)
{
PreprocessComplexType((XmlSchemaComplexType)element.SchemaType, true);
}
else
{
PreprocessSimpleType((XmlSchemaSimpleType)element.SchemaType, true);
}
}
if (!element.SchemaTypeName.IsEmpty)
{
ValidateQNameAttribute(element, "type", element.SchemaTypeName);
}
if (element.DefaultValue != null && element.FixedValue != null)
{
SendValidationEvent(SR.Sch_DefaultFixedAttributes, element);
}
for (int i = 0; i < element.Constraints.Count; ++i)
{
SetParent(element.Constraints[i], element);
PreprocessIdentityConstraint((XmlSchemaIdentityConstraint)element.Constraints[i]);
}
}
private void PreprocessIdentityConstraint(XmlSchemaIdentityConstraint constraint)
{
bool valid = true;
PreprocessAnnotation(constraint); //Set parent of annotation child of key/keyref/unique
if (constraint.Name != null)
{
ValidateNameAttribute(constraint);
constraint.SetQualifiedName(new XmlQualifiedName(constraint.Name, _targetNamespace));
}
else
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "name", constraint);
valid = false;
}
if (_schema.IdentityConstraints[constraint.QualifiedName] != null)
{
SendValidationEvent(SR.Sch_DupIdentityConstraint, constraint.QualifiedName.ToString(), constraint);
valid = false;
}
else
{
_schema.IdentityConstraints.Add(constraint.QualifiedName, constraint);
}
if (constraint.Selector == null)
{
SendValidationEvent(SR.Sch_IdConstraintNoSelector, constraint);
valid = false;
}
if (constraint.Fields.Count == 0)
{
SendValidationEvent(SR.Sch_IdConstraintNoFields, constraint);
valid = false;
}
if (constraint is XmlSchemaKeyref)
{
XmlSchemaKeyref keyref = (XmlSchemaKeyref)constraint;
if (keyref.Refer.IsEmpty)
{
SendValidationEvent(SR.Sch_IdConstraintNoRefer, constraint);
valid = false;
}
else
{
ValidateQNameAttribute(keyref, "refer", keyref.Refer);
}
}
if (valid)
{
ValidateIdAttribute(constraint);
ValidateIdAttribute(constraint.Selector);
SetParent(constraint.Selector, constraint);
for (int i = 0; i < constraint.Fields.Count; ++i)
{
SetParent(constraint.Fields[i], constraint);
ValidateIdAttribute(constraint.Fields[i]);
}
}
}
private void PreprocessSimpleType(XmlSchemaSimpleType simpleType, bool local)
{
if (local)
{
if (simpleType.Name != null)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "name", simpleType);
}
}
else
{
if (simpleType.Name != null)
{
ValidateNameAttribute(simpleType);
simpleType.SetQualifiedName(new XmlQualifiedName(simpleType.Name, _targetNamespace));
}
else
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "name", simpleType);
}
if (simpleType.Final == XmlSchemaDerivationMethod.All)
{
simpleType.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else if (simpleType.Final == XmlSchemaDerivationMethod.None)
{
if (_finalDefault == XmlSchemaDerivationMethod.All)
{
simpleType.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else
{
simpleType.SetFinalResolved(_finalDefault & simpleTypeFinalAllowed);
}
}
else
{
if ((simpleType.Final & ~simpleTypeFinalAllowed) != 0)
{
SendValidationEvent(SR.Sch_InvalidSimpleTypeFinalValue, simpleType);
}
simpleType.SetFinalResolved(simpleType.Final & simpleTypeFinalAllowed);
}
}
if (simpleType.Content == null)
{
SendValidationEvent(SR.Sch_NoSimpleTypeContent, simpleType);
}
else if (simpleType.Content is XmlSchemaSimpleTypeRestriction)
{
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)simpleType.Content;
//SetParent
SetParent(restriction, simpleType);
for (int i = 0; i < restriction.Facets.Count; ++i)
{
SetParent(restriction.Facets[i], restriction);
}
if (restriction.BaseType != null)
{
if (!restriction.BaseTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_SimpleTypeRestRefBase, restriction);
}
PreprocessSimpleType(restriction.BaseType, true);
}
else
{
if (restriction.BaseTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_SimpleTypeRestRefBaseNone, restriction);
}
else
{
ValidateQNameAttribute(restriction, "base", restriction.BaseTypeName);
}
}
PreprocessAnnotation(restriction); //set parent of annotation child of simple type restriction
ValidateIdAttribute(restriction);
}
else if (simpleType.Content is XmlSchemaSimpleTypeList)
{
XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)simpleType.Content;
SetParent(list, simpleType);
if (list.ItemType != null)
{
if (!list.ItemTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_SimpleTypeListRefBase, list);
}
SetParent(list.ItemType, list);
PreprocessSimpleType(list.ItemType, true);
}
else
{
if (list.ItemTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_SimpleTypeListRefBaseNone, list);
}
else
{
ValidateQNameAttribute(list, "itemType", list.ItemTypeName);
}
}
PreprocessAnnotation(list); //set parent of annotation child of simple type list
ValidateIdAttribute(list);
}
else
{ // union
XmlSchemaSimpleTypeUnion union1 = (XmlSchemaSimpleTypeUnion)simpleType.Content;
SetParent(union1, simpleType);
int baseTypeCount = union1.BaseTypes.Count;
if (union1.MemberTypes != null)
{
baseTypeCount += union1.MemberTypes.Length;
for (int i = 0; i < union1.MemberTypes.Length; ++i)
{
ValidateQNameAttribute(union1, "memberTypes", union1.MemberTypes[i]);
}
}
if (baseTypeCount == 0)
{
SendValidationEvent(SR.Sch_SimpleTypeUnionNoBase, union1);
}
for (int i = 0; i < union1.BaseTypes.Count; ++i)
{
SetParent(union1.BaseTypes[i], union1);
PreprocessSimpleType((XmlSchemaSimpleType)union1.BaseTypes[i], true);
}
PreprocessAnnotation(union1); //set parent of annotation child of simple type union
ValidateIdAttribute(union1);
}
ValidateIdAttribute(simpleType);
}
private void PreprocessComplexType(XmlSchemaComplexType complexType, bool local)
{
if (local)
{
if (complexType.Name != null)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "name", complexType);
}
}
else
{
if (complexType.Name != null)
{
ValidateNameAttribute(complexType);
complexType.SetQualifiedName(new XmlQualifiedName(complexType.Name, _targetNamespace));
}
else
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "name", complexType);
}
if (complexType.Block == XmlSchemaDerivationMethod.All)
{
complexType.SetBlockResolved(XmlSchemaDerivationMethod.All);
}
else if (complexType.Block == XmlSchemaDerivationMethod.None)
{
complexType.SetBlockResolved(_blockDefault & complexTypeBlockAllowed);
}
else
{
if ((complexType.Block & ~complexTypeBlockAllowed) != 0)
{
SendValidationEvent(SR.Sch_InvalidComplexTypeBlockValue, complexType);
}
complexType.SetBlockResolved(complexType.Block & complexTypeBlockAllowed);
}
if (complexType.Final == XmlSchemaDerivationMethod.All)
{
complexType.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else if (complexType.Final == XmlSchemaDerivationMethod.None)
{
if (_finalDefault == XmlSchemaDerivationMethod.All)
{
complexType.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else
{
complexType.SetFinalResolved(_finalDefault & complexTypeFinalAllowed);
}
}
else
{
if ((complexType.Final & ~complexTypeFinalAllowed) != 0)
{
SendValidationEvent(SR.Sch_InvalidComplexTypeFinalValue, complexType);
}
complexType.SetFinalResolved(complexType.Final & complexTypeFinalAllowed);
}
}
if (complexType.ContentModel != null)
{
SetParent(complexType.ContentModel, complexType); //SimpleContent / complexCotent
PreprocessAnnotation(complexType.ContentModel);
if (complexType.Particle != null || complexType.Attributes != null)
{
// this is illigal
}
if (complexType.ContentModel is XmlSchemaSimpleContent)
{
XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)complexType.ContentModel;
if (content.Content == null)
{
if (complexType.QualifiedName == XmlQualifiedName.Empty)
{
SendValidationEvent(SR.Sch_NoRestOrExt, complexType);
}
else
{
SendValidationEvent(SR.Sch_NoRestOrExtQName, complexType.QualifiedName.Name, complexType.QualifiedName.Namespace, complexType);
}
}
else
{
SetParent(content.Content, content); //simplecontent extension / restriction
PreprocessAnnotation(content.Content); //annotation child of simple extension / restriction
if (content.Content is XmlSchemaSimpleContentExtension)
{
XmlSchemaSimpleContentExtension contentExtension = (XmlSchemaSimpleContentExtension)content.Content;
if (contentExtension.BaseTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_MissAttribute, "base", contentExtension);
}
else
{
ValidateQNameAttribute(contentExtension, "base", contentExtension.BaseTypeName);
}
PreprocessAttributes(contentExtension.Attributes, contentExtension.AnyAttribute, contentExtension);
ValidateIdAttribute(contentExtension);
}
else
{ //XmlSchemaSimpleContentRestriction
XmlSchemaSimpleContentRestriction contentRestriction = (XmlSchemaSimpleContentRestriction)content.Content;
if (contentRestriction.BaseTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_MissAttribute, "base", contentRestriction);
}
else
{
ValidateQNameAttribute(contentRestriction, "base", contentRestriction.BaseTypeName);
}
if (contentRestriction.BaseType != null)
{
SetParent(contentRestriction.BaseType, contentRestriction);
PreprocessSimpleType(contentRestriction.BaseType, true);
}
PreprocessAttributes(contentRestriction.Attributes, contentRestriction.AnyAttribute, contentRestriction);
ValidateIdAttribute(contentRestriction);
}
}
ValidateIdAttribute(content);
}
else
{ // XmlSchemaComplexContent
XmlSchemaComplexContent content = (XmlSchemaComplexContent)complexType.ContentModel;
if (content.Content == null)
{
if (complexType.QualifiedName == XmlQualifiedName.Empty)
{
SendValidationEvent(SR.Sch_NoRestOrExt, complexType);
}
else
{
SendValidationEvent(SR.Sch_NoRestOrExtQName, complexType.QualifiedName.Name, complexType.QualifiedName.Namespace, complexType);
}
}
else
{
if (!content.HasMixedAttribute && complexType.IsMixed)
{
content.IsMixed = true; // fixup
}
SetParent(content.Content, content); //complexcontent extension / restriction
PreprocessAnnotation(content.Content); //Annotation child of extension / restriction
if (content.Content is XmlSchemaComplexContentExtension)
{
XmlSchemaComplexContentExtension contentExtension = (XmlSchemaComplexContentExtension)content.Content;
if (contentExtension.BaseTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_MissAttribute, "base", contentExtension);
}
else
{
ValidateQNameAttribute(contentExtension, "base", contentExtension.BaseTypeName);
}
if (contentExtension.Particle != null)
{
SetParent(contentExtension.Particle, contentExtension); //Group / all / choice / sequence
PreprocessParticle(contentExtension.Particle);
}
PreprocessAttributes(contentExtension.Attributes, contentExtension.AnyAttribute, contentExtension);
ValidateIdAttribute(contentExtension);
}
else
{ // XmlSchemaComplexContentRestriction
XmlSchemaComplexContentRestriction contentRestriction = (XmlSchemaComplexContentRestriction)content.Content;
if (contentRestriction.BaseTypeName.IsEmpty)
{
SendValidationEvent(SR.Sch_MissAttribute, "base", contentRestriction);
}
else
{
ValidateQNameAttribute(contentRestriction, "base", contentRestriction.BaseTypeName);
}
if (contentRestriction.Particle != null)
{
SetParent(contentRestriction.Particle, contentRestriction); //Group / all / choice / sequence
PreprocessParticle(contentRestriction.Particle);
}
PreprocessAttributes(contentRestriction.Attributes, contentRestriction.AnyAttribute, contentRestriction);
ValidateIdAttribute(contentRestriction);
}
ValidateIdAttribute(content);
}
}
}
else
{
if (complexType.Particle != null)
{
SetParent(complexType.Particle, complexType);
PreprocessParticle(complexType.Particle);
}
PreprocessAttributes(complexType.Attributes, complexType.AnyAttribute, complexType);
}
ValidateIdAttribute(complexType);
}
private void PreprocessGroup(XmlSchemaGroup group)
{
if (group.Name != null)
{
ValidateNameAttribute(group);
group.SetQualifiedName(new XmlQualifiedName(group.Name, _targetNamespace));
}
else
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "name", group);
}
if (group.Particle == null)
{
SendValidationEvent(SR.Sch_NoGroupParticle, group);
return;
}
if (group.Particle.MinOccursString != null)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "minOccurs", group.Particle);
}
if (group.Particle.MaxOccursString != null)
{
SendValidationEvent(SR.Sch_ForbiddenAttribute, "maxOccurs", group.Particle);
}
PreprocessParticle(group.Particle);
PreprocessAnnotation(group); //Set parent of annotation child of group
ValidateIdAttribute(group);
}
private void PreprocessNotation(XmlSchemaNotation notation)
{
if (notation.Name != null)
{
ValidateNameAttribute(notation);
notation.QualifiedName = new XmlQualifiedName(notation.Name, _targetNamespace);
}
else
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "name", notation);
}
if (notation.Public != null)
{
try
{
XmlConvert.ToUri(notation.Public); // can throw
}
catch
{
SendValidationEvent(SR.Sch_InvalidPublicAttribute, notation.Public, notation);
}
}
else
{
SendValidationEvent(SR.Sch_MissRequiredAttribute, "public", notation);
}
if (notation.System != null)
{
try
{
XmlConvert.ToUri(notation.System); // can throw
}
catch
{
SendValidationEvent(SR.Sch_InvalidSystemAttribute, notation.System, notation);
}
}
PreprocessAnnotation(notation); //Set parent of annotation child of notation
ValidateIdAttribute(notation);
}
private void PreprocessParticle(XmlSchemaParticle particle)
{
XmlSchemaAll schemaAll = particle as XmlSchemaAll;
if (schemaAll != null)
{
if (particle.MinOccurs != decimal.Zero && particle.MinOccurs != decimal.One)
{
particle.MinOccurs = decimal.One;
SendValidationEvent(SR.Sch_InvalidAllMin, particle);
}
if (particle.MaxOccurs != decimal.One)
{
particle.MaxOccurs = decimal.One;
SendValidationEvent(SR.Sch_InvalidAllMax, particle);
}
for (int i = 0; i < schemaAll.Items.Count; ++i)
{
XmlSchemaElement element = (XmlSchemaElement)schemaAll.Items[i];
if (element.MaxOccurs != decimal.Zero && element.MaxOccurs != decimal.One)
{
element.MaxOccurs = decimal.One;
SendValidationEvent(SR.Sch_InvalidAllElementMax, element);
}
SetParent(element, particle);
PreprocessLocalElement(element);
}
}
else
{
if (particle.MinOccurs > particle.MaxOccurs)
{
particle.MinOccurs = particle.MaxOccurs;
SendValidationEvent(SR.Sch_MinGtMax, particle);
}
XmlSchemaChoice choice = particle as XmlSchemaChoice;
if (choice != null)
{
XmlSchemaObjectCollection choices = choice.Items;
for (int i = 0; i < choices.Count; ++i)
{
SetParent(choices[i], particle);
XmlSchemaElement element = choices[i] as XmlSchemaElement;
if (element != null)
{
PreprocessLocalElement(element);
}
else
{
PreprocessParticle((XmlSchemaParticle)choices[i]);
}
}
}
else if (particle is XmlSchemaSequence)
{
XmlSchemaObjectCollection sequences = ((XmlSchemaSequence)particle).Items;
for (int i = 0; i < sequences.Count; ++i)
{
SetParent(sequences[i], particle);
XmlSchemaElement element = sequences[i] as XmlSchemaElement;
if (element != null)
{
PreprocessLocalElement(element);
}
else
{
PreprocessParticle((XmlSchemaParticle)sequences[i]);
}
}
}
else if (particle is XmlSchemaGroupRef)
{
XmlSchemaGroupRef groupRef = (XmlSchemaGroupRef)particle;
if (groupRef.RefName.IsEmpty)
{
SendValidationEvent(SR.Sch_MissAttribute, "ref", groupRef);
}
else
{
ValidateQNameAttribute(groupRef, "ref", groupRef.RefName);
}
}
else if (particle is XmlSchemaAny)
{
try
{
((XmlSchemaAny)particle).BuildNamespaceListV1Compat(_targetNamespace);
}
catch
{
SendValidationEvent(SR.Sch_InvalidAny, particle);
}
}
}
PreprocessAnnotation(particle); //set parent of annotation child of group / all/ choice / sequence
ValidateIdAttribute(particle);
}
private void PreprocessAttributes(XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute anyAttribute, XmlSchemaObject parent)
{
for (int i = 0; i < attributes.Count; ++i)
{
SetParent(attributes[i], parent);
XmlSchemaAttribute attribute = attributes[i] as XmlSchemaAttribute;
if (attribute != null)
{
PreprocessLocalAttribute(attribute);
}
else
{ // XmlSchemaAttributeGroupRef
XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)attributes[i];
if (attributeGroupRef.RefName.IsEmpty)
{
SendValidationEvent(SR.Sch_MissAttribute, "ref", attributeGroupRef);
}
else
{
ValidateQNameAttribute(attributeGroupRef, "ref", attributeGroupRef.RefName);
}
PreprocessAnnotation(attributes[i]); //set parent of annotation child of attributeGroupRef
ValidateIdAttribute(attributes[i]);
}
}
if (anyAttribute != null)
{
try
{
SetParent(anyAttribute, parent);
PreprocessAnnotation(anyAttribute); //set parent of annotation child of any attribute
anyAttribute.BuildNamespaceListV1Compat(_targetNamespace);
}
catch
{
SendValidationEvent(SR.Sch_InvalidAnyAttribute, anyAttribute);
}
ValidateIdAttribute(anyAttribute);
}
}
private void ValidateIdAttribute(XmlSchemaObject xso)
{
if (xso.IdAttribute != null)
{
try
{
xso.IdAttribute = NameTable.Add(XmlConvert.VerifyNCName(xso.IdAttribute));
if (_schema.Ids[xso.IdAttribute] != null)
{
SendValidationEvent(SR.Sch_DupIdAttribute, xso);
}
else
{
_schema.Ids.Add(xso.IdAttribute, xso);
}
}
catch (Exception ex)
{
SendValidationEvent(SR.Sch_InvalidIdAttribute, ex.Message, xso);
}
}
}
private void ValidateNameAttribute(XmlSchemaObject xso)
{
string name = xso.NameAttribute;
if (name == null || name.Length == 0)
{
SendValidationEvent(SR.Sch_InvalidNameAttributeEx, null, SR.Sch_NullValue, xso);
}
//Normalize whitespace since NCName has whitespace facet="collapse"
name = XmlComplianceUtil.NonCDataNormalize(name);
int len = ValidateNames.ParseNCName(name, 0);
if (len != name.Length)
{ // If the string is not a valid NCName, then throw or return false
string[] invCharArgs = XmlException.BuildCharExceptionArgs(name, len);
string innerStr = SR.Format(SR.Xml_BadNameCharWithPos, invCharArgs[0], invCharArgs[1], len);
SendValidationEvent(SR.Sch_InvalidNameAttributeEx, name, innerStr, xso);
}
else
{
xso.NameAttribute = NameTable.Add(name);
}
}
private void ValidateQNameAttribute(XmlSchemaObject xso, string attributeName, XmlQualifiedName value)
{
try
{
value.Verify();
value.Atomize(NameTable);
if (_referenceNamespaces[value.Namespace] == null)
{
SendValidationEvent(SR.Sch_UnrefNS, value.Namespace, xso, XmlSeverityType.Warning);
}
}
catch (Exception ex)
{
SendValidationEvent(SR.Sch_InvalidAttribute, attributeName, ex.Message, xso);
}
}
private void SetParent(XmlSchemaObject child, XmlSchemaObject parent)
{
child.Parent = parent;
}
private void PreprocessAnnotation(XmlSchemaObject schemaObject)
{
XmlSchemaAnnotated annotated = schemaObject as XmlSchemaAnnotated;
if (annotated != null)
{
if (annotated.Annotation != null)
{
annotated.Annotation.Parent = schemaObject;
for (int i = 0; i < annotated.Annotation.Items.Count; ++i)
{
annotated.Annotation.Items[i].Parent = annotated.Annotation; //Can be documentation or appInfo
}
}
}
}
private Uri ResolveSchemaLocationUri(XmlSchema enclosingSchema, string location)
{
try
{
return _xmlResolver.ResolveUri(enclosingSchema.BaseUri, location);
}
catch
{
return null;
}
}
private Stream GetSchemaEntity(Uri ruri)
{
try
{
return (Stream)_xmlResolver.GetEntity(ruri, null, null);
}
catch
{
return null;
}
}
};
#pragma warning restore 618
} // namespace System.Xml
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace DocSharp.Generators
{
public enum HTMLTag
{
HTML,
Head,
Body,
Title,
Meta,
Script,
Link,
Div,
Section,
Ul,
Ol,
Li,
A,
P,
H1,
H2,
H3,
H4,
H5,
H6,
Hr,
Table,
Td,
Tr,
Span,
Br,
Th
}
public class HTMLTextGenerator : TextGenerator
{
public Stack<HTMLTag> Tags;
public string LinkHrefPrefix;
public HTMLTextGenerator()
{
Tags = new Stack<HTMLTag>();
LinkHrefPrefix = string.Empty;
}
public void Doctype()
{
WriteLine("<!DOCTYPE html>");
}
public void Comment(string text)
{
WriteLine("<!-- {0} -->", text);
}
static string GetAttributesString(params object[] attributes)
{
if (attributes == null)
return string.Empty;
var keyValues = new List<string>();
foreach (var attr in attributes)
{
foreach (var prop in attr.GetType().GetProperties())
{
var name = prop.Name.Replace('_', '-');
var value = prop.GetValue(attr);
keyValues.Add(string.Format("{0}='{1}'", name, value));
}
}
var attrs = string.Join(" ", keyValues);
if (keyValues.Count > 0)
attrs = " " + attrs;
return attrs;
}
public void Paragraph(string text)
{
if (text == null)
text = string.Empty;
Content(HTMLTag.P, text);
}
public void Paragraph(string text, params object[] args)
{
if (text == null)
text = string.Empty;
Content(HTMLTag.P, string.Format(text, args));
}
public void Content(HTMLTag tag, string content, params object[] attributes)
{
Write("<{0}{1}>", tag.ToString().ToLowerInvariant(),
GetAttributesString(attributes));
Write(content);
CloseTag(tag);
}
public void Link(string _href, params object[] attributes)
{
var href = Path.Combine(LinkHrefPrefix, _href);
var attrs = new object[] { new { href } }.Concat(attributes)
.ToArray();
InlineTag(HTMLTag.Link, attrs);
NewLine();
}
public void Script(string src, params object[] attributes)
{
var attrs = new object[] { new { src } }.Concat(attributes)
.ToArray();
InlineTag(HTMLTag.Script, attrs);
CloseTag(HTMLTag.Script);
}
public void Javascript(string src)
{
Script(src, new { type = "text/javascript" });
}
public void Anchor(string href, params object[] attributes)
{
var attrs = new object[] { new { href } }.Concat(attributes)
.ToArray();
InlineTag(HTMLTag.A, attrs);
}
public void GlyphIcon(string name)
{
var classes = string.Format("glyphicon glyphicon-{0}", name);
InlineTag(HTMLTag.Span, new { @class = classes });
CloseTag(HTMLTag.Span);
}
public void Heading(string text, int level = 2)
{
var heading = (int) HTMLTag.H1 + level - 1;
Content((HTMLTag) heading, text);
}
public void HorizontalRule()
{
Content(HTMLTag.Hr, "");
}
public void LineBreak()
{
Content(HTMLTag.Br, "");
}
public void Div(params object[] attributes)
{
TagIndent(HTMLTag.Div, attributes);
}
public void Section(params object[] attributes)
{
TagIndent(HTMLTag.Section, attributes);
}
#region Generic tags
public void Tag(HTMLTag tag, params object[] attributes)
{
InlineTag(tag, attributes);
Tags.Push(tag);
}
public void TagIndent(HTMLTag tag, params object[] attributes)
{
Tag(tag, attributes);
NewLine();
PushIndent();
}
public void InlineTag(HTMLTag tag, params object[] attributes)
{
Write("<{0}{1}>", tag.ToString().ToLowerInvariant(),
GetAttributesString(attributes));
}
public void CloseTag()
{
var tag = Tags.Pop();
CloseTag(tag);
}
public void CloseInlineTag(HTMLTag tag)
{
Write("</{0}>", tag.ToString().ToLowerInvariant());
}
public void CloseTag(HTMLTag tag)
{
WriteLine("</{0}>", tag.ToString().ToLowerInvariant());
}
public void CloseTagIndent()
{
PopIndent();
CloseTag();
}
public void CloseTagIndent(HTMLTag tag)
{
PopIndent();
CloseTag(tag);
}
#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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Thread tracks managed thread IDs, recycling them when threads die to keep the set of
// live IDs compact.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using Internal.Runtime.Augments;
using System.Diagnostics;
namespace System.Threading
{
internal class ManagedThreadId
{
//
// Binary tree used to keep track of active thread ids. Each node of the tree keeps track of 32 consecutive ids.
// Implemented as immutable collection to avoid locks. Each modification creates a new top level node.
//
private class ImmutableIdDispenser
{
private readonly ImmutableIdDispenser _left; // Child nodes
private readonly ImmutableIdDispenser _right;
private readonly int _used; // Number of ids tracked by this node and all its childs
private readonly int _size; // Maximum number of ids that can be tracked by this node and all its childs
private readonly uint _bitmap; // Bitmap of ids tracked by this node
private const int BitsPerNode = 32;
private ImmutableIdDispenser(ImmutableIdDispenser left, ImmutableIdDispenser right, int used, int size, uint bitmap)
{
_left = left;
_right = right;
_used = used;
_size = size;
_bitmap = bitmap;
CheckInvariants();
}
[Conditional("DEBUG")]
private void CheckInvariants()
{
int actualUsed = 0;
uint countBits = _bitmap;
while (countBits != 0)
{
actualUsed += (int)(countBits & 1);
countBits >>= 1;
}
if (_left != null)
{
Debug.Assert(_left._size == ChildSize);
actualUsed += _left._used;
}
if (_right != null)
{
Debug.Assert(_right._size == ChildSize);
actualUsed += _right._used;
}
Debug.Assert(actualUsed == _used);
Debug.Assert(_used <= _size);
}
private int ChildSize
{
get
{
Debug.Assert((_size / 2) >= (BitsPerNode / 2));
return (_size / 2) - (BitsPerNode / 2);
}
}
public static ImmutableIdDispenser Empty
{
get
{
// The empty dispenser has the id=0 allocated, so it is not really empty.
// It saves us from dealing with the corner case of true empty dispenser,
// and it ensures that IdNone will not be ever given out.
return new ImmutableIdDispenser(null, null, 1, BitsPerNode, 1);
}
}
public ImmutableIdDispenser AllocateId(out int id)
{
if (_used == _size)
{
id = _size;
return new ImmutableIdDispenser(this, null, _size + 1, checked(2 * _size + BitsPerNode), 1);
}
var bitmap = _bitmap;
var left = _left;
var right = _right;
// Any free bits in current node?
if (bitmap != UInt32.MaxValue)
{
int bit = 0;
while ((bitmap & (uint)(1 << bit)) != 0)
bit++;
bitmap |= (uint)(1 << bit);
id = ChildSize + bit;
}
else
{
Debug.Assert(ChildSize > 0);
if (left == null)
{
left = new ImmutableIdDispenser(null, null, 1, ChildSize, 1);
id = left.ChildSize;
}
else
if (right == null)
{
right = new ImmutableIdDispenser(null, null, 1, ChildSize, 1);
id = ChildSize + BitsPerNode + right.ChildSize;
}
else
{
if (left._used < right._used)
{
Debug.Assert(left._used < left._size);
left = left.AllocateId(out id);
}
else
{
Debug.Assert(right._used < right._size);
right = right.AllocateId(out id);
id += (ChildSize + BitsPerNode);
}
}
}
return new ImmutableIdDispenser(left, right, _used + 1, _size, bitmap);
}
public ImmutableIdDispenser RecycleId(int id)
{
Debug.Assert(id < _size);
if (_used == 1)
return null;
var bitmap = _bitmap;
var left = _left;
var right = _right;
int childSize = ChildSize;
if (id < childSize)
{
left = left.RecycleId(id);
}
else
{
id -= childSize;
if (id < BitsPerNode)
{
Debug.Assert((bitmap & (uint)(1 << id)) != 0);
bitmap &= ~(uint)(1 << id);
}
else
{
right = right.RecycleId(id - BitsPerNode);
}
}
return new ImmutableIdDispenser(left, right, _used - 1, _size, bitmap);
}
}
public const int IdNone = 0;
// The main thread takes the first available id, which is 1. This id will not be recycled until the process exit.
// We use this id to detect the main thread and report it as a foreground one.
public const int IdMainThread = 1;
// We store ManagedThreadId both here and in the Thread.CurrentThread object. We store it here,
// because we may need the id very early in the process lifetime (e.g., in ClassConstructorRunner),
// when a Thread object cannot be created yet. We also store it in the Thread.CurrentThread object,
// because that object may have longer lifetime than the OS thread.
[ThreadStatic]
private static ManagedThreadId t_currentThreadId;
[ThreadStatic]
private static int t_currentManagedThreadId;
// We have to avoid the static constructors on the ManagedThreadId class, otherwise we can run into stack overflow as first time Current property get called,
// the runtime will ensure running the static constructor and this process will call the Current property again (when taking any lock)
// System::Environment.get_CurrentManagedThreadId
// System::Threading::Lock.Acquire
// System::Runtime::CompilerServices::ClassConstructorRunner::Cctor.GetCctor
// System::Runtime::CompilerServices::ClassConstructorRunner.EnsureClassConstructorRun
// System::Threading::ManagedThreadId.get_Current
// System::Environment.get_CurrentManagedThreadId
private static ImmutableIdDispenser s_idDispenser;
private int _managedThreadId;
public int Id => _managedThreadId;
public static int AllocateId()
{
if (s_idDispenser == null)
Interlocked.CompareExchange(ref s_idDispenser, ImmutableIdDispenser.Empty, null);
int id;
var priorIdDispenser = Volatile.Read(ref s_idDispenser);
for (;;)
{
var updatedIdDispenser = priorIdDispenser.AllocateId(out id);
var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser);
if (Object.ReferenceEquals(priorIdDispenser, interlockedResult))
break;
priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
Debug.Assert(id != IdNone);
return id;
}
public static void RecycleId(int id)
{
if (id == IdNone)
{
return;
}
var priorIdDispenser = Volatile.Read(ref s_idDispenser);
for (;;)
{
var updatedIdDispenser = s_idDispenser.RecycleId(id);
var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser);
if (Object.ReferenceEquals(priorIdDispenser, interlockedResult))
break;
priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop
}
}
public static int Current
{
get
{
int currentManagedThreadId = t_currentManagedThreadId;
if (currentManagedThreadId == IdNone)
return MakeForCurrentThread();
else
return currentManagedThreadId;
}
}
public static ManagedThreadId GetCurrentThreadId()
{
if (t_currentManagedThreadId == IdNone)
MakeForCurrentThread();
return t_currentThreadId;
}
private static int MakeForCurrentThread()
{
return SetForCurrentThread(new ManagedThreadId());
}
public static int SetForCurrentThread(ManagedThreadId threadId)
{
t_currentThreadId = threadId;
t_currentManagedThreadId = threadId.Id;
return threadId.Id;
}
public ManagedThreadId()
{
_managedThreadId = AllocateId();
}
~ManagedThreadId()
{
RecycleId(_managedThreadId);
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Xml;
using System.Text;
using System.Globalization;
using System.Diagnostics;
using Google.GData.Client;
namespace Google.GData.Photos {
//////////////////////////////////////////////////////////////////////
/// <summary>
/// A subclass of FeedQuery, to create an PicasaQuery query URI.
/// Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
/// The PicasaQuery supports the following GData parameters:
/// start-index and max-results parameters. It does not currently support the other standard parameters.
/// in addition, the following parameters:
/// Parameter Meaning
/// kind what feed to retrieve
/// access Visibility parameter
/// thumbsize Thumbnail size parameter
/// </summary>
//////////////////////////////////////////////////////////////////////
public class PicasaQuery : FeedQuery
{
/// <summary>
/// The kind parameter lets you request information about a particular kind
/// of item. The parameter value should be a comma-separated list of requested kinds.
/// If you omit the kind parameter, Picasa Web Albums chooses a default kind
/// depending on the level of feed you're requesting. For a user-based feed,
/// the default kind is album; for an album-based feed, the default kind is
/// photo; for a photo-based feed, the default kind is comment; for a community
/// search feed, the default kind is photo.
/// </summary>
public enum Kinds
{
/// <summary>
/// Feed includes some or all of the albums the specified
/// user has in their gallery. Which albums are returned
/// depends on the visibility value specified.
/// </summary>
album,
/// <summary>
/// Feed includes the photos in an album (album-based),
/// recent photos uploaded by a user (user-based) or
/// photos uploaded by all users (community search).
/// </summary>
photo,
/// <summary>
/// Feed includes the comments that have been made on a photo.
/// </summary>
comment,
/// <summary>
/// Includes all tags associated with the specified user, album,
/// or photo. For user-based and album-based feeds, the tags
/// include a weight value indicating how often they occurred.
/// </summary>
tag,
/// <summary>
/// using none implies the server default
/// </summary>
none
}
/// <summary>
/// describing the visibility level of picasa feeds
/// </summary>
public enum AccessLevel
{
/// <summary>
/// no parameter. Setting the accessLevel to undefined
/// implies the server default
/// </summary>
AccessUndefined,
/// <summary>
/// Shows both public and private data.
/// Requires authentication. Default for authenticated users.
/// </summary>
AccessAll,
/// <summary>
/// Shows only private data. Requires authentication.
/// </summary>
AccessPrivate,
/// <summary>
/// Shows only public data.
/// Does not require authentication. Default for unauthenticated users.
/// </summary>
AccessPublic,
}
/// <summary>
/// holds the kind parameters a query can have
/// </summary>
protected string kindsAsText = "";
/// <summary>
/// holds the tag parameters a query can have
/// </summary>
private string tags = "";
private AccessLevel access;
private string thumbsize;
/// <summary>
/// picasa base URI
/// </summary>
public static string picasaBaseUri = "https://picasaweb.google.com/data/feed/api/user/";
/// <summary>
/// picasa base URI for posting against the default album
/// </summary>
public static string picasaDefaultPostUri = "https://picasaweb.google.com/data/feed/api/user/default/albumid/default";
/// <summary>
/// base constructor
/// </summary>
public PicasaQuery()
: base()
{
this.kindsAsText = Kinds.tag.ToString();
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public PicasaQuery(string queryUri)
: base(queryUri)
{
this.kindsAsText = Kinds.tag.ToString();
}
/// <summary>
/// convienience method to create an URI based on a userID for a picasafeed
/// </summary>
/// <param name="userID"></param>
/// <returns>string</returns>
public static string CreatePicasaUri(string userID)
{
return PicasaQuery.picasaBaseUri + Utilities.UriEncodeUnsafe(userID);
}
/// <summary>
/// convienience method to create an URI based on a userID
/// and an album ID for a picasafeed
/// </summary>
/// <param name="userID"></param>
/// <param name="albumID"></param>
/// <returns>string</returns>
public static string CreatePicasaUri(string userID, string albumID)
{
return CreatePicasaUri(userID) +"/albumid/"+ Utilities.UriEncodeUnsafe(albumID);
}
/// <summary>
/// Convenience method to create a URI based on a user id, albumID, and photoid
/// </summary>
/// <param name="userID">The username that owns the content</param>
/// <param name="albumID"></param>
/// <param name="photoID">The ID of the photo that contains the content</param>
/// <returns>A URI to a Picasa Web Albums feed</returns>
public static string CreatePicasaUri(string userID, string albumID, string photoID)
{
return CreatePicasaUri(userID, albumID) + "/photoid/" + Utilities.UriEncodeUnsafe(photoID);
}
//////////////////////////////////////////////////////////////////////
/// <summary>comma separated list of kinds to retrieve</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public virtual string KindParameter
{
get {return this.kindsAsText;}
set {this.kindsAsText = value;}
}
// end of accessor public WebAlbumKinds
/// <summary>
/// comma separated list of the tags to search for in the feed.
/// </summary>
public string Tags
{
get { return this.tags; }
set { this.tags = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>indicates the access</summary>
//////////////////////////////////////////////////////////////////////
public AccessLevel Access
{
get {return this.access;}
set {this.access = value;}
}
// end of accessor public Access
//////////////////////////////////////////////////////////////////////
/// <summary>indicates the thumbsize required</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Thumbsize
{
get {return this.thumbsize;}
set {this.thumbsize = value;}
}
// end of accessor public Thumbsize
//////////////////////////////////////////////////////////////////////
/// <summary>protected void ParseUri</summary>
/// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param>
/// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns>
//////////////////////////////////////////////////////////////////////
protected override Uri ParseUri(Uri targetUri)
{
base.ParseUri(targetUri);
if (targetUri != null)
{
char[] deli = { '?', '&' };
string source = HttpUtility.UrlDecode(targetUri.Query);
TokenCollection tokens = new TokenCollection(source, deli);
foreach (String token in tokens)
{
if (token.Length > 0)
{
char[] otherDeli = { '=' };
String[] parameters = token.Split(otherDeli, 2);
switch (parameters[0])
{
case "kind":
this.kindsAsText = parameters[1];
break;
case "tag":
this.tags = parameters[1];
break;
case "thumbsize":
this.thumbsize = parameters[1];
break;
case "access":
if (String.Compare("all", parameters[1], false, CultureInfo.InvariantCulture) == 0)
{
this.Access = AccessLevel.AccessAll;
}
else if (String.Compare("private", parameters[1], false, CultureInfo.InvariantCulture) == 0)
{
this.Access = AccessLevel.AccessPrivate;
}
else
{
this.Access = AccessLevel.AccessPublic;
}
break;
}
}
}
}
return this.Uri;
}
//////////////////////////////////////////////////////////////////////
/// <summary>Resets object state to default, as if newly created.
/// </summary>
//////////////////////////////////////////////////////////////////////
protected override void Reset()
{
base.Reset();
}
//////////////////////////////////////////////////////////////////////
/// <summary>Creates the partial URI query string based on all
/// set properties.</summary>
/// <returns> string => the query part of the URI </returns>
//////////////////////////////////////////////////////////////////////
protected override string CalculateQuery(string basePath)
{
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (this.KindParameter.Length > 0)
{
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "kind={0}", Utilities.UriEncodeReserved(this.KindParameter));
paramInsertion = '&';
}
if (this.Tags.Length > 0)
{
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "tag={0}", Utilities.UriEncodeReserved(this.Tags));
paramInsertion = '&';
}
if (Utilities.IsPersistable(this.Thumbsize))
{
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "thumbsize={0}", Utilities.UriEncodeReserved(this.Thumbsize));
paramInsertion = '&';
}
if (this.Access != AccessLevel.AccessUndefined)
{
String acc;
if (this.Access == AccessLevel.AccessAll)
{
acc = "all";
}
else if (this.Access == AccessLevel.AccessPrivate)
{
acc = "private";
}
else
{
acc = "public";
}
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "access={0}", acc);
}
return newPath.ToString();
}
}
}
| |
/**************************************************************************\
Copyright Microsoft Corporation. All Rights Reserved.
\**************************************************************************/
// Conditional to use more aggressive fail-fast behaviors when debugging.
#define DEV_DEBUG
// This file contains general utilities to aid in development.
// It is distinct from unit test Assert classes.
// Classes here generally shouldn't be exposed publicly since
// they're not particular to any library functionality.
// Because the classes here are internal, it's likely this file
// might be included in multiple assemblies.
namespace Standard
{
using System;
using System.Diagnostics;
using System.Threading;
/// <summary>A static class for verifying assumptions.</summary>
internal static class Assert
{
private static void _Break()
{
#if DEV_DEBUG
Debugger.Break();
#else
Debug.Assert(false);
#endif
}
/// <summary>A function signature for Assert.Evaluate.</summary>
public delegate void EvaluateFunction();
/// <summary>A function signature for Assert.Implies.</summary>
/// <returns>Returns the truth of a predicate.</returns>
public delegate bool ImplicationFunction();
/// <summary>
/// Executes the specified argument.
/// </summary>
/// <param name="argument">The function to execute.</param>
[Conditional("DEBUG")]
public static void Evaluate(EvaluateFunction argument)
{
IsNotNull(argument);
argument();
}
/// <summary>Obsolete: Use Standard.Assert.AreEqual instead of Assert.Equals</summary>
/// <typeparam name="T">The generic type to compare for equality.</typeparam>
/// <param name="expected">The first generic type data to compare. This is is the expected value.</param>
/// <param name="actual">The second generic type data to compare. This is the actual value.</param>
[
Obsolete("Use Assert.AreEqual instead of Assert.Equals", false),
Conditional("DEBUG")
]
public static void Equals<T>(T expected, T actual)
{
AreEqual(expected, actual);
}
/// <summary>
/// Verifies that two generic type data are equal. The assertion fails if they are not.
/// </summary>
/// <typeparam name="T">The generic type to compare for equality.</typeparam>
/// <param name="expected">The first generic type data to compare. This is is the expected value.</param>
/// <param name="actual">The second generic type data to compare. This is the actual value.</param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void AreEqual<T>(T expected, T actual)
{
if (null == expected)
{
// Two nulls are considered equal, regardless of type semantics.
if (null != actual && !actual.Equals(expected))
{
_Break();
}
}
else if (!expected.Equals(actual))
{
_Break();
}
}
/// <summary>
/// Verifies that two generic type data are not equal. The assertion fails if they are.
/// </summary>
/// <typeparam name="T">The generic type to compare for inequality.</typeparam>
/// <param name="notExpected">The first generic type data to compare. This is is the value that's not expected.</param>
/// <param name="actual">The second generic type data to compare. This is the actual value.</param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void AreNotEqual<T>(T notExpected, T actual)
{
if (null == notExpected)
{
// Two nulls are considered equal, regardless of type semantics.
if (null == actual || actual.Equals(notExpected))
{
_Break();
}
}
else if (notExpected.Equals(actual))
{
_Break();
}
}
/// <summary>
/// Verifies that if the specified condition is true, then so is the result.
/// The assertion fails if the condition is true but the result is false.
/// </summary>
/// <param name="condition">if set to <c>true</c> [condition].</param>
/// <param name="result">
/// A second Boolean statement. If the first was true then so must this be.
/// If the first statement was false then the value of this is ignored.
/// </param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void Implies(bool condition, bool result)
{
if (condition && !result)
{
_Break();
}
}
/// <summary>
/// Lazy evaluation overload. Verifies that if a condition is true, then so is a secondary value.
/// </summary>
/// <param name="condition">The conditional value.</param>
/// <param name="result">A function to be evaluated for truth if the condition argument is true.</param>
/// <remarks>
/// This overload only evaluates the result if the first condition is true.
/// </remarks>
[Conditional("DEBUG")]
public static void Implies(bool condition, ImplicationFunction result)
{
if (condition && !result())
{
_Break();
}
}
/// <summary>
/// Verifies that a string has content. I.e. it is not null and it is not empty.
/// </summary>
/// <param name="value">The string to verify.</param>
[Conditional("DEBUG")]
public static void IsNeitherNullNorEmpty(string value)
{
IsFalse(string.IsNullOrEmpty(value));
}
/// <summary>
/// Verifies that a string has content. I.e. it is not null and it is not purely whitespace.
/// </summary>
/// <param name="value">The string to verify.</param>
[Conditional("DEBUG")]
public static void IsNeitherNullNorWhitespace(string value)
{
if (string.IsNullOrEmpty(value))
{
_Break();
}
if (value.Trim().Length == 0)
{
_Break();
}
}
/// <summary>
/// Verifies the specified value is not null. The assertion fails if it is.
/// </summary>
/// <typeparam name="T">The generic reference type.</typeparam>
/// <param name="value">The value to check for nullness.</param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void IsNotNull<T>(T value) where T : class
{
if (null == value)
{
_Break();
}
}
[Conditional("DEBUG")]
public static void IsDefault<T>(T value) where T : struct
{
if (!value.Equals(default(T)))
{
Assert.Fail();
}
}
[Conditional("DEBUG")]
public static void IsNotDefault<T>(T value) where T : struct
{
if (value.Equals(default(T)))
{
Assert.Fail();
}
}
/// <summary>
/// Verifies that the specified condition is false. The assertion fails if it is true.
/// </summary>
/// <param name="condition">The expression that should be <c>false</c>.</param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void IsFalse(bool condition)
{
if (condition)
{
_Break();
}
}
/// <summary>
/// Verifies that the specified condition is false. The assertion fails if it is true.
/// </summary>
/// <param name="condition">The expression that should be <c>false</c>.</param>
/// <param name="message">The message to display if the condition is <c>true</c>.</param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void IsFalse(bool condition, string message)
{
if (condition)
{
_Break();
}
}
/// <summary>
/// Verifies that the specified condition is true. The assertion fails if it is not.
/// </summary>
/// <param name="condition">A condition that is expected to be <c>true</c>.</param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void IsTrue(bool condition)
{
if (!condition)
{
_Break();
}
}
/// <summary>
/// Verifies that the specified condition is true. The assertion fails if it is not.
/// </summary>
/// <param name="condition">A condition that is expected to be <c>true</c>.</param>
/// <param name="message">The message to write in case the condition is <c>false</c>.</param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void IsTrue(bool condition, string message)
{
if (!condition)
{
_Break();
}
}
/// <summary>
/// This line should never be executed. The assertion always fails.
/// </summary>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void Fail()
{
_Break();
}
/// <summary>
/// This line should never be executed. The assertion always fails.
/// </summary>
/// <param name="message">The message to display if this function is executed.</param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void Fail(string message)
{
_Break();
}
/// <summary>
/// Verifies that the specified object is null. The assertion fails if it is not.
/// </summary>
/// <param name="item">The item to verify is null.</param>
[Conditional("DEBUG")]
public static void IsNull<T>(T item) where T : class
{
if (null != item)
{
_Break();
}
}
/// <summary>
/// Verifies that the specified value is within the expected range. The assertion fails if it isn't.
/// </summary>
/// <param name="lowerBoundInclusive">The lower bound inclusive value.</param>
/// <param name="value">The value to verify.</param>
/// <param name="upperBoundInclusive">The upper bound inclusive value.</param>
[Conditional("DEBUG")]
public static void BoundedDoubleInc(double lowerBoundInclusive, double value, double upperBoundInclusive)
{
if (value < lowerBoundInclusive || value > upperBoundInclusive)
{
_Break();
}
}
/// <summary>
/// Verifies that the specified value is within the expected range. The assertion fails if it isn't.
/// </summary>
/// <param name="lowerBoundInclusive">The lower bound inclusive value.</param>
/// <param name="value">The value to verify.</param>
/// <param name="upperBoundExclusive">The upper bound exclusive value.</param>
[Conditional("DEBUG")]
public static void BoundedInteger(int lowerBoundInclusive, int value, int upperBoundExclusive)
{
if (value < lowerBoundInclusive || value >= upperBoundExclusive)
{
_Break();
}
}
/// <summary>
/// Verify the current thread's apartment state is what's expected. The assertion fails if it isn't
/// </summary>
/// <param name="expectedState">
/// The expected apartment state for the current thread.
/// </param>
/// <remarks>This breaks into the debugger in the case of a failed assertion.</remarks>
[Conditional("DEBUG")]
public static void IsApartmentState(ApartmentState expectedState)
{
if (Thread.CurrentThread.GetApartmentState() != expectedState)
{
_Break();
}
}
[Conditional("DEBUG")]
public static void NullableIsNotNull<T>(T? value) where T : struct
{
if (null == value)
{
_Break();
}
}
[Conditional("DEBUG")]
public static void NullableIsNull<T>(T? value) where T : struct
{
if (null != value)
{
_Break();
}
}
[Conditional("DEBUG")]
public static void IsNotOnMainThread()
{
if (System.Windows.Application.Current.Dispatcher.CheckAccess())
{
_Break();
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using log4net;
using NetGore;
using NetGore.Graphics.GUI;
using NetGore.Network;
namespace DemoGame.Client
{
/// <summary>
/// A very simple client-side Inventory, used only by the client's character.
/// </summary>
public class Inventory
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
readonly ItemEntity[] _buffer = new ItemEntity[GameData.MaxInventorySize];
readonly INetworkSender _socket;
/// <summary>
/// Initializes a new instance of the <see cref="Inventory"/> class.
/// </summary>
/// <param name="socket">The <see cref="INetworkSender"/> to use to communicate with the server.</param>
/// <exception cref="ArgumentNullException"><paramref name="socket" /> is <c>null</c>.</exception>
public Inventory(INetworkSender socket)
{
if (socket == null)
throw new ArgumentNullException("socket");
_socket = socket;
}
/// <summary>
/// Clears out all the inventory slots.
/// </summary>
public void Clear()
{
for (int i = 0; i < GameData.MaxInventorySize; i++)
{
UpdateEmpty((InventorySlot)i);
}
}
/// <summary>
/// Gets an inventory item.
/// </summary>
/// <param name="slot">Index of the inventory item slot.</param>
/// <returns>Item in the specified inventory slot, or null if the slot is empty or invalid</returns>
public ItemEntity this[InventorySlot slot]
{
get
{
// Check for a valid index
if (!slot.IsLegalValue())
{
const string errmsg = "Tried to get invalid inventory slot `{0}`.";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, slot);
Debug.Fail(string.Format(errmsg, slot));
return null;
}
// If the item has an amount of 0, return null
var item = _buffer[(int)slot];
if (item != null && item.Amount == 0)
return null;
// Item is either null or valid
return _buffer[(int)slot];
}
private set
{
// Check for a valid index
if (!slot.IsLegalValue())
{
const string errmsg = "Tried to set invalid inventory slot `{0}`.";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, slot);
Debug.Fail(string.Format(errmsg, slot));
return;
}
_buffer[(int)slot] = value;
}
}
/// <summary>
/// Drops an item from the inventory onto the ground. If the user has just one item in the given <paramref name="slot"/>,
/// then it is dropped. If they have multiple items in the <paramref name="slot"/>, then they are presented with an
/// <see cref="InputBox"/> so they can enter in how much to drop.
/// </summary>
/// <param name="slot">The slot of the item to drop.</param>
/// <param name="guiManager">The <see cref="IGUIManager"/> to use to create the <see cref="InputBox"/> if it is needed.</param>
public void Drop(InventorySlot slot, IGUIManager guiManager)
{
// Check for a valid item
var item = this[slot];
if (item == null)
return;
// Check the amount
if (item.Amount > 1)
{
// Create an InputBox to ask how much to drop
const string text = "Drop item";
const string message = "How much of the item do you wish to drop?\n(Enter a value from 1 to {0})";
var inBox = InputBox.CreateNumericInputBox(guiManager, text, string.Format(message, item.Amount));
inBox.Tag = slot;
inBox.OptionSelected += DropInputBox_OptionSelected;
}
else
{
// Auto-drop if there is just one of the item
Drop(slot, 1);
}
}
/// <summary>
/// Drops an item from the inventory onto the ground.
/// </summary>
/// <param name="slot">The slot of the item to drop.</param>
/// <param name="amount">The amount of the item in the slot to drop.</param>
public void Drop(InventorySlot slot, byte amount)
{
// Check for a valid item
var item = this[slot];
if (item == null)
return;
// Drop
using (var pw = ClientPacket.DropInventoryItem(slot, amount))
{
_socket.Send(pw, ClientMessageType.GUIItems);
}
}
/// <summary>
/// Handles the OptionSelected event of the DropInputBox, which is the <see cref="InputBox"/> created to
/// let the user specify how much of the item they want to drop.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="NetGore.EventArgs{MessageBoxButton}"/> instance containing the event data.</param>
void DropInputBox_OptionSelected(Control sender, EventArgs<MessageBoxButton> args)
{
var slot = (InventorySlot)sender.Tag;
var inBox = (InputBox)sender;
byte amount;
if (!byte.TryParse(inBox.InputText, out amount))
return;
Drop(slot, amount);
}
/// <summary>
/// Sells an inventory item to the currently open shop.
/// </summary>
/// <param name="slot">The slot of the item to sell.</param>
/// <param name="guiManager">The <see cref="IGUIManager"/> to use to create the <see cref="InputBox"/> if it is needed.</param>
public void SellToShop(InventorySlot slot, IGUIManager guiManager)
{
// Check for a valid item
var item = this[slot];
if (item == null)
return;
// Check the amount
if (item.Amount > 1)
{
// Create an InputBox to ask how much to drop
const string text = "Sell item";
const string message = "How much of the item do you wish to sell?\n(Enter a value from 1 to {0})";
var inBox = InputBox.CreateNumericInputBox(guiManager, text, string.Format(message, item.Amount));
inBox.Tag = slot;
inBox.OptionSelected += SellToShopInputBox_OptionSelected;
}
else
{
// Auto-drop if there is just one of the item
SellToShop(slot, 1);
}
}
/// <summary>
/// Sells an inventory item to the currently open shop.
/// </summary>
/// <param name="slot">The slot of the item to sell.</param>
/// <param name="amount">The amount of the item in the slot to sell.</param>
public void SellToShop(InventorySlot slot, byte amount)
{
// Check for a valid item
var item = this[slot];
if (item == null)
return;
using (var pw = ClientPacket.SellInventoryToShop(slot, amount))
{
_socket.Send(pw, ClientMessageType.GUIItems);
}
}
/// <summary>
/// Handles the OptionSelected event of the SellToShopInputBox, which is the <see cref="InputBox"/> created to
/// let the user specify how much of the item they want to sell to a shop.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs{MessageBoxButton}"/> instance containing the event data.</param>
void SellToShopInputBox_OptionSelected(Control sender, EventArgs<MessageBoxButton> e)
{
var slot = (InventorySlot)sender.Tag;
var inBox = (InputBox)sender;
byte amount;
if (!byte.TryParse(inBox.InputText, out amount))
return;
SellToShop(slot, amount);
}
/// <summary>
/// Updates a slot in the Inventory
/// </summary>
/// <param name="slot">Slot to update</param>
/// <param name="graphic">New graphic index</param>
/// <param name="amount">New item amount</param>
/// <param name="time">Current time</param>
public void Update(InventorySlot slot, GrhIndex graphic, byte amount, TickCount time)
{
// If we get an amount of 0, just use UpdateEmpty()
if (amount == 0)
{
UpdateEmpty(slot);
return;
}
if (this[slot] == null)
{
// Add a new item
this[slot] = new ItemEntity(graphic, amount, time);
}
else
{
// Update an existing item
var item = this[slot];
item.GraphicIndex = graphic;
item.Amount = amount;
}
}
/// <summary>
/// Updates a slot in the Invetory by setting it to an empty item
/// </summary>
public void UpdateEmpty(InventorySlot slot)
{
var item = this[slot];
if (item == null)
return;
// Only need to clear the item if one already exists in the slot
item.GraphicIndex = GrhIndex.Invalid;
item.Amount = 0;
}
/// <summary>
/// Uses an item in the inventory.
/// </summary>
/// <param name="slot">Slot of the item to use.</param>
public void Use(InventorySlot slot)
{
var item = this[slot];
if (item == null)
return;
using (var pw = ClientPacket.UseInventoryItem(slot))
{
_socket.Send(pw, ClientMessageType.GUIItems);
}
}
}
}
| |
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Cottle.Parsers;
using NUnit.Framework;
namespace Cottle.Test.Parsers
{
internal class ForwardParserTester
{
[Test]
[TestCase("<|", "|>", "1 || 0", "true")]
[TestCase("<&", "&>", "1 && 0", "")]
public void Parse_Ambiguous_Block(string blockBegin, string blockEnd, string expression, string expected)
{
var configuration = new DocumentConfiguration
{ BlockBegin = blockBegin, BlockContinue = "<>", BlockEnd = blockEnd };
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(configuration),
blockBegin + expression + blockEnd);
Assert.That(statement.Type, Is.EqualTo(StatementType.Echo));
Assert.That(statement.Operand.Type, Is.EqualTo(ExpressionType.Invoke));
Assert.That(statement.Operand.Arguments.Count, Is.EqualTo(2));
Assert.That(statement.Operand.Arguments[0].Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(statement.Operand.Arguments[0].Value, Is.EqualTo((Value)1));
Assert.That(statement.Operand.Arguments[1].Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(statement.Operand.Arguments[1].Value, Is.EqualTo((Value)0));
}
[Test]
[TestCase("declare")]
[TestCase("dump")]
[TestCase("echo")]
[TestCase("for")]
[TestCase("if")]
[TestCase("set")]
[TestCase("unwrap")]
[TestCase("while")]
[TestCase("wrap")]
public void Parse_Ambiguous_Echo(string name)
{
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(), "{" + name + "}");
Assert.That(statement.Type, Is.EqualTo(StatementType.Echo));
Assert.That(statement.Operand.Type, Is.EqualTo(ExpressionType.Symbol));
Assert.That(statement.Operand.Value, Is.EqualTo((Value)name));
}
[Test]
[TestCase("{1|2|3}", StatementType.Echo, StatementType.Echo, StatementType.Echo)]
[TestCase("{echo 1|echo 2|echo 3}", StatementType.Echo, StatementType.Echo, StatementType.Echo)]
[TestCase("{if 1:x|echo 2|set x to 3}", StatementType.If, StatementType.Echo, StatementType.AssignValue)]
[TestCase("{if 1:x|else:y|echo 2|set x to 3}", StatementType.If, StatementType.Echo, StatementType.AssignValue)]
[TestCase("{dump 1|for i in x:y|echo 3}", StatementType.Dump, StatementType.For, StatementType.Echo)]
[TestCase("{dump 1|for i in x:y|empty:z|echo 3}", StatementType.Dump, StatementType.For, StatementType.Echo)]
public void Parse_StatementCommandThrice(string template, StatementType expectedFirst, StatementType expectedSecond, StatementType expectedThird)
{
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(), template);
Assert.That(statement.Body.Type, Is.EqualTo(expectedFirst));
Assert.That(statement.Next.Type, Is.EqualTo(StatementType.Composite));
Assert.That(statement.Next.Body.Type, Is.EqualTo(expectedSecond));
Assert.That(statement.Next.Next.Type, Is.EqualTo(expectedThird));
}
[Test]
[TestCase("{1|2}", StatementType.Echo, StatementType.Echo)]
[TestCase("{echo 1|echo 2}", StatementType.Echo, StatementType.Echo)]
[TestCase("{echo 1|set x to 2}", StatementType.Echo, StatementType.AssignValue)]
[TestCase("{set x to 1|set y to 2}", StatementType.AssignValue, StatementType.AssignValue)]
[TestCase("{set x to 1|if 1:y}", StatementType.AssignValue, StatementType.If)]
[TestCase("{set x to 1|if 1:y|else:z}", StatementType.AssignValue, StatementType.If)]
[TestCase("{if 1:x|echo 2}", StatementType.If, StatementType.Echo)]
[TestCase("{if 1:x|else:y|echo 2}", StatementType.If, StatementType.Echo)]
[TestCase("{_ dummy|dump 1|echo 2}", StatementType.Dump, StatementType.Echo)]
[TestCase("{dump 1|_ dummy|echo 2}", StatementType.Dump, StatementType.Echo)]
[TestCase("{dump 1|echo 2|_ dummy}", StatementType.Dump, StatementType.Echo)]
public void Parse_StatementCommandTwice(string template, StatementType expectedFirst, StatementType expectedSecond)
{
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(), template);
Assert.That(statement.Body.Type, Is.EqualTo(expectedFirst));
Assert.That(statement.Next.Type, Is.EqualTo(expectedSecond));
}
[Test]
[TestCase("{for i in c:x}", "", "i", ExpressionType.Symbol, StatementType.Literal, StatementType.None)]
[TestCase("{for k, v in []:{echo i}|empty:x}", "k", "v", ExpressionType.Map, StatementType.Echo,
StatementType.Literal)]
public void Parse_StatementFor(string template, string expectedKey, string expectedValue,
ExpressionType expectedOperand, StatementType expectedBody, StatementType expectedNext)
{
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(), template);
Assert.That(statement.Body.Type, Is.EqualTo(expectedBody));
Assert.That(statement.Key, Is.EqualTo(expectedKey));
Assert.That(statement.Value, Is.EqualTo(expectedValue));
Assert.That(statement.Operand.Type, Is.EqualTo(expectedOperand));
Assert.That(statement.Next.Type, Is.EqualTo(expectedNext));
Assert.That(statement.Type, Is.EqualTo(StatementType.For));
}
[Test]
[TestCase("{unwrap:test}", StatementType.Literal)]
[TestCase("{unwrap:{echo 5}}", StatementType.Echo)]
public void Parse_StatementUnwrap(string template, StatementType expectedbody)
{
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(), template);
Assert.That(statement.Body.Type, Is.EqualTo(expectedbody));
Assert.That(statement.Type, Is.EqualTo(StatementType.Unwrap));
}
[Test]
[TestCase("{wrap 42:test}", ExpressionType.Constant, StatementType.Literal)]
[TestCase("{wrap f:{echo 5}}", ExpressionType.Symbol, StatementType.Echo)]
public void Parse_StatementWrap(string template, ExpressionType expectedOperand, StatementType expectedbody)
{
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(), template);
Assert.That(statement.Body.Type, Is.EqualTo(expectedbody));
Assert.That(statement.Operand.Type, Is.EqualTo(expectedOperand));
Assert.That(statement.Type, Is.EqualTo(StatementType.Wrap));
}
[Test]
[TestCase("{\"\\\"\"}", '\\', "\"")]
[TestCase("{\"xxxy\"}", 'x', "xy")]
public void Parse_ConfigurationEscapeStatement(string template, char escape, string expected)
{
var configuration = new DocumentConfiguration { Escape = escape };
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(configuration), template);
Assert.That(statement.Type, Is.EqualTo(StatementType.Echo));
Assert.That(statement.Operand.Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(statement.Operand.Value, Is.EqualTo((Value)expected));
}
[Test]
[TestCase("Escaped\\ Literal", '\\', "Escaped Literal")]
[TestCase("-{'x'-}", '-', "{'x'}")]
[TestCase("ABC", 'x', "ABC")]
[TestCase("--", '-', "-")]
public void Parse_ConfigurationEscapeLiteral(string template, char escape, string expected)
{
var configuration = new DocumentConfiguration { Escape = escape };
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(configuration), template);
Assert.That(statement.Type, Is.EqualTo(StatementType.Literal));
Assert.That(statement.Value, Is.EqualTo(expected));
}
[Test]
[TestCase("A", "A", "B", "B")]
[TestCase("X Y", " +", " ", "X Y")]
[TestCase("df98gd76dfg5df4g321gh0", "[^0-9]", "", "9876543210")]
public void Parse_ConfigurationTrimmer(string template, string pattern, string replacement, string expected)
{
var configuration = new DocumentConfiguration { Trimmer = s => Regex.Replace(s, pattern, replacement) };
var statement = ForwardParserTester.Parse(ForwardParserTester.Create(configuration), template);
Assert.That(statement.Type, Is.EqualTo(StatementType.Literal));
Assert.That(statement.Value, Is.EqualTo(expected));
}
[TestCase("{1", 2, 0, "expected block continue or block end, found end of stream")]
[TestCase("{1.2.3", 5, 1, "expected field name, found 3")]
[TestCase("{\"abc", 1, 4, "expected expression, found unfinished string")]
[TestCase("a{1", 3, 0, "expected block continue or block end, found end of stream")]
[TestCase("a{1+}", 4, 1, "expected expression, found unexpected character")]
public void Parse_Reports(string template, int expectedOffset, int expectedLength, string expectedMessage)
{
var parser = ForwardParserTester.Create();
using (var reader = new StringReader(template))
{
var state = new ParserState();
Assert.That(parser.Parse(reader, state, out _), Is.False);
var firstError = state.Reports.FirstOrDefault(r => r.Severity == DocumentSeverity.Error);
Assert.That(firstError.Length, Is.EqualTo(expectedLength));
Assert.That(firstError.Message, Does.Contain(expectedMessage));
Assert.That(firstError.Offset, Is.EqualTo(expectedOffset));
}
}
private static ForwardParser Create(DocumentConfiguration configuration = default)
{
return new ForwardParser(configuration.BlockBegin ?? "{", configuration.BlockContinue ?? "|",
configuration.BlockEnd ?? "}", configuration.Escape.GetValueOrDefault('\\'),
configuration.Trimmer ?? (s => s));
}
private static Statement Parse(IParser parser, string template)
{
using (var reader = new StringReader(template))
{
var state = new ParserState();
Assert.That(parser.Parse(reader, state, out var statement), Is.True);
return statement;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Storage.Queues;
using Azure.Storage.Queues.Models;
using Microsoft.Extensions.Logging;
using Orleans.AzureUtils.Utilities;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime;
namespace Orleans.AzureUtils
{
/// <summary>
/// How to use the Queue Storage Service: http://www.windowsazure.com/en-us/develop/net/how-to-guides/queue-service/
/// Windows Azure Storage Abstractions and their Scalability Targets: http://blogs.msdn.com/b/windowsazurestorage/archive/2010/05/10/windows-azure-storage-abstractions-and-their-scalability-targets.aspx
/// Naming Queues and Metadata: http://msdn.microsoft.com/en-us/library/windowsazure/dd179349.aspx
/// Windows Azure Queues and Windows Azure Service Bus Queues - Compared and Contrasted: http://msdn.microsoft.com/en-us/library/hh767287(VS.103).aspx
/// Status and Error Codes: http://msdn.microsoft.com/en-us/library/dd179382.aspx
///
/// http://blogs.msdn.com/b/windowsazurestorage/archive/tags/scalability/
/// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/12/30/windows-azure-storage-architecture-overview.aspx
/// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/11/06/how-to-get-most-out-of-windows-azure-tables.aspx
///
/// </summary>
internal static class AzureQueueDefaultPolicies
{
public static int MaxQueueOperationRetries;
public static TimeSpan PauseBetweenQueueOperationRetries;
public static TimeSpan QueueOperationTimeout;
static AzureQueueDefaultPolicies()
{
MaxQueueOperationRetries = 5;
PauseBetweenQueueOperationRetries = TimeSpan.FromMilliseconds(100);
QueueOperationTimeout = PauseBetweenQueueOperationRetries.Multiply(MaxQueueOperationRetries).Multiply(6); // 3 sec
}
}
/// <summary>
/// Utility class to encapsulate access to Azure queue storage.
/// </summary>
/// <remarks>
/// Used by Azure queue streaming provider.
/// </remarks>
public class AzureQueueDataManager
{
/// <summary> Name of the table queue instance is managing. </summary>
public string QueueName { get; private set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
private readonly ILogger logger;
private readonly TimeSpan? messageVisibilityTimeout;
private readonly QueueClient queueClient;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="loggerFactory">logger factory to use</param>
/// <param name="queueName">Name of the queue to be connected to.</param>
/// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param>
/// <param name="visibilityTimeout">A TimeSpan specifying the visibility timeout interval</param>
public AzureQueueDataManager(ILoggerFactory loggerFactory, string queueName, string storageConnectionString, TimeSpan? visibilityTimeout = null)
: this (loggerFactory, queueName, new AzureQueueOptions { ConnectionString = storageConnectionString, MessageVisibilityTimeout = visibilityTimeout })
{
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="loggerFactory">logger factory to use</param>
/// <param name="queueName">Name of the queue to be connected to.</param>
/// <param name="options">Queue connection options.</param>
public AzureQueueDataManager(ILoggerFactory loggerFactory, string queueName, AzureQueueOptions options)
{
queueName = SanitizeQueueName(queueName);
ValidateQueueName(queueName);
logger = loggerFactory.CreateLogger<AzureQueueDataManager>();
QueueName = queueName;
messageVisibilityTimeout = options.MessageVisibilityTimeout;
queueClient = GetCloudQueueClient(options, logger);
}
/// <summary>
/// Initializes the connection to the queue.
/// </summary>
public async Task InitQueueAsync()
{
var startTime = DateTime.UtcNow;
try
{
// Create the queue if it doesn't already exist.
var response = await queueClient.CreateIfNotExistsAsync();
logger.Info((int)AzureQueueErrorCode.AzureQueue_01, "Connected to Azure storage queue {0}", QueueName);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "CreateIfNotExist", AzureQueueErrorCode.AzureQueue_02);
}
finally
{
CheckAlertSlowAccess(startTime, "InitQueue_Async");
}
}
/// <summary>
/// Deletes the queue.
/// </summary>
public async Task DeleteQueue()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Deleting queue: {0}", QueueName);
try
{
// that way we don't have first to create the queue to be able later to delete it.
if (await queueClient.DeleteIfExistsAsync())
{
logger.Info((int)AzureQueueErrorCode.AzureQueue_03, "Deleted Azure Queue {0}", QueueName);
}
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "DeleteQueue", AzureQueueErrorCode.AzureQueue_04);
}
finally
{
CheckAlertSlowAccess(startTime, "DeleteQueue");
}
}
/// <summary>
/// Clears the queue.
/// </summary>
public async Task ClearQueue()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Clearing a queue: {0}", QueueName);
try
{
// that way we don't have first to create the queue to be able later to delete it.
await queueClient.ClearMessagesAsync();
logger.Info((int)AzureQueueErrorCode.AzureQueue_05, "Cleared Azure Queue {0}", QueueName);
}
catch (RequestFailedException exc)
{
if (exc.Status != (int)HttpStatusCode.NotFound)
{
ReportErrorAndRethrow(exc, "ClearQueue", AzureQueueErrorCode.AzureQueue_06);
}
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "ClearQueue", AzureQueueErrorCode.AzureQueue_06);
}
finally
{
CheckAlertSlowAccess(startTime, "ClearQueue");
}
}
/// <summary>
/// Adds a new message to the queue.
/// </summary>
/// <param name="message">Message to be added to the queue.</param>
public async Task AddQueueMessage(string message)
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Adding message {0} to queue: {1}", message, QueueName);
try
{
await queueClient.SendMessageAsync(message);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "AddQueueMessage", AzureQueueErrorCode.AzureQueue_07);
}
finally
{
CheckAlertSlowAccess(startTime, "AddQueueMessage");
}
}
/// <summary>
/// Peeks in the queue for latest message, without dequeuing it.
/// </summary>
public async Task<PeekedMessage> PeekQueueMessage()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Peeking a message from queue: {0}", QueueName);
try
{
var messages = await queueClient.PeekMessagesAsync(maxMessages: 1);
return messages.Value.FirstOrDefault();
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "PeekQueueMessage", AzureQueueErrorCode.AzureQueue_08);
return null; // Dummy statement to keep compiler happy
}
finally
{
CheckAlertSlowAccess(startTime, "PeekQueueMessage");
}
}
/// <summary>
/// Gets a new message from the queue.
/// </summary>
public async Task<QueueMessage> GetQueueMessage()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Getting a message from queue: {0}", QueueName);
try
{
//BeginGetMessage and EndGetMessage is not supported in netstandard, may be use GetMessageAsync
// http://msdn.microsoft.com/en-us/library/ee758456.aspx
// If no messages are visible in the queue, GetMessage returns null.
var messages = await queueClient.ReceiveMessagesAsync(maxMessages: 1, messageVisibilityTimeout);
return messages.Value.FirstOrDefault();
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "GetQueueMessage", AzureQueueErrorCode.AzureQueue_09);
return null; // Dummy statement to keep compiler happy
}
finally
{
CheckAlertSlowAccess(startTime, "GetQueueMessage");
}
}
/// <summary>
/// Gets a number of new messages from the queue.
/// </summary>
/// <param name="count">Number of messages to get from the queue.</param>
public async Task<IEnumerable<QueueMessage>> GetQueueMessages(int? count = null)
{
var startTime = DateTime.UtcNow;
if (count == -1)
{
count = null;
}
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Getting up to {0} messages from queue: {1}", count, QueueName);
try
{
var messages = await queueClient.ReceiveMessagesAsync(count, messageVisibilityTimeout);
return messages.Value;
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "GetQueueMessages", AzureQueueErrorCode.AzureQueue_10);
return null; // Dummy statement to keep compiler happy
}
finally
{
CheckAlertSlowAccess(startTime, "GetQueueMessages");
}
}
/// <summary>
/// Deletes a messages from the queue.
/// </summary>
/// <param name="message">A message to be deleted from the queue.</param>
public async Task DeleteQueueMessage(QueueMessage message)
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Deleting a message from queue: {0}", QueueName);
try
{
await queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "DeleteMessage", AzureQueueErrorCode.AzureQueue_11);
}
finally
{
CheckAlertSlowAccess(startTime, "DeleteQueueMessage");
}
}
internal async Task GetAndDeleteQueueMessage()
{
var message = await GetQueueMessage();
await DeleteQueueMessage(message);
}
/// <summary>
/// Returns an approximate number of messages in the queue.
/// </summary>
public async Task<int> GetApproximateMessageCount()
{
var startTime = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("GetApproximateMessageCount a message from queue: {0}", QueueName);
try
{
var properties = await queueClient.GetPropertiesAsync();
return properties.Value.ApproximateMessagesCount;
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "FetchAttributes", AzureQueueErrorCode.AzureQueue_12);
return 0; // Dummy statement to keep compiler happy
}
finally
{
CheckAlertSlowAccess(startTime, "GetApproximateMessageCount");
}
}
private void CheckAlertSlowAccess(DateTime startOperation, string operation)
{
var timeSpan = DateTime.UtcNow - startOperation;
if (timeSpan > AzureQueueDefaultPolicies.QueueOperationTimeout)
{
logger.Warn((int)AzureQueueErrorCode.AzureQueue_13, "Slow access to Azure queue {0} for {1}, which took {2}.", QueueName, operation, timeSpan);
}
}
private void ReportErrorAndRethrow(Exception exc, string operation, AzureQueueErrorCode errorCode)
{
var errMsg = String.Format(
"Error doing {0} for Azure storage queue {1} " + Environment.NewLine
+ "Exception = {2}", operation, QueueName, exc);
logger.Error((int)errorCode, errMsg, exc);
throw new AggregateException(errMsg, exc);
}
private QueueClient GetCloudQueueClient(AzureQueueOptions options, ILogger logger)
{
try
{
var clientOptions = new QueueClientOptions
{
Retry =
{
Mode = RetryMode.Fixed,
Delay = AzureQueueDefaultPolicies.PauseBetweenQueueOperationRetries,
MaxRetries = AzureQueueDefaultPolicies.MaxQueueOperationRetries,
NetworkTimeout = AzureQueueDefaultPolicies.QueueOperationTimeout,
}
};
var client = options.ServiceUri != null
? new QueueClient(new Uri(options.ServiceUri, QueueName), options.TokenCredential, clientOptions)
: new QueueClient(options.ConnectionString, QueueName, clientOptions);
return client;
}
catch (Exception exc)
{
logger.Error((int)AzureQueueErrorCode.AzureQueue_14, String.Format("Error creating GetCloudQueueOperationsClient."), exc);
throw;
}
}
private string SanitizeQueueName(string queueName)
{
var tmp = queueName;
//Azure queue naming rules : https://docs.microsoft.com/en-us/rest/api/storageservices/Naming-Queues-and-Metadata?redirectedfrom=MSDN
tmp = tmp.ToLowerInvariant();
tmp = tmp
.Replace('/', '-') // Forward slash
.Replace('\\', '-') // Backslash
.Replace('#', '-') // Pound sign
.Replace('?', '-') // Question mark
.Replace('&', '-')
.Replace('+', '-')
.Replace(':', '-')
.Replace('.', '-')
.Replace('%', '-');
return tmp;
}
private void ValidateQueueName(string queueName)
{
// Naming Queues and Metadata: http://msdn.microsoft.com/en-us/library/windowsazure/dd179349.aspx
if (!(queueName.Length >= 3 && queueName.Length <= 63))
{
// A queue name must be from 3 through 63 characters long.
throw new ArgumentException(String.Format("A queue name must be from 3 through 63 characters long, while your queueName length is {0}, queueName is {1}.", queueName.Length, queueName), queueName);
}
if (!Char.IsLetterOrDigit(queueName.First()))
{
// A queue name must start with a letter or number
throw new ArgumentException(String.Format("A queue name must start with a letter or number, while your queueName is {0}.", queueName), queueName);
}
if (!Char.IsLetterOrDigit(queueName.Last()))
{
// The first and last letters in the queue name must be alphanumeric. The dash (-) character cannot be the first or last character.
throw new ArgumentException(String.Format("The last letter in the queue name must be alphanumeric, while your queueName is {0}.", queueName), queueName);
}
if (!queueName.All(c => Char.IsLetterOrDigit(c) || c.Equals('-')))
{
// A queue name can only contain letters, numbers, and the dash (-) character.
throw new ArgumentException(String.Format("A queue name can only contain letters, numbers, and the dash (-) character, while your queueName is {0}.", queueName), queueName);
}
if (queueName.Contains("--"))
{
// Consecutive dash characters are not permitted in the queue name.
throw new ArgumentException(String.Format("Consecutive dash characters are not permitted in the queue name, while your queueName is {0}.", queueName), queueName);
}
if (queueName.Where(Char.IsLetter).Any(c => !Char.IsLower(c)))
{
// All letters in a queue name must be lowercase.
throw new ArgumentException(String.Format("All letters in a queue name must be lowercase, while your queueName is {0}.", queueName), queueName);
}
}
}
}
| |
using Newtonsoft.Json.Linq;
using ReactNative.Reflection;
using ReactNative.UIManager;
using ReactNative.UIManager.Annotations;
using ReactNative.Views.Text;
using System;
using System.Collections.Generic;
using Windows.System;
using Windows.UI;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
namespace ReactNative.Views.TextInput
{
/// <summary>
/// View manager for <see cref="ReactTextBox"/>.
/// </summary>
class ReactTextInputManager : BaseViewManager<ReactTextBox, ReactTextInputShadowNode>
{
internal const int FocusTextInput = 1;
internal const int BlurTextInput = 2;
//
// Grabbed these defaults from running a UWP app.
//
private const uint DefaultTextControlForeground = 0xFF000000;
private const uint DefaultTextControlForegroundPointerOver = 0xFF000000;
private const uint DefaultTextControlForegroundFocused = 0xFF000000;
private const uint DefaultTextControlForegroundDisabled = 0xFF7A7A7A;
private const uint DefaultTextControlBackground = 0x66FFFFFF;
private const uint DefaultTextControlBackgroundPointerOver = 0x99FFFFFF;
private const uint DefaultTextControlBackgroundFocused = 0xFFFFFFFF;
private const uint DefaultTextControlBackgroundDisabled = 0x33000000;
private const uint DefaultTextControlPlaceholderForeground = 0x99000000;
private const uint DefaultTextControlPlaceholderForegroundPointerOver = 0x99000000;
private const uint DefaultTextControlPlaceholderForegroundFocused = 0x66000000;
private const uint DefaultTextControlPlaceholderForegroundDisabled = 0xFF7A7A7A;
private const uint DefaultTextControlBorderBrush = 0xFF7A7A7A;
private const uint DefaultTextControlBorderBrushPointerOver = 0xFF171717;
private const uint DefaultTextControlBorderBrushFocused = 0xFF298FCC;
private const uint DefaultTextControlBorderBrushDisabled = 0x33000000;
/// <summary>
/// The name of the view manager.
/// </summary>
public override string Name
{
get
{
return "RCTTextBox";
}
}
/// <summary>
/// The exported custom bubbling event types.
/// </summary>
public override IReadOnlyDictionary<string, object> ExportedCustomBubblingEventTypeConstants
{
get
{
return new Dictionary<string, object>()
{
{
"topSubmitEditing",
new Dictionary<string, object>()
{
{
"phasedRegistrationNames",
new Dictionary<string, string>()
{
{ "bubbled" , "onSubmitEditing" },
{ "captured" , "onSubmitEditingCapture" }
}
}
}
},
{
"topEndEditing",
new Dictionary<string, object>()
{
{
"phasedRegistrationNames",
new Dictionary<string, string>()
{
{ "bubbled" , "onEndEditing" },
{ "captured" , "onEndEditingCapture" }
}
}
}
},
{
"topFocus",
new Dictionary<string, object>()
{
{
"phasedRegistrationNames",
new Dictionary<string, string>()
{
{ "bubbled" , "onFocus" },
{ "captured" , "onFocusCapture" }
}
}
}
},
{
"topBlur",
new Dictionary<string, object>()
{
{
"phasedRegistrationNames",
new Dictionary<string, string>()
{
{ "bubbled" , "onBlur" },
{ "captured" , "onBlurCapture" }
}
}
}
},
};
}
}
/// <summary>
/// The commands map for the <see cref="ReactTextInputManager"/>.
/// </summary>
public override IReadOnlyDictionary<string, object> CommandsMap
{
get
{
return new Dictionary<string, object>()
{
{ "focusTextInput", FocusTextInput },
{ "blurTextInput", BlurTextInput },
};
}
}
/// <summary>
/// Sets the font size on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="fontSize">The font size.</param>
[ReactProp(ViewProps.FontSize)]
public void SetFontSize(ReactTextBox view, double fontSize)
{
view.FontSize = fontSize;
}
/// <summary>
/// Sets the font color for the node.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="color">The masked color value.</param>
[ReactProp(ViewProps.Color, CustomType = "Color")]
public void SetColor(ReactTextBox view, uint? color)
{
if (color.HasValue)
{
var brush = new SolidColorBrush(ColorHelpers.Parse(color.Value));
view.Resources["TextControlForeground"] = brush;
view.Resources["TextControlForegroundPointerOver"] = brush;
view.Resources["TextControlForegroundFocused"] = brush;
view.Resources["TextControlForegroundDisabled"] = brush;
}
else
{
view.Resources["TextControlForeground"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlForeground));
view.Resources["TextControlForegroundPointerOver"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlForegroundPointerOver));
view.Resources["TextControlForegroundFocused"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlForegroundFocused));
view.Resources["TextControlForegroundDisabled"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlForegroundDisabled));
}
}
/// <summary>
/// Sets the font family for the node.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="familyName">The font family.</param>
[ReactProp(ViewProps.FontFamily)]
public void SetFontFamily(ReactTextBox view, string familyName)
{
view.FontFamily = familyName != null
? new FontFamily(familyName)
: FontFamily.XamlAutoFontFamily;
}
/// <summary>
/// Sets the font weight for the node.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="fontWeightString">The font weight string.</param>
[ReactProp(ViewProps.FontWeight)]
public void SetFontWeight(ReactTextBox view, string fontWeightString)
{
var fontWeight = FontStyleHelpers.ParseFontWeight(fontWeightString);
view.FontWeight = fontWeight ?? FontWeights.Normal;
}
/// <summary>
/// Sets the font style for the node.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="fontStyleString">The font style string.</param>
[ReactProp(ViewProps.FontStyle)]
public void SetFontStyle(ReactTextBox view, string fontStyleString)
{
var fontStyle = EnumHelpers.ParseNullable<FontStyle>(fontStyleString);
view.FontStyle = fontStyle ?? FontStyle.Normal;
}
/// <summary>
/// Sets whether to track selection changes on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="onSelectionChange">The indicator.</param>
[ReactProp("onSelectionChange", DefaultBoolean = false)]
public void SetOnSelectionChange(ReactTextBox view, bool onSelectionChange)
{
view.OnSelectionChange = onSelectionChange;
}
/// <summary>
/// Sets whether to track size changes on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="onContentSizeChange">The indicator.</param>
[ReactProp("onContentSizeChange", DefaultBoolean = false)]
public void setOnContentSizeChange(ReactTextBox view, bool onContentSizeChange)
{
view.OnContentSizeChange = onContentSizeChange;
}
/// <summary>
/// Sets the selected text on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="selection">The selection.</param>
[ReactProp("selection")]
public void SetSelection(ReactTextBox view, JObject selection)
{
var start = selection.Value<int>("start");
var textLength = view.Text?.Length ?? 0;
var normalizedStart = Math.Min(start, textLength);
var end = selection.Value<int>("end");
var selectionLength = end - start;
var normalizedSelectionLength = Math.Max(selectionLength, 0);
var maxLength = textLength - normalizedStart;
view.SelectionStart = normalizedStart;
view.SelectionLength = Math.Min(normalizedSelectionLength, maxLength);
}
/// <summary>
/// Sets the default text placeholder property on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="placeholder">The placeholder text.</param>
[ReactProp("placeholder")]
public void SetPlaceholder(ReactTextBox view, string placeholder)
{
view.PlaceholderText = placeholder;
}
/// <summary>
/// Sets the placeholderTextColor property on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="color">The placeholder text color.</param>
[ReactProp("placeholderTextColor", CustomType = "Color")]
public void SetPlaceholderTextColor(ReactTextBox view, uint? color)
{
if (color.HasValue)
{
var brush = new SolidColorBrush(ColorHelpers.Parse(color.Value));
view.Resources["TextControlPlaceholderForeground"] = brush;
view.Resources["TextControlPlaceholderForegroundPointerOver"] = brush;
view.Resources["TextControlPlaceholderForegroundFocused"] = brush;
view.Resources["TextControlPlaceholderForegroundDisabled"] = brush;
}
else
{
view.Resources["TextControlPlaceholderForeground"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlPlaceholderForeground));
view.Resources["TextControlPlaceholderForegroundPointerOver"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlPlaceholderForegroundPointerOver));
view.Resources["TextControlPlaceholderForegroundFocused"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlPlaceholderForegroundFocused));
view.Resources["TextControlPlaceholderForegroundDisabled"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlPlaceholderForegroundDisabled));
}
}
/// <summary>
/// Sets the border color for the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance</param>
/// <param name="color">The masked color value.</param>
[ReactProp("borderColor", CustomType = "Color")]
public void SetBorderColor(ReactTextBox view, uint? color)
{
if (color.HasValue)
{
var brush = new SolidColorBrush(ColorHelpers.Parse(color.Value));
view.Resources["TextControlBorderBrush"] = brush;
view.Resources["TextControlBorderBrushPointerOver"] = brush;
view.Resources["TextControlBorderBrushFocused"] = brush;
view.Resources["TextControlBorderBrushDisabled"] = brush;
}
else
{
view.Resources["TextControlBorderBrush"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBorderBrush));
view.Resources["TextControlBorderBrushPointerOver"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBorderBrushPointerOver));
view.Resources["TextControlBorderBrushFocused"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBorderBrushFocused));
view.Resources["TextControlBorderBrushDisabled"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBorderBrushDisabled));
}
}
/// <summary>
/// Sets the background color for the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="color">The masked color value.</param>
[ReactProp(ViewProps.BackgroundColor, CustomType = "Color")]
public void SetBackgroundColor(ReactTextBox view, uint? color)
{
if (color.HasValue)
{
var brush = new SolidColorBrush(ColorHelpers.Parse(color.Value));
view.Resources["TextControlBackground"] = brush;
view.Resources["TextControlBackgroundPointerOver"] = brush;
view.Resources["TextControlBackgroundFocused"] = brush;
view.Resources["TextControlBackgroundDisabled"] = brush;
}
else
{
view.Resources["TextControlBackground"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBackground));
view.Resources["TextControlBackgroundPointerOver"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBackgroundPointerOver));
view.Resources["TextControlBackgroundFocused"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBackgroundFocused));
view.Resources["TextControlBackgroundDisabled"] = new SolidColorBrush(ColorHelpers.Parse(DefaultTextControlBackgroundDisabled));
}
}
/// <summary>
/// Sets the selection color for the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="color">The masked color value.</param>
[ReactProp("selectionColor", CustomType = "Color")]
public void SetSelectionColor(ReactTextBox view, uint color)
{
view.SelectionHighlightColor = new SolidColorBrush(ColorHelpers.Parse(color));
}
/// <summary>
/// Sets the text alignment property on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="alignment">The text alignment.</param>
[ReactProp(ViewProps.TextAlign)]
public void SetTextAlign(ReactTextBox view, string alignment)
{
view.TextAlignment = EnumHelpers.Parse<TextAlignment>(alignment);
}
/// <summary>
/// Sets the text alignment property on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="alignment">The text alignment.</param>
[ReactProp(ViewProps.TextAlignVertical)]
public void SetTextVerticalAlign(ReactTextBox view, string alignment)
{
view.VerticalContentAlignment = EnumHelpers.Parse<VerticalAlignment>(alignment);
}
/// <summary>
/// Sets the editablity property on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="editable">The editable flag.</param>
[ReactProp("editable")]
public void SetEditable(ReactTextBox view, bool editable)
{
view.IsEnabled = editable;
}
/// <summary>
/// Sets the max character length property on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="maxCharLength">The max length.</param>
[ReactProp("maxLength")]
public void SetMaxLength(ReactTextBox view, int maxCharLength)
{
view.MaxLength = maxCharLength;
}
/// <summary>
/// Sets whether to enable autocorrect on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="autoCorrect">The autocorrect flag.</param>
[ReactProp("autoCorrect")]
public void SetAutoCorrect(ReactTextBox view, bool autoCorrect)
{
view.IsSpellCheckEnabled = autoCorrect;
}
/// <summary>
/// Sets whether to enable multiline input on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="multiline">The multiline flag.</param>
[ReactProp("multiline", DefaultBoolean = false)]
public void SetMultiline(ReactTextBox view, bool multiline)
{
view.AcceptsReturn = multiline;
view.TextWrapping = multiline ? TextWrapping.Wrap : TextWrapping.NoWrap;
}
/// <summary>
/// Sets whether to enable the <see cref="ReactTextBox"/> to autogrow.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="autoGrow">The auto-grow flag.</param>
[ReactProp("autoGrow", DefaultBoolean = false)]
public void SetAutoGrow(ReactTextBox view, bool autoGrow)
{
view.AutoGrow = autoGrow;
if (autoGrow)
{
view.Height = double.NaN;
}
}
/// <summary>
/// Sets the keyboard type on the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="keyboardType">The keyboard type.</param>
[ReactProp("keyboardType")]
public void SetKeyboardType(ReactTextBox view, string keyboardType)
{
view.InputScope = null;
if (keyboardType != null)
{
var inputScope = new InputScope();
inputScope.Names.Add(
new InputScopeName(
InputScopeHelpers.FromString(keyboardType)));
view.InputScope = inputScope;
}
}
/// <summary>
/// Sets the border width for a <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="width">The border width.</param>
[ReactProp(ViewProps.BorderWidth)]
public void SetBorderWidth(ReactTextBox view, int width)
{
view.BorderThickness = new Thickness(width);
}
/// <summary>
/// Sets whether the text should be cleared on focus.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="clearTextOnFocus">The indicator.</param>
[ReactProp("clearTextOnFocus")]
public void SetClearTextOnFocus(ReactTextBox view, bool clearTextOnFocus)
{
view.ClearTextOnFocus = clearTextOnFocus;
}
/// <summary>
/// Sets whether the text should be selected on focus.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="selectTextOnFocus">The indicator.</param>
[ReactProp("selectTextOnFocus")]
public void SetSelectTextOnFocus(ReactTextBox view, bool selectTextOnFocus)
{
view.SelectTextOnFocus = selectTextOnFocus;
}
/// <summary>
/// Sets the max height of the text box.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="height">The max height.</param>
[ReactProp("maxHeight")]
public void SetMaxHeight(ReactTextBox view, double height)
{
view.MaxHeight = height;
}
/// <summary>
/// Create the shadow node instance.
/// </summary>
/// <returns>The shadow node instance.</returns>
public override ReactTextInputShadowNode CreateShadowNodeInstance()
{
return new ReactTextInputShadowNode();
}
/// <summary>
/// Implement this method to receive events/commands directly from
/// JavaScript through the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="view">
/// The view instance that should receive the command.
/// </param>
/// <param name="commandId">Identifer for the command.</param>
/// <param name="args">Optional arguments for the command.</param>
public override void ReceiveCommand(ReactTextBox view, int commandId, JArray args)
{
if (commandId == FocusTextInput)
{
view.Focus(FocusState.Programmatic);
}
else if (commandId == BlurTextInput)
{
if (FocusManager.GetFocusedElement() == view)
{
var frame = Window.Current?.Content as Frame;
frame?.Focus(FocusState.Programmatic);
}
}
}
/// <summary>
/// Update the view with extra data.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="extraData">The extra data.</param>
public override void UpdateExtraData(ReactTextBox view, object extraData)
{
var paddings = extraData as float[];
var textUpdate = default(Tuple<int, string>);
if (paddings != null)
{
view.Padding = new Thickness(
paddings[0],
paddings[1],
paddings[2],
paddings[3]);
}
else if ((textUpdate = extraData as Tuple<int, string>) != null)
{
var javaScriptCount = textUpdate.Item1;
if (javaScriptCount < view.CurrentEventCount)
{
return;
}
view.TextChanging -= OnTextChanging;
view.TextChanged -= OnTextChanged;
var removeOnSelectionChange = view.OnSelectionChange;
if (removeOnSelectionChange)
{
view.OnSelectionChange = false;
}
var text = textUpdate.Item2;
var previousText = view.Text;
var selectionStart = view.SelectionStart;
var textLength = text?.Length ?? 0;
var normalizedStart = Math.Min(selectionStart, textLength);
var selectionLength = view.SelectionLength;
var maxLength = textLength - normalizedStart;
view.Text = text ?? "";
if (selectionStart == previousText.Length)
{
view.SelectionStart = textLength;
}
else
{
view.SelectionStart = normalizedStart;
view.SelectionLength = Math.Min(selectionLength, maxLength);
}
if (removeOnSelectionChange)
{
view.OnSelectionChange = true;
}
view.TextChanged += OnTextChanged;
view.TextChanging += OnTextChanging;
}
}
/// <summary>
/// Called when view is detached from view hierarchy and allows for
/// additional cleanup by the <see cref="ReactTextInputManager"/>.
/// subclass. Unregister all event handlers for the <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The <see cref="ReactTextBox"/>.</param>
public override void OnDropViewInstance(ThemedReactContext reactContext, ReactTextBox view)
{
base.OnDropViewInstance(reactContext, view);
view.KeyDown -= OnKeyDown;
view.LostFocus -= OnLostFocus;
view.GotFocus -= OnGotFocus;
view.TextChanged -= OnTextChanged;
view.TextChanging -= OnTextChanging;
}
/// <summary>
/// Sets the dimensions of the view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="dimensions">The dimensions.</param>
public override void SetDimensions(ReactTextBox view, Dimensions dimensions)
{
view.MinWidth = dimensions.Width;
view.MinHeight = dimensions.Height;
if (view.AutoGrow)
{
// TODO: investigate Yoga bug that rounds up height 1px
view.DimensionsUpdated = true;
Canvas.SetLeft(view, dimensions.X);
Canvas.SetTop(view, dimensions.Y);
view.Width = dimensions.Width;
}
else
{
base.SetDimensions(view, dimensions);
}
}
/// <summary>
/// Returns the view instance for <see cref="ReactTextBox"/>.
/// </summary>
/// <param name="reactContext"></param>
/// <returns></returns>
protected override ReactTextBox CreateViewInstance(ThemedReactContext reactContext)
{
return new ReactTextBox
{
AcceptsReturn = false,
};
}
/// <summary>
/// Installing the textchanged event emitter on the <see cref="TextInput"/> Control.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The <see cref="ReactTextBox"/> view instance.</param>
protected override void AddEventEmitters(ThemedReactContext reactContext, ReactTextBox view)
{
base.AddEventEmitters(reactContext, view);
view.TextChanging += OnTextChanging;
view.TextChanged += OnTextChanged;
view.GotFocus += OnGotFocus;
view.LostFocus += OnLostFocus;
view.KeyDown += OnKeyDown;
}
private void OnTextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
var textBox = (ReactTextBox)sender;
textBox.IncrementEventCount();
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (ReactTextBox)sender;
textBox.GetReactContext()
.GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new ReactTextChangedEvent(
textBox.GetTag(),
textBox.Text,
textBox.CurrentEventCount));
}
private void OnGotFocus(object sender, RoutedEventArgs e)
{
var textBox = (ReactTextBox)sender;
textBox.GetReactContext()
.GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new ReactTextInputFocusEvent(textBox.GetTag()));
}
private void OnLostFocus(object sender, RoutedEventArgs e)
{
var textBox = (ReactTextBox)sender;
var eventDispatcher = textBox.GetReactContext()
.GetNativeModule<UIManagerModule>()
.EventDispatcher;
eventDispatcher.DispatchEvent(
new ReactTextInputBlurEvent(textBox.GetTag()));
eventDispatcher.DispatchEvent(
new ReactTextInputEndEditingEvent(
textBox.GetTag(),
textBox.Text));
}
private void OnKeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
var textBox = (ReactTextBox)sender;
if (!textBox.AcceptsReturn)
{
e.Handled = true;
textBox.GetReactContext()
.GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new ReactTextInputSubmitEditingEvent(
textBox.GetTag(),
textBox.Text));
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Relay
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// HybridConnectionsOperations operations.
/// </summary>
public partial interface IHybridConnectionsOperations
{
/// <summary>
/// Lists the HybridConnection within the namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<HybridConnection>>> ListByNamespaceWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or Updates a service HybridConnection. This operation is
/// idempotent.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a HybridConnection.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<HybridConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, HybridConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a HybridConnection .
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the description for the specified HybridConnection.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<HybridConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorization rules for a HybridConnection.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or Updates an authorization rule for a HybridConnection
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='parameters'>
/// The authorization rule parameters
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, AuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a HybridConnection authorization rule
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// HybridConnection authorizationRule for a HybridConnection by name.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Primary and Secondary ConnectionStrings to the HybridConnection.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AccessKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Regenerates the Primary or Secondary ConnectionStrings to the
/// HybridConnection
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='hybridConnectionName'>
/// The hybrid connection name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate Auth Rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string hybridConnectionName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the HybridConnection within the namespace.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<HybridConnection>>> ListByNamespaceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorization rules for a HybridConnection.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// 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,
// MERCHANTABILITY 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.ComponentModel;
using Microsoft.PythonTools.Ipc.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Microsoft.PythonTools.Debugger {
// IMPORTANT:
// Names of all fields, commands and events must match the names in
// ptvsd/debugger.py and ptvsd/attach_server.py
internal static class LegacyDebuggerProtocol {
public static readonly Dictionary<string, Type> RegisteredTypes = CollectCommands();
private static Dictionary<string, Type> CollectCommands() {
Dictionary<string, Type> all = new Dictionary<string, Type>();
foreach (var type in typeof(LegacyDebuggerProtocol).GetNestedTypes()) {
if (type.IsSubclassOf(typeof(Request))) {
var command = type.GetField("Command");
if (command != null) {
all["request." + (string) command.GetRawConstantValue()] = type;
}
}
else if (type.IsSubclassOf(typeof(Event))) {
var name = type.GetField("Name");
if (name != null) {
all["event." + (string) name.GetRawConstantValue()] = type;
}
}
}
return all;
}
//////////////////////////////////////////////////////////////////////
/// Requests
//////////////////////////////////////////////////////////////////////
public sealed class StepIntoRequest : GenericRequest {
public const string Command = "legacyStepInto";
public override string command => Command;
public long threadId;
}
public sealed class StepOutRequest : GenericRequest {
public const string Command = "legacyStepOut";
public override string command => Command;
public long threadId;
}
public sealed class StepOverRequest : GenericRequest {
public const string Command = "legacyStepOver";
public override string command => Command;
public long threadId;
}
public sealed class BreakAllRequest : GenericRequest {
public const string Command = "legacyBreakAll";
public override string command => Command;
}
public sealed class SetBreakpointRequest : GenericRequest {
public const string Command = "legacySetBreakpoint";
public override string command => Command;
public LanguageKind language;
public int breakpointId;
public int breakpointLineNo;
public string breakpointFileName;
public BreakpointConditionKind conditionKind;
public string condition;
public BreakpointPassCountKind passCountKind;
public int passCount;
}
public sealed class RemoveBreakpointRequest : GenericRequest {
public const string Command = "legacyRemoveBreakpoint";
public override string command => Command;
public LanguageKind language;
public int breakpointId;
public int breakpointLineNo;
public string breakpointFileName;
}
public sealed class SetBreakpointConditionRequest : GenericRequest {
public const string Command = "legacySetBreakpointCondition";
public override string command => Command;
public int breakpointId;
public BreakpointConditionKind conditionKind;
public string condition;
}
public sealed class SetBreakpointPassCountRequest : GenericRequest {
public const string Command = "legacySetBreakpointPassCount";
public override string command => Command;
public int breakpointId;
public BreakpointPassCountKind passCountKind;
public int passCount;
}
public sealed class SetBreakpointHitCountRequest : GenericRequest {
public const string Command = "legacySetBreakpointHitCount";
public override string command => Command;
public int breakpointId;
public int hitCount;
}
public sealed class GetBreakpointHitCountRequest : Request<GetBreakpointHitCountResponse> {
public const string Command = "legacyGetBreakpointHitCount";
public override string command => Command;
public int breakpointId;
}
public sealed class GetBreakpointHitCountResponse : Response {
public int hitCount;
}
public sealed class ResumeAllRequest : GenericRequest {
public const string Command = "legacyResumeAll";
public override string command => Command;
}
public sealed class ResumeThreadRequest : GenericRequest {
public const string Command = "legacyResumeThread";
public override string command => Command;
public long threadId;
}
public sealed class AutoResumeThreadRequest : GenericRequest {
public const string Command = "legacyAutoResumeThread";
public override string command => Command;
public long threadId;
}
public sealed class ClearSteppingRequest : GenericRequest {
public const string Command = "legacyClearStepping";
public override string command => Command;
public long threadId;
}
public sealed class ExecuteTextRequest : GenericRequest {
public const string Command = "legacyExecuteText";
public override string command => Command;
public string text;
public int executionId;
public long threadId;
public int frameId;
public FrameKind frameKind;
public ReprKind reprKind;
public string moduleName;
public bool printResult;
}
public sealed class DetachRequest : GenericRequest {
public const string Command = "legacyDetach";
public override string command => Command;
}
public sealed class SetExceptionInfoRequest : GenericRequest {
public const string Command = "legacySetExceptionInfo";
public override string command => Command;
public int defaultBreakOnMode;
public ExceptionInfo[] breakOn;
}
public sealed class LastAckRequest : GenericRequest {
public const string Command = "legacyLastAck";
public override string command => Command;
}
public sealed class EnumThreadFramesRequest : GenericRequest {
public const string Command = "legacyGetThreadFrames";
public override string command => Command;
public long threadId;
}
public sealed class EnumChildrenRequest : GenericRequest {
public const string Command = "legacyEnumChildren";
public override string command => Command;
public string text;
public int executionId;
public long threadId;
public int frameId;
public FrameKind frameKind;
}
public sealed class SetLineNumberRequest : Request<SetLineNumberResponse> {
public const string Command = "legacySetLineNumber";
public override string command => Command;
public long threadId;
public int frameId;
public int lineNo;
}
public sealed class SetLineNumberResponse : Response {
public int result;
public long threadId;
public int newLineNo;
}
// This request is in response to a RequestHandlersEvent.
// Python process waits for this request after firing that event.
public sealed class SetExceptionHandlerInfoRequest : GenericRequest {
public const string Command = "legacySetExceptionHandlerInfo";
public override string command => Command;
public string fileName;
public ExceptionHandlerStatement[] statements;
}
public sealed class RemoteDebuggerAuthenticateRequest : Request<RemoteDebuggerAuthenticateResponse> {
public const string Command = "legacyRemoteDebuggerAuthenticate";
public override string command => Command;
public string debuggerName;
public int debuggerProtocolVersion;
public string clientSecret;
}
public sealed class RemoteDebuggerAuthenticateResponse : Response {
public bool accepted;
}
public sealed class RemoteDebuggerInfoRequest : Request<RemoteDebuggerInfoResponse> {
public const string Command = "legacyRemoteDebuggerInfo";
public override string command => Command;
}
public sealed class RemoteDebuggerInfoResponse : Response {
public int processId;
public string executable;
public string user;
public string pythonVersion; // maybe split into its components, right now it's just for display, it's never parsed
}
public sealed class RemoteDebuggerAttachRequest : Request<RemoteDebuggerAttachResponse> {
public const string Command = "legacyRemoteDebuggerAttach";
public override string command => Command;
public string debugOptions;
}
public sealed class RemoteDebuggerAttachResponse : Response {
public bool accepted;
public int processId;
public int pythonMajor;
public int pythonMinor;
public int pythonMicro;
}
public sealed class ListReplModulesRequest : Request<ListReplModulesResponse> {
public const string Command = "legacyListReplModules";
public override string command => Command;
}
public sealed class ListReplModulesResponse : Response {
public ModuleItem[] modules;
}
//////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////
public sealed class LocalConnectedEvent : Event {
public const string Name = "legacyLocalConnected";
public override string name => Name;
public string processGuid;
public int result;
}
public sealed class RemoteConnectedEvent : Event {
public const string Name = "legacyRemoteConnected";
public override string name => Name;
public string debuggerName;
public int debuggerProtocolVersion;
}
public sealed class DetachEvent : Event {
public const string Name = "legacyDetach";
public override string name => Name;
}
public sealed class LastEvent : Event {
public const string Name = "legacyLast";
public override string name => Name;
}
public sealed class RequestHandlersEvent : Event {
public const string Name = "legacyRequestHandlers";
public override string name => Name;
public string fileName;
}
public sealed class ExceptionEvent : Event {
public const string Name = "legacyException";
public override string name => Name;
public long threadId;
public Dictionary<string, string> data;
}
public sealed class BreakpointHitEvent : Event {
public const string Name = "legacyBreakpointHit";
public override string name => Name;
public int breakpointId;
public long threadId;
}
public sealed class AsyncBreakEvent : Event {
public const string Name = "legacyAsyncBreak";
public override string name => Name;
public long threadId;
}
public sealed class ThreadCreateEvent : Event {
public const string Name = "legacyThreadCreate";
public override string name => Name;
public long threadId;
}
public sealed class ThreadExitEvent : Event {
public const string Name = "legacyThreadExit";
public override string name => Name;
public long threadId;
}
public sealed class ModuleLoadEvent : Event {
public const string Name = "legacyModuleLoad";
public override string name => Name;
public int moduleId;
public string moduleFileName;
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public string moduleName;
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore)]
public bool isStdLib;
}
public sealed class StepDoneEvent : Event {
public const string Name = "legacyStepDone";
public override string name => Name;
public long threadId;
}
public sealed class ProcessLoadEvent : Event {
public const string Name = "legacyProcessLoad";
public override string name => Name;
public long threadId;
}
public sealed class BreakpointSetEvent : Event {
public const string Name = "legacyBreakpointSet";
public override string name => Name;
public int breakpointId;
}
public sealed class BreakpointFailedEvent : Event {
public const string Name = "legacyBreakpointFailed";
public override string name => Name;
public int breakpointId;
}
public sealed class DebuggerOutputEvent : Event {
public const string Name = "legacyDebuggerOutput";
public override string name => Name;
public long threadId;
public string output;
public OutputChannel channel;
// Legacy fallback in case channel is not specified. Should only be used for serialization.
[Obsolete]
public bool? isStdOut {
get {
switch (channel) {
case OutputChannel.stdout:
return true;
case OutputChannel.stderr:
return false;
default:
return null;
}
}
set {
switch (value) {
case true:
channel = OutputChannel.stdout;
break;
case false:
channel = OutputChannel.stderr;
break;
case null:
throw new ArgumentNullException("value");
}
}
}
}
public sealed class ExecutionResultEvent : Event {
public const string Name = "legacyExecutionResult";
public override string name => Name;
public int executionId;
public PythonObject obj;
}
public sealed class ExecutionExceptionEvent : Event {
public const string Name = "legacyExecutionException";
public override string name => Name;
public int executionId;
public string exceptionText;
}
public sealed class EnumChildrenEvent : Event {
public const string Name = "legacyEnumChildrenResult";
public override string name => Name;
public int executionId;
public EnumChildrenItem[] children;
}
public sealed class ThreadFrameListEvent : Event {
public const string Name = "legacyThreadFrameList";
public override string name => Name;
public long threadId;
public string threadName;
public ThreadFrameItem[] threadFrames;
}
public sealed class ModulesChangedEvent : Event {
public const string Name = "legacyModulesChanged";
public override string name => Name;
}
//////////////////////////////////////////////////////////////////////
/// Protocol types
//////////////////////////////////////////////////////////////////////
[Flags]
public enum EvaluationResultFlags {
None = 0,
Expandable = 1,
MethodCall = 2,
SideEffects = 4,
Raw = 8,
HasRawRepr = 16,
}
public enum LanguageKind {
Python = 0,
Django = 1,
}
public enum FrameKind {
None = 0,
Python = 1,
Django = 2,
}
public enum ReprKind {
Normal = 0,
Raw = 1,
RawLen = 2,
}
public enum BreakpointConditionKind {
Always = 0,
WhenTrue = 1,
WhenChanged = 2,
}
public enum BreakpointPassCountKind {
Always = 0,
Every = 1,
WhenEqual = 2,
WhenEqualOrGreater = 3,
}
[JsonConverter(typeof(StringEnumConverter))]
public enum OutputChannel {
debug,
stdout,
stderr,
}
public sealed class PythonObject {
public string objRepr;
public string hexRepr;
public string typeName;
public long length;
public EvaluationResultFlags flags;
}
public sealed class ExceptionInfo {
public string name;
public int mode;
}
public sealed class EnumChildrenItem {
public string name;
public string expression;
public PythonObject obj;
}
public sealed class ThreadFrameVariable {
public string name;
public PythonObject obj;
}
public sealed class ThreadFrameItem {
public int startLine, endLine, lineNo, argCount;
public string frameName, fileName;
public FrameKind frameKind;
public string djangoSourceFile; // optional, only if frame kind is django
public int djangoSourceLine; // optional, only if frame kind is django
public ThreadFrameVariable[] variables;
}
public sealed class ExceptionHandlerStatement {
public int lineStart;
public int lineEnd;
public string[] expressions;
}
public sealed class ModuleItem {
public string name;
public string fileName;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/rpc/cancellation_reason_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.Booking.RPC {
public static partial class CancellationReasonSvc
{
static readonly string __ServiceName = "holms.types.booking.rpc.CancellationReasonSvc";
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.RPC.CancellationReasonSvcEnumResponse> __Marshaller_CancellationReasonSvcEnumResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.RPC.CancellationReasonSvcEnumResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.Uuid> __Marshaller_Uuid = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.Uuid.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.CancellationReason> __Marshaller_CancellationReason = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.CancellationReason.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.ServerActionConfirmation> __Marshaller_ServerActionConfirmation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.ServerActionConfirmation.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Booking.RPC.CancellationReasonSvcEnumResponse> __Method_All = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Booking.RPC.CancellationReasonSvcEnumResponse>(
grpc::MethodType.Unary,
__ServiceName,
"All",
__Marshaller_Empty,
__Marshaller_CancellationReasonSvcEnumResponse);
static readonly grpc::Method<global::HOLMS.Types.Primitive.Uuid, global::HOLMS.Types.Booking.CancellationReason> __Method_GetById = new grpc::Method<global::HOLMS.Types.Primitive.Uuid, global::HOLMS.Types.Booking.CancellationReason>(
grpc::MethodType.Unary,
__ServiceName,
"GetById",
__Marshaller_Uuid,
__Marshaller_CancellationReason);
static readonly grpc::Method<global::HOLMS.Types.Booking.CancellationReason, global::HOLMS.Types.Booking.CancellationReason> __Method_Create = new grpc::Method<global::HOLMS.Types.Booking.CancellationReason, global::HOLMS.Types.Booking.CancellationReason>(
grpc::MethodType.Unary,
__ServiceName,
"Create",
__Marshaller_CancellationReason,
__Marshaller_CancellationReason);
static readonly grpc::Method<global::HOLMS.Types.Booking.CancellationReason, global::HOLMS.Types.Booking.CancellationReason> __Method_Update = new grpc::Method<global::HOLMS.Types.Booking.CancellationReason, global::HOLMS.Types.Booking.CancellationReason>(
grpc::MethodType.Unary,
__ServiceName,
"Update",
__Marshaller_CancellationReason,
__Marshaller_CancellationReason);
static readonly grpc::Method<global::HOLMS.Types.Booking.CancellationReason, global::HOLMS.Types.Primitive.ServerActionConfirmation> __Method_Delete = new grpc::Method<global::HOLMS.Types.Booking.CancellationReason, global::HOLMS.Types.Primitive.ServerActionConfirmation>(
grpc::MethodType.Unary,
__ServiceName,
"Delete",
__Marshaller_CancellationReason,
__Marshaller_ServerActionConfirmation);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.Booking.RPC.CancellationReasonSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of CancellationReasonSvc</summary>
public abstract partial class CancellationReasonSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.CancellationReasonSvcEnumResponse> All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.CancellationReason> GetById(global::HOLMS.Types.Primitive.Uuid request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.CancellationReason> Create(global::HOLMS.Types.Booking.CancellationReason request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.CancellationReason> Update(global::HOLMS.Types.Booking.CancellationReason request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Primitive.ServerActionConfirmation> Delete(global::HOLMS.Types.Booking.CancellationReason request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for CancellationReasonSvc</summary>
public partial class CancellationReasonSvcClient : grpc::ClientBase<CancellationReasonSvcClient>
{
/// <summary>Creates a new client for CancellationReasonSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public CancellationReasonSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for CancellationReasonSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public CancellationReasonSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected CancellationReasonSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected CancellationReasonSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.Booking.RPC.CancellationReasonSvcEnumResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return All(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.RPC.CancellationReasonSvcEnumResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.CancellationReasonSvcEnumResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.CancellationReasonSvcEnumResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request);
}
public virtual global::HOLMS.Types.Booking.CancellationReason GetById(global::HOLMS.Types.Primitive.Uuid request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.CancellationReason GetById(global::HOLMS.Types.Primitive.Uuid request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.CancellationReason> GetByIdAsync(global::HOLMS.Types.Primitive.Uuid request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.CancellationReason> GetByIdAsync(global::HOLMS.Types.Primitive.Uuid request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request);
}
public virtual global::HOLMS.Types.Booking.CancellationReason Create(global::HOLMS.Types.Booking.CancellationReason request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.CancellationReason Create(global::HOLMS.Types.Booking.CancellationReason request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.CancellationReason> CreateAsync(global::HOLMS.Types.Booking.CancellationReason request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.CancellationReason> CreateAsync(global::HOLMS.Types.Booking.CancellationReason request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request);
}
public virtual global::HOLMS.Types.Booking.CancellationReason Update(global::HOLMS.Types.Booking.CancellationReason request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.CancellationReason Update(global::HOLMS.Types.Booking.CancellationReason request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.CancellationReason> UpdateAsync(global::HOLMS.Types.Booking.CancellationReason request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.CancellationReason> UpdateAsync(global::HOLMS.Types.Booking.CancellationReason request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request);
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.Booking.CancellationReason request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.Booking.CancellationReason request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.Booking.CancellationReason request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.Booking.CancellationReason request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override CancellationReasonSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new CancellationReasonSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(CancellationReasonSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_All, serviceImpl.All)
.AddMethod(__Method_GetById, serviceImpl.GetById)
.AddMethod(__Method_Create, serviceImpl.Create)
.AddMethod(__Method_Update, serviceImpl.Update)
.AddMethod(__Method_Delete, serviceImpl.Delete).Build();
}
}
}
#endregion
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using NUnit.Framework.Internal;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Development;
using osu.Framework.Extensions;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Platform;
using osu.Framework.Testing.Drawables;
using osu.Framework.Testing.Drawables.Steps;
using osu.Framework.Timing;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
using Logger = osu.Framework.Logging.Logger;
namespace osu.Framework.Testing
{
[Cached]
public class TestBrowser : KeyBindingContainer<TestBrowserAction>, IKeyBindingHandler<TestBrowserAction>, IHandleGlobalKeyboardInput
{
public TestScene CurrentTest { get; private set; }
private BasicTextBox searchTextBox;
private SearchContainer<TestGroupButton> leftFlowContainer;
private Container testContentContainer;
private Container compilingNotice;
public readonly List<Type> TestTypes = new List<Type>();
private ConfigManager<TestBrowserSetting> config;
private bool interactive;
private readonly List<Assembly> assemblies;
/// <summary>
/// Creates a new TestBrowser that displays the TestCases of every assembly that start with either "osu" or the specified namespace (if it isn't null)
/// </summary>
/// <param name="assemblyNamespace">Assembly prefix which is used to match assemblies whose tests should be displayed</param>
public TestBrowser(string assemblyNamespace = null)
{
assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(n =>
{
Debug.Assert(n.FullName != null);
return n.FullName.StartsWith("osu", StringComparison.Ordinal) || assemblyNamespace != null && n.FullName.StartsWith(assemblyNamespace, StringComparison.Ordinal);
}).ToList();
//we want to build the lists here because we're interested in the assembly we were *created* on.
foreach (Assembly asm in assemblies.ToList())
{
var tests = asm.GetLoadableTypes().Where(isValidVisualTest).ToList();
if (!tests.Any())
{
assemblies.Remove(asm);
continue;
}
foreach (Type type in tests)
TestTypes.Add(type);
}
TestTypes.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
}
private bool isValidVisualTest(Type t) => t.IsSubclassOf(typeof(TestScene)) && !t.IsAbstract && t.IsPublic && !t.GetCustomAttributes<HeadlessTestAttribute>().Any();
private void updateList(ValueChangedEvent<Assembly> args)
{
leftFlowContainer.Clear();
//Add buttons for each TestCase.
string namespacePrefix = TestTypes.Select(t => t.Namespace).GetCommonPrefix();
leftFlowContainer.AddRange(TestTypes.Where(t => t.Assembly == args.NewValue)
.GroupBy(
t =>
{
string group = t.Namespace?.AsSpan(namespacePrefix.Length).TrimStart('.').ToString();
return string.IsNullOrWhiteSpace(group) ? "Ungrouped" : group;
},
t => t,
(group, types) => new TestGroup { Name = group, TestTypes = types.ToArray() }
).OrderBy(g => g.Name)
.Select(t => new TestGroupButton(type => LoadTest(type), t)));
}
internal readonly BindableDouble PlaybackRate = new BindableDouble(1) { MinValue = 0, MaxValue = 2, Default = 1 };
internal readonly Bindable<Assembly> Assembly = new Bindable<Assembly>();
internal readonly Bindable<bool> RunAllSteps = new Bindable<bool>();
internal readonly Bindable<RecordState> RecordState = new Bindable<RecordState>();
internal readonly BindableInt CurrentFrame = new BindableInt { MinValue = 0, MaxValue = 0 };
private TestBrowserToolbar toolbar;
private Container leftContainer;
private Container mainContainer;
private const float test_list_width = 200;
private Action exit;
private readonly BindableDouble audioRateAdjust = new BindableDouble(1);
[BackgroundDependencyLoader]
private void load(Storage storage, GameHost host, AudioManager audio)
{
interactive = host.Window != null;
config = new TestBrowserConfig(storage);
if (host.CanExit)
exit = host.Exit;
else if (host.CanSuspendToBackground)
exit = () => host.SuspendToBackground();
audio.AddAdjustment(AdjustableProperty.Frequency, audioRateAdjust);
var rateAdjustClock = new StopwatchClock(true);
var framedClock = new FramedClock(rateAdjustClock);
Children = new Drawable[]
{
mainContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Left = test_list_width },
Children = new Drawable[]
{
new SafeAreaContainer
{
SafeAreaOverrideEdges = Edges.Right | Edges.Bottom,
RelativeSizeAxes = Axes.Both,
Child = testContentContainer = new Container
{
Clock = framedClock,
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = 50 },
Child = compilingNotice = new Container
{
Alpha = 0,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Masking = true,
Depth = float.MinValue,
CornerRadius = 5,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
},
new SpriteText
{
Font = FrameworkFont.Regular.With(size: 30),
Text = @"Compiling new version..."
}
},
}
}
},
toolbar = new TestBrowserToolbar
{
RelativeSizeAxes = Axes.X,
Height = 50,
},
}
},
leftContainer = new Container
{
RelativeSizeAxes = Axes.Y,
Size = new Vector2(test_list_width, 1),
Masking = true,
Children = new Drawable[]
{
new SafeAreaContainer
{
SafeAreaOverrideEdges = Edges.Left | Edges.Top | Edges.Bottom,
RelativeSizeAxes = Axes.Both,
Child = new Box
{
Colour = FrameworkColour.GreenDark,
RelativeSizeAxes = Axes.Both
}
},
new FillFlowContainer
{
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
searchTextBox = new TestBrowserTextBox
{
Height = 25,
RelativeSizeAxes = Axes.X,
PlaceholderText = "type to search",
Depth = -1,
},
new BasicScrollContainer
{
RelativeSizeAxes = Axes.Both,
Masking = false,
Child = leftFlowContainer = new SearchContainer<TestGroupButton>
{
AllowNonContiguousMatching = true,
Padding = new MarginPadding { Top = 3, Bottom = 20 },
Direction = FillDirection.Vertical,
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
}
}
}
}
}
},
};
searchTextBox.OnCommit += delegate
{
var firstTest = leftFlowContainer.Where(b => b.IsPresent).SelectMany(b => b.FilterableChildren).OfType<TestSubButton>()
.FirstOrDefault(b => b.MatchingFilter)?.TestType;
if (firstTest != null)
LoadTest(firstTest);
};
searchTextBox.Current.ValueChanged += e => leftFlowContainer.SearchTerm = e.NewValue;
if (RuntimeInfo.IsDesktop)
HotReloadCallbackReceiver.CompilationFinished += compileFinished;
foreach (Assembly asm in assemblies)
toolbar.AddAssembly(asm.GetName().Name, asm);
Assembly.BindValueChanged(updateList);
RunAllSteps.BindValueChanged(v => runTests(null));
PlaybackRate.BindValueChanged(e =>
{
rateAdjustClock.Rate = e.NewValue;
audioRateAdjust.Value = e.NewValue;
}, true);
}
private void compileFinished(Type[] updatedTypes) => Schedule(() =>
{
compilingNotice.FadeOut(800, Easing.InQuint);
compilingNotice.FadeColour(Color4.YellowGreen, 100);
if (CurrentTest == null)
return;
try
{
LoadTest(CurrentTest.GetType(), isDynamicLoad: true);
}
catch (Exception e)
{
compileFailed(e);
}
});
private void compileFailed(Exception ex) => Schedule(() =>
{
Logger.Error(ex, "Error with dynamic compilation!");
compilingNotice.FadeIn(100, Easing.OutQuint).Then().FadeOut(800, Easing.InQuint);
compilingNotice.FadeColour(Color4.Red, 100);
});
protected override void LoadComplete()
{
base.LoadComplete();
if (CurrentTest == null)
{
string lastTest = config.Get<string>(TestBrowserSetting.LastTest);
var foundTest = TestTypes.Find(t => t.FullName == lastTest);
LoadTest(foundTest);
}
}
private void toggleTestList()
{
if (leftContainer.Width > 0)
{
leftContainer.Width = 0;
mainContainer.Padding = new MarginPadding();
}
else
{
leftContainer.Width = test_list_width;
mainContainer.Padding = new MarginPadding { Left = test_list_width };
}
}
protected override bool OnKeyDown(KeyDownEvent e)
{
if (!e.Repeat)
{
switch (e.Key)
{
case Key.Escape:
exit?.Invoke();
return true;
}
}
return base.OnKeyDown(e);
}
public override IEnumerable<IKeyBinding> DefaultKeyBindings => new[]
{
new KeyBinding(new[] { InputKey.Control, InputKey.F }, TestBrowserAction.Search),
new KeyBinding(new[] { InputKey.Control, InputKey.R }, TestBrowserAction.Reload), // for macOS
new KeyBinding(new[] { InputKey.Super, InputKey.F }, TestBrowserAction.Search), // for macOS
new KeyBinding(new[] { InputKey.Super, InputKey.R }, TestBrowserAction.Reload), // for macOS
new KeyBinding(new[] { InputKey.Control, InputKey.H }, TestBrowserAction.ToggleTestList),
};
public bool OnPressed(KeyBindingPressEvent<TestBrowserAction> e)
{
if (e.Repeat)
return false;
switch (e.Action)
{
case TestBrowserAction.Search:
if (leftContainer.Width == 0) toggleTestList();
GetContainingInputManager().ChangeFocus(searchTextBox);
return true;
case TestBrowserAction.Reload:
LoadTest(CurrentTest.GetType());
return true;
case TestBrowserAction.ToggleTestList:
toggleTestList();
return true;
}
return false;
}
public void OnReleased(KeyBindingReleaseEvent<TestBrowserAction> e)
{
}
public void LoadTest(Type testType = null, Action onCompletion = null, bool isDynamicLoad = false)
{
if (CurrentTest?.Parent != null)
{
testContentContainer.Remove(CurrentTest.Parent);
CurrentTest.Dispose();
}
CurrentTest = null;
if (testType == null && TestTypes.Count > 0)
testType = TestTypes[0];
config.SetValue(TestBrowserSetting.LastTest, testType?.FullName ?? string.Empty);
if (testType == null)
return;
var newTest = (TestScene)Activator.CreateInstance(testType);
Debug.Assert(newTest != null);
Assembly.Value = testType.Assembly;
CurrentTest = newTest;
CurrentTest.OnLoadComplete += _ => Schedule(() => finishLoad(newTest, onCompletion));
updateButtons();
resetRecording();
testContentContainer.Add(new ErrorCatchingDelayedLoadWrapper(CurrentTest, isDynamicLoad)
{
OnCaughtError = compileFailed
});
}
private void resetRecording()
{
CurrentFrame.Value = 0;
if (RecordState.Value == Testing.RecordState.Stopped)
RecordState.Value = Testing.RecordState.Normal;
}
private void finishLoad(TestScene newTest, Action onCompletion)
{
if (CurrentTest != newTest)
{
// There could have been multiple loads fired after us. In such a case we want to silently remove ourselves.
testContentContainer.Remove(newTest.Parent);
return;
}
updateButtons();
bool hadTestAttributeTest = false;
foreach (var m in newTest.GetType().GetMethods())
{
string name = m.Name;
if (name == nameof(TestScene.TestConstructor) || m.GetCustomAttribute(typeof(IgnoreAttribute), false) != null)
continue;
if (name.StartsWith("Test", StringComparison.Ordinal))
name = name.Substring(4);
int runCount = 1;
if (m.GetCustomAttribute(typeof(RepeatAttribute), false) != null)
{
object count = m.GetCustomAttributesData().Single(a => a.AttributeType == typeof(RepeatAttribute)).ConstructorArguments.Single().Value;
Debug.Assert(count != null);
runCount += (int)count;
}
for (int i = 0; i < runCount; i++)
{
string repeatSuffix = i > 0 ? $" ({i + 1})" : string.Empty;
var methodWrapper = new MethodWrapper(m.GetType(), m);
if (methodWrapper.GetCustomAttributes<TestAttribute>(false).SingleOrDefault() != null)
{
var parameters = m.GetParameters();
if (parameters.Length > 0)
{
var valueMatrix = new List<List<object>>();
foreach (var p in methodWrapper.GetParameters())
{
var valueAttrib = p.GetCustomAttributes<ValuesAttribute>(false).SingleOrDefault();
if (valueAttrib == null)
throw new ArgumentException($"Parameter is present on a {nameof(TestAttribute)} method without values specification.", p.ParameterInfo.Name);
List<object> choices = new List<object>();
foreach (object choice in valueAttrib.GetData(p))
choices.Add(choice);
valueMatrix.Add(choices);
}
foreach (var combination in valueMatrix.CartesianProduct())
{
hadTestAttributeTest = true;
CurrentTest.AddLabel($"{name}({string.Join(", ", combination)}){repeatSuffix}");
handleTestMethod(m, combination.ToArray());
}
}
else
{
hadTestAttributeTest = true;
CurrentTest.AddLabel($"{name}{repeatSuffix}");
handleTestMethod(m);
}
}
foreach (var tc in m.GetCustomAttributes(typeof(TestCaseAttribute), false).OfType<TestCaseAttribute>())
{
hadTestAttributeTest = true;
CurrentTest.AddLabel($"{name}({string.Join(", ", tc.Arguments)}){repeatSuffix}");
handleTestMethod(m, tc.Arguments);
}
foreach (var tcs in m.GetCustomAttributes(typeof(TestCaseSourceAttribute), false).OfType<TestCaseSourceAttribute>())
{
IEnumerable sourceValue = getTestCaseSourceValue(m, tcs);
if (sourceValue == null)
{
Debug.Assert(tcs.SourceName != null);
throw new InvalidOperationException($"The value of the source member {tcs.SourceName} must be non-null.");
}
foreach (object argument in sourceValue)
{
hadTestAttributeTest = true;
if (argument is IEnumerable argumentsEnumerable)
{
object[] arguments = argumentsEnumerable.Cast<object>().ToArray();
CurrentTest.AddLabel($"{name}({string.Join(", ", arguments)}){repeatSuffix}");
handleTestMethod(m, arguments);
}
else
{
CurrentTest.AddLabel($"{name}({argument}){repeatSuffix}");
handleTestMethod(m, argument);
}
}
}
}
}
// even if no [Test] or [TestCase] methods were found, [SetUp] steps should be added.
if (!hadTestAttributeTest)
addSetUpSteps();
runTests(onCompletion);
updateButtons();
void addSetUpSteps()
{
var setUpMethods = ReflectionUtils.GetMethodsWithAttribute(newTest.GetType(), typeof(SetUpAttribute), true)
.Where(m => m.Name != nameof(TestScene.SetUpTestForNUnit));
if (setUpMethods.Any())
{
CurrentTest.AddStep(new SingleStepButton(true)
{
Text = "[SetUp]",
LightColour = Color4.Teal,
Action = () => setUpMethods.ForEach(s => s.Invoke(CurrentTest, null))
});
}
CurrentTest.RunSetUpSteps();
}
void handleTestMethod(MethodInfo methodInfo, params object[] arguments)
{
addSetUpSteps();
methodInfo.Invoke(CurrentTest, arguments);
CurrentTest.RunTearDownSteps();
}
}
private static IEnumerable getTestCaseSourceValue(MethodInfo testMethod, TestCaseSourceAttribute tcs)
{
var sourceDeclaringType = tcs.SourceType ?? testMethod.DeclaringType;
Debug.Assert(sourceDeclaringType != null);
if (tcs.SourceType != null && tcs.SourceName == null)
return (IEnumerable)Activator.CreateInstance(tcs.SourceType);
var sourceMembers = sourceDeclaringType.AsNonNull().GetMember(tcs.SourceName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
if (sourceMembers.Length == 0)
throw new InvalidOperationException($"No static member with the name of {tcs.SourceName} exists in {sourceDeclaringType} or its base types.");
if (sourceMembers.Length > 1)
throw new NotSupportedException($"There are multiple members with the same source name ({tcs.SourceName}) (e.g. method overloads).");
var sourceMember = sourceMembers.Single();
switch (sourceMember)
{
case FieldInfo sf:
return (IEnumerable)sf.GetValue(null);
case PropertyInfo sp:
if (!sp.CanRead)
throw new InvalidOperationException($"The source property {sp.Name} in {sp.DeclaringType.ReadableName()} must have a getter.");
return (IEnumerable)sp.GetValue(null);
case MethodInfo sm:
int methodParamsLength = sm.GetParameters().Length;
if (methodParamsLength != (tcs.MethodParams?.Length ?? 0))
throw new InvalidOperationException($"The given source method parameters count doesn't match the method. (attribute has {tcs.MethodParams?.Length ?? 0}, method has {methodParamsLength})");
return (IEnumerable)sm.Invoke(null, tcs.MethodParams);
default:
throw new NotSupportedException($"{sourceMember.MemberType} is not a supported member type for {nameof(TestCaseSourceAttribute)} (must be static field, property or method)");
}
}
private void runTests(Action onCompletion)
{
int actualStepCount = 0;
CurrentTest.RunAllSteps(onCompletion, e => Logger.Log($@"Error on step: {e}"), s =>
{
if (!interactive || RunAllSteps.Value)
return false;
if (actualStepCount > 0)
// stop once one actual step has been run.
return true;
if (!s.IsSetupStep && !(s is LabelStep))
actualStepCount++;
return false;
});
}
private void updateButtons()
{
foreach (var b in leftFlowContainer.Children)
b.Current = CurrentTest.GetType();
}
private class ErrorCatchingDelayedLoadWrapper : DelayedLoadWrapper
{
private readonly bool catchErrors;
private bool hasCaught;
public Action<Exception> OnCaughtError;
public ErrorCatchingDelayedLoadWrapper(Drawable content, bool catchErrors)
: base(content, 0)
{
this.catchErrors = catchErrors;
}
public override bool UpdateSubTree()
{
try
{
return base.UpdateSubTree();
}
catch (Exception e)
{
if (!catchErrors)
throw;
// without this we will enter an infinite loading loop (DelayedLoadWrapper will see the child removed below and retry).
hasCaught = true;
OnCaughtError?.Invoke(e);
RemoveInternal(Content);
}
return false;
}
protected override bool ShouldLoadContent => !hasCaught;
}
private class TestBrowserTextBox : BasicTextBox
{
protected override float LeftRightPadding => TestButtonBase.LEFT_TEXT_PADDING;
public TestBrowserTextBox()
{
TextFlow.Height = 0.75f;
}
}
}
internal enum RecordState
{
/// <summary>
/// The game is playing back normally.
/// </summary>
Normal,
/// <summary>
/// Drawn game frames are currently being recorded.
/// </summary>
Recording,
/// <summary>
/// The default game playback is stopped, recorded frames are being played back.
/// </summary>
Stopped
}
public enum TestBrowserAction
{
ToggleTestList,
Reload,
Search
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable sorted dictionary implementation.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableDictionaryDebuggerProxy<,>))]
public sealed partial class ImmutableSortedDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, ISortKeyCollection<TKey>, IDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// An empty sorted dictionary with default sort and equality comparers.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly ImmutableSortedDictionary<TKey, TValue> Empty = new ImmutableSortedDictionary<TKey, TValue>();
/// <summary>
/// The root node of the AVL tree that stores this map.
/// </summary>
private readonly Node _root;
/// <summary>
/// The number of elements in the set.
/// </summary>
private readonly int _count;
/// <summary>
/// The comparer used to sort keys in this map.
/// </summary>
private readonly IComparer<TKey> _keyComparer;
/// <summary>
/// The comparer used to detect equivalent values in this map.
/// </summary>
private readonly IEqualityComparer<TValue> _valueComparer;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
internal ImmutableSortedDictionary(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null)
{
_keyComparer = keyComparer ?? Comparer<TKey>.Default;
_valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
_root = Node.EmptyNode;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="root">The root of the tree containing the contents of the map.</param>
/// <param name="count">The number of elements in this map.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
private ImmutableSortedDictionary(Node root, int count, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(root, nameof(root));
Requires.Range(count >= 0, nameof(count));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
root.Freeze();
_root = root;
_count = count;
_keyComparer = keyComparer;
_valueComparer = valueComparer;
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public ImmutableSortedDictionary<TKey, TValue> Clear()
{
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>().IsEmpty);
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>().KeyComparer == ((ISortKeyCollection<TKey>)this).KeyComparer);
return _root.IsEmpty ? this : Empty.WithComparers(_keyComparer, _valueComparer);
}
#region IImmutableMap<TKey, TValue> Properties
/// <summary>
/// Gets the value comparer used to determine whether values are equal.
/// </summary>
public IEqualityComparer<TValue> ValueComparer
{
get { return _valueComparer; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool IsEmpty
{
get { return _root.IsEmpty; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public IEnumerable<TKey> Keys
{
get { return _root.Keys; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public IEnumerable<TValue> Values
{
get { return _root.Values; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear()
{
return this.Clear();
}
#endregion
#region IDictionary<TKey, TValue> Properties
/// <summary>
/// Gets the keys.
/// </summary>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return new KeysCollectionAccessor<TKey, TValue>(this); }
}
/// <summary>
/// Gets the values.
/// </summary>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return new ValuesCollectionAccessor<TKey, TValue>(this); }
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Properties
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
#endregion
#region ISortKeyCollection<TKey> Properties
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public IComparer<TKey> KeyComparer
{
get { return _keyComparer; }
}
#endregion
/// <summary>
/// Gets the root node (for testing purposes).
/// </summary>
internal Node Root
{
get { return _root; }
}
#region IImmutableMap<TKey, TValue> Indexers
/// <summary>
/// Gets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
public TValue this[TKey key]
{
get
{
Requires.NotNullAllowStructs(key, nameof(key));
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException();
}
}
#endregion
/// <summary>
/// Gets or sets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get { return this[key]; }
set { throw new NotSupportedException(); }
}
#region Public methods
/// <summary>
/// Creates a collection with the same contents as this collection that
/// can be efficiently mutated across multiple operations using standard
/// mutable interfaces.
/// </summary>
/// <remarks>
/// This is an O(1) operation and results in only a single (small) memory allocation.
/// The mutable collection that is returned is *not* thread-safe.
/// </remarks>
[Pure]
public Builder ToBuilder()
{
// We must not cache the instance created here and return it to various callers.
// Those who request a mutable collection must get references to the collection
// that version independently of each other.
return new Builder(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> Add(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
bool mutated;
var result = _root.Add(key, value, _keyComparer, _valueComparer, out mutated);
return this.Wrap(result, _count + 1);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
Contract.Ensures(!Contract.Result<ImmutableSortedDictionary<TKey, TValue>>().IsEmpty);
bool replacedExistingValue, mutated;
var result = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated);
return this.Wrap(result, replacedExistingValue ? _count : _count + 1);
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public ImmutableSortedDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, nameof(items));
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return this.AddRange(items, overwriteOnCollision: true, avoidToSortedMap: false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public ImmutableSortedDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, nameof(items));
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
return this.AddRange(items, overwriteOnCollision: false, avoidToSortedMap: false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> Remove(TKey value)
{
Requires.NotNullAllowStructs(value, nameof(value));
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
bool mutated;
var result = _root.Remove(value, _keyComparer, out mutated);
return this.Wrap(result, _count - 1);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, nameof(keys));
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
var result = _root;
int count = _count;
foreach (TKey key in keys)
{
bool mutated;
var newResult = result.Remove(key, _keyComparer, out mutated);
if (mutated)
{
result = newResult;
count--;
}
}
return this.Wrap(result, count);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> WithComparers(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>().IsEmpty == this.IsEmpty);
if (keyComparer == null)
{
keyComparer = Comparer<TKey>.Default;
}
if (valueComparer == null)
{
valueComparer = EqualityComparer<TValue>.Default;
}
if (keyComparer == _keyComparer)
{
if (valueComparer == _valueComparer)
{
return this;
}
else
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
return new ImmutableSortedDictionary<TKey, TValue>(_root, _count, _keyComparer, valueComparer);
}
}
else
{
// A new key comparer means the whole tree structure could change. We must build a new one.
var result = new ImmutableSortedDictionary<TKey, TValue>(Node.EmptyNode, 0, keyComparer, valueComparer);
result = result.AddRange(this, overwriteOnCollision: false, avoidToSortedMap: true);
return result;
}
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> WithComparers(IComparer<TKey> keyComparer)
{
return this.WithComparers(keyComparer, _valueComparer);
}
/// <summary>
/// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
return _root.ContainsValue(value, _valueComparer);
}
#endregion
#region IImmutableDictionary<TKey, TValue> Methods
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
return this.Add(key, value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
{
return this.SetItem(key, value);
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return this.SetItems(items);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
return this.AddRange(pairs);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
{
return this.RemoveRange(keys);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key)
{
return this.Remove(key);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool ContainsKey(TKey key)
{
Requires.NotNullAllowStructs(key, nameof(key));
return _root.ContainsKey(key, _keyComparer);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool Contains(KeyValuePair<TKey, TValue> pair)
{
return _root.Contains(pair, _keyComparer, _valueComparer);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
return _root.TryGetValue(key, _keyComparer, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, nameof(equalKey));
return _root.TryGetKey(equalKey, _keyComparer, out actualKey);
}
#endregion
#region IDictionary<TKey, TValue> Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.
/// </exception>
/// <exception cref="NotSupportedException">
/// The <see cref="IDictionary{TKey, TValue}"/> is read-only.
/// </exception>
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
/// <exception cref="NotSupportedException">
/// The <see cref="IDictionary{TKey, TValue}"/> is read-only.
/// </exception>
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException();
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Methods
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex));
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Keys
{
get { return new KeysCollectionAccessor<TKey, TValue>(this); }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Values
{
get { return new ValuesCollectionAccessor<TKey, TValue>(this); }
}
#endregion
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Clears this instance.
/// </summary>
/// <exception cref="System.NotSupportedException"></exception>
void IDictionary.Clear()
{
throw new NotSupportedException();
}
#endregion
#region ICollection Methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int index)
{
_root.CopyTo(array, index, this.Count);
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
// This is immutable, so it is always thread-safe.
return true;
}
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage]
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage]
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return _root.GetEnumerator();
}
/// <summary>
/// Creates a new sorted set wrapper for a node tree.
/// </summary>
/// <param name="root">The root of the collection.</param>
/// <param name="count">The number of elements in the map.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <param name="valueComparer">The value comparer to use for the map.</param>
/// <returns>The immutable sorted set instance.</returns>
[Pure]
private static ImmutableSortedDictionary<TKey, TValue> Wrap(Node root, int count, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
return root.IsEmpty
? Empty.WithComparers(keyComparer, valueComparer)
: new ImmutableSortedDictionary<TKey, TValue>(root, count, keyComparer, valueComparer);
}
/// <summary>
/// Attempts to discover an <see cref="ImmutableSortedDictionary{TKey, TValue}"/> instance beneath some enumerable sequence
/// if one exists.
/// </summary>
/// <param name="sequence">The sequence that may have come from an immutable map.</param>
/// <param name="other">Receives the concrete <see cref="ImmutableSortedDictionary{TKey, TValue}"/> typed value if one can be found.</param>
/// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns>
private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, out ImmutableSortedDictionary<TKey, TValue> other)
{
other = sequence as ImmutableSortedDictionary<TKey, TValue>;
if (other != null)
{
return true;
}
var builder = sequence as Builder;
if (builder != null)
{
other = builder.ToImmutable();
return true;
}
return false;
}
/// <summary>
/// Bulk adds entries to the map.
/// </summary>
/// <param name="items">The entries to add.</param>
/// <param name="overwriteOnCollision"><c>true</c> to allow the <paramref name="items"/> sequence to include duplicate keys and let the last one win; <c>false</c> to throw on collisions.</param>
/// <param name="avoidToSortedMap"><c>true</c> when being called from <see cref="WithComparers(IComparer{TKey}, IEqualityComparer{TValue})"/> to avoid <see cref="T:System.StackOverflowException"/>.</param>
[Pure]
private ImmutableSortedDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items, bool overwriteOnCollision, bool avoidToSortedMap)
{
Requires.NotNull(items, nameof(items));
Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
// Some optimizations may apply if we're an empty set.
if (this.IsEmpty && !avoidToSortedMap)
{
return this.FillFromEmpty(items, overwriteOnCollision);
}
// Let's not implement in terms of ImmutableSortedMap.Add so that we're
// not unnecessarily generating a new wrapping map object for each item.
var result = _root;
var count = _count;
foreach (var item in items)
{
bool mutated;
bool replacedExistingValue = false;
var newResult = overwriteOnCollision
? result.SetItem(item.Key, item.Value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated)
: result.Add(item.Key, item.Value, _keyComparer, _valueComparer, out mutated);
if (mutated)
{
result = newResult;
if (!replacedExistingValue)
{
count++;
}
}
}
return this.Wrap(result, count);
}
/// <summary>
/// Creates a wrapping collection type around a root node.
/// </summary>
/// <param name="root">The root node to wrap.</param>
/// <param name="adjustedCountIfDifferentRoot">The number of elements in the new tree, assuming it's different from the current tree.</param>
/// <returns>A wrapping collection type for the new tree.</returns>
[Pure]
private ImmutableSortedDictionary<TKey, TValue> Wrap(Node root, int adjustedCountIfDifferentRoot)
{
if (_root != root)
{
return root.IsEmpty ? this.Clear() : new ImmutableSortedDictionary<TKey, TValue>(root, adjustedCountIfDifferentRoot, _keyComparer, _valueComparer);
}
else
{
return this;
}
}
/// <summary>
/// Efficiently creates a new collection based on the contents of some sequence.
/// </summary>
[Pure]
private ImmutableSortedDictionary<TKey, TValue> FillFromEmpty(IEnumerable<KeyValuePair<TKey, TValue>> items, bool overwriteOnCollision)
{
Debug.Assert(this.IsEmpty);
Requires.NotNull(items, nameof(items));
// If the items being added actually come from an ImmutableSortedSet<T>,
// and the sort order is equivalent, then there is no value in reconstructing it.
ImmutableSortedDictionary<TKey, TValue> other;
if (TryCastToImmutableMap(items, out other))
{
return other.WithComparers(this.KeyComparer, this.ValueComparer);
}
var itemsAsDictionary = items as IDictionary<TKey, TValue>;
SortedDictionary<TKey, TValue> dictionary;
if (itemsAsDictionary != null)
{
dictionary = new SortedDictionary<TKey, TValue>(itemsAsDictionary, this.KeyComparer);
}
else
{
dictionary = new SortedDictionary<TKey, TValue>(this.KeyComparer);
foreach (var item in items)
{
if (overwriteOnCollision)
{
dictionary[item.Key] = item.Value;
}
else
{
TValue value;
if (dictionary.TryGetValue(item.Key, out value))
{
if (!_valueComparer.Equals(value, item.Value))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, item.Key));
}
}
else
{
dictionary.Add(item.Key, item.Value);
}
}
}
}
if (dictionary.Count == 0)
{
return this;
}
Node root = Node.NodeTreeFromSortedDictionary(dictionary);
return new ImmutableSortedDictionary<TKey, TValue>(root, dictionary.Count, this.KeyComparer, this.ValueComparer);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Buffers
{
public static unsafe partial class BoundedMemory
{
private static readonly int SystemPageSize = Environment.SystemPageSize;
private static WindowsImplementation<T> AllocateWithoutDataPopulation<T>(int elementCount, PoisonPagePlacement placement) where T : unmanaged
{
long cb, totalBytesToAllocate;
checked
{
cb = elementCount * sizeof(T);
totalBytesToAllocate = cb;
// We only need to round the count up if it's not an exact multiple
// of the system page size.
var leftoverBytes = totalBytesToAllocate % SystemPageSize;
if (leftoverBytes != 0)
{
totalBytesToAllocate += SystemPageSize - leftoverBytes;
}
// Finally, account for the poison pages at the front and back.
totalBytesToAllocate += 2 * SystemPageSize;
}
// Reserve and commit the entire range as NOACCESS.
var handle = UnsafeNativeMethods.VirtualAlloc(
lpAddress: IntPtr.Zero,
dwSize: (IntPtr)totalBytesToAllocate /* cast throws OverflowException if out of range */,
flAllocationType: VirtualAllocAllocationType.MEM_RESERVE | VirtualAllocAllocationType.MEM_COMMIT,
flProtect: VirtualAllocProtection.PAGE_NOACCESS);
if (handle == null || handle.IsInvalid)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
throw new InvalidOperationException("VirtualAlloc failed unexpectedly.");
}
// Done allocating! Now carve out a READWRITE section bookended by the NOACCESS
// pages and return that carved-out section to the caller. Since memory protection
// flags only apply at page-level granularity, we need to "left-align" or "right-
// align" the section we carve out so that it's guaranteed adjacent to one of
// the NOACCESS bookend pages.
return new WindowsImplementation<T>(
handle: handle,
byteOffsetIntoHandle: (placement == PoisonPagePlacement.Before)
? SystemPageSize /* just after leading poison page */
: checked((int)(totalBytesToAllocate - SystemPageSize - cb)) /* just before trailing poison page */,
elementCount: elementCount)
{
Protection = VirtualAllocProtection.PAGE_READWRITE
};
}
private sealed class WindowsImplementation<T> : BoundedMemory<T> where T : unmanaged
{
private readonly VirtualAllocHandle _handle;
private readonly int _byteOffsetIntoHandle;
private readonly int _elementCount;
private readonly BoundedMemoryManager _memoryManager;
internal WindowsImplementation(VirtualAllocHandle handle, int byteOffsetIntoHandle, int elementCount)
{
_handle = handle;
_byteOffsetIntoHandle = byteOffsetIntoHandle;
_elementCount = elementCount;
_memoryManager = new BoundedMemoryManager(this);
}
public override bool IsReadonly => (Protection != VirtualAllocProtection.PAGE_READWRITE);
internal VirtualAllocProtection Protection
{
get
{
bool refAdded = false;
try
{
_handle.DangerousAddRef(ref refAdded);
if (UnsafeNativeMethods.VirtualQuery(
lpAddress: _handle.DangerousGetHandle() + _byteOffsetIntoHandle,
lpBuffer: out var memoryInfo,
dwLength: (IntPtr)sizeof(MEMORY_BASIC_INFORMATION)) == IntPtr.Zero)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
throw new InvalidOperationException("VirtualQuery failed unexpectedly.");
}
return memoryInfo.Protect;
}
finally
{
if (refAdded)
{
_handle.DangerousRelease();
}
}
}
set
{
if (_elementCount > 0)
{
bool refAdded = false;
try
{
_handle.DangerousAddRef(ref refAdded);
if (!UnsafeNativeMethods.VirtualProtect(
lpAddress: _handle.DangerousGetHandle() + _byteOffsetIntoHandle,
dwSize: (IntPtr)(&((T*)null)[_elementCount]),
flNewProtect: value,
lpflOldProtect: out _))
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
throw new InvalidOperationException("VirtualProtect failed unexpectedly.");
}
}
finally
{
if (refAdded)
{
_handle.DangerousRelease();
}
}
}
}
}
public override Memory<T> Memory => _memoryManager.Memory;
public override Span<T> Span
{
get
{
bool refAdded = false;
try
{
_handle.DangerousAddRef(ref refAdded);
return new Span<T>((void*)(_handle.DangerousGetHandle() + _byteOffsetIntoHandle), _elementCount);
}
finally
{
if (refAdded)
{
_handle.DangerousRelease();
}
}
}
}
public override void Dispose()
{
_handle.Dispose();
}
public override void MakeReadonly()
{
Protection = VirtualAllocProtection.PAGE_READONLY;
}
public override void MakeWriteable()
{
Protection = VirtualAllocProtection.PAGE_READWRITE;
}
private sealed class BoundedMemoryManager : MemoryManager<T>
{
private readonly WindowsImplementation<T> _impl;
public BoundedMemoryManager(WindowsImplementation<T> impl)
{
_impl = impl;
}
public override Memory<T> Memory => CreateMemory(_impl._elementCount);
protected override void Dispose(bool disposing)
{
// no-op; the handle will be disposed separately
}
public override Span<T> GetSpan()
{
throw new NotImplementedException();
}
public override MemoryHandle Pin(int elementIndex)
{
if ((uint)elementIndex > (uint)_impl._elementCount)
{
throw new ArgumentOutOfRangeException(paramName: nameof(elementIndex));
}
bool refAdded = false;
try
{
_impl._handle.DangerousAddRef(ref refAdded);
return new MemoryHandle((T*)(_impl._handle.DangerousGetHandle() + _impl._byteOffsetIntoHandle) + elementIndex);
}
finally
{
if (refAdded)
{
_impl._handle.DangerousRelease();
}
}
}
public override void Unpin()
{
// no-op - we don't unpin native memory
}
}
}
// from winnt.h
[Flags]
private enum VirtualAllocAllocationType : uint
{
MEM_COMMIT = 0x1000,
MEM_RESERVE = 0x2000,
MEM_DECOMMIT = 0x4000,
MEM_RELEASE = 0x8000,
MEM_FREE = 0x10000,
MEM_PRIVATE = 0x20000,
MEM_MAPPED = 0x40000,
MEM_RESET = 0x80000,
MEM_TOP_DOWN = 0x100000,
MEM_WRITE_WATCH = 0x200000,
MEM_PHYSICAL = 0x400000,
MEM_ROTATE = 0x800000,
MEM_LARGE_PAGES = 0x20000000,
MEM_4MB_PAGES = 0x80000000,
}
// from winnt.h
[Flags]
private enum VirtualAllocProtection : uint
{
PAGE_NOACCESS = 0x01,
PAGE_READONLY = 0x02,
PAGE_READWRITE = 0x04,
PAGE_WRITECOPY = 0x08,
PAGE_EXECUTE = 0x10,
PAGE_EXECUTE_READ = 0x20,
PAGE_EXECUTE_READWRITE = 0x40,
PAGE_EXECUTE_WRITECOPY = 0x80,
PAGE_GUARD = 0x100,
PAGE_NOCACHE = 0x200,
PAGE_WRITECOMBINE = 0x400,
}
[StructLayout(LayoutKind.Sequential)]
private struct MEMORY_BASIC_INFORMATION
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public VirtualAllocProtection AllocationProtect;
public IntPtr RegionSize;
public VirtualAllocAllocationType State;
public VirtualAllocProtection Protect;
public VirtualAllocAllocationType Type;
};
private sealed class VirtualAllocHandle : SafeHandle
{
// Called by P/Invoke when returning SafeHandles
private VirtualAllocHandle()
: base(IntPtr.Zero, ownsHandle: true)
{
}
// Do not provide a finalizer - SafeHandle's critical finalizer will
// call ReleaseHandle for you.
public override bool IsInvalid => (handle == IntPtr.Zero);
protected override bool ReleaseHandle() =>
UnsafeNativeMethods.VirtualFree(handle, IntPtr.Zero, VirtualAllocAllocationType.MEM_RELEASE);
}
[SuppressUnmanagedCodeSecurity]
private static class UnsafeNativeMethods
{
private const string KERNEL32_LIB = "kernel32.dll";
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366887(v=vs.85).aspx
[DllImport(KERNEL32_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
public static extern VirtualAllocHandle VirtualAlloc(
[In] IntPtr lpAddress,
[In] IntPtr dwSize,
[In] VirtualAllocAllocationType flAllocationType,
[In] VirtualAllocProtection flProtect);
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366892(v=vs.85).aspx
[DllImport(KERNEL32_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool VirtualFree(
[In] IntPtr lpAddress,
[In] IntPtr dwSize,
[In] VirtualAllocAllocationType dwFreeType);
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366898(v=vs.85).aspx
[DllImport(KERNEL32_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool VirtualProtect(
[In] IntPtr lpAddress,
[In] IntPtr dwSize,
[In] VirtualAllocProtection flNewProtect,
[Out] out VirtualAllocProtection lpflOldProtect);
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366902(v=vs.85).aspx
[DllImport(KERNEL32_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
public static extern IntPtr VirtualQuery(
[In] IntPtr lpAddress,
[Out] out MEMORY_BASIC_INFORMATION lpBuffer,
[In] IntPtr dwLength);
}
}
}
| |
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 SIT.Web.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;
}
}
}
| |
// JsonObject.cs
//
// Copyright (C) 2006 Andy Kernahan
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace NetServ.Net.Json
{
/// <summary>
/// Represents a JavaScript Object Notation Object data type which contains a
/// collection of <see cref="NetServ.Net.Json.IJsonType"/>s accessed by key.
/// </summary>
[Serializable()]
public class JsonObject : Dictionary<string, IJsonType>, IJsonObject
{
#region Protected Interface.
/// <summary>
/// Deserialisation constructor.
/// </summary>
/// <param name="info">The object containing the data needed to deserialise an instance.</param>
/// <param name="context">The boejct which specifies the source of the deserialisation.</param>
protected JsonObject(SerializationInfo info, StreamingContext context)
: base(info, context) {
}
#endregion
#region Public Interface.
/// <summary>
/// Inialises a new instance of the JsonObject class.
/// </summary>
public JsonObject()
: base(StringComparer.Ordinal) {
}
/// <summary>
/// Writes the contents of this Json type using the specified
/// <see cref="NetServ.Net.Json.IJsonWriter"/>.
/// </summary>
/// <param name="writer">The Json writer.</param>
public void Write(IJsonWriter writer) {
if(writer == null)
throw new ArgumentNullException("writer");
writer.WriteBeginObject();
foreach(KeyValuePair<string, IJsonType> pair in this) {
writer.WriteName(pair.Key);
pair.Value.Write(writer);
}
writer.WriteEndObject();
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
public void Add(string key, string item) {
if(string.IsNullOrEmpty(item))
base.Add(key, JsonString.Empty);
else
base.Add(key, new JsonString(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
public void Add(string key, bool item) {
base.Add(key, JsonBoolean.Get(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
public void Add(string key, byte item) {
base.Add(key, new JsonNumber(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
[CLSCompliant(false)]
public void Add(string key, sbyte item) {
base.Add(key, new JsonNumber(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
public void Add(string key, short item) {
base.Add(key, new JsonNumber(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
[CLSCompliant(false)]
public void Add(string key, ushort item) {
base.Add(key, new JsonNumber(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
[CLSCompliant(false)]
public void Add(string key, int item) {
base.Add(key, new JsonNumber(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
[CLSCompliant(false)]
public void Add(string key, uint item) {
base.Add(key, new JsonNumber(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
public void Add(string key, long item) {
base.Add(key, new JsonNumber(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
[CLSCompliant(false)]
public void Add(string key, ulong item) {
base.Add(key, new JsonNumber(item));
}
/// <summary>
/// Adds the specified key and item to this dictionary.
/// </summary>
/// <param name="key">The key of the item</param>
/// <param name="item">The value of the item.</param>
public void Add(string key, double item) {
base.Add(key, new JsonNumber(item));
}
/// <summary>
/// Returns the JsonTypeCode for this instance.
/// </summary>
public JsonTypeCode JsonTypeCode {
get { return JsonTypeCode.Object; }
}
/// <summary>
/// Implicit conversion operator.
/// </summary>
/// <param name="value"></param>
/// <returns>This method always returns null.</returns>
public static implicit operator JsonObject(JsonNull value) {
return null;
}
#endregion
}
}
| |
using System;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Routing;
using Castle.MonoRail.Routing;
using NUnit.Framework;
using Rhino.Mocks;
namespace Castle.MonoRail.Routing.Test
{
[TestFixture]
public class RouteCollectionExtensionsTest
{
[Test]
public void MapResourceAddsIndexRoute()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients", "GET",
new { controller = "Patients", action = "Index" });
}
[Test]
public void MapResourceAddsCreateRoute()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients", "POST",
new { controller = "Patients", action = "Create" });
}
[Test]
public void MapResourceAddsNewRoute()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients/New", "GET",
new { controller = "Patients", action = "New" });
}
[Test]
public void MapResourceAddsShowRoute()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients/123", "GET",
new { controller = "Patients", action = "Show", id = "123" });
}
[Test]
public void MapResourceAddsTrueUpdateRoute()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients/123", "PUT",
new { controller = "Patients", action = "Update", id = "123" });
}
[Test]
public void MapResourceAddsUpdateRoute()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients/123?method=put", "POST",
new { controller = "Patients", action = "Update", id = "123" });
}
[Test]
public void MapResourceAddsDestroyRoute()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients/123", "DELETE",
new { controller = "Patients", action = "Destroy", id = "123" });
}
[Test]
public void MapResourceAddsLegacyDestroyRoute()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients/123?method=Delete", "POST",
new { controller = "Patients", action = "Destroy", id = "123" });
}
[Test]
public void MapResourceAddsEditRoute()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients/123/Edit", "GET",
new { controller = "Patients", action = "Edit", id = "123" });
}
[Test]
public void MapResourceAddsNestedIndex()
{
var routes = new RouteCollection();
routes.MapResource("labs", "patients/{mrn}");
AssertRoute(routes, "~/Patients/123/Labs", "GET",
new { controller = "Labs", action = "Index", mrn = "123" });
}
[Test]
public void MapRouteWithExplicitControllerAndAction()
{
var routes = new RouteCollection();
routes.Map("{controller}/{action}");
AssertRoute(routes, "~/Patients/Index", "GET",
new { controller = "Patients", action = "Index" });
}
[Test]
public void MapRouteWithImplicitAction()
{
var routes = new RouteCollection();
routes.Map("{controller}", new { action = "Index" });
AssertRoute(routes, "~/Patients", "GET",
new { controller = "Patients", action = "Index" });
}
[Test]
public void MapRouteWithExtraParameters()
{
var routes = new RouteCollection();
routes.Map("Patients/{mrn}/Labs/{id}", new { controller = "Labs", action = "Show" });
AssertRoute(routes, "~/Patients/123/Labs/abc", "GET",
new { controller = "Labs", action = "Show", mrn = "123", id = "abc" });
}
[Test]
public void MapRouteWithHttpVerb()
{
var routes = new RouteCollection();
routes.Map("{controller}/{action}", new { }, new { httpMethod = new HttpMethodConstraint("GET") });
AssertRoute(routes, "~/Patients/Index", "GET",
new { controller = "Patients", action = "Index" });
}
[Test]
public void MapRouteWithExplicitHttpVerb_DoesntMatchWrongVerb()
{
var routes = new RouteCollection();
routes.Map("{controller}/{action}", new { }, new { httpMethod = new HttpMethodConstraint("GET") });
Assert.IsNull(GetRoute(routes, "~/Patients/Index", "POST"));
}
[Test]
public void MapRouteWithHttpVerbAsString()
{
var routes = new RouteCollection();
routes.Map("{controller}/{action}", new { }, "GET");
AssertRoute(routes, "~/Patients/Index", "GET",
new { controller = "Patients", action = "Index" });
}
[Test]
public void MapRouteWithHttpVerbAsString_DoesntMatchWrongVerb()
{
var routes = new RouteCollection();
routes.Map("{controller}/{action}", new { }, "GET");
Assert.IsNull(GetRoute(routes, "~/Patients/Index", "POST"));
}
[Test]
public void MappingRoot()
{
var routes = new RouteCollection();
routes.MapRoot("Patients", "Index");
Assert.AreEqual("Patients", routes.Root().Values["controller"]);
Assert.AreEqual("Index", routes.Root().Values["action"]);
}
[Test]
public void ResourcesAllowOptionalExtension()
{
var routes = new RouteCollection();
routes.MapResource("patients");
AssertRoute(routes, "~/Patients.xml", "GET",
new { controller = "Patients", action = "Index", format = "xml" });
}
/// <summary>
/// Adapted from http://haacked.com/archive/2007/12/17/testing-routes-in-asp.net-mvc.aspx
/// </summary>
public void AssertRoute(RouteCollection routes, string url, string httpMethod, object expectations)
{
var routeData = GetRoute(routes, url, httpMethod);
Assert.IsNotNull(routeData, "Did not find the route");
var hash = new Hash(expectations);
foreach (var pair in hash)
{
Assert.IsTrue(routeData.Values.ContainsKey(pair.Key),
string.Format("Missing route value: {0}", pair.Key));
Assert.IsTrue(string.Equals(pair.Value.ToString(),
routeData.Values[pair.Key].ToString(),
StringComparison.OrdinalIgnoreCase),
string.Format("Expected '{0}', not '{1}' for '{2}'.",
pair.Value, routeData.Values[pair.Key], pair.Key));
}
}
private RouteData GetRoute(RouteCollection routes, string url, string httpMethod)
{
var matches = Regex.Match(url, @"([^\?]+)(\?(.*))?");
var stem = matches.Groups[1].Value;
var queryString = GetQueryString(matches.Groups[3].Value);
var mockRequest = MockRepository.GenerateStub<HttpRequestBase>();
mockRequest.Stub(r => r.AppRelativeCurrentExecutionFilePath).Return(stem).Repeat.Any();
mockRequest.Stub(r => r.QueryString).Return(queryString).Repeat.Any();
mockRequest.Stub(r => r.HttpMethod).Return(httpMethod).Repeat.Any();
var mockContext = MockRepository.GenerateStub<HttpContextBase>();
mockContext.Stub(c => c.Request).Return(mockRequest).Repeat.Any();
return routes.GetRouteData(mockContext);
}
private NameValueCollection GetQueryString(string queryStringText)
{
var queryString = new NameValueCollection(StringComparer.InvariantCultureIgnoreCase);
if (string.IsNullOrEmpty(queryStringText))
return queryString;
foreach (var keyValuePair in queryStringText.Split('&'))
{
var keyValue = keyValuePair.Split('=');
queryString.Add(keyValue[0], keyValue[1]);
}
return queryString;
}
}
}
| |
// 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 Test.Utilities;
using Xunit;
namespace Desktop.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests : DiagnosticAnalyzerTestBase
{
private static readonly string s_CA3075XmlDocumentWithNoSecureResolverMessage = DesktopAnalyzersResources.XmlDocumentWithNoSecureResolverMessage;
private DiagnosticResult GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(int line, int column)
{
return GetCSharpResultAt(line, column, CA3075RuleId, s_CA3075XmlDocumentWithNoSecureResolverMessage);
}
private DiagnosticResult GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(int line, int column)
{
return GetBasicResultAt(line, column, CA3075RuleId, s_CA3075XmlDocumentWithNoSecureResolverMessage);
}
[Fact]
public void XmlDocumentSetResolverToNullShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
XmlDocument doc = new XmlDocument();
doc.XmlResolver = null;
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
Dim doc As New XmlDocument()
doc.XmlResolver = Nothing
End Sub
End Class
End Namespace
"
);
}
[Fact]
public void XmlDocumentSetResolverToNullInInitializerShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
XmlDocument doc = new XmlDocument()
{
XmlResolver = null
};
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
Dim doc As New XmlDocument() With { _
.XmlResolver = Nothing _
}
End Sub
End Class
End Namespace"
);
}
[Fact]
public void XmlDocumentAsFieldSetResolverToNullInInitializerShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public XmlDocument doc = new XmlDocument()
{
XmlResolver = null
};
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public doc As XmlDocument = New XmlDocument() With { _
.XmlResolver = Nothing _
}
End Class
End Namespace"
);
}
[Fact]
public void XmlDocumentAsFieldSetInsecureResolverInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public XmlDocument doc = new XmlDocument() { XmlResolver = new XmlUrlResolver() };
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 54)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public doc As XmlDocument = New XmlDocument() With { _
.XmlResolver = New XmlUrlResolver() _
}
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(7, 13)
);
}
[Fact]
public void XmlDocumentAsFieldNoResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public XmlDocument doc = new XmlDocument();
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public doc As XmlDocument = New XmlDocument()
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37)
);
}
[Fact]
public void XmlDocumentUseSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlSecureResolver resolver)
{
XmlDocument doc = new XmlDocument();
doc.XmlResolver = resolver;
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(resolver As XmlSecureResolver)
Dim doc As New XmlDocument()
doc.XmlResolver = resolver
End Sub
End Class
End Namespace"
);
}
[Fact]
public void XmlDocumentSetSecureResolverInInitializerShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlSecureResolver resolver)
{
XmlDocument doc = new XmlDocument()
{
XmlResolver = resolver
};
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(resolver As XmlSecureResolver)
Dim doc As New XmlDocument() With { _
.XmlResolver = resolver _
}
End Sub
End Class
End Namespace"
);
}
[Fact]
public void XmlDocumentUseSecureResolverWithPermissionsShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Net;
using System.Security;
using System.Security.Permissions;
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
PermissionSet myPermissions = new PermissionSet(PermissionState.None);
WebPermission permission = new WebPermission(PermissionState.None);
permission.AddPermission(NetworkAccess.Connect, ""http://www.contoso.com/"");
permission.AddPermission(NetworkAccess.Connect, ""http://litwareinc.com/data/"");
myPermissions.SetPermission(permission);
XmlSecureResolver resolver = new XmlSecureResolver(new XmlUrlResolver(), myPermissions);
XmlDocument doc = new XmlDocument();
doc.XmlResolver = resolver;
}
}
}"
);
VerifyBasic(@"
Imports System.Net
Imports System.Security
Imports System.Security.Permissions
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
Dim myPermissions As New PermissionSet(PermissionState.None)
Dim permission As New WebPermission(PermissionState.None)
permission.AddPermission(NetworkAccess.Connect, ""http://www.contoso.com/"")
permission.AddPermission(NetworkAccess.Connect, ""http://litwareinc.com/data/"")
myPermissions.SetPermission(permission)
Dim resolver As New XmlSecureResolver(New XmlUrlResolver(), myPermissions)
Dim doc As New XmlDocument()
doc.XmlResolver = resolver
End Sub
End Class
End Namespace"
);
}
[Fact]
public void XmlDocumentSetResolverToNullInTryClauseShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
XmlDocument doc = new XmlDocument();
try
{
doc.XmlResolver = null;
}
catch { throw; }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
Dim doc As New XmlDocument()
Try
doc.XmlResolver = Nothing
Catch
Throw
End Try
End Sub
End Class
End Namespace"
);
}
[Fact]
public void XmlDocumentNoResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
XmlDocument doc = new XmlDocument();
}
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(10, 31)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
Dim doc As New XmlDocument()
End Sub
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(7, 24)
);
}
[Fact]
public void XmlDocumentUseNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
XmlDocument doc = new XmlDocument();
doc.XmlResolver = new XmlUrlResolver(); // warn
}
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
Dim doc As New XmlDocument()
doc.XmlResolver = New XmlUrlResolver()
' warn
End Sub
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 13)
);
}
[Fact]
public void XmlDocumentUseNonSecureResolverInTryClauseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
XmlDocument doc = new XmlDocument();
try
{
doc.XmlResolver = new XmlUrlResolver(); // warn
}
catch { throw; }
}
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(13, 17)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
Dim doc As New XmlDocument()
Try
' warn
doc.XmlResolver = New XmlUrlResolver()
Catch
Throw
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(10, 17)
);
}
[Fact]
public void XmlDocumentReassignmentSetResolverToNullInInitializerShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
XmlDocument doc = new XmlDocument();
doc = new XmlDocument()
{
XmlResolver = null
};
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
Dim doc As New XmlDocument()
doc = New XmlDocument() With { _
.XmlResolver = Nothing _
}
End Sub
End Class
End Namespace"
);
}
[Fact]
public void XmlDocumentReassignmentDefaultShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
XmlDocument doc = new XmlDocument()
{
XmlResolver = null
};
doc = new XmlDocument(); // warn
}
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(14, 19)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
Dim doc As New XmlDocument() With { _
.XmlResolver = Nothing _
}
doc = New XmlDocument()
' warn
End Sub
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(10, 19)
);
}
[Fact]
public void XmlDocumentSetResolversInDifferentBlock()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod()
{
{
XmlDocument doc = new XmlDocument();
}
{
XmlDocument doc = new XmlDocument();
doc.XmlResolver = null;
}
}
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 35)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod()
If True Then
Dim doc As New XmlDocument()
End If
If True Then
Dim doc As New XmlDocument()
doc.XmlResolver = Nothing
End If
End Sub
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 28)
);
}
[Fact]
public void XmlDocumentAsFieldSetResolverToInsecureResolverInOnlyMethodShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public XmlDocument doc = new XmlDocument();
public void Method1()
{
this.doc.XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34),
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(12, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public doc As XmlDocument = New XmlDocument()
' warn
Public Sub Method1()
Me.doc.XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37),
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(9, 13)
);
}
[Fact]
public void XmlDocumentAsFieldSetResolverToInsecureResolverInSomeMethodShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public XmlDocument doc = new XmlDocument(); // warn
public void Method1()
{
this.doc.XmlResolver = null;
}
public void Method2()
{
this.doc.XmlResolver = new XmlUrlResolver(); // warn
}
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34),
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(17, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public doc As XmlDocument = New XmlDocument()
' warn
Public Sub Method1()
Me.doc.XmlResolver = Nothing
End Sub
Public Sub Method2()
Me.doc.XmlResolver = New XmlUrlResolver()
' warn
End Sub
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37),
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(13, 13)
);
}
[Fact]
public void XmlDocumentAsFieldSetResolverToNullInSomeMethodShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public XmlDocument doc = new XmlDocument();
public void Method1()
{
this.doc.XmlResolver = null;
}
public void Method2(XmlReader reader)
{
this.doc.Load(reader);
}
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(8, 34)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public doc As XmlDocument = New XmlDocument()
Public Sub Method1()
Me.doc.XmlResolver = Nothing
End Sub
Public Sub Method2(reader As XmlReader)
Me.doc.Load(reader)
End Sub
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(6, 37)
);
}
[Fact]
public void XmlDocumentCreatedAsTempNotSetResolverShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1()
{
Method2(new XmlDocument());
}
public void Method2(XmlDocument doc){}
}
}",
GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1()
Method2(New XmlDocument())
End Sub
Public Sub Method2(doc As XmlDocument)
End Sub
End Class
End Namespace",
GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 21)
);
}
[Fact]
public void XmlDocumentDerivedTypeNotSetResolverShouldNotGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass1 : XmlDocument
{
public TestClass1()
{
XmlResolver = null;
}
}
class TestClass2
{
void TestMethod()
{
var c = new TestClass1();
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass1
Inherits XmlDocument
Public Sub New()
XmlResolver = Nothing
End Sub
End Class
Class TestClass2
Private Sub TestMethod()
Dim c = New TestClass1()
End Sub
End Class
End Namespace
"
);
}
[Fact]
public void XmlDocumentDerivedTypeWithNoSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class DerivedType : XmlDocument {}
class TestClass
{
void TestMethod()
{
var c = new DerivedType();
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class DerivedType
Inherits XmlDocument
End Class
Class TestClass
Private Sub TestMethod()
Dim c = New DerivedType()
End Sub
End Class
End Namespace"
);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Analysis {
/// <summary>
/// Encapsulates all of the information about a single module which has been analyzed.
///
/// Can be queried for various information about the resulting analysis.
/// </summary>
public sealed class ModuleAnalysis {
private readonly AnalysisUnit _unit;
private readonly InterpreterScope _scope;
private static Regex _otherPrivateRegex = new Regex("^_[a-zA-Z_]\\w*__[a-zA-Z_]\\w*$");
private static readonly IEnumerable<IOverloadResult> GetSignaturesError =
new[] { new SimpleOverloadResult(new ParameterResult[0], "Unknown", "IntellisenseError_Sigs") };
internal ModuleAnalysis(AnalysisUnit unit, InterpreterScope scope) {
_unit = unit;
_scope = scope;
}
#region Public API
/// <summary>
/// Evaluates the given expression in at the provided line number and returns the values
/// that the expression can evaluate to.
/// </summary>
/// <param name="exprText">The expression to determine the result of.</param>
/// <param name="index">The 0-based absolute index into the file where the expression should be evaluated.</param>
public IEnumerable<AnalysisValue> GetValuesByIndex(string exprText, int index) {
return GetValues(exprText, _unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Evaluates the given expression in at the provided line number and returns the values
/// that the expression can evaluate to.
/// </summary>
/// <param name="exprText">The expression to determine the result of.</param>
/// <param name="location">The location in the file where the expression should be evaluated.</param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<AnalysisValue> GetValues(string exprText, SourceLocation location) {
var scope = FindScope(location);
var privatePrefix = GetPrivatePrefixClassName(scope);
var expr = Statement.GetExpression(GetAstFromText(exprText, privatePrefix).Body);
var unit = GetNearestEnclosingAnalysisUnit(scope);
var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true);
var values = eval.Evaluate(expr);
var res = AnalysisSet.EmptyUnion;
foreach (var v in values) {
MultipleMemberInfo multipleMembers = v as MultipleMemberInfo;
if (multipleMembers != null) {
foreach (var member in multipleMembers.Members) {
if (member.IsCurrent) {
res = res.Add(member);
}
}
} else if (v.IsCurrent) {
res = res.Add(v);
}
}
return res;
}
internal IEnumerable<AnalysisVariable> ReferencablesToVariables(IEnumerable<IReferenceable> defs) {
foreach (var def in defs) {
foreach (var res in ToVariables(def)) {
yield return res;
}
}
}
internal IEnumerable<AnalysisVariable> ToVariables(IReferenceable referenceable) {
LocatedVariableDef locatedDef = referenceable as LocatedVariableDef;
if (locatedDef != null &&
locatedDef.Entry.Tree != null && // null tree if there are errors in the file
locatedDef.DeclaringVersion == locatedDef.Entry.AnalysisVersion) {
var start = locatedDef.Node.GetStart(locatedDef.Entry.Tree);
yield return new AnalysisVariable(VariableType.Definition, new LocationInfo(locatedDef.Entry.FilePath, start.Line, start.Column));
}
VariableDef def = referenceable as VariableDef;
if (def != null) {
foreach (var location in def.TypesNoCopy.SelectMany(type => type.Locations)) {
yield return new AnalysisVariable(VariableType.Value, location);
}
}
foreach (var reference in referenceable.Definitions) {
yield return new AnalysisVariable(
VariableType.Definition,
reference.GetLocationInfo()
);
}
foreach (var reference in referenceable.References) {
yield return new AnalysisVariable(
VariableType.Reference,
reference.GetLocationInfo()
);
}
}
/// <summary>
/// Gets the variables the given expression evaluates to. Variables
/// include parameters, locals, and fields assigned on classes, modules
/// and instances.
///
/// Variables are classified as either definitions or references. Only
/// parameters have unique definition points - all other types of
/// variables have only one or more references.
/// </summary>
/// <param name="exprText">The expression to find variables for.</param>
/// <param name="index">
/// The 0-based absolute index into the file where the expression should
/// be evaluated.
/// </param>
public VariablesResult GetVariablesByIndex(string exprText, int index) {
return GetVariables(exprText, _unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets the variables the given expression evaluates to. Variables
/// include parameters, locals, and fields assigned on classes, modules
/// and instances.
///
/// Variables are classified as either definitions or references. Only
/// parameters have unique definition points - all other types of
/// variables have only one or more references.
/// </summary>
/// <param name="exprText">The expression to find variables for.</param>
/// <param name="location">
/// The location in the file where the expression should be evaluated.
/// </param>
/// <remarks>New in 2.2</remarks>
public VariablesResult GetVariables(string exprText, SourceLocation location) {
var scope = FindScope(location);
string privatePrefix = GetPrivatePrefixClassName(scope);
var ast = GetAstFromText(exprText, privatePrefix);
var expr = Statement.GetExpression(ast.Body);
var unit = GetNearestEnclosingAnalysisUnit(scope);
NameExpression name = expr as NameExpression;
IEnumerable<IAnalysisVariable> variables = Enumerable.Empty<IAnalysisVariable>();
if (name != null) {
var defScope = scope.EnumerateTowardsGlobal.FirstOrDefault(s =>
s.ContainsVariable(name.Name) && (s == scope || s.VisibleToChildren || IsFirstLineOfFunction(scope, s, location)));
if (defScope == null) {
variables = _unit.ProjectState.BuiltinModule.GetDefinitions(name.Name)
.SelectMany(ToVariables);
} else {
variables = GetVariablesInScope(name, defScope).Distinct();
}
} else {
MemberExpression member = expr as MemberExpression;
if (member != null && !string.IsNullOrEmpty(member.Name)) {
var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true);
var objects = eval.Evaluate(member.Target);
foreach (var v in objects) {
var container = v as IReferenceableContainer;
if (container != null) {
variables = ReferencablesToVariables(container.GetDefinitions(member.Name));
break;
}
}
}
}
return new VariablesResult(variables, ast);
}
private IEnumerable<IAnalysisVariable> GetVariablesInScope(NameExpression name, InterpreterScope scope) {
var result = new List<IAnalysisVariable>();
result.AddRange(scope.GetMergedVariables(name.Name).SelectMany(ToVariables));
// if a variable is imported from another module then also yield the defs/refs for the
// value in the defining module.
result.AddRange(scope.GetLinkedVariables(name.Name).SelectMany(ToVariables));
var classScope = scope as ClassScope;
if (classScope != null) {
// if the member is defined in a base class as well include the base class member and references
var cls = classScope.Class;
if (cls.Push()) {
try {
foreach (var baseNs in cls.Bases.SelectMany()) {
if (baseNs.Push()) {
try {
ClassInfo baseClassNs = baseNs as ClassInfo;
if (baseClassNs != null) {
result.AddRange(
baseClassNs.Scope.GetMergedVariables(name.Name).SelectMany(ToVariables)
);
}
} finally {
baseNs.Pop();
}
}
}
} finally {
cls.Pop();
}
}
}
return result;
}
/// <summary>
/// Gets the list of modules known by the current analysis.
/// </summary>
/// <param name="topLevelOnly">Only return top-level modules.</param>
public MemberResult[] GetModules(bool topLevelOnly = false) {
List<MemberResult> res = new List<MemberResult>(ProjectState.GetModules(topLevelOnly));
var children = GlobalScope.GetChildrenPackages(InterpreterContext);
foreach (var child in children) {
res.Add(new MemberResult(child.Key, PythonMemberType.Module));
}
return res.ToArray();
}
/// <summary>
/// Gets the list of modules and members matching the provided names.
/// </summary>
/// <param name="names">The dotted name parts to match</param>
/// <param name="includeMembers">Include module members that match as
/// well as just modules.</param>
public MemberResult[] GetModuleMembers(string[] names, bool includeMembers = false) {
var res = new List<MemberResult>(ProjectState.GetModuleMembers(InterpreterContext, names, includeMembers));
var children = GlobalScope.GetChildrenPackages(InterpreterContext);
foreach (var child in children) {
var mod = (ModuleInfo)child.Value;
if (string.IsNullOrEmpty(mod.Name)) {
// Module does not have an importable name
continue;
}
var childName = mod.Name.Split('.');
if (childName.Length >= 2 && childName[0] == GlobalScope.Name && childName[1] == names[0]) {
res.AddRange(PythonAnalyzer.GetModuleMembers(InterpreterContext, names, includeMembers, mod as IModule));
}
}
return res.ToArray();
}
private static bool IsFirstLineOfFunction(InterpreterScope innerScope, InterpreterScope outerScope, SourceLocation location) {
if (innerScope.OuterScope == outerScope && innerScope is FunctionScope) {
var funcScope = (FunctionScope)innerScope;
var def = funcScope.Function.FunctionDefinition;
// TODO: Use indexes rather than lines to check location
if (location.Line == def.GetStart(def.GlobalParent).Line) {
return true;
}
}
return false;
}
private class ErrorWalker : PythonWalker {
public bool HasError { get; private set; }
public override bool Walk(ErrorStatement node) {
HasError = true;
return false;
}
public override bool Walk(ErrorExpression node) {
HasError = true;
return false;
}
}
/// <summary>
/// Evaluates a given expression and returns a list of members which
/// exist in the expression.
///
/// If the expression is an empty string returns all available members
/// at that location.
/// </summary>
/// <param name="exprText">The expression to find members for.</param>
/// <param name="index">
/// The 0-based absolute index into the file where the expression should
/// be evaluated.
/// </param>
public IEnumerable<MemberResult> GetMembersByIndex(
string exprText,
int index,
GetMemberOptions options = GetMemberOptions.IntersectMultipleResults
) {
return GetMembers(exprText, _unit.Tree.IndexToLocation(index), options);
}
/// <summary>
/// Evaluates a given expression and returns a list of members which
/// exist in the expression.
///
/// If the expression is an empty string returns all available members
/// at that location.
/// </summary>
/// <param name="exprText">The expression to find members for.</param>
/// </param>
/// <param name="location">
/// The location in the file where the expression should be evaluated.
/// </param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<MemberResult> GetMembers(
string exprText,
SourceLocation location,
GetMemberOptions options = GetMemberOptions.IntersectMultipleResults
) {
if (exprText.Length == 0) {
return GetAllAvailableMembers(location, options);
}
var scope = FindScope(location);
var privatePrefix = GetPrivatePrefixClassName(scope);
var expr = Statement.GetExpression(GetAstFromText(exprText, privatePrefix).Body);
if (expr is ConstantExpression && ((ConstantExpression)expr).Value is int) {
// no completions on integer ., the user is typing a float
return Enumerable.Empty<MemberResult>();
}
var errorWalker = new ErrorWalker();
expr.Walk(errorWalker);
if (errorWalker.HasError) {
return null;
}
var unit = GetNearestEnclosingAnalysisUnit(scope);
var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true);
IAnalysisSet lookup;
if (options.HasFlag(GetMemberOptions.NoMemberRecursion)) {
lookup = eval.EvaluateNoMemberRecursion(expr);
} else {
lookup = eval.Evaluate(expr);
}
return GetMemberResults(lookup, scope, options);
}
/// <summary>
/// Gets information about the available signatures for the given expression.
/// </summary>
/// <param name="exprText">The expression to get signatures for.</param>
/// <param name="index">The 0-based absolute index into the file.</param>
public IEnumerable<IOverloadResult> GetSignaturesByIndex(string exprText, int index) {
return GetSignatures(exprText, _unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets information about the available signatures for the given expression.
/// </summary>
/// <param name="exprText">The expression to get signatures for.</param>
/// <param name="location">The location in the file.</param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<IOverloadResult> GetSignatures(string exprText, SourceLocation location) {
try {
var scope = FindScope(location);
var unit = GetNearestEnclosingAnalysisUnit(scope);
var eval = new ExpressionEvaluator(unit.CopyForEval(), scope, mergeScopes: true);
using (var parser = Parser.CreateParser(new StringReader(exprText), _unit.ProjectState.LanguageVersion)) {
var expr = GetExpression(parser.ParseTopExpression().Body);
if (expr is ListExpression ||
expr is TupleExpression ||
expr is DictionaryExpression) {
return Enumerable.Empty<IOverloadResult>();
}
var lookup = eval.Evaluate(expr);
lookup = AnalysisSet.Create(lookup.Where(av => !(av is MultipleMemberInfo)).Concat(
lookup.OfType<MultipleMemberInfo>().SelectMany(mmi => mmi.Members)
));
var result = new HashSet<OverloadResult>(OverloadResultComparer.Instance);
// TODO: Include relevant type info on the parameter...
result.UnionWith(lookup
// Exclude constant values first time through
.Where(av => av.MemberType != PythonMemberType.Constant)
.SelectMany(av => av.Overloads ?? Enumerable.Empty<OverloadResult>())
);
if (!result.Any()) {
result.UnionWith(lookup
.Where(av => av.MemberType == PythonMemberType.Constant)
.SelectMany(av => av.Overloads ?? Enumerable.Empty<OverloadResult>()));
}
return result;
}
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
Debug.Fail(ex.ToString());
return GetSignaturesError;
}
}
/// <summary>
/// Gets the hierarchy of class and function definitions at the
/// specified location.
/// </summary>
/// <param name="index">The 0-based absolute index into the file.</param>
public IEnumerable<MemberResult> GetDefinitionTreeByIndex(int index) {
return GetDefinitionTree(_unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets the hierarchy of class and function definitions at the
/// specified location.
/// </summary>
/// <param name="location">The location in the file.</param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<MemberResult> GetDefinitionTree(SourceLocation location) {
try {
return FindScope(location).EnumerateTowardsGlobal
.Select(s => new MemberResult(s.Name, s.GetMergedAnalysisValues()))
.ToList();
} catch (Exception) {
// TODO: log exception
Debug.Fail("Failed to find scope. Bad state in analysis");
return new[] { new MemberResult("Unknown", new AnalysisValue[] { }) };
}
}
/// <summary>
/// Gets information about methods defined on base classes but not
/// directly on the current class.
/// </summary>
/// <param name="index">The 0-based absolute index into the file.</param>
public IEnumerable<IOverloadResult> GetOverrideableByIndex(int index) {
return GetOverrideable(_unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets information about methods defined on base classes but not
/// directly on the current class.
/// </summary>
/// <param name="location">The location in the file.</param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<IOverloadResult> GetOverrideable(SourceLocation location) {
try {
var result = new List<IOverloadResult>();
var scope = FindScope(location);
var cls = scope as ClassScope;
if (cls == null) {
return result;
}
var handled = new HashSet<string>(cls.Children.Select(child => child.Name));
var cls2 = scope as ClassScope;
var mro = (cls2 ?? cls).Class.Mro;
if (mro == null) {
return result;
}
foreach (var baseClass in mro.Skip(1).SelectMany()) {
ClassInfo klass;
BuiltinClassInfo builtinClass;
IEnumerable<AnalysisValue> source;
if ((klass = baseClass as ClassInfo) != null) {
source = klass.Scope.Children
.Where(child => child != null && child.AnalysisValue != null)
.Select(child => child.AnalysisValue);
} else if ((builtinClass = baseClass as BuiltinClassInfo) != null) {
source = builtinClass.GetAllMembers(InterpreterContext)
.SelectMany(kv => kv.Value)
.Where(child => child != null &&
(child.MemberType == PythonMemberType.Function ||
child.MemberType == PythonMemberType.Method));
} else {
continue;
}
foreach (var child in source) {
if (!child.Overloads.Any()) {
continue;
}
try {
var overload = child.Overloads.Aggregate(
(best, o) => o.Parameters.Length > best.Parameters.Length ? o : best
);
if (handled.Contains(overload.Name)) {
continue;
}
handled.Add(overload.Name);
result.Add(overload);
} catch {
// TODO: log exception
// Exceptions only affect the current override. Others may still be offerred.
}
}
}
return result;
} catch (Exception) {
// TODO: log exception
return new IOverloadResult[0];
}
}
/// <summary>
/// Gets the available names at the given location. This includes
/// built-in variables, global variables, and locals.
/// </summary>
/// <param name="index">
/// The 0-based absolute index into the file where the available members
/// should be looked up.
/// </param>
public IEnumerable<MemberResult> GetAllAvailableMembersByIndex(
int index,
GetMemberOptions options = GetMemberOptions.IntersectMultipleResults
) {
return GetAllAvailableMembers(_unit.Tree.IndexToLocation(index), options);
}
/// <summary>
/// Gets the available names at the given location. This includes
/// built-in variables, global variables, and locals.
/// </summary>
/// <param name="location">
/// The location in the file where the available members should be
/// looked up.
/// </param>
/// <remarks>New in 2.2</remarks>
public IEnumerable<MemberResult> GetAllAvailableMembers(SourceLocation location, GetMemberOptions options = GetMemberOptions.IntersectMultipleResults) {
var result = new Dictionary<string, IEnumerable<AnalysisValue>>();
// collect builtins
if (!options.HasFlag(GetMemberOptions.ExcludeBuiltins)) {
foreach (var variable in ProjectState.BuiltinModule.GetAllMembers(ProjectState._defaultContext)) {
result[variable.Key] = new List<AnalysisValue>(variable.Value);
}
}
// collect variables from user defined scopes
var scope = FindScope(location);
foreach (var s in scope.EnumerateTowardsGlobal) {
foreach (var kvp in s.GetAllMergedVariables()) {
// deliberately overwrite variables from outer scopes
result[kvp.Key] = new List<AnalysisValue>(kvp.Value.TypesNoCopy);
}
}
var res = MemberDictToResultList(GetPrivatePrefix(scope), options, result);
if (options.Keywords()) {
res = GetKeywordMembers(options, scope).Union(res);
}
return res;
}
private IEnumerable<MemberResult> GetKeywordMembers(GetMemberOptions options, InterpreterScope scope) {
IEnumerable<string> keywords = null;
if (options.ExpressionKeywords()) {
// keywords available in any context
keywords = PythonKeywords.Expression(ProjectState.LanguageVersion);
} else {
keywords = Enumerable.Empty<string>();
}
if (options.StatementKeywords()) {
keywords = keywords.Union(PythonKeywords.Statement(ProjectState.LanguageVersion));
}
if (!(scope is FunctionScope)) {
keywords = keywords.Except(PythonKeywords.InvalidOutsideFunction(ProjectState.LanguageVersion));
}
return keywords.Select(kw => new MemberResult(kw, PythonMemberType.Keyword));
}
#endregion
/// <summary>
/// Gets the available names at the given location. This includes
/// global variables and locals, but not built-in variables.
/// </summary>
/// <param name="index">
/// The 0-based absolute index into the file where the available members
/// should be looked up.
/// </param>
/// <remarks>TODO: Remove; this is only used for tests</remarks>
internal IEnumerable<string> GetVariablesNoBuiltinsByIndex(int index) {
return GetVariablesNoBuiltins(_unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets the available names at the given location. This includes
/// global variables and locals, but not built-in variables.
/// </summary>
/// <param name="location">
/// The location in the file where the available members should be
/// looked up.
/// </param>
/// <remarks>TODO: Remove; this is only used for tests</remarks>
/// <remarks>New in 2.2</remarks>
internal IEnumerable<string> GetVariablesNoBuiltins(SourceLocation location) {
var result = Enumerable.Empty<string>();
var chain = FindScope(location);
foreach (var scope in chain.EnumerateFromGlobal) {
if (scope.VisibleToChildren || scope == chain) {
result = result.Concat(scope.GetAllMergedVariables().Select(val => val.Key));
}
}
return result.Distinct();
}
/// <summary>
/// Gets the top-level scope for the module.
/// </summary>
internal ModuleInfo GlobalScope {
get {
var result = (ModuleScope)Scope;
return result.Module;
}
}
public IModuleContext InterpreterContext {
get {
return GlobalScope.InterpreterContext;
}
}
public PythonAnalyzer ProjectState {
get { return GlobalScope.ProjectEntry.ProjectState; }
}
internal InterpreterScope Scope {
get { return _scope; }
}
internal IEnumerable<MemberResult> GetMemberResults(
IEnumerable<AnalysisValue> vars,
InterpreterScope scope,
GetMemberOptions options
) {
IList<AnalysisValue> namespaces = new List<AnalysisValue>();
foreach (var ns in vars) {
if (ns != null) {
namespaces.Add(ns);
}
}
if (namespaces.Count == 1) {
// optimize for the common case of only a single namespace
var newMembers = namespaces[0].GetAllMembers(GlobalScope.InterpreterContext, options);
if (newMembers == null || newMembers.Count == 0) {
return new MemberResult[0];
}
return SingleMemberResult(GetPrivatePrefix(scope), options, newMembers);
}
Dictionary<string, IEnumerable<AnalysisValue>> memberDict = null;
Dictionary<string, IEnumerable<AnalysisValue>> ownerDict = null;
HashSet<string> memberSet = null;
int namespacesCount = namespaces.Count;
foreach (AnalysisValue ns in namespaces) {
if (ProjectState._noneInst == ns) {
namespacesCount -= 1;
continue;
}
var newMembers = ns.GetAllMembers(GlobalScope.InterpreterContext, options);
// IntersectMembers(members, memberSet, memberDict);
if (newMembers == null || newMembers.Count == 0) {
continue;
}
if (memberSet == null) {
// first namespace, add everything
memberSet = new HashSet<string>(newMembers.Keys);
memberDict = new Dictionary<string, IEnumerable<AnalysisValue>>();
ownerDict = new Dictionary<string, IEnumerable<AnalysisValue>>();
foreach (var kvp in newMembers) {
var tmp = new List<AnalysisValue>(kvp.Value);
memberDict[kvp.Key] = tmp;
ownerDict[kvp.Key] = new List<AnalysisValue> { ns };
}
} else {
// 2nd or nth namespace, union or intersect
HashSet<string> toRemove;
IEnumerable<string> adding;
if (options.Intersect()) {
adding = new HashSet<string>(newMembers.Keys);
// Find the things only in memberSet that we need to remove from memberDict
// toRemove = (memberSet ^ adding) & memberSet
toRemove = new HashSet<string>(memberSet);
toRemove.SymmetricExceptWith(adding);
toRemove.IntersectWith(memberSet);
// intersect memberSet with what we're adding
memberSet.IntersectWith(adding);
// we're only adding things they both had
adding = memberSet;
} else {
// we're adding all of newMembers keys
adding = newMembers.Keys;
toRemove = null;
}
// update memberDict
foreach (var name in adding) {
IEnumerable<AnalysisValue> values;
List<AnalysisValue> valueList;
if (!memberDict.TryGetValue(name, out values)) {
memberDict[name] = values = new List<AnalysisValue>();
}
if ((valueList = values as List<AnalysisValue>) == null) {
memberDict[name] = valueList = new List<AnalysisValue>(values);
}
valueList.AddRange(newMembers[name]);
if (!ownerDict.TryGetValue(name, out values)) {
ownerDict[name] = values = new List<AnalysisValue>();
}
if ((valueList = values as List<AnalysisValue>) == null) {
ownerDict[name] = valueList = new List<AnalysisValue>(values);
}
valueList.Add(ns);
}
if (toRemove != null) {
foreach (var name in toRemove) {
memberDict.Remove(name);
ownerDict.Remove(name);
}
}
}
}
if (memberDict == null) {
return new MemberResult[0];
}
if (options.Intersect()) {
// No need for this information if we're only showing the
// intersection. Setting it to null saves lookups later.
ownerDict = null;
}
return MemberDictToResultList(GetPrivatePrefix(scope), options, memberDict, ownerDict, namespacesCount);
}
/// <summary>
/// Gets the AST for the given text as if it appeared at the specified
/// location.
///
/// If the expression is a member expression such as "fob.__bar" and the
/// line number is inside of a class definition this will return a
/// MemberExpression with the mangled name like "fob.__ClassName_Bar".
/// </summary>
/// <param name="exprText">The expression to evaluate.</param>
/// <param name="index">
/// The 0-based index into the file where the expression should be
/// evaluated.
/// </param>
/// <remarks>New in 1.1</remarks>
public PythonAst GetAstFromTextByIndex(string exprText, int index) {
return GetAstFromText(exprText, _unit.Tree.IndexToLocation(index));
}
/// <summary>
/// Gets the AST for the given text as if it appeared at the specified
/// location.
///
/// If the expression is a member expression such as "fob.__bar" and the
/// line number is inside of a class definition this will return a
/// MemberExpression with the mangled name like "fob._ClassName__bar".
/// </summary>
/// <param name="exprText">The expression to evaluate.</param>
/// <param name="index">
/// The 0-based index into the file where the expression should be
/// evaluated.
/// </param>
/// <remarks>New in 2.2</remarks>
public PythonAst GetAstFromText(string exprText, SourceLocation location) {
var scopes = FindScope(location);
var privatePrefix = GetPrivatePrefixClassName(scopes);
return GetAstFromText(exprText, privatePrefix);
}
public string ModuleName {
get {
return _scope.GlobalScope.Name;
}
}
private PythonAst GetAstFromText(string exprText, string privatePrefix) {
using (var parser = Parser.CreateParser(new StringReader(exprText), _unit.ProjectState.LanguageVersion, new ParserOptions() { PrivatePrefix = privatePrefix, Verbatim = true })) {
return parser.ParseTopExpression();
}
}
internal static Expression GetExpression(Statement statement) {
if (statement is ExpressionStatement) {
return ((ExpressionStatement)statement).Expression;
} else if (statement is ReturnStatement) {
return ((ReturnStatement)statement).Expression;
} else {
return null;
}
}
/// <summary>
/// Gets the chain of scopes which are associated with the given position in the code.
/// </summary>
private InterpreterScope FindScope(SourceLocation location) {
var res = FindScope(Scope, _unit.Tree, location);
Debug.Assert(res != null, "Should never return null from FindScope");
return res;
}
private static bool IsInFunctionParameter(InterpreterScope scope, PythonAst tree, SourceLocation location) {
var function = scope.Node as FunctionDefinition;
if (function == null) {
// Not a function
return false;
}
if (location.Index < function.StartIndex || location.Index >= function.Body.StartIndex) {
// Not within the def line
return false;
}
return function.Parameters != null &&
function.Parameters.Any(p => {
var paramName = p.GetVerbatimImage(tree) ?? p.Name;
return location.Index >= p.StartIndex && location.Index <= p.StartIndex + paramName.Length;
});
}
private static int GetParentScopeIndent(InterpreterScope scope, PythonAst tree) {
if (scope is ClassScope) {
// Return column of "class" statement
return tree.IndexToLocation(scope.GetStart(tree)).Column;
}
var function = scope as FunctionScope;
if (function != null && !((FunctionDefinition)function.Node).IsLambda) {
// Return column of "def" statement
return tree.IndexToLocation(scope.GetStart(tree)).Column;
}
var isinstance = scope as IsInstanceScope;
if (isinstance != null && isinstance._effectiveSuite != null) {
int col = tree.IndexToLocation(isinstance._startIndex).Column;
if (isinstance._effectiveSuite.StartIndex < isinstance._startIndex) {
// "assert isinstance", so scope is before the test
return col - 1;
} else {
// "if isinstance", so scope is at the test
return col;
}
}
return -1;
}
private static InterpreterScope FindScope(InterpreterScope parent, PythonAst tree, SourceLocation location) {
var children = parent.Children.Where(c => !(c is StatementScope)).ToList();
InterpreterScope candidate = null;
for (int i = 0; i < children.Count; ++i) {
if (IsInFunctionParameter(children[i], tree, location)) {
// In parameter name scope, so consider the function scope.
candidate = children[i];
continue;
}
int start = children[i].GetBodyStart(tree);
if (start > location.Index) {
// We've gone past index completely so our last candidate is
// the best one.
break;
}
int end = children[i].GetStop(tree);
if (i + 1 < children.Count) {
int nextStart = children[i + 1].GetStart(tree);
if (nextStart > end) {
end = nextStart;
}
}
if (location.Index <= end || (candidate == null && i + 1 == children.Count)) {
candidate = children[i];
}
}
if (candidate == null) {
// No children, so we must belong in our parent
return parent;
}
int scopeIndent = GetParentScopeIndent(candidate, tree);
if (location.Column <= scopeIndent) {
// Candidate is at deeper indentation than location and the
// candidate is scoped, so return the parent instead.
return parent;
}
// Recurse to check children of candidate scope
var child = FindScope(candidate, tree, location);
var funcChild = child as FunctionScope;
if (funcChild != null &&
funcChild.Function.FunctionDefinition.IsLambda &&
child.GetStop(tree) < location.Index) {
// Do not want to extend a lambda function's scope to the end of
// the parent scope.
return parent;
}
return child;
}
private static IEnumerable<MemberResult> MemberDictToResultList(
string privatePrefix,
GetMemberOptions options,
Dictionary<string, IEnumerable<AnalysisValue>> memberDict,
Dictionary<string, IEnumerable<AnalysisValue>> ownerDict = null,
int maximumOwners = 0
) {
foreach (var kvp in memberDict) {
string name = GetMemberName(privatePrefix, options, kvp.Key);
string completion = name;
if (name != null) {
IEnumerable<AnalysisValue> owners;
if (ownerDict != null && ownerDict.TryGetValue(kvp.Key, out owners) &&
owners.Any() && owners.Count() < maximumOwners) {
// This member came from less than the full set of types.
var seenNames = new HashSet<string>();
var newName = new StringBuilder(name);
newName.Append(" (");
foreach (var v in owners) {
if (!string.IsNullOrWhiteSpace(v.ShortDescription) && seenNames.Add(v.ShortDescription)) {
// Restrict each displayed type to 25 characters
if (v.ShortDescription.Length > 25) {
newName.Append(v.ShortDescription.Substring(0, 22));
newName.Append("...");
} else {
newName.Append(v.ShortDescription);
}
newName.Append(", ");
}
if (newName.Length > 200) break;
}
// Restrict the entire completion string to 200 characters
if (newName.Length > 200) {
newName.Length = 197;
// Avoid showing more than three '.'s in a row
while (newName[newName.Length - 1] == '.') {
newName.Length -= 1;
}
newName.Append("...");
} else {
newName.Length -= 2;
}
newName.Append(")");
name = newName.ToString();
}
yield return new MemberResult(name, completion, kvp.Value, null);
}
}
}
private static IEnumerable<MemberResult> SingleMemberResult(string privatePrefix, GetMemberOptions options, IDictionary<string, IAnalysisSet> memberDict) {
foreach (var kvp in memberDict) {
string name = GetMemberName(privatePrefix, options, kvp.Key);
if (name != null) {
yield return new MemberResult(name, kvp.Value);
}
}
}
private static string GetMemberName(string privatePrefix, GetMemberOptions options, string name) {
if (privatePrefix != null && name.StartsWith(privatePrefix) && !name.EndsWith("__")) {
// private prefix inside of the class, filter out the prefix.
return name.Substring(privatePrefix.Length - 2);
} else if (!_otherPrivateRegex.IsMatch(name) || !options.HideAdvanced()) {
return name;
}
return null;
}
private static string GetPrivatePrefixClassName(InterpreterScope scope) {
var klass = scope.EnumerateTowardsGlobal.OfType<ClassScope>().FirstOrDefault();
return klass == null ? null : klass.Name;
}
private static string GetPrivatePrefix(InterpreterScope scope) {
string classScopePrefix = GetPrivatePrefixClassName(scope);
if (classScopePrefix != null) {
return "_" + classScopePrefix + "__";
}
return null;
}
private int LineToIndex(int line) {
if (line <= 1) { // <= because v1 allowed zero even though we take 1 based lines.
return 0;
}
// line is 1 based, and index 0 in the array is the position of the 2nd line in the file.
line -= 2;
return _unit.Tree._lineLocations[line].EndIndex;
}
/// <summary>
/// Finds the best available analysis unit for lookup. This will be the one that is provided
/// by the nearest enclosing scope that is capable of providing one.
/// </summary>
private AnalysisUnit GetNearestEnclosingAnalysisUnit(InterpreterScope scopes) {
var units = from scope in scopes.EnumerateTowardsGlobal
let ns = scope.AnalysisValue
where ns != null
let unit = ns.AnalysisUnit
where unit != null
select unit;
return units.FirstOrDefault() ?? _unit;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class MinTests
{
// Get a set of ranges from 0 to each count, with an extra parameter for a minimum where each item is negated (-x).
public static IEnumerable<object[]> MinData(int[] counts)
{
Func<int, int> min = x => 1 - x;
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), min))
{
yield return results;
}
}
//
// Min
//
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Int(Labeled<ParallelQuery<int>> labeled, int count, int min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Min());
Assert.Equal(0, query.Select(x => (int?)x).Min());
Assert.Equal(min, query.Min(x => -x));
Assert.Equal(min, query.Min(x => -(int?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(MinData), new[] { 1024 * 32, 1024 * 1024 })]
public static void Min_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int min)
{
Min_Int(labeled, count, min);
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (int?)x : null).Min());
Assert.Equal(min, query.Min(x => x >= count / 2 ? -(int?)x : null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (int?)null).Min());
Assert.Null(query.Min(x => (int?)null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Long(Labeled<ParallelQuery<int>> labeled, int count, long min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (long)x).Min());
Assert.Equal(0, query.Select(x => (long?)x).Min());
Assert.Equal(min, query.Min(x => -(long)x));
Assert.Equal(min, query.Min(x => -(long?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(MinData), new[] { 1024 * 32, 1024 * 1024 })]
public static void Min_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long min)
{
Min_Long(labeled, count, min);
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (long?)x : null).Min());
Assert.Equal(min, query.Min(x => x >= count / 2 ? -(long?)x : null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (long?)null).Min());
Assert.Null(query.Min(x => (long?)null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Float(Labeled<ParallelQuery<int>> labeled, int count, float min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (float)x).Min());
Assert.Equal(0, query.Select(x => (float?)x).Min());
Assert.Equal(min, query.Min(x => -(float)x));
Assert.Equal(min, query.Min(x => -(float?)x));
Assert.Equal(float.NegativeInfinity, query.Select(x => x == count / 2 ? float.NegativeInfinity : x).Min());
Assert.Equal(float.NegativeInfinity, query.Select(x => x == count / 2 ? (float?)float.NegativeInfinity : x).Min());
Assert.Equal(float.NaN, query.Select(x => x == count / 2 ? float.NaN : x).Min());
Assert.Equal(float.NaN, query.Select(x => x == count / 2 ? (float?)float.NaN : x).Min());
}
[Theory]
[OuterLoop]
[MemberData(nameof(MinData), new[] { 1024 * 32, 1024 * 1024 })]
public static void Min_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float min)
{
Min_Float(labeled, count, min);
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (float?)x : null).Min());
Assert.Equal(min, query.Min(x => x >= count / 2 ? -(float?)x : null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 3 })]
public static void Min_Float_Special(Labeled<ParallelQuery<int>> labeled, int count, float min)
{
// Null is defined as 'least' when ordered, but is not the minimum.
Func<int, float?> translate = x =>
x % 3 == 0 ? (float?)null :
x % 3 == 1 ? float.MinValue :
float.NaN;
ParallelQuery<int> query = labeled.Item;
Assert.Equal(float.NaN, query.Select(x => x == count / 2 ? float.NaN : float.MinValue).Min());
Assert.Equal(float.NaN, query.Select(translate).Min());
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (float?)null).Min());
Assert.Null(query.Min(x => (float?)null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Double(Labeled<ParallelQuery<int>> labeled, int count, double min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (double)x).Min());
Assert.Equal(0, query.Select(x => (double?)x).Min());
Assert.Equal(min, query.Min(x => -(double)x));
Assert.Equal(min, query.Min(x => -(double?)x));
Assert.Equal(double.NegativeInfinity, query.Select(x => x == count / 2 ? double.NegativeInfinity : x).Min());
Assert.Equal(double.NegativeInfinity, query.Select(x => x == count / 2 ? (double?)double.NegativeInfinity : x).Min());
Assert.Equal(double.NaN, query.Select(x => x == count / 2 ? double.NaN : x).Min());
Assert.Equal(double.NaN, query.Select(x => x == count / 2 ? (double?)double.NaN : x).Min());
}
[Theory]
[OuterLoop]
[MemberData(nameof(MinData), new[] { 1024 * 32, 1024 * 1024 })]
public static void Min_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double min)
{
Min_Double(labeled, count, min);
}
[Theory]
[MemberData(nameof(MinData), new[] { 3 })]
public static void Min_Double_Special(Labeled<ParallelQuery<int>> labeled, int count, double min)
{
// Null is defined as 'least' when ordered, but is not the minimum.
Func<int, double?> translate = x =>
x % 3 == 0 ? (double?)null :
x % 3 == 1 ? double.MinValue :
double.NaN;
ParallelQuery<int> query = labeled.Item;
Assert.Equal(double.NaN, query.Select(x => x == count / 2 ? double.NaN : double.MinValue).Min());
Assert.Equal(double.NaN, query.Select(translate).Min());
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (double?)x : null).Min());
Assert.Equal(min, query.Min(x => x >= count / 2 ? -(double?)x : null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (double?)null).Min());
Assert.Null(query.Min(x => (double?)null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (decimal)x).Min());
Assert.Equal(0, query.Select(x => (decimal?)x).Min());
Assert.Equal(min, query.Min(x => -(decimal)x));
Assert.Equal(min, query.Min(x => -(decimal?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(MinData), new[] { 1024 * 32, 1024 * 1024 })]
public static void Min_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal min)
{
Min_Decimal(labeled, count, min);
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(count / 2, query.Select(x => x >= count / 2 ? (decimal?)x : null).Min());
Assert.Equal(min, query.Min(x => x >= count / 2 ? -(decimal?)x : null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (decimal?)null).Min());
Assert.Null(query.Min(x => (decimal?)null));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Other(Labeled<ParallelQuery<int>> labeled, int count, int min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => DelgatedComparable.Delegate(x, Comparer<int>.Default)).Min().Value);
Assert.Equal(count - 1, query.Select(x => DelgatedComparable.Delegate(x, ReverseComparer.Instance)).Min().Value);
}
[Theory]
[OuterLoop]
[MemberData(nameof(MinData), new[] { 1024 * 32, 1024 * 1024 })]
public static void Min_Other_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int min)
{
Min_Other(labeled, count, min);
}
[Theory]
[MemberData(nameof(MinData), new[] { 1 })]
public static void Min_NotComparable(Labeled<ParallelQuery<int>> labeled, int count, int min)
{
NotComparable a = new NotComparable(0);
Assert.Equal(a, labeled.Item.Min(x => a));
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Other_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(count / 2, query.Min(x => x >= count / 2 ? DelgatedComparable.Delegate(x, Comparer<int>.Default) : null).Value);
Assert.Equal(count - 1, query.Min(x => x >= count / 2 ? DelgatedComparable.Delegate(x, ReverseComparer.Instance) : null).Value);
}
[Theory]
[MemberData(nameof(MinData), new[] { 1, 2, 16 })]
public static void Min_Other_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int min)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (string)null).Min());
Assert.Null(query.Min(x => (string)null));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0 }, MemberType = typeof(UnorderedSources))]
public static void Min_EmptyNullable(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Null(labeled.Item.Min(x => (int?)x));
Assert.Null(labeled.Item.Min(x => (long?)x));
Assert.Null(labeled.Item.Min(x => (float?)x));
Assert.Null(labeled.Item.Min(x => (double?)x));
Assert.Null(labeled.Item.Min(x => (decimal?)x));
Assert.Null(labeled.Item.Min(x => new object()));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0 }, MemberType = typeof(UnorderedSources))]
public static void Min_InvalidOperationException(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Throws<InvalidOperationException>(() => labeled.Item.Min());
Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (long)x));
Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (float)x));
Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (double)x));
Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => (decimal)x));
Assert.Throws<InvalidOperationException>(() => labeled.Item.Min(x => new NotComparable(x)));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1 }, MemberType = typeof(UnorderedSources))]
public static void Min_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (int?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (long)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (long?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (float)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (float?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (double)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (double?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (decimal)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => (decimal?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Min(x => new NotComparable(x)));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1 }, MemberType = typeof(UnorderedSources))]
public static void Min_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, int>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, int?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, long>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, long?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, float>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, float?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, double>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, double?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, decimal>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, decimal?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Min((Func<int, NotComparable>)(x => { throw new DeliberateTestException(); })));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Min_AggregateException_NotComparable(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<ArgumentException>(() => labeled.Item.Min(x => new NotComparable(x)));
}
[Fact]
public static void Min_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Min((Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Min((Func<int?, int?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Min((Func<long, long>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Min((Func<long?, long?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Min((Func<float, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Min((Func<float?, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Min((Func<double, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Min((Func<double?, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Min((Func<decimal, decimal>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Min((Func<decimal?, decimal>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<NotComparable>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Min((Func<int, NotComparable>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<object>)null).Min());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(new object(), 1).Min((Func<object, object>)null));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Batch
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Batch.Common;
using Microsoft.Azure.Batch.FileStaging;
using Microsoft.Rest.Azure;
using Models = Microsoft.Azure.Batch.Protocol.Models;
/// <summary>
/// An Azure Batch task. A task is a piece of work that is associated with a job and runs on a compute node.
/// </summary>
public partial class CloudTask : IRefreshable
{
#region // Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CloudTask"/> class.
/// </summary>
/// <param name="id">The id of the task.</param>
/// <param name="commandline">The command line of the task.</param>
/// <remarks>The newly created CloudTask is initially not associated with any task in the Batch service.
/// To associate it with a job and submit it to the Batch service, use <see cref="JobOperations.AddTaskAsync(string, IEnumerable{CloudTask}, BatchClientParallelOptions, ConcurrentBag{ConcurrentDictionary{Type, IFileStagingArtifact}}, TimeSpan?, IEnumerable{BatchClientBehavior})"/>.</remarks>
public CloudTask(string id, string commandline)
{
this.propertyContainer = new PropertyContainer();
// set initial conditions
this.Id = id;
this.CommandLine = commandline;
// set up custom behaviors
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, null);
}
#endregion // Constructors
internal BindingState BindingState
{
get { return this.propertyContainer.BindingState; }
}
/// <summary>
/// Stages the files listed in the <see cref="FilesToStage"/> list.
/// </summary>
/// <param name="allFileStagingArtifacts">An optional collection to customize and receive information about the file staging process.
/// For more information see <see cref="IFileStagingArtifact"/>.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The staging operation runs asynchronously.</remarks>
public async System.Threading.Tasks.Task StageFilesAsync(ConcurrentDictionary<Type, IFileStagingArtifact> allFileStagingArtifacts = null)
{
// stage all these files
// TODO: align this copy with threadsafe implementation of the IList<>
List<IFileStagingProvider> allFiles = this.FilesToStage == null ? new List<IFileStagingProvider>() : new List<IFileStagingProvider>(this.FilesToStage);
//TODO: There is a threading issue doing this - expose a change tracking box directly and use a lock?
if (this.FilesToStage != null && this.ResourceFiles == null)
{
this.ResourceFiles = new List<ResourceFile>(); //We're about to have some resource files
}
// now we have all files, send off to file staging machine
System.Threading.Tasks.Task fileStagingTask = FileStagingUtils.StageFilesAsync(allFiles, allFileStagingArtifacts);
// wait for file staging async task
await fileStagingTask.ConfigureAwait(continueOnCapturedContext: false);
// now update Task with its new ResourceFiles
foreach (IFileStagingProvider curFile in allFiles)
{
IEnumerable<ResourceFile> curStagedFiles = curFile.StagedFiles;
foreach (ResourceFile curStagedFile in curStagedFiles)
{
this.ResourceFiles.Add(curStagedFile);
}
}
}
/// <summary>
/// Stages the files listed in the <see cref="FilesToStage"/> list.
/// </summary>
/// <returns>A collection of information about the file staging process.
/// For more information see <see cref="IFileStagingArtifact"/>.</returns>
/// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="StageFilesAsync"/>.</remarks>
public ConcurrentDictionary<Type, IFileStagingArtifact> StageFiles()
{
ConcurrentDictionary<Type, IFileStagingArtifact> allFileStagingArtifacts = new ConcurrentDictionary<Type,IFileStagingArtifact>();
Task asyncTask = StageFilesAsync(allFileStagingArtifacts);
asyncTask.WaitAndUnaggregateException();
return allFileStagingArtifacts;
}
/// <summary>
/// Enumerates the files in the <see cref="CloudTask"/>'s directory on its compute node.
/// </summary>
/// <param name="recursive">If true, performs a recursive list of all files of the task. If false, returns only the files in the root task directory.</param>
/// <param name="detailLevel">A <see cref="DetailLevel"/> used for filtering the list and for controlling which properties are retrieved from the service.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/> and <paramref name="detailLevel"/>.</param>
/// <returns>An <see cref="IPagedEnumerable{NodeFile}"/> that can be used to enumerate files asynchronously or synchronously.</returns>
/// <remarks>This method returns immediately; the file data is retrieved from the Batch service only when the collection is enumerated.
/// Retrieval is non-atomic; file data is retrieved in pages during enumeration of the collection.</remarks>
public IPagedEnumerable<NodeFile> ListNodeFiles(bool? recursive = null, DetailLevel detailLevel = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// craft the behavior manager for this call
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
IPagedEnumerable<NodeFile> enumerator = this.parentBatchClient.JobOperations.ListNodeFilesImpl(this.parentJobId, this.Id, recursive, bhMgr, detailLevel);
return enumerator;
}
/// <summary>
/// Enumerates the subtasks of the multi-instance <see cref="CloudTask"/>.
/// </summary>
/// <param name="detailLevel">A <see cref="DetailLevel"/> used for filtering the list and for controlling which properties are retrieved from the service.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/> and <paramref name="detailLevel"/>.</param>
/// <returns>An <see cref="IPagedEnumerable{SubtaskInformation}"/> that can be used to enumerate files asynchronously or synchronously.</returns>
/// <remarks>This method returns immediately; the file data is retrieved from the Batch service only when the collection is enumerated.
/// Retrieval is non-atomic; file data is retrieved in pages during enumeration of the collection.</remarks>
public IPagedEnumerable<SubtaskInformation> ListSubtasks(DetailLevel detailLevel = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// craft the behavior manager for this call
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
IPagedEnumerable<SubtaskInformation> enumerator = this.parentBatchClient.JobOperations.ListSubtasksImpl(this.parentJobId, this.Id, bhMgr, detailLevel);
return enumerator;
}
/// <summary>
/// Commits all pending changes to this <see cref="CloudTask" /> to the Azure Batch service.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
/// <remarks>The commit operation runs asynchronously.</remarks>
public async System.Threading.Tasks.Task CommitAsync(IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken))
{
this.propertyContainer.IsReadOnly = true;
// craft the behavior manager for this call
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
if (BindingState.Unbound == this.propertyContainer.BindingState)
{
//TODO: Implement task submission via .Commit here
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
}
else
{
Models.TaskConstraints protoTaskConstraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, o => o.GetTransportObject());
System.Threading.Tasks.Task<AzureOperationHeaderResponse<Models.TaskUpdateHeaders>> asyncTaskUpdate =
this.parentBatchClient.ProtocolLayer.UpdateTask(
this.parentJobId,
this.Id,
protoTaskConstraints,
bhMgr,
cancellationToken);
await asyncTaskUpdate.ConfigureAwait(continueOnCapturedContext: false);
}
}
/// <summary>
/// Commits all pending changes to this <see cref="CloudTask" /> to the Azure Batch service.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
/// <remarks>
/// <para>This is a blocking operation. For a non-blocking equivalent, see <see cref="CommitAsync"/>.</para>
/// </remarks>
public void Commit(IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = CommitAsync(additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
/// <summary>
/// Terminates this <see cref="CloudTask"/>, marking it as completed.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="Task"/> object that represents the asynchronous operation.</returns>
/// <remarks>The terminate operation runs asynchronously.</remarks>
public System.Threading.Tasks.Task TerminateAsync(IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
System.Threading.Tasks.Task asyncTask = this.parentBatchClient.ProtocolLayer.TerminateTask(
this.parentJobId,
this.Id,
bhMgr,
cancellationToken);
return asyncTask;
}
/// <summary>
/// Terminates this <see cref="CloudTask"/>, marking it as completed.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="TerminateAsync"/>.</remarks>
public void Terminate(IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = TerminateAsync(additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
/// <summary>
/// Deletes this <see cref="CloudTask"/>.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The delete operation runs asynchronously.</remarks>
public System.Threading.Tasks.Task DeleteAsync(IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
System.Threading.Tasks.Task asyncTask = this.parentBatchClient.ProtocolLayer.DeleteTask(
this.parentJobId,
this.Id,
bhMgr,
cancellationToken);
return asyncTask;
}
/// <summary>
/// Deletes this <see cref="CloudTask"/>.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="DeleteAsync"/>.</remarks>
public void Delete(IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = DeleteAsync(additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
/// <summary>
/// Reactivates this <see cref="CloudTask"/>, allowing it to run again even if its retry count has been exhausted.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns>
/// <remarks>
/// <para>
/// Reactivation makes a task eligible to be retried again up to its maximum retry count.
/// </para>
/// <para>
/// This operation will fail for tasks that are not completed or that previously completed successfully (with an exit code of 0).
/// Additionally, this will fail if the job is in the <see cref="JobState.Completed"/> or <see cref="JobState.Terminating"/> or <see cref="JobState.Deleting"/> state.
/// </para>
/// <para>
/// The reactivate operation runs asynchronously.
/// </para>
/// </remarks>
public System.Threading.Tasks.Task ReactivateAsync(IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
System.Threading.Tasks.Task asyncTask = this.parentBatchClient.ProtocolLayer.ReactivateTask(
this.parentJobId,
this.Id,
bhMgr,
cancellationToken);
return asyncTask;
}
/// <summary>
/// Reactivates this <see cref="CloudTask"/>, allowing it to run again even if its retry count has been exhausted.
/// </summary>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <remarks>
/// <para>
/// Reactivation makes a task eligible to be retried again up to its maximum retry count.
/// </para>
/// <para>
/// This operation will fail for tasks that are not completed or that previously completed successfully (with an exit code of 0).
/// Additionally, this will fail if the job is in the <see cref="JobState.Completed"/> or <see cref="JobState.Terminating"/> or <see cref="JobState.Deleting"/> state.
/// </para>
/// <para>
/// This is a blocking operation. For a non-blocking equivalent, see <see cref="ReactivateAsync"/>.
/// </para>
/// </remarks>
public void Reactivate(IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = ReactivateAsync(additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
/// <summary>
/// Gets the specified <see cref="NodeFile"/> from the <see cref="CloudTask"/>'s directory on its compute node.
/// </summary>
/// <param name="filePath">The path of the file to retrieve.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="NodeFile"/> representing the specified file.</returns>
/// <remarks>The get file operation runs asynchronously.</remarks>
public System.Threading.Tasks.Task<NodeFile> GetNodeFileAsync(
string filePath,
IEnumerable<BatchClientBehavior> additionalBehaviors = null,
CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
//create the behavior manager
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);
//make the call
System.Threading.Tasks.Task<NodeFile> asyncTask = this.parentBatchClient.JobOperations.GetNodeFileAsyncImpl(this.parentJobId, this.Id, filePath, bhMgr, cancellationToken);
return asyncTask;
}
/// <summary>
/// Gets the specified <see cref="NodeFile"/> from the <see cref="CloudTask"/>'s directory on its compute node.
/// </summary>
/// <param name="filePath">The path of the file to retrieve.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <returns>A <see cref="NodeFile"/> representing the specified file.</returns>
/// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="GetNodeFileAsync"/>.</remarks>
public NodeFile GetNodeFile(string filePath, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task<NodeFile> asyncTask = this.GetNodeFileAsync(filePath, additionalBehaviors);
NodeFile file = asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
return file;
}
#region IRefreshable
/// <summary>
/// Refreshes the current <see cref="CloudTask"/>.
/// </summary>
/// <param name="detailLevel">The detail level for the refresh. If a detail level which omits the <see cref="Id"/> property is specified, refresh will fail.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns>
public async System.Threading.Tasks.Task RefreshAsync(
DetailLevel detailLevel = null,
IEnumerable<BatchClientBehavior> additionalBehaviors = null,
CancellationToken cancellationToken = default(CancellationToken))
{
UtilitiesInternal.ThrowOnUnbound(this.propertyContainer.BindingState);
// create the behavior managaer
BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors, detailLevel);
System.Threading.Tasks.Task<AzureOperationResponse<Models.CloudTask, Models.TaskGetHeaders>> asyncTask =
this.parentBatchClient.ProtocolLayer.GetTask(
this.parentJobId,
this.Id,
bhMgr,
cancellationToken);
AzureOperationResponse<Models.CloudTask, Models.TaskGetHeaders> response = await asyncTask.ConfigureAwait(continueOnCapturedContext: false);
// get task from response
Models.CloudTask newProtocolTask = response.Body;
// immediately available to all threads
this.propertyContainer = new PropertyContainer(newProtocolTask);
}
/// <summary>
/// Refreshes the current <see cref="CloudTask"/>.
/// </summary>
/// <param name="detailLevel">The detail level for the refresh. If a detail level which omits the <see cref="Id"/> property is specified, refresh will fail.</param>
/// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param>
public void Refresh(
DetailLevel detailLevel = null,
IEnumerable<BatchClientBehavior> additionalBehaviors = null)
{
Task asyncTask = RefreshAsync(detailLevel, additionalBehaviors);
asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors);
}
#endregion IRefreshable
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ColumnEnums.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller
{
using System;
using System.Diagnostics.CodeAnalysis;
// Enumerations are in alphabetical order.
/// <summary>
/// Available values for the Attributes column of the Component table.
/// </summary>
[Flags]
public enum ComponentAttributes : int
{
/// <summary>
/// Local only - Component cannot be run from source.
/// </summary>
/// <remarks><p>
/// Set this value for all components belonging to a feature to prevent the feature from being run-from-network or
/// run-from-source. Note that if a feature has no components, the feature always shows run-from-source and
/// run-from-my-computer as valid options.
/// </p></remarks>
None = 0x0000,
/// <summary>
/// Component can only be run from source.
/// </summary>
/// <remarks><p>
/// Set this bit for all components belonging to a feature to prevent the feature from being run-from-my-computer.
/// Note that if a feature has no components, the feature always shows run-from-source and run-from-my-computer
/// as valid options.
/// </p></remarks>
SourceOnly = 0x0001,
/// <summary>
/// Component can run locally or from source.
/// </summary>
Optional = 0x0002,
/// <summary>
/// If this bit is set, the value in the KeyPath column is used as a key into the Registry table.
/// </summary>
/// <remarks><p>
/// If the Value field of the corresponding record in the Registry table is null, the Name field in that record
/// must not contain "+", "-", or "*". For more information, see the description of the Name field in Registry
/// table.
/// <p>Setting this bit is recommended for registry entries written to the HKCU hive. This ensures the installer
/// writes the necessary HKCU registry entries when there are multiple users on the same machine.</p>
/// </p></remarks>
RegistryKeyPath = 0x0004,
/// <summary>
/// If this bit is set, the installer increments the reference count in the shared DLL registry of the component's
/// key file. If this bit is not set, the installer increments the reference count only if the reference count
/// already exists.
/// </summary>
SharedDllRefCount = 0x0008,
/// <summary>
/// If this bit is set, the installer does not remove the component during an uninstall. The installer registers
/// an extra system client for the component in the Windows Installer registry settings.
/// </summary>
Permanent = 0x0010,
/// <summary>
/// If this bit is set, the value in the KeyPath column is a key into the ODBCDataSource table.
/// </summary>
OdbcDataSource = 0x0020,
/// <summary>
/// If this bit is set, the installer reevaluates the value of the statement in the Condition column upon a reinstall.
/// If the value was previously False and has changed to true, the installer installs the component. If the value
/// was previously true and has changed to false, the installer removes the component even if the component has
/// other products as clients.
/// </summary>
Transitive = 0x0040,
/// <summary>
/// If this bit is set, the installer does not install or reinstall the component if a key path file or a key path
/// registry entry for the component already exists. The application does register itself as a client of the component.
/// </summary>
/// <remarks><p>
/// Use this flag only for components that are being registered by the Registry table. Do not use this flag for
/// components registered by the AppId, Class, Extension, ProgId, MIME, and Verb tables.
/// </p></remarks>
NeverOverwrite = 0x0080,
/// <summary>
/// Set this bit to mark this as a 64-bit component. This attribute facilitates the installation of packages that
/// include both 32-bit and 64-bit components. If this bit is not set, the component is registered as a 32-bit component.
/// </summary>
/// <remarks><p>
/// If this is a 64-bit component replacing a 32-bit component, set this bit and assign a new GUID in the
/// ComponentId column.
/// </p></remarks>
SixtyFourBit = 0x0100,
/// <summary>
/// Set this bit to disable registry reflection on all existing and new registry keys affected by this component.
/// </summary>
/// <remarks><p>
/// If this bit is set, the Windows Installer calls the RegDisableReflectionKey on each key being accessed by the component.
/// This bit is available with Windows Installer version 4.0 and is ignored on 32-bit systems.
/// </p></remarks>
DisableRegistryReflection = 0x0200,
/// <summary>
/// [MSI 4.5] Set this bit for a component in a patch package to prevent leaving orphan components on the computer.
/// </summary>
/// <remarks><p>
/// If a subsequent patch is installed, marked with the SupersedeEarlier flag in its MsiPatchSequence
/// table to supersede the first patch, Windows Installer 4.5 can unregister and uninstall components marked with the
/// UninstallOnSupersedence value. If the component is not marked with this bit, installation of a superseding patch can leave
/// behind an unused component on the computer.
/// </p></remarks>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Supersedence")]
UninstallOnSupersedence = 0x0400,
/// <summary>
/// [MSI 4.5] If a component is marked with this attribute value in at least one package installed on the system,
/// the installer treats the component as marked in all packages. If a package that shares the marked component
/// is uninstalled, Windows Installer 4.5 can continue to share the highest version of the component on the system,
/// even if that highest version was installed by the package that is being uninstalled.
/// </summary>
Shared = 0x0800,
}
/// <summary>
/// Defines flags for the Attributes column of the Control table.
/// </summary>
[Flags]
public enum ControlAttributes : int
{
/// <summary>If this bit is set, the control is visible on the dialog box.</summary>
Visible = 0x00000001,
/// <summary>specifies if the given control is enabled or disabled. Most controls appear gray when disabled.</summary>
Enabled = 0x00000002,
/// <summary>If this bit is set, the control is displayed with a sunken, three dimensional look.</summary>
Sunken = 0x00000004,
/// <summary>The Indirect control attribute specifies whether the value displayed or changed by this control is referenced indirectly.</summary>
Indirect = 0x00000008,
/// <summary>If this bit is set on a control, the associated property specified in the Property column of the Control table is an integer.</summary>
Integer = 0x00000010,
/// <summary>If this bit is set the text in the control is displayed in a right-to-left reading order.</summary>
RightToLeftReadingOrder = 0x00000020,
/// <summary>If this style bit is set, text in the control is aligned to the right.</summary>
RightAligned = 0x00000040,
/// <summary>If this bit is set, the scroll bar is located on the left side of the control, otherwise it is on the right.</summary>
LeftScroll = 0x00000080,
/// <summary>This is a combination of the RightToLeftReadingOrder, RightAligned, and LeftScroll attributes.</summary>
Bidirectional = RightToLeftReadingOrder | RightAligned | LeftScroll,
/// <summary>If this bit is set on a text control, the control is displayed transparently with the background showing through the control where there are no characters.</summary>
Transparent = 0x00010000,
/// <summary>If this bit is set on a text control, the occurrence of the character "&" in a text string is displayed as itself.</summary>
NoPrefix = 0x00020000,
/// <summary>If this bit is set the text in the control is displayed on a single line.</summary>
NoWrap = 0x00040000,
/// <summary>If this bit is set for a text control, the control will automatically attempt to format the displayed text as a number representing a count of bytes.</summary>
FormatSize = 0x00080000,
/// <summary>If this bit is set, fonts are created using the user's default UI code page. Otherwise it is created using the database code page.</summary>
UsersLanguage = 0x00100000,
/// <summary>If this bit is set on an Edit control, the installer creates a multiple line edit control with a vertical scroll bar.</summary>
Multiline = 0x00010000,
/// <summary>This attribute creates an edit control for entering passwords. The control displays each character as an asterisk (*) as they are typed into the control.</summary>
PasswordInput = 0x00200000,
/// <summary>If this bit is set on a ProgressBar control, the bar is drawn as a series of small rectangles in Microsoft Windows 95-style. Otherwise it is drawn as a single continuous rectangle.</summary>
Progress95 = 0x00010000,
/// <summary>If this bit is set, the control shows removable volumes.</summary>
RemovableVolume = 0x00010000,
/// <summary>If this bit is set, the control shows fixed internal hard drives.</summary>
FixedVolume = 0x00020000,
/// <summary>If this bit is set, the control shows remote volumes.</summary>
RemoteVolume = 0x00040000,
/// <summary>If this bit is set, the control shows CD-ROM volumes.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cdrom")]
CdromVolume = 0x00080000,
/// <summary>If this bit is set, the control shows RAM disk volumes.</summary>
RamDiskVolume = 0x00100000,
/// <summary>If this bit is set, the control shows floppy volumes.</summary>
FloppyVolume = 0x00200000,
/// <summary>Specifies whether or not the rollback backup files are included in the costs displayed by the VolumeCostList control.</summary>
ShowRollbackCost = 0x00400000,
/// <summary>If this bit is set, the items listed in the control are displayed in a specified order. Otherwise, items are displayed in alphabetical order.</summary>
Sorted = 0x00010000,
/// <summary>If this bit is set on a combo box, the edit field is replaced by a static text field. This prevents a user from entering a new value and requires the user to choose only one of the predefined values.</summary>
ComboList = 0x00020000,
//ImageHandle = 0x00010000,
/// <summary>If this bit is set on a check box or a radio button group, the button is drawn with the appearance of a push button, but its logic stays the same.</summary>
PushLike = 0x00020000,
/// <summary>If this bit is set, the text in the control is replaced by a bitmap image. The Text column in the Control table is a foreign key into the Binary table.</summary>
Bitmap = 0x00040000,
/// <summary>If this bit is set, text is replaced by an icon image and the Text column in the Control table is a foreign key into the Binary table.</summary>
Icon = 0x00080000,
/// <summary>If this bit is set, the picture is cropped or centered in the control without changing its shape or size.</summary>
FixedSize = 0x00100000,
/// <summary>Specifies which size of the icon image to load. If none of the bits are set, the first image is loaded.</summary>
IconSize16 = 0x00200000,
/// <summary>Specifies which size of the icon image to load. If none of the bits are set, the first image is loaded.</summary>
IconSize32 = 0x00400000,
/// <summary>Specifies which size of the icon image to load. If none of the bits are set, the first image is loaded.</summary>
IconSize48 = 0x00600000,
/// <summary>If this bit is set, and the installation is not yet running with elevated privileges, the control is created with a UAC icon.</summary>
ElevationShield = 0x00800000,
/// <summary>If this bit is set, the RadioButtonGroup has text and a border displayed around it.</summary>
HasBorder = 0x01000000,
}
/// <summary>
/// Defines flags for the Type column of the CustomAction table.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags")]
[Flags]
public enum CustomActionTypes : int
{
/// <summary>Unspecified custom action type.</summary>
None = 0x0000,
/// <summary>Target = entry point name</summary>
Dll = 0x0001,
/// <summary>Target = command line args</summary>
Exe = 0x0002,
/// <summary>Target = text string to be formatted and set into property</summary>
TextData = 0x0003,
/// <summary>Target = entry point name, null if none to call</summary>
JScript = 0x0005,
/// <summary>Target = entry point name, null if none to call</summary>
VBScript = 0x0006,
/// <summary>Target = property list for nested engine initialization</summary>
Install = 0x0007,
/// <summary>Source = File.File, file part of installation</summary>
SourceFile = 0x0010,
/// <summary>Source = Directory.Directory, folder containing existing file</summary>
Directory = 0x0020,
/// <summary>Source = Property.Property, full path to executable</summary>
Property = 0x0030,
/// <summary>Ignore action return status, continue running</summary>
Continue = 0x0040,
/// <summary>Run asynchronously</summary>
Async = 0x0080,
/// <summary>Skip if UI sequence already run</summary>
FirstSequence = 0x0100,
/// <summary>Skip if UI sequence already run in same process</summary>
OncePerProcess = 0x0200,
/// <summary>Run on client only if UI already run on client</summary>
ClientRepeat = 0x0300,
/// <summary>Queue for execution within script</summary>
InScript = 0x0400,
/// <summary>In conjunction with InScript: queue in Rollback script</summary>
Rollback = 0x0100,
/// <summary>In conjunction with InScript: run Commit ops from script on success</summary>
Commit = 0x0200,
/// <summary>No impersonation, run in system context</summary>
NoImpersonate = 0x0800,
/// <summary>Impersonate for per-machine installs on TS machines</summary>
TSAware = 0x4000,
/// <summary>Script requires 64bit process</summary>
SixtyFourBitScript = 0x1000,
/// <summary>Don't record the contents of the Target field in the log file</summary>
HideTarget = 0x2000,
/// <summary>The custom action runs only when a patch is being uninstalled</summary>
PatchUninstall = 0x8000,
}
/// <summary>
/// Defines flags for the Attributes column of the Dialog table.
/// </summary>
[Flags]
public enum DialogAttributes : int
{
/// <summary>If this bit is set, the dialog is originally created as visible, otherwise it is hidden.</summary>
Visible = 0x00000001,
/// <summary>If this bit is set, the dialog box is modal, other dialogs of the same application cannot be put on top of it, and the dialog keeps the control while it is running.</summary>
Modal = 0x00000002,
/// <summary>If this bit is set, the dialog box can be minimized. This bit is ignored for modal dialog boxes, which cannot be minimized.</summary>
Minimize = 0x00000004,
/// <summary>If this style bit is set, the dialog box will stop all other applications and no other applications can take the focus.</summary>
SysModal = 0x00000008,
/// <summary>If this bit is set, the other dialogs stay alive when this dialog box is created.</summary>
KeepModeless = 0x00000010,
/// <summary>If this bit is set, the dialog box periodically calls the installer. If the property changes, it notifies the controls on the dialog.</summary>
TrackDiskSpace = 0x00000020,
/// <summary>If this bit is set, the pictures on the dialog box are created with the custom palette (one per dialog received from the first control created).</summary>
UseCustomPalette = 0x00000040,
/// <summary>If this style bit is set the text in the dialog box is displayed in right-to-left-reading order.</summary>
RightToLeftReadingOrder = 0x00000080,
/// <summary>If this style bit is set, the text is aligned on the right side of the dialog box.</summary>
RightAligned = 0x00000100,
/// <summary>If this style bit is set, the scroll bar is located on the left side of the dialog box.</summary>
LeftScroll = 0x00000200,
/// <summary>This is a combination of the RightToLeftReadingOrder, RightAligned, and the LeftScroll dialog style bits.</summary>
Bidirectional = RightToLeftReadingOrder | RightAligned | LeftScroll,
/// <summary>If this bit is set, the dialog box is an error dialog.</summary>
Error = 0x00010000,
}
/// <summary>
/// Available values for the Attributes column of the Feature table.
/// </summary>
[Flags]
public enum FeatureAttributes : int
{
/// <summary>
/// Favor local - Components of this feature that are not marked for installation from source are installed locally.
/// </summary>
/// <remarks><p>
/// A component shared by two or more features, some of which are set to FavorLocal and some to FavorSource,
/// is installed locally. Components marked <see cref="ComponentAttributes.SourceOnly"/> in the Component
/// table are always run from the source CD/server. The bits FavorLocal and FavorSource work with features not
/// listed by the ADVERTISE property.
/// </p></remarks>
None = 0x0000,
/// <summary>
/// Components of this feature not marked for local installation are installed to run from the source
/// CD-ROM or server.
/// </summary>
/// <remarks><p>
/// A component shared by two or more features, some of which are set to FavorLocal and some to FavorSource,
/// is installed to run locally. Components marked <see cref="ComponentAttributes.None"/> (local-only) in the
/// Component table are always installed locally. The bits FavorLocal and FavorSource work with features
/// not listed by the ADVERTISE property.
/// </p></remarks>
FavorSource = 0x0001,
/// <summary>
/// Set this attribute and the state of the feature is the same as the state of the feature's parent.
/// You cannot use this option if the feature is located at the root of a feature tree.
/// </summary>
/// <remarks><p>
/// Omit this attribute and the feature state is determined according to DisallowAdvertise and
/// FavorLocal and FavorSource.
/// <p>To guarantee that the child feature's state always follows the state of its parent, even when the
/// child and parent are initially set to absent in the SelectionTree control, you must include both
/// FollowParent and UIDisallowAbsent in the attributes of the child feature.</p>
/// <p>Note that if you set FollowParent without setting UIDisallowAbsent, the installer cannot force
/// the child feature out of the absent state. In this case, the child feature matches the parent's
/// installation state only if the child is set to something other than absent.</p>
/// <p>Set FollowParent and UIDisallowAbsent to ensure a child feature follows the state of the parent feature.</p>
/// </p></remarks>
FollowParent = 0x0002,
/// <summary>
/// Set this attribute and the feature state is Advertise.
/// </summary>
/// <remarks><p>
/// If the feature is listed by the ADDDEFAULT property this bit is ignored and the feature state is determined
/// according to FavorLocal and FavorSource.
/// <p>Omit this attribute and the feature state is determined according to DisallowAdvertise and FavorLocal
/// and FavorSource.</p>
/// </p></remarks>
FavorAdvertise = 0x0004,
/// <summary>
/// Set this attribute to prevent the feature from being advertised.
/// </summary>
/// <remarks><p>
/// Note that this bit works only with features that are listed by the ADVERTISE property.
/// <p>Set this attribute and if the listed feature is not a parent or child, the feature is installed according to
/// FavorLocal and FavorSource.</p>
/// <p>Set this attribute for the parent of a listed feature and the parent is installed.</p>
/// <p>Set this attribute for the child of a listed feature and the state of the child is Absent.</p>
/// <p>Omit this attribute and if the listed feature is not a parent or child, the feature state is Advertise.</p>
/// <p>Omit this attribute and if the listed feature is a parent or child, the state of both features is Advertise.</p>
/// </p></remarks>
DisallowAdvertise = 0x0008,
/// <summary>
/// Set this attribute and the user interface does not display an option to change the feature state
/// to Absent. Setting this attribute forces the feature to the installation state, whether or not the
/// feature is visible in the UI.
/// </summary>
/// <remarks><p>
/// Omit this attribute and the user interface displays an option to change the feature state to Absent.
/// <p>Set FollowParent and UIDisallowAbsent to ensure a child feature follows the state of the parent feature.</p>
/// <p>Setting this attribute not only affects the UI, but also forces the feature to the install state whether
/// the feature is visible in the UI or not.</p>
/// </p></remarks>
UIDisallowAbsent = 0x0010,
/// <summary>
/// Set this attribute and advertising is disabled for the feature if the operating system shell does not
/// support Windows Installer descriptors.
/// </summary>
NoUnsupportedAdvertise = 0x0020,
}
/// <summary>
/// Available values for the Attributes column of the File table.
/// </summary>
[Flags]
public enum FileAttributes : int
{
/// <summary>No attributes.</summary>
None = 0x0000,
/// <summary>Read-only.</summary>
ReadOnly = 0x0001,
/// <summary>Hidden.</summary>
Hidden = 0x0002,
/// <summary>System.</summary>
System = 0x0004,
/// <summary>The file is vital for the proper operation of the component to which it belongs.</summary>
Vital = 0x0200,
/// <summary>The file contains a valid checksum. A checksum is required to repair a file that has become corrupted.</summary>
Checksum = 0x0400,
/// <summary>This bit must only be added by a patch and if the file is being added by the patch.</summary>
PatchAdded = 0x1000,
/// <summary>
/// The file's source type is uncompressed. If set, ignore the WordCount summary information property. If neither
/// Noncompressed nor Compressed are set, the compression state of the file is specified by the WordCount summary
/// information property. Do not set both Noncompressed and Compressed.
/// </summary>
NonCompressed = 0x2000,
/// <summary>
/// The file's source type is compressed. If set, ignore the WordCount summary information property. If neither
/// Noncompressed or Compressed are set, the compression state of the file is specified by the WordCount summary
/// information property. Do not set both Noncompressed and Compressed.
/// </summary>
Compressed = 0x4000,
}
/// <summary>
/// Defines values for the Action column of the IniFile and RemoveIniFile tables.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ini")]
public enum IniFileAction : int
{
/// <summary>Creates or updates a .ini entry.</summary>
AddLine = 0,
/// <summary>Creates a .ini entry only if the entry does not already exist.</summary>
CreateLine = 1,
/// <summary>Deletes .ini entry.</summary>
RemoveLine = 2,
/// <summary>Creates a new entry or appends a new comma-separated value to an existing entry.</summary>
AddTag = 3,
/// <summary>Deletes a tag from a .ini entry.</summary>
RemoveTag = 4,
}
/// <summary>
/// Defines values for the Type column of the CompLocator, IniLocator, and RegLocator tables.
/// </summary>
[Flags]
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
public enum LocatorTypes : int
{
/// <summary>Key path is a directory.</summary>
Directory = 0x00000000,
/// <summary>Key path is a file name.</summary>
FileName = 0x00000001,
/// <summary>Key path is a registry value.</summary>
RawValue = 0x00000002,
/// <summary>Set this bit to have the installer search the 64-bit portion of the registry.</summary>
SixtyFourBit = 0x00000010,
}
/// <summary>
/// Defines values for the Root column of the Registry, RemoveRegistry, and RegLocator tables.
/// </summary>
public enum RegistryRoot : int
{
/// <summary>HKEY_CURRENT_USER for a per-user installation,
/// or HKEY_LOCAL_MACHINE for a per-machine installation.</summary>
UserOrMachine = -1,
/// <summary>HKEY_CLASSES_ROOT</summary>
ClassesRoot = 0,
/// <summary>HKEY_CURRENT_USER</summary>
CurrentUser = 1,
/// <summary>HKEY_LOCAL_MACHINE</summary>
LocalMachine = 2,
/// <summary>HKEY_USERS</summary>
Users = 3,
}
/// <summary>
/// Defines values for the InstallMode column of the RemoveFile table.
/// </summary>
[Flags]
public enum RemoveFileModes : int
{
/// <summary>Never remove.</summary>
None = 0,
/// <summary>Remove when the associated component is being installed (install state = local or source).</summary>
OnInstall = 1,
/// <summary>Remove when the associated component is being removed (install state = absent).</summary>
OnRemove = 2,
}
/// <summary>
/// Defines values for the ServiceType, StartType, and ErrorControl columns of the ServiceInstall table.
/// </summary>
[Flags]
public enum ServiceAttributes : int
{
/// <summary>No flags.</summary>
None = 0,
/// <summary>A Win32 service that runs its own process.</summary>
OwnProcess = 0x0010,
/// <summary>A Win32 service that shares a process.</summary>
ShareProcess = 0x0020,
/// <summary>A Win32 service that interacts with the desktop.
/// This value cannot be used alone and must be added to either
/// <see cref="OwnProcess"/> or <see cref="ShareProcess"/>.</summary>
Interactive = 0x0100,
/// <summary>Service starts during startup of the system.</summary>
AutoStart = 0x0002,
/// <summary>Service starts when the service control manager calls the StartService function.</summary>
DemandStart = 0x0003,
/// <summary>Specifies a service that can no longer be started.</summary>
Disabled = 0x0004,
/// <summary>Logs the error, displays a message box and continues the startup operation.</summary>
ErrorMessage = 0x0001,
/// <summary>Logs the error if it is possible and the system is restarted with the last configuration
/// known to be good. If the last-known-good configuration is being started, the startup operation fails.</summary>
ErrorCritical = 0x0003,
/// <summary>When combined with other error flags, specifies that the overall install should fail if
/// the service cannot be installed into the system.</summary>
ErrorControlVital = 0x8000,
}
/// <summary>
/// Defines values for the Event column of the ServiceControl table.
/// </summary>
[Flags]
public enum ServiceControlEvents : int
{
/// <summary>No control events.</summary>
None = 0x0000,
/// <summary>During an install, starts the service during the StartServices action.</summary>
Start = 0x0001,
/// <summary>During an install, stops the service during the StopServices action.</summary>
Stop = 0x0002,
/// <summary>During an install, deletes the service during the DeleteServices action.</summary>
Delete = 0x0008,
/// <summary>During an uninstall, starts the service during the StartServices action.</summary>
UninstallStart = 0x0010,
/// <summary>During an uninstall, stops the service during the StopServices action.</summary>
UninstallStop = 0x0020,
/// <summary>During an uninstall, deletes the service during the DeleteServices action.</summary>
UninstallDelete = 0x0080,
}
/// <summary>
/// Defines values for the StyleBits column of the TextStyle table.
/// </summary>
[Flags]
public enum TextStyles : int
{
/// <summary>Bold</summary>
Bold = 0x0001,
/// <summary>Italic</summary>
Italic = 0x0002,
/// <summary>Underline</summary>
Underline = 0x0004,
/// <summary>Strike out</summary>
Strike = 0x0008,
}
/// <summary>
/// Defines values for the Attributes column of the Upgrade table.
/// </summary>
[Flags]
public enum UpgradeAttributes : int
{
/// <summary>Migrates feature states by enabling the logic in the MigrateFeatureStates action.</summary>
MigrateFeatures = 0x0001,
/// <summary>Detects products and applications but does not remove.</summary>
OnlyDetect = 0x0002,
/// <summary>Continues installation upon failure to remove a product or application.</summary>
IgnoreRemoveFailure = 0x0004,
/// <summary>Detects the range of versions including the value in VersionMin.</summary>
VersionMinInclusive = 0x0100,
/// <summary>Dectects the range of versions including the value in VersionMax.</summary>
VersionMaxInclusive = 0x0200,
/// <summary>Detects all languages, excluding the languages listed in the Language column.</summary>
LanguagesExclusive = 0x0400,
}
}
| |
// Copyright 2008 Adrian Akison
// Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx
using System;
using System.Collections;
using System.Collections.Generic;
namespace Facet.Combinatorics {
/// <summary>
/// Permutations defines a meta-collection, typically a list of lists, of all
/// possible orderings of a set of values. This list is enumerable and allows
/// the scanning of all possible permutations using a simple foreach() loop.
/// The MetaCollectionType parameter of the constructor allows for the creation of
/// two types of sets, those with and without repetition in the output set when
/// presented with repetition in the input set.
/// </summary>
/// <remarks>
/// When given a input collect {A A B}, the following sets are generated:
/// MetaCollectionType.WithRepetition =>
/// {A A B}, {A B A}, {A A B}, {A B A}, {B A A}, {B A A}
/// MetaCollectionType.WithoutRepetition =>
/// {A A B}, {A B A}, {B A A}
///
/// When generating non-repetition sets, ordering is based on the lexicographic
/// ordering of the lists based on the provided Comparer.
/// If no comparer is provided, then T must be IComparable on T.
///
/// When generating repetition sets, no comparisions are performed and therefore
/// no comparer is required and T does not need to be IComparable.
/// </remarks>
/// <typeparam name="T">The type of the values within the list.</typeparam>
public class Permutations<T> : IMetaCollection<T> {
#region Constructors
/// <summary>
/// No default constructor, must at least provided a list of values.
/// </summary>
protected Permutations() {
;
}
/// <summary>
/// Create a permutation set from the provided list of values.
/// The values (T) must implement IComparable.
/// If T does not implement IComparable use a constructor with an explict IComparer.
/// The repetition type defaults to MetaCollectionType.WithholdRepetitionSets
/// </summary>
/// <param name="values">List of values to permute.</param>
public Permutations(IList<T> values) {
Initialize(values, GenerateOption.WithoutRepetition, null);
}
/// <summary>
/// Create a permutation set from the provided list of values.
/// If type is MetaCollectionType.WithholdRepetitionSets, then values (T) must implement IComparable.
/// If T does not implement IComparable use a constructor with an explict IComparer.
/// </summary>
/// <param name="values">List of values to permute.</param>
/// <param name="type">The type of permutation set to calculate.</param>
public Permutations(IList<T> values, GenerateOption type) {
Initialize(values, type, null);
}
/// <summary>
/// Create a permutation set from the provided list of values.
/// The values will be compared using the supplied IComparer.
/// The repetition type defaults to MetaCollectionType.WithholdRepetitionSets
/// </summary>
/// <param name="values">List of values to permute.</param>
/// <param name="comparer">Comparer used for defining the lexigraphic order.</param>
public Permutations(IList<T> values, IComparer<T> comparer) {
Initialize(values, GenerateOption.WithoutRepetition, comparer);
}
#endregion
#region IEnumerable Interface
/// <summary>
/// Gets an enumerator for collecting the list of permutations.
/// </summary>
/// <returns>The enumerator.</returns>
public virtual IEnumerator GetEnumerator() {
return new Enumerator(this);
}
/// <summary>
/// Gets an enumerator for collecting the list of permutations.
/// </summary>
/// <returns>The enumerator.</returns>
IEnumerator<IList<T>> IEnumerable<IList<T>>.GetEnumerator() {
return new Enumerator(this);
}
#endregion
#region Enumerator Inner-Class
/// <summary>
/// The enumerator that enumerates each meta-collection of the enclosing Permutations class.
/// </summary>
public class Enumerator : IEnumerator<IList<T>> {
#region Constructors
/// <summary>
/// Construct a enumerator with the parent object.
/// </summary>
/// <param name="source">The source Permutations object.</param>
public Enumerator(Permutations<T> source) {
myParent = source;
myLexicographicalOrders = new int[source.myLexicographicOrders.Length];
source.myLexicographicOrders.CopyTo(myLexicographicalOrders, 0);
Reset();
}
#endregion
#region IEnumerator Interface
/// <summary>
/// Resets the permutations enumerator to the first permutation.
/// This will be the first lexicographically order permutation.
/// </summary>
public void Reset() {
myPosition = Position.BeforeFirst;
}
/// <summary>
/// Advances to the next permutation.
/// </summary>
/// <returns>True if successfully moved to next permutation, False if no more permutations exist.</returns>
/// <remarks>
/// Continuation was tried (i.e. yield return) by was not nearly as efficient.
/// Performance is further increased by using value types and removing generics, that is, the LexicographicOrder parellel array.
/// This is a issue with the .NET CLR not optimizing as well as it could in this infrequently used scenario.
/// </remarks>
public bool MoveNext() {
if(myPosition == Position.BeforeFirst) {
myValues = new List<T>(myParent.myValues.Count);
myValues.AddRange(myParent.myValues);
Array.Sort(myLexicographicalOrders);
myPosition = Position.InSet;
} else if(myPosition == Position.InSet) {
if(myValues.Count < 2) {
myPosition = Position.AfterLast;
}
else if(NextPermutation() == false) {
myPosition = Position.AfterLast;
}
}
return myPosition != Position.AfterLast;
}
/// <summary>
/// The current permutation.
/// </summary>
public object Current {
get {
if(myPosition == Position.InSet) {
return new List<T>(myValues);
}
else {
throw new InvalidOperationException();
}
}
}
/// <summary>
/// The current permutation.
/// </summary>
IList<T> IEnumerator<IList<T>>.Current {
get {
if(myPosition == Position.InSet) {
return new List<T>(myValues);
}
else {
throw new InvalidOperationException();
}
}
}
/// <summary>
/// Cleans up non-managed resources, of which there are none used here.
/// </summary>
public virtual void Dispose() {
;
}
#endregion
#region Heavy Lifting Methods
/// <summary>
/// Calculates the next lexicographical permutation of the set.
/// This is a permutation with repetition where values that compare as equal will not
/// swap positions to create a new permutation.
/// http://www.cut-the-knot.org/do_you_know/AllPerm.shtml
/// E. W. Dijkstra, A Discipline of Programming, Prentice-Hall, 1997
/// </summary>
/// <returns>True if a new permutation has been returned, false if not.</returns>
/// <remarks>
/// This uses the integers of the lexicographical order of the values so that any
/// comparison of values are only performed during initialization.
/// </remarks>
private bool NextPermutation() {
int i = myLexicographicalOrders.Length - 1;
while(myLexicographicalOrders[i - 1] >= myLexicographicalOrders[i]) {
--i;
if(i == 0) {
return false;
}
}
int j = myLexicographicalOrders.Length;
while(myLexicographicalOrders[j - 1] <= myLexicographicalOrders[i - 1]) {
--j;
}
Swap(i - 1, j - 1);
++i;
j = myLexicographicalOrders.Length;
while(i < j) {
Swap(i - 1, j - 1);
++i;
--j;
}
return true;
}
/// <summary>
/// Helper function for swapping two elements within the internal collection.
/// This swaps both the lexicographical order and the values, maintaining the parallel array.
/// </summary>
private void Swap(int i, int j) {
myTemp = myValues[i];
myValues[i] = myValues[j];
myValues[j] = myTemp;
myKviTemp = myLexicographicalOrders[i];
myLexicographicalOrders[i] = myLexicographicalOrders[j];
myLexicographicalOrders[j] = myKviTemp;
}
#endregion
#region Data and Internal Members
/// <summary>
/// Single instance of swap variable for T, small performance improvement over declaring in Swap function scope.
/// </summary>
private T myTemp;
/// <summary>
/// Single instance of swap variable for int, small performance improvement over declaring in Swap function scope.
/// </summary>
private int myKviTemp;
/// <summary>
/// Flag indicating the position of the enumerator.
/// </summary>
private Position myPosition = Position.BeforeFirst;
/// <summary>
/// Parrellel array of integers that represent the location of items in the myValues array.
/// This is generated at Initialization and is used as a performance speed up rather that
/// comparing T each time, much faster to let the CLR optimize around integers.
/// </summary>
private int[] myLexicographicalOrders;
/// <summary>
/// The list of values that are current to the enumerator.
/// </summary>
private List<T> myValues;
/// <summary>
/// The set of permuations that this enumerator enumerates.
/// </summary>
private Permutations<T> myParent;
/// <summary>
/// Internal position type for tracking enumertor position.
/// </summary>
private enum Position {
BeforeFirst,
InSet,
AfterLast
}
#endregion
}
#endregion
#region IMetaList Interface
/// <summary>
/// The count of all permutations that will be returned.
/// If type is MetaCollectionType.WithholdGeneratedSets, then this does not double count permutations with multiple identical values.
/// I.e. count of permutations of "AAB" will be 3 instead of 6.
/// If type is MetaCollectionType.WithRepetition, then this is all combinations and is therefore N!, where N is the number of values.
/// </summary>
public long Count {
get {
return myCount;
}
}
/// <summary>
/// The type of Permutations set that is generated.
/// </summary>
public GenerateOption Type {
get {
return myMetaCollectionType;
}
}
/// <summary>
/// The upper index of the meta-collection, equal to the number of items in the initial set.
/// </summary>
public int UpperIndex {
get {
return myValues.Count;
}
}
/// <summary>
/// The lower index of the meta-collection, equal to the number of items returned each iteration.
/// For Permutation, this is always equal to the UpperIndex.
/// </summary>
public int LowerIndex {
get {
return myValues.Count;
}
}
#endregion
#region Heavy Lifting Members
/// <summary>
/// Common intializer used by the multiple flavors of constructors.
/// </summary>
/// <remarks>
/// Copies information provided and then creates a parellel int array of lexicographic
/// orders that will be used for the actual permutation algorithm.
/// The input array is first sorted as required for WithoutRepetition and always just for consistency.
/// This array is constructed one of two way depending on the type of the collection.
///
/// When type is MetaCollectionType.WithRepetition, then all N! permutations are returned
/// and the lexicographic orders are simply generated as 1, 2, ... N.
/// E.g.
/// Input array: {A A B C D E E}
/// Lexicograhpic Orders: {1 2 3 4 5 6 7}
///
/// When type is MetaCollectionType.WithoutRepetition, then fewer are generated, with each
/// identical element in the input array not repeated. The lexicographic sort algorithm
/// handles this natively as long as the repetition is repeated.
/// E.g.
/// Input array: {A A B C D E E}
/// Lexicograhpic Orders: {1 1 2 3 4 5 5}
/// </remarks>
private void Initialize(IList<T> values, GenerateOption type, IComparer<T> comparer) {
myMetaCollectionType = type;
myValues = new List<T>(values.Count);
myValues.AddRange(values);
myLexicographicOrders = new int[values.Count];
if(type == GenerateOption.WithRepetition) {
for(int i = 0; i < myLexicographicOrders.Length; ++i) {
myLexicographicOrders[i] = i;
}
}
else {
if(comparer == null) {
comparer = new SelfComparer<T>();
}
myValues.Sort(comparer);
int j = 1;
if(myLexicographicOrders.Length > 0) {
myLexicographicOrders[0] = j;
}
for(int i = 1; i < myLexicographicOrders.Length; ++i) {
if(comparer.Compare(myValues[i - 1], myValues[i]) != 0) {
++j;
}
myLexicographicOrders[i] = j;
}
}
myCount = GetCount();
}
/// <summary>
/// Calculates the total number of permutations that will be returned.
/// As this can grow very large, extra effort is taken to avoid overflowing the accumulator.
/// While the algorithm looks complex, it really is just collecting numerator and denominator terms
/// and cancelling out all of the denominator terms before taking the product of the numerator terms.
/// </summary>
/// <returns>The number of permutations.</returns>
private long GetCount() {
int runCount = 1;
List<int> divisors = new List<int>();
List<int> numerators = new List<int>();
for(int i = 1; i < myLexicographicOrders.Length; ++i) {
numerators.AddRange(SmallPrimeUtility.Factor(i + 1));
if(myLexicographicOrders[i] == myLexicographicOrders[i - 1]) {
++runCount;
}
else {
for(int f = 2; f <= runCount; ++f) {
divisors.AddRange(SmallPrimeUtility.Factor(f));
}
runCount = 1;
}
}
for(int f = 2; f <= runCount; ++f) {
divisors.AddRange(SmallPrimeUtility.Factor(f));
}
return SmallPrimeUtility.EvaluatePrimeFactors(SmallPrimeUtility.DividePrimeFactors(numerators, divisors));
}
#endregion
#region Data and Internal Members
/// <summary>
/// A list of T that represents the order of elements as originally provided, used for Reset.
/// </summary>
private List<T> myValues;
/// <summary>
/// Parrellel array of integers that represent the location of items in the myValues array.
/// This is generated at Initialization and is used as a performance speed up rather that
/// comparing T each time, much faster to let the CLR optimize around integers.
/// </summary>
private int[] myLexicographicOrders;
/// <summary>
/// Inner class that wraps an IComparer around a type T when it is IComparable
/// </summary>
private class SelfComparer<U> : IComparer<U> {
public int Compare(U x, U y) {
return ((IComparable<U>)x).CompareTo(y);
}
}
/// <summary>
/// The count of all permutations. Calculated at Initialization and returned by Count property.
/// </summary>
private long myCount;
/// <summary>
/// The type of Permutations that this was intialized from.
/// </summary>
private GenerateOption myMetaCollectionType;
#endregion
}
}
| |
using LibGD;
public static class GlobalMembersGdTrivialResize
{
#if __cplusplus
#endif
#define GD_H
#define GD_MAJOR_VERSION
#define GD_MINOR_VERSION
#define GD_RELEASE_VERSION
#define GD_EXTRA_VERSION
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext
#define GDXXX_VERSION_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s)
#define GDXXX_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s
#define GDXXX_SSTR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION
#define GD_VERSION_STRING
#if _WIN32 || CYGWIN || _WIN32_WCE
#if BGDWIN32
#if NONDLL
#define BGD_EXPORT_DATA_PROT
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_STDCALL __stdcall
#define BGD_STDCALL
#define BGD_EXPORT_DATA_IMPL
#else
#if HAVE_VISIBILITY
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#else
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#endif
#define BGD_STDCALL
#endif
#if BGD_EXPORT_DATA_PROT_ConditionalDefinition1
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#else
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#endif
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GD_IO_H
#if VMS
#endif
#if __cplusplus
#endif
#define gdMaxColors
#define gdAlphaMax
#define gdAlphaOpaque
#define gdAlphaTransparent
#define gdRedMax
#define gdGreenMax
#define gdBlueMax
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24)
#define gdTrueColorGetAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16)
#define gdTrueColorGetRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8)
#define gdTrueColorGetGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF)
#define gdTrueColorGetBlue
#define gdEffectReplace
#define gdEffectAlphaBlend
#define gdEffectNormal
#define gdEffectOverlay
#define GD_TRUE
#define GD_FALSE
#define GD_EPSILON
#define M_PI
#define gdDashSize
#define gdStyled
#define gdBrushed
#define gdStyledBrushed
#define gdTiled
#define gdTransparent
#define gdAntiAliased
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate
#define gdImageCreatePalette
#define gdFTEX_LINESPACE
#define gdFTEX_CHARMAP
#define gdFTEX_RESOLUTION
#define gdFTEX_DISABLE_KERNING
#define gdFTEX_XSHOW
#define gdFTEX_FONTPATHNAME
#define gdFTEX_FONTCONFIG
#define gdFTEX_RETURNFONTPATHNAME
#define gdFTEX_Unicode
#define gdFTEX_Shift_JIS
#define gdFTEX_Big5
#define gdFTEX_Adobe_Custom
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b))
#define gdTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b))
#define gdTrueColorAlpha
#define gdArc
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdPie gdArc
#define gdPie
#define gdChord
#define gdNoFill
#define gdEdged
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor)
#define gdImageTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx)
#define gdImageSX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy)
#define gdImageSY
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal)
#define gdImageColorsTotal
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)])
#define gdImageRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)])
#define gdImageGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)])
#define gdImageBlue
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)])
#define gdImageAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent)
#define gdImageGetTransparent
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace)
#define gdImageGetInterlaced
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)]
#define gdImagePalettePixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)]
#define gdImageTrueColorPixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x
#define gdImageResolutionX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y
#define gdImageResolutionY
#define GD2_CHUNKSIZE
#define GD2_CHUNKSIZE_MIN
#define GD2_CHUNKSIZE_MAX
#define GD2_VERS
#define GD2_ID
#define GD2_FMT_RAW
#define GD2_FMT_COMPRESSED
#define GD_FLIP_HORINZONTAL
#define GD_FLIP_VERTICAL
#define GD_FLIP_BOTH
#define GD_CMP_IMAGE
#define GD_CMP_NUM_COLORS
#define GD_CMP_COLOR
#define GD_CMP_SIZE_X
#define GD_CMP_SIZE_Y
#define GD_CMP_TRANSPARENT
#define GD_CMP_BACKGROUND
#define GD_CMP_INTERLACE
#define GD_CMP_TRUECOLOR
#define GD_RESOLUTION
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDFX_H
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDTEST_TOP_DIR
#define GDTEST_STRING_MAX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEqualsToFile
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageFileEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEquals
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond))
#define gdTestAssert
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__)
#define gdTestErrorMsg
/* Test gd.gdImageScale() with bicubic interpolation on a simple
* all-white image. */
public static gdImageStruct mkwhite(int x, int y)
{
gdImageStruct im;
im = gd.gdImageCreateTrueColor(x, y);
gd.gdImageFilledRectangle(im, 0, 0, x - 1, y - 1, gd.gdImageColorExactAlpha(im, 255, 255, 255, 0));
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (im != null));
gd.gdImageSetInterpolationMethod(im, gdInterpolationMethod.GD_BICUBIC); // FP interp'n
return im;
} // mkwhite
/* Fill with almost-black. */
public static void mkblack(gdImageStruct ptr)
{
gd.gdImageFilledRectangle(ptr, 0, 0, ptr.sx - 1, ptr.sy - 1, gd.gdImageColorExactAlpha(ptr, 2, 2, 2, 0));
} // mkblack
#define CLOSE_ENOUGH
public static void scaletest(int x, int y, int nx, int ny)
{
gdImageStruct im;
gdImageStruct imref;
gdImageStruct tmp;
gdImageStruct same;
imref = GlobalMembersGdnametest.mkwhite(x, y);
im = GlobalMembersGdnametest.mkwhite(x, y);
tmp = gd.gdImageScale(im, nx, ny);
same = gd.gdImageScale(tmp, x, y);
/* Test the result to insure that it's close enough to the
* original. */
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (GlobalMembersGdtest.gd.gdMaxPixelDiff(im, same) < DefineConstants.CLOSE_ENOUGH));
/* Modify the original and test for a change again. (I.e. test
* for accidentally shared memory.) */
GlobalMembersGdCopyBlurred.mkblack(tmp);
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (GlobalMembersGdtest.gd.gdMaxPixelDiff(imref, same) < DefineConstants.CLOSE_ENOUGH));
gd.gdImageDestroy(im);
gd.gdImageDestroy(tmp);
gd.gdImageDestroy(same);
} // scaletest
public static void do_test(int x, int y, int nx, int ny)
{
gdImageStruct im;
gdImageStruct imref;
gdImageStruct tmp;
gdImageStruct same;
gdImageStruct same2;
im = GlobalMembersGdnametest.mkwhite(x, y);
imref = GlobalMembersGdnametest.mkwhite(x, y);
same = gd.gdImageScale(im, x, y);
/* Trivial resize should be a straight copy. */
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (im != same));
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (GlobalMembersGdtest.gd.gdMaxPixelDiff(im, same) == 0));
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (GlobalMembersGdtest.gd.gdMaxPixelDiff(imref, same) == 0));
/* Ensure that modifying im doesn't modify same (i.e. see if we
* can catch them accidentally sharing the same pixel buffer.) */
GlobalMembersGdCopyBlurred.mkblack(im);
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
GlobalMembersGdtest._gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (GlobalMembersGdtest.gd.gdMaxPixelDiff(imref, same) == 0));
gd.gdImageDestroy(same);
gd.gdImageDestroy(im);
/* Scale horizontally, vertically and both. */
GlobalMembersGdTrivialResize.scaletest(x, y, nx, y);
GlobalMembersGdTrivialResize.scaletest(x, y, x, ny);
GlobalMembersGdTrivialResize.scaletest(x, y, nx, ny);
}
static int Main(string[] args)
{
GlobalMembersGdnametest.do_test(300, 300, 600, 600);
GlobalMembersGdnametest.do_test(3200, 2133, 640, 427);
return GlobalMembersGdtest.gd.gdNumFailures();
}
}
| |
// 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 gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCustomerAssetServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCustomerAssetRequestObject()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
GetCustomerAssetRequest request = new GetCustomerAssetRequest
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::CustomerAsset expectedResponse = new gagvr::CustomerAsset
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetCustomerAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerAsset response = client.GetCustomerAsset(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerAssetRequestObjectAsync()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
GetCustomerAssetRequest request = new GetCustomerAssetRequest
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::CustomerAsset expectedResponse = new gagvr::CustomerAsset
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetCustomerAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerAsset responseCallSettings = await client.GetCustomerAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerAsset responseCancellationToken = await client.GetCustomerAssetAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerAsset()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
GetCustomerAssetRequest request = new GetCustomerAssetRequest
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::CustomerAsset expectedResponse = new gagvr::CustomerAsset
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetCustomerAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerAsset response = client.GetCustomerAsset(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerAssetAsync()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
GetCustomerAssetRequest request = new GetCustomerAssetRequest
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::CustomerAsset expectedResponse = new gagvr::CustomerAsset
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetCustomerAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerAsset responseCallSettings = await client.GetCustomerAssetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerAsset responseCancellationToken = await client.GetCustomerAssetAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerAssetResourceNames()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
GetCustomerAssetRequest request = new GetCustomerAssetRequest
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::CustomerAsset expectedResponse = new gagvr::CustomerAsset
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetCustomerAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerAsset response = client.GetCustomerAsset(request.ResourceNameAsCustomerAssetName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerAssetResourceNamesAsync()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
GetCustomerAssetRequest request = new GetCustomerAssetRequest
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::CustomerAsset expectedResponse = new gagvr::CustomerAsset
{
ResourceNameAsCustomerAssetName = gagvr::CustomerAssetName.FromCustomerAssetFieldType("[CUSTOMER_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
};
mockGrpcClient.Setup(x => x.GetCustomerAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerAsset responseCallSettings = await client.GetCustomerAssetAsync(request.ResourceNameAsCustomerAssetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerAsset responseCancellationToken = await client.GetCustomerAssetAsync(request.ResourceNameAsCustomerAssetName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomerAssetsRequestObject()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
MutateCustomerAssetsRequest request = new MutateCustomerAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerAssetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCustomerAssetsResponse expectedResponse = new MutateCustomerAssetsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateCustomerAssetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateCustomerAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerAssetsResponse response = client.MutateCustomerAssets(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerAssetsRequestObjectAsync()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
MutateCustomerAssetsRequest request = new MutateCustomerAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerAssetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCustomerAssetsResponse expectedResponse = new MutateCustomerAssetsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateCustomerAssetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateCustomerAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerAssetsResponse responseCallSettings = await client.MutateCustomerAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerAssetsResponse responseCancellationToken = await client.MutateCustomerAssetsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomerAssets()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
MutateCustomerAssetsRequest request = new MutateCustomerAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerAssetOperation(),
},
};
MutateCustomerAssetsResponse expectedResponse = new MutateCustomerAssetsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateCustomerAssetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateCustomerAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerAssetsResponse response = client.MutateCustomerAssets(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerAssetsAsync()
{
moq::Mock<CustomerAssetService.CustomerAssetServiceClient> mockGrpcClient = new moq::Mock<CustomerAssetService.CustomerAssetServiceClient>(moq::MockBehavior.Strict);
MutateCustomerAssetsRequest request = new MutateCustomerAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerAssetOperation(),
},
};
MutateCustomerAssetsResponse expectedResponse = new MutateCustomerAssetsResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateCustomerAssetResult(),
},
};
mockGrpcClient.Setup(x => x.MutateCustomerAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerAssetServiceClient client = new CustomerAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerAssetsResponse responseCallSettings = await client.MutateCustomerAssetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerAssetsResponse responseCancellationToken = await client.MutateCustomerAssetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Sensus.Probes.Context;
using Plugin.Permissions.Abstractions;
using Android.Bluetooth.LE;
using Android.Bluetooth;
using Android.OS;
using Java.Util;
using System.Collections.Generic;
using System.Text;
using Sensus.Context;
using System.Threading;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Linq;
using Sensus.Probes;
using Android.App;
using Android.Content;
namespace Sensus.Android.Probes.Context
{
/// <summary>
/// Scans for the presence of other devices nearby that are running the current <see cref="Protocol"/>. When
/// encountered, this Probe will read the device ID of other devices. This Probe also advertises the presence
/// of the current device and serves requests for the current device's ID. This Probe reports data in the form
/// of <see cref="BluetoothDeviceProximityDatum"/> objects.
///
/// There are caveats to the conditions under which an Android device running this Probe will detect another
/// device:
///
/// * If the other device is an Android device with Sensus running in the foreground or background, detection is possible.
/// * If the other device is an iOS device with Sensus running in the foreground, detection is possible.
/// * If the other device is an iOS device with Sensus running in the background, detection is not possible.
///
/// NOTE: The value of <see cref="Protocol.Id"/> running on the other device must equal the value of
/// <see cref="Protocol.Id"/> running on the current device. When a Protocol is created from within the
/// Sensus app, it is assigned a unique identifier. This value is maintained or changed depending on what you
/// do:
///
/// * When the newly created Protocol is copied on the current device, a new unique identifier is assigned to
/// it. This breaks the connection between the Protocols.
///
/// * When the newly created Protocol is shared via the app with another device, its identifier remains
/// unchanged. This maintains the connection between the Protocols.
///
/// Thus, in order for this <see cref="AndroidBluetoothDeviceProximityProbe"/> to operate properly, you must configure
/// your Protocols in one of the two following ways:
///
/// * Create your Protocol on one platform (either Android or iOS) and then share it with a device from the other
/// platform for customization. The <see cref="Protocol.Id"/> values of these Protocols will remain equal
/// and this <see cref="AndroidBluetoothDeviceProximityProbe"/> will detect encounters across platforms.
///
/// * Create your Protocols separately on each platform and then set the <see cref="Protocol.Id"/> field on
/// one platform (using the "Set Study Identifier" button) to match the <see cref="Protocol.Id"/> value
/// of the other platform (obtained via "Copy Study Identifier").
///
/// See the iOS subclass of <see cref="BluetoothDeviceProximityProbe"/> for additional information.
/// </summary>
public class AndroidBluetoothDeviceProximityProbe : BluetoothDeviceProximityProbe
{
private AndroidBluetoothClientScannerCallback _bluetoothScannerCallback;
private AndroidBluetoothServerAdvertisingCallback _bluetoothAdvertiserCallback;
private BluetoothGattService _deviceIdService;
private BluetoothGattCharacteristic _deviceIdCharacteristic;
private AndroidBluetoothDeviceReceiver _bluetoothBroadcastReceiver;
[JsonIgnore]
public override int DefaultPollingSleepDurationMS => (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
protected override async Task InitializeAsync()
{
await base.InitializeAsync();
// BLE requires location permissions
if (await SensusServiceHelper.Get().ObtainPermissionAsync(Permission.Location) != PermissionStatus.Granted)
{
// throw standard exception instead of NotSupportedException, since the user might decide to enable location in the future
// and we'd like the probe to be restarted at that time.
string error = "Geolocation is not permitted on this device. Cannot start Bluetooth probe.";
await SensusServiceHelper.Get().FlashNotificationAsync(error);
throw new Exception(error);
}
_deviceIdCharacteristic = new BluetoothGattCharacteristic(UUID.FromString(DEVICE_ID_CHARACTERISTIC_UUID), GattProperty.Read, GattPermission.Read);
_deviceIdCharacteristic.SetValue(Encoding.UTF8.GetBytes(SensusServiceHelper.Get().DeviceId));
_deviceIdService = new BluetoothGattService(UUID.FromString(Protocol.Id), GattServiceType.Primary);
_deviceIdService.AddCharacteristic(_deviceIdCharacteristic);
_bluetoothAdvertiserCallback = new AndroidBluetoothServerAdvertisingCallback(_deviceIdService, _deviceIdCharacteristic);
if (ScanMode.HasFlag(BluetoothScanModes.Classic))
{
_bluetoothBroadcastReceiver = new AndroidBluetoothDeviceReceiver(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.AddAction(BluetoothDevice.ActionFound);
Application.Context.RegisterReceiver(_bluetoothBroadcastReceiver, intentFilter);
}
}
protected override Task ProtectedStopAsync()
{
Application.Context.UnregisterReceiver(_bluetoothBroadcastReceiver);
return base.ProtectedStopAsync();
}
#region central -- scan
protected override async Task ScanAsync(CancellationToken cancellationToken)
{
// start a scan if bluetooth is present and enabled
if (BluetoothAdapter.DefaultAdapter?.IsEnabled ?? false)
{
try
{
if (ScanMode.HasFlag(BluetoothScanModes.LE))
{
List<ScanFilter> scanFilters = new List<ScanFilter>();
if (DiscoverAll == false)
{
ScanFilter scanFilter = new ScanFilter.Builder()
.SetServiceUuid(new ParcelUuid(_deviceIdService.Uuid))
.Build();
scanFilters.Add(scanFilter);
}
ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder()
.SetScanMode(global::Android.Bluetooth.LE.ScanMode.Balanced);
// return batched scan results periodically if supported on the BLE chip
if (BluetoothAdapter.DefaultAdapter.IsOffloadedScanBatchingSupported)
{
scanSettingsBuilder.SetReportDelay((long)(ScanDurationMS / 2.0));
}
// start a fresh manager delegate to collect/read results
_bluetoothScannerCallback = new AndroidBluetoothClientScannerCallback(_deviceIdService, _deviceIdCharacteristic, this);
BluetoothAdapter.DefaultAdapter.BluetoothLeScanner.StartScan(scanFilters, scanSettingsBuilder.Build(), _bluetoothScannerCallback);
}
if (ScanMode.HasFlag(BluetoothScanModes.Classic))
{
BluetoothAdapter.DefaultAdapter.StartDiscovery();
}
TaskCompletionSource<bool> scanCompletionSource = new TaskCompletionSource<bool>();
cancellationToken.Register(() =>
{
try
{
if (ScanMode.HasFlag(BluetoothScanModes.LE))
{
BluetoothAdapter.DefaultAdapter.BluetoothLeScanner.StopScan(_bluetoothScannerCallback);
}
else if (ScanMode.HasFlag(BluetoothScanModes.Classic) && BluetoothAdapter.DefaultAdapter.IsDiscovering)
{
BluetoothAdapter.DefaultAdapter.CancelDiscovery();
}
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Exception while stopping scan: " + ex.Message, LoggingLevel.Normal, GetType());
}
finally
{
scanCompletionSource.TrySetResult(true);
}
});
await scanCompletionSource.Task;
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Exception while scanning: " + ex.Message, LoggingLevel.Normal, GetType());
}
}
}
protected async override Task<List<BluetoothDeviceProximityDatum>> ReadPeripheralCharacteristicValuesAsync(CancellationToken cancellationToken)
{
if (ScanMode == BluetoothScanModes.LE)
{
return await _bluetoothScannerCallback.ReadPeripheralCharacteristicValuesAsync(cancellationToken);
}
else
{
return await CreateBluetoothData(cancellationToken);
}
}
private async Task<List<BluetoothDeviceProximityDatum>> CreateBluetoothData(CancellationToken cancellationToken)
{
List<BluetoothDeviceProximityDatum> bluetoothDeviceProximityData = new List<BluetoothDeviceProximityDatum>();
// copy list of peripherals to read. note that the same device may be reported more than once. read each once.
List<AndroidBluetoothDevice> le = _bluetoothScannerCallback.GetDiscoveredDevices();
List<AndroidBluetoothDevice> classic = _bluetoothBroadcastReceiver.GetDiscoveredDevices();
List<IGrouping<string, AndroidBluetoothDevice>> scanResults = le.Union(classic)
.GroupBy(scanResult => scanResult.Device.Address)
.ToList();
ReadAttemptCount += scanResults.Count;
// read characteristic from each peripheral
foreach (IGrouping<string, AndroidBluetoothDevice> deviceGroup in scanResults)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
AndroidBluetoothClientGattCallback readCallback = null;
try
{
readCallback = new AndroidBluetoothClientGattCallback(_deviceIdService, _deviceIdCharacteristic);
BluetoothGatt gatt = deviceGroup.First().Device.ConnectGatt(Application.Context, false, readCallback);
string deviceId = await readCallback.ReadCharacteristicValueAsync(cancellationToken);
if (DiscoverAll || deviceId != null)
{
DateTimeOffset timestamp = deviceGroup.Min(x => x.Timestamp);
string address = deviceGroup.Key;
string name = deviceGroup.FirstOrDefault(x => x.Device.Name != null)?.Device.Name;
int rssi = deviceGroup.Min(x => x.Rssi);
bool paired = deviceGroup.Any(x => x.Device.BondState != Bond.None);
bluetoothDeviceProximityData.Add(new BluetoothDeviceProximityDatum(timestamp, deviceId, address, name, rssi, paired, deviceId != null));
ReadSuccessCount++;
}
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Exception while reading peripheral: " + ex, LoggingLevel.Normal, GetType());
}
finally
{
readCallback?.DisconnectPeripheral();
}
}
return bluetoothDeviceProximityData;
}
#endregion
#region peripheral -- advertise
protected override void StartAdvertising()
{
try
{
if (BluetoothAdapter.DefaultAdapter?.IsMultipleAdvertisementSupported ?? false)
{
AdvertiseSettings advertisingSettings = new AdvertiseSettings.Builder()
.SetAdvertiseMode(AdvertiseMode.Balanced)
.SetTxPowerLevel(AdvertiseTx.PowerLow)
.SetConnectable(true)
.Build();
AdvertiseData advertisingData = new AdvertiseData.Builder()
.SetIncludeDeviceName(false)
.AddServiceUuid(new ParcelUuid(_deviceIdService.Uuid))
.Build();
BluetoothAdapter.DefaultAdapter.BluetoothLeAdvertiser.StartAdvertising(advertisingSettings, advertisingData, _bluetoothAdvertiserCallback);
}
else
{
throw new Exception("BLE advertising is not available.");
}
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Exception while starting advertiser: " + ex.Message, LoggingLevel.Normal, GetType());
}
}
protected override void StopAdvertising()
{
try
{
BluetoothAdapter.DefaultAdapter?.BluetoothLeAdvertiser.StopAdvertising(_bluetoothAdvertiserCallback);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Exception while stopping advertising: " + ex.Message, LoggingLevel.Normal, GetType());
}
_bluetoothAdvertiserCallback.CloseServer();
}
public override async Task<HealthTestResult> TestHealthAsync(List<AnalyticsTrackedEvent> events)
{
HealthTestResult result = await base.TestHealthAsync(events);
if (State == ProbeState.Running)
{
// if the user disables/enables BT manually, we will no longer be advertising the service. start advertising
// on each health test to ensure we're advertising.
StartAdvertising();
}
return result;
}
#endregion
}
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERLevel;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G06_Country (editable child object).<br/>
/// This is a generated base class of <see cref="G06_Country"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="G07_RegionObjects"/> of type <see cref="G07_RegionColl"/> (1:M relation to <see cref="G08_Region"/>)<br/>
/// This class is an item of <see cref="G05_CountryColl"/> collection.
/// </remarks>
[Serializable]
public partial class G06_Country : BusinessBase<G06_Country>
{
#region Static Fields
private static int _lastID;
#endregion
#region State Fields
[NotUndoable]
private byte[] _rowVersion = new byte[] {};
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Countries ID");
/// <summary>
/// Gets the Countries ID.
/// </summary>
/// <value>The Countries ID.</value>
public int Country_ID
{
get { return GetProperty(Country_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Country_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Countries Name");
/// <summary>
/// Gets or sets the Countries Name.
/// </summary>
/// <value>The Countries Name.</value>
public string Country_Name
{
get { return GetProperty(Country_NameProperty); }
set { SetProperty(Country_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ParentSubContinentID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ParentSubContinentIDProperty = RegisterProperty<int>(p => p.ParentSubContinentID, "ParentSubContinentID");
/// <summary>
/// Gets or sets the ParentSubContinentID.
/// </summary>
/// <value>The ParentSubContinentID.</value>
public int ParentSubContinentID
{
get { return GetProperty(ParentSubContinentIDProperty); }
set { SetProperty(ParentSubContinentIDProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G07_Country_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<G07_Country_Child> G07_Country_SingleObjectProperty = RegisterProperty<G07_Country_Child>(p => p.G07_Country_SingleObject, "G07 Country Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the G07 Country Single Object ("self load" child property).
/// </summary>
/// <value>The G07 Country Single Object.</value>
public G07_Country_Child G07_Country_SingleObject
{
get { return GetProperty(G07_Country_SingleObjectProperty); }
private set { LoadProperty(G07_Country_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G07_Country_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<G07_Country_ReChild> G07_Country_ASingleObjectProperty = RegisterProperty<G07_Country_ReChild>(p => p.G07_Country_ASingleObject, "G07 Country ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the G07 Country ASingle Object ("self load" child property).
/// </summary>
/// <value>The G07 Country ASingle Object.</value>
public G07_Country_ReChild G07_Country_ASingleObject
{
get { return GetProperty(G07_Country_ASingleObjectProperty); }
private set { LoadProperty(G07_Country_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G07_RegionObjects"/> property.
/// </summary>
public static readonly PropertyInfo<G07_RegionColl> G07_RegionObjectsProperty = RegisterProperty<G07_RegionColl>(p => p.G07_RegionObjects, "G07 Region Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the G07 Region Objects ("self load" child property).
/// </summary>
/// <value>The G07 Region Objects.</value>
public G07_RegionColl G07_RegionObjects
{
get { return GetProperty(G07_RegionObjectsProperty); }
private set { LoadProperty(G07_RegionObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G06_Country"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G06_Country"/> object.</returns>
internal static G06_Country NewG06_Country()
{
return DataPortal.CreateChild<G06_Country>();
}
/// <summary>
/// Factory method. Loads a <see cref="G06_Country"/> object from the given G06_CountryDto.
/// </summary>
/// <param name="data">The <see cref="G06_CountryDto"/>.</param>
/// <returns>A reference to the fetched <see cref="G06_Country"/> object.</returns>
internal static G06_Country GetG06_Country(G06_CountryDto data)
{
G06_Country obj = new G06_Country();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G06_Country"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G06_Country()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G06_Country"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(G07_Country_SingleObjectProperty, DataPortal.CreateChild<G07_Country_Child>());
LoadProperty(G07_Country_ASingleObjectProperty, DataPortal.CreateChild<G07_Country_ReChild>());
LoadProperty(G07_RegionObjectsProperty, DataPortal.CreateChild<G07_RegionColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G06_Country"/> object from the given <see cref="G06_CountryDto"/>.
/// </summary>
/// <param name="data">The G06_CountryDto to use.</param>
private void Fetch(G06_CountryDto data)
{
// Value properties
LoadProperty(Country_IDProperty, data.Country_ID);
LoadProperty(Country_NameProperty, data.Country_Name);
LoadProperty(ParentSubContinentIDProperty, data.ParentSubContinentID);
_rowVersion = data.RowVersion;
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(G07_Country_SingleObjectProperty, G07_Country_Child.GetG07_Country_Child(Country_ID));
LoadProperty(G07_Country_ASingleObjectProperty, G07_Country_ReChild.GetG07_Country_ReChild(Country_ID));
LoadProperty(G07_RegionObjectsProperty, G07_RegionColl.GetG07_RegionColl(Country_ID));
}
/// <summary>
/// Inserts a new <see cref="G06_Country"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G04_SubContinent parent)
{
var dto = new G06_CountryDto();
dto.Parent_SubContinent_ID = parent.SubContinent_ID;
dto.Country_Name = Country_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IG06_CountryDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(Country_IDProperty, resultDto.Country_ID);
_rowVersion = resultDto.RowVersion;
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G06_Country"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new G06_CountryDto();
dto.Country_ID = Country_ID;
dto.Country_Name = Country_Name;
dto.ParentSubContinentID = ParentSubContinentID;
dto.RowVersion = _rowVersion;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IG06_CountryDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
_rowVersion = resultDto.RowVersion;
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="G06_Country"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IG06_CountryDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(Country_IDProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner.Initialization;
namespace FluentMigrator.Runner
{
public class MigrationRunner : IMigrationRunner
{
private Assembly _migrationAssembly;
private IAnnouncer _announcer;
private IStopWatch _stopWatch;
private bool _alreadyOutputPreviewOnlyModeWarning;
public bool SilentlyFail { get; set; }
public IMigrationProcessor Processor { get; private set; }
public IMigrationLoader MigrationLoader { get; set; }
public IProfileLoader ProfileLoader { get; set; }
public IMigrationConventions Conventions { get; private set; }
public IList<Exception> CaughtExceptions { get; private set; }
public MigrationRunner(Assembly assembly, IRunnerContext runnerContext, IMigrationProcessor processor)
{
_migrationAssembly = assembly;
_announcer = runnerContext.Announcer;
Processor = processor;
_stopWatch = runnerContext.StopWatch;
SilentlyFail = false;
CaughtExceptions = null;
Conventions = new MigrationConventions();
if (!string.IsNullOrEmpty(runnerContext.WorkingDirectory))
Conventions.GetWorkingDirectory = () => runnerContext.WorkingDirectory;
VersionLoader = new VersionLoader(this, _migrationAssembly, Conventions);
MigrationLoader = new MigrationLoader(Conventions, _migrationAssembly, runnerContext.Namespace);
ProfileLoader = new ProfileLoader(runnerContext, this, Conventions);
}
public IVersionLoader VersionLoader { get; set; }
public void ApplyProfiles()
{
ProfileLoader.ApplyProfiles();
}
public void MigrateUp()
{
MigrateUp(true);
}
public void MigrateUp(bool useAutomaticTransactionManagement)
{
try
{
foreach (var version in MigrationLoader.Migrations.Keys)
{
ApplyMigrationUp(version);
}
ApplyProfiles();
if (useAutomaticTransactionManagement) { Processor.CommitTransaction(); }
VersionLoader.LoadVersionInfo();
}
catch (Exception)
{
if (useAutomaticTransactionManagement) { Processor.RollbackTransaction(); }
throw;
}
}
public void MigrateUp(long targetVersion)
{
MigrateUp(targetVersion, true);
}
public void MigrateUp(long targetVersion, bool useAutomaticTransactionManagement)
{
try
{
foreach (var neededMigrationVersion in GetUpMigrationsToApply(targetVersion))
{
ApplyMigrationUp(neededMigrationVersion);
}
if (useAutomaticTransactionManagement) { Processor.CommitTransaction(); }
VersionLoader.LoadVersionInfo();
}
catch (Exception)
{
if (useAutomaticTransactionManagement) { Processor.RollbackTransaction(); }
throw;
}
}
private IEnumerable<long> GetUpMigrationsToApply(long version)
{
return MigrationLoader.Migrations.Keys.Where(x => IsMigrationStepNeededForUpMigration(x, version));
}
private bool IsMigrationStepNeededForUpMigration(long versionOfMigration, long targetVersion)
{
if (versionOfMigration <= targetVersion && !VersionLoader.VersionInfo.HasAppliedMigration(versionOfMigration))
{
return true;
}
return false;
}
public void MigrateDown(long targetVersion)
{
MigrateDown(targetVersion, true);
}
public void MigrateDown(long targetVersion, bool useAutomaticTransactionManagement)
{
try
{
foreach (var neededMigrationVersion in GetDownMigrationsToApply(targetVersion))
{
ApplyMigrationDown(neededMigrationVersion);
}
if (useAutomaticTransactionManagement) { Processor.CommitTransaction(); }
VersionLoader.LoadVersionInfo();
}
catch (Exception)
{
if (useAutomaticTransactionManagement) { Processor.RollbackTransaction(); }
throw;
}
}
private IEnumerable<long> GetDownMigrationsToApply(long targetVersion)
{
return MigrationLoader.Migrations.Keys.Where(x => IsMigrationStepNeededForDownMigration(x, targetVersion)).Reverse();
}
private bool IsMigrationStepNeededForDownMigration(long versionOfMigration, long targetVersion)
{
if (versionOfMigration > targetVersion && VersionLoader.VersionInfo.HasAppliedMigration(versionOfMigration))
{
return true;
}
return false;
}
private void ApplyMigrationUp(long version)
{
if (!_alreadyOutputPreviewOnlyModeWarning && Processor.Options.PreviewOnly)
{
_announcer.Heading("PREVIEW-ONLY MODE");
_alreadyOutputPreviewOnlyModeWarning = true;
}
if (!VersionLoader.VersionInfo.HasAppliedMigration(version))
{
Up(MigrationLoader.Migrations[version]);
VersionLoader.UpdateVersionInfo(version);
}
}
private void ApplyMigrationDown(long version)
{
try
{
Down(MigrationLoader.Migrations[version]);
VersionLoader.DeleteVersion(version);
}
catch (KeyNotFoundException ex)
{
string msg = string.Format("VersionInfo references version {0} but no Migrator was found attributed with that version.", version);
throw new Exception(msg, ex);
}
catch (Exception ex)
{
throw new Exception("Error rolling back version " + version, ex);
}
}
public void Rollback(int steps)
{
Rollback(steps, true);
}
public void Rollback(int steps, bool useAutomaticTransactionManagement)
{
try
{
foreach (var migrationNumber in VersionLoader.VersionInfo.AppliedMigrations().Take(steps))
{
ApplyMigrationDown(migrationNumber);
}
VersionLoader.LoadVersionInfo();
if (!VersionLoader.VersionInfo.AppliedMigrations().Any())
VersionLoader.RemoveVersionTable();
if (useAutomaticTransactionManagement) { Processor.CommitTransaction(); }
}
catch (Exception)
{
if (useAutomaticTransactionManagement) { Processor.RollbackTransaction(); }
throw;
}
}
public void RollbackToVersion(long version)
{
RollbackToVersion(version, true);
}
public void RollbackToVersion(long version, bool useAutomaticTransactionManagement)
{
//TODO: Extract VersionsToApply Strategy
try
{
// Get the migrations between current and the to version
foreach (var migrationNumber in VersionLoader.VersionInfo.AppliedMigrations())
{
if (version < migrationNumber || version == 0)
{
ApplyMigrationDown(migrationNumber);
}
}
if (version == 0)
VersionLoader.RemoveVersionTable();
else
VersionLoader.LoadVersionInfo();
if (useAutomaticTransactionManagement) { Processor.CommitTransaction(); }
}
catch (Exception)
{
if (useAutomaticTransactionManagement) { Processor.RollbackTransaction(); }
throw;
}
}
public Assembly MigrationAssembly
{
get { return _migrationAssembly; }
}
public void Up(IMigration migration)
{
var name = migration.GetType().Name;
_announcer.Heading(name + ": migrating");
CaughtExceptions = new List<Exception>();
var context = new MigrationContext(Conventions, Processor, MigrationAssembly);
migration.GetUpExpressions(context);
_stopWatch.Start();
ExecuteExpressions(context.Expressions);
_stopWatch.Stop();
_announcer.Say(name + ": migrated");
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
public void Down(IMigration migration)
{
var name = migration.GetType().Name;
_announcer.Heading(name + ": reverting");
CaughtExceptions = new List<Exception>();
var context = new MigrationContext(Conventions, Processor, MigrationAssembly);
migration.GetDownExpressions(context);
_stopWatch.Start();
ExecuteExpressions(context.Expressions);
_stopWatch.Stop();
_announcer.Say(name + ": reverted");
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
/// <summary>
/// execute each migration expression in the expression collection
/// </summary>
/// <param name="expressions"></param>
protected void ExecuteExpressions(ICollection<IMigrationExpression> expressions)
{
long insertTicks = 0;
int insertCount = 0;
foreach (IMigrationExpression expression in expressions)
{
try
{
expression.ApplyConventions(Conventions);
if (expression is InsertDataExpression)
{
insertTicks += Time(() => expression.ExecuteWith(Processor));
insertCount++;
}
else
{
AnnounceTime(expression.ToString(), () => expression.ExecuteWith(Processor));
}
}
catch (Exception er)
{
_announcer.Error(er.Message);
//catch the error and move onto the next expression
if (SilentlyFail)
{
CaughtExceptions.Add(er);
continue;
}
throw;
}
}
if (insertCount > 0)
{
var avg = new TimeSpan(insertTicks / insertCount);
var msg = string.Format("-> {0} Insert operations completed in {1} taking an average of {2}", insertCount, new TimeSpan(insertTicks), avg);
_announcer.Say(msg);
}
}
private void AnnounceTime(string message, Action action)
{
_announcer.Say(message);
_stopWatch.Start();
action();
_stopWatch.Stop();
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
private long Time(Action action)
{
_stopWatch.Start();
action();
_stopWatch.Stop();
return _stopWatch.ElapsedTime().Ticks;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Xml;
using System.Reflection;
namespace System.Management.Automation
{
/// <summary>
/// Class ProviderHelpProvider implement the help provider for commands.
/// </summary>
/// <remarks>
/// Provider Help information are stored in 'help.xml' files. Location of these files
/// can be found from CommandDiscovery.
/// </remarks>
internal class ProviderHelpProvider : HelpProviderWithCache
{
/// <summary>
/// Constructor for HelpProvider.
/// </summary>
internal ProviderHelpProvider(HelpSystem helpSystem) : base(helpSystem)
{
_sessionState = helpSystem.ExecutionContext.SessionState;
}
private readonly SessionState _sessionState;
#region Common Properties
/// <summary>
/// Name of this help provider.
/// </summary>
/// <value>Name of this help provider.</value>
internal override string Name
{
get
{
return "Provider Help Provider";
}
}
/// <summary>
/// Help category of this provider.
/// </summary>
/// <value>Help category of this provider</value>
internal override HelpCategory HelpCategory
{
get
{
return HelpCategory.Provider;
}
}
#endregion
#region Help Provider Interface
/// <summary>
/// Do exact match help based on the target.
/// </summary>
/// <param name="helpRequest">Help request object.</param>
internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest)
{
Collection<ProviderInfo> matchingProviders = null;
try
{
matchingProviders = _sessionState.Provider.Get(helpRequest.Target);
}
catch (ProviderNotFoundException e)
{
// We distinguish two cases here,
// a. If the "Provider" is the only category to search for in this case,
// an error will be written.
// b. Otherwise, no errors will be written since in end user's mind,
// he may mean to search for provider help.
if (this.HelpSystem.LastHelpCategory == HelpCategory.Provider)
{
ErrorRecord errorRecord = new ErrorRecord(e, "ProviderLoadError", ErrorCategory.ResourceUnavailable, null);
errorRecord.ErrorDetails = new ErrorDetails(typeof(ProviderHelpProvider).Assembly, "HelpErrors", "ProviderLoadError", helpRequest.Target, e.Message);
this.HelpSystem.LastErrors.Add(errorRecord);
}
}
if (matchingProviders != null)
{
foreach (ProviderInfo providerInfo in matchingProviders)
{
try
{
LoadHelpFile(providerInfo);
}
catch (IOException ioException)
{
ReportHelpFileError(ioException, helpRequest.Target, providerInfo.HelpFile);
}
catch (System.Security.SecurityException securityException)
{
ReportHelpFileError(securityException, helpRequest.Target, providerInfo.HelpFile);
}
catch (XmlException xmlException)
{
ReportHelpFileError(xmlException, helpRequest.Target, providerInfo.HelpFile);
}
HelpInfo helpInfo = GetCache(providerInfo.PSSnapInName + "\\" + providerInfo.Name);
if (helpInfo != null)
{
yield return helpInfo;
}
}
}
}
private static string GetProviderAssemblyPath(ProviderInfo providerInfo)
{
if (providerInfo == null)
return null;
if (providerInfo.ImplementingType == null)
return null;
return Path.GetDirectoryName(providerInfo.ImplementingType.Assembly.Location);
}
/// <summary>
/// This is a hashtable to track which help files are loaded already.
///
/// This will avoid one help file getting loaded again and again.
/// (Which should not happen unless some provider is pointing
/// to a help file that actually doesn't contain the help for it).
/// </summary>
private readonly Hashtable _helpFiles = new Hashtable();
/// <summary>
/// Load help file provided.
/// </summary>
/// <remarks>
/// This will load providerHelpInfo from help file into help cache.
/// </remarks>
/// <param name="providerInfo">ProviderInfo for which to locate help.</param>
private void LoadHelpFile(ProviderInfo providerInfo)
{
if (providerInfo == null)
{
throw PSTraceSource.NewArgumentNullException("providerInfo");
}
string helpFile = providerInfo.HelpFile;
if (string.IsNullOrEmpty(helpFile) || _helpFiles.Contains(helpFile))
{
return;
}
string helpFileToLoad = helpFile;
// Get the mshsnapinfo object for this cmdlet.
PSSnapInInfo mshSnapInInfo = providerInfo.PSSnapIn;
// Search fallback
// 1. If PSSnapInInfo exists, then always look in the application base
// of the mshsnapin
// Otherwise,
// Look in the default search path and cmdlet assembly path
Collection<string> searchPaths = new Collection<string>();
if (mshSnapInInfo != null)
{
Diagnostics.Assert(!string.IsNullOrEmpty(mshSnapInInfo.ApplicationBase),
"Application Base is null or empty.");
// not minishell case..
// we have to search only in the application base for a mshsnapin...
// if you create an absolute path for helpfile, then MUIFileSearcher
// will look only in that path.
helpFileToLoad = Path.Combine(mshSnapInInfo.ApplicationBase, helpFile);
}
else if ((providerInfo.Module != null) && (!string.IsNullOrEmpty(providerInfo.Module.Path)))
{
helpFileToLoad = Path.Combine(providerInfo.Module.ModuleBase, helpFile);
}
else
{
searchPaths.Add(GetDefaultShellSearchPath());
searchPaths.Add(GetProviderAssemblyPath(providerInfo));
}
string location = MUIFileSearcher.LocateFile(helpFileToLoad, searchPaths);
if (string.IsNullOrEmpty(location))
throw new FileNotFoundException(helpFile);
XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
new FileInfo(location),
false, /* ignore whitespace, comments, etc. */
null); /* default maxCharactersInDocument */
// Add this file into _helpFiles hashtable to prevent it to be loaded again.
_helpFiles[helpFile] = 0;
XmlNode helpItemsNode = null;
if (doc.HasChildNodes)
{
for (int i = 0; i < doc.ChildNodes.Count; i++)
{
XmlNode node = doc.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Compare(node.Name, "helpItems", StringComparison.OrdinalIgnoreCase) == 0)
{
helpItemsNode = node;
break;
}
}
}
if (helpItemsNode == null)
return;
using (this.HelpSystem.Trace(location))
{
if (helpItemsNode.HasChildNodes)
{
for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++)
{
XmlNode node = helpItemsNode.ChildNodes[i];
if (node.NodeType == XmlNodeType.Element && string.Compare(node.Name, "providerHelp", StringComparison.OrdinalIgnoreCase) == 0)
{
HelpInfo helpInfo = ProviderHelpInfo.Load(node);
if (helpInfo != null)
{
this.HelpSystem.TraceErrors(helpInfo.Errors);
// Add snapin qualified type name for this command..
// this will enable customizations of the help object.
helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture,
"ProviderHelpInfo#{0}#{1}", providerInfo.PSSnapInName, helpInfo.Name));
if (!string.IsNullOrEmpty(providerInfo.PSSnapInName))
{
helpInfo.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", providerInfo.PSSnapIn));
helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture,
"ProviderHelpInfo#{0}", providerInfo.PSSnapInName));
}
AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo);
}
}
}
}
}
}
/// <summary>
/// Search for provider help based on a search target.
/// </summary>
/// <param name="helpRequest">Help request object.</param>
/// <param name="searchOnlyContent">
/// If true, searches for pattern in the help content. Individual
/// provider can decide which content to search in.
///
/// If false, searches for pattern in the command names.
/// </param>
/// <returns></returns>
internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
{
int countOfHelpInfoObjectsFound = 0;
string target = helpRequest.Target;
string pattern = target;
// this will be used only when searchOnlyContent == true
WildcardPattern wildCardPattern = null;
bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(target);
if (!searchOnlyContent)
{
if (decoratedSearch)
{
pattern += "*";
}
}
else
{
string searchTarget = helpRequest.Target;
if (decoratedSearch)
{
searchTarget = "*" + helpRequest.Target + "*";
}
wildCardPattern = WildcardPattern.Get(searchTarget, WildcardOptions.Compiled | WildcardOptions.IgnoreCase);
// search in all providers
pattern = "*";
}
PSSnapinQualifiedName snapinQualifiedNameForPattern =
PSSnapinQualifiedName.GetInstance(pattern);
if (snapinQualifiedNameForPattern == null)
{
yield break;
}
foreach (ProviderInfo providerInfo in _sessionState.Provider.GetAll())
{
if (providerInfo.IsMatch(pattern))
{
try
{
LoadHelpFile(providerInfo);
}
catch (IOException ioException)
{
if (!decoratedSearch)
{
ReportHelpFileError(ioException, providerInfo.Name, providerInfo.HelpFile);
}
}
catch (System.Security.SecurityException securityException)
{
if (!decoratedSearch)
{
ReportHelpFileError(securityException, providerInfo.Name, providerInfo.HelpFile);
}
}
catch (XmlException xmlException)
{
if (!decoratedSearch)
{
ReportHelpFileError(xmlException, providerInfo.Name, providerInfo.HelpFile);
}
}
HelpInfo helpInfo = GetCache(providerInfo.PSSnapInName + "\\" + providerInfo.Name);
if (helpInfo != null)
{
if (searchOnlyContent)
{
// ignore help objects that do not have pattern in its help
// content.
if (!helpInfo.MatchPatternInContent(wildCardPattern))
{
continue;
}
}
countOfHelpInfoObjectsFound++;
yield return helpInfo;
if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0)
yield break;
}
}
}
}
internal override IEnumerable<HelpInfo> ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest)
{
ProviderCommandHelpInfo providerCommandHelpInfo = new ProviderCommandHelpInfo(
helpInfo, helpRequest.ProviderContext);
yield return providerCommandHelpInfo;
}
#if V2
/// <summary>
/// Process a helpInfo forwarded from other providers (normally commandHelpProvider)
/// </summary>
/// <remarks>
/// For command help info, this will
/// 1. check whether provider-specific commandlet help exists.
/// 2. merge found provider-specific help with commandlet help provided.
/// </remarks>
/// <param name="helpInfo">HelpInfo forwarded in.</param>
/// <param name="helpRequest">Help request object.</param>
/// <returns>The help info object after processing.</returns>
override internal HelpInfo ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest)
{
if (helpInfo == null)
return null;
if (helpInfo.HelpCategory != HelpCategory.Command)
{
return helpInfo;
}
string providerName = helpRequest.Provider;
if (string.IsNullOrEmpty(providerName))
{
providerName = this._sessionState.Path.CurrentLocation.Provider.Name;
}
HelpRequest providerHelpRequest = helpRequest.Clone();
providerHelpRequest.Target = providerName;
ProviderHelpInfo providerHelpInfo = (ProviderHelpInfo)this.ExactMatchHelp(providerHelpRequest);
if (providerHelpInfo == null)
return null;
CommandHelpInfo commandHelpInfo = (CommandHelpInfo)helpInfo;
CommandHelpInfo result = commandHelpInfo.MergeProviderSpecificHelp(providerHelpInfo.GetCmdletHelp(commandHelpInfo.Name), providerHelpInfo.GetDynamicParameterHelp(helpRequest.DynamicParameters));
// Reset ForwardHelpCategory for the helpinfo to be returned so that it will not be forwarded back again.
result.ForwardHelpCategory = HelpCategory.None;
return result;
}
#endif
/// <summary>
/// This will reset the help cache. Normally this corresponds to a
/// help culture change.
/// </summary>
internal override void Reset()
{
base.Reset();
_helpFiles.Clear();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type Half with 2 columns and 4 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct hmat2x4 : IReadOnlyList<Half>, IEquatable<hmat2x4>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public Half m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public Half m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
[DataMember]
public Half m02;
/// <summary>
/// Column 0, Rows 3
/// </summary>
[DataMember]
public Half m03;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public Half m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public Half m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
[DataMember]
public Half m12;
/// <summary>
/// Column 1, Rows 3
/// </summary>
[DataMember]
public Half m13;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public hmat2x4(Half m00, Half m01, Half m02, Half m03, Half m10, Half m11, Half m12, Half m13)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m03 = m03;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m13 = m13;
}
/// <summary>
/// Constructs this matrix from a hmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = Half.Zero;
this.m03 = Half.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = Half.Zero;
this.m13 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a hmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = Half.Zero;
this.m03 = Half.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = Half.Zero;
this.m13 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a hmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = Half.Zero;
this.m03 = Half.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = Half.Zero;
this.m13 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a hmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = Half.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a hmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = Half.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a hmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = Half.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a hmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a hmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a hmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hvec2 c0, hvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = Half.Zero;
this.m03 = Half.Zero;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = Half.Zero;
this.m13 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hvec3 c0, hvec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = Half.Zero;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = Half.Zero;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public hmat2x4(hvec4 c0, hvec4 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = c0.w;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = c1.w;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public Half[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public Half[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public hvec4 Column0
{
get
{
return new hvec4(m00, m01, m02, m03);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
m03 = value.w;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public hvec4 Column1
{
get
{
return new hvec4(m10, m11, m12, m13);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
m13 = value.w;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public hvec2 Row0
{
get
{
return new hvec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public hvec2 Row1
{
get
{
return new hvec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public hvec2 Row2
{
get
{
return new hvec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 3
/// </summary>
public hvec2 Row3
{
get
{
return new hvec2(m03, m13);
}
set
{
m03 = value.x;
m13 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static hmat2x4 Zero { get; } = new hmat2x4(Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static hmat2x4 Ones { get; } = new hmat2x4(Half.One, Half.One, Half.One, Half.One, Half.One, Half.One, Half.One, Half.One);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static hmat2x4 Identity { get; } = new hmat2x4(Half.One, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.One, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static hmat2x4 AllMaxValue { get; } = new hmat2x4(Half.MaxValue, Half.MaxValue, Half.MaxValue, Half.MaxValue, Half.MaxValue, Half.MaxValue, Half.MaxValue, Half.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static hmat2x4 DiagonalMaxValue { get; } = new hmat2x4(Half.MaxValue, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.MaxValue, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static hmat2x4 AllMinValue { get; } = new hmat2x4(Half.MinValue, Half.MinValue, Half.MinValue, Half.MinValue, Half.MinValue, Half.MinValue, Half.MinValue, Half.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static hmat2x4 DiagonalMinValue { get; } = new hmat2x4(Half.MinValue, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.MinValue, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-Epsilon matrix
/// </summary>
public static hmat2x4 AllEpsilon { get; } = new hmat2x4(Half.Epsilon, Half.Epsilon, Half.Epsilon, Half.Epsilon, Half.Epsilon, Half.Epsilon, Half.Epsilon, Half.Epsilon);
/// <summary>
/// Predefined diagonal-Epsilon matrix
/// </summary>
public static hmat2x4 DiagonalEpsilon { get; } = new hmat2x4(Half.Epsilon, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.Epsilon, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-NaN matrix
/// </summary>
public static hmat2x4 AllNaN { get; } = new hmat2x4(Half.NaN, Half.NaN, Half.NaN, Half.NaN, Half.NaN, Half.NaN, Half.NaN, Half.NaN);
/// <summary>
/// Predefined diagonal-NaN matrix
/// </summary>
public static hmat2x4 DiagonalNaN { get; } = new hmat2x4(Half.NaN, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.NaN, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-NegativeInfinity matrix
/// </summary>
public static hmat2x4 AllNegativeInfinity { get; } = new hmat2x4(Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity, Half.NegativeInfinity);
/// <summary>
/// Predefined diagonal-NegativeInfinity matrix
/// </summary>
public static hmat2x4 DiagonalNegativeInfinity { get; } = new hmat2x4(Half.NegativeInfinity, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.NegativeInfinity, Half.Zero, Half.Zero);
/// <summary>
/// Predefined all-PositiveInfinity matrix
/// </summary>
public static hmat2x4 AllPositiveInfinity { get; } = new hmat2x4(Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity, Half.PositiveInfinity);
/// <summary>
/// Predefined diagonal-PositiveInfinity matrix
/// </summary>
public static hmat2x4 DiagonalPositiveInfinity { get; } = new hmat2x4(Half.PositiveInfinity, Half.Zero, Half.Zero, Half.Zero, Half.Zero, Half.PositiveInfinity, Half.Zero, Half.Zero);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<Half> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m03;
yield return m10;
yield return m11;
yield return m12;
yield return m13;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 4 = 8).
/// </summary>
public int Count => 8;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public Half this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m03;
case 4: return m10;
case 5: return m11;
case 6: return m12;
case 7: return m13;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m03 = value; break;
case 4: this.m10 = value; break;
case 5: this.m11 = value; break;
case 6: this.m12 = value; break;
case 7: this.m13 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public Half this[int col, int row]
{
get
{
return this[col * 4 + row];
}
set
{
this[col * 4 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(hmat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is hmat2x4 && Equals((hmat2x4) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(hmat2x4 lhs, hmat2x4 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(hmat2x4 lhs, hmat2x4 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m03.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m13.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public hmat4x2 Transposed => new hmat4x2(m00, m10, m01, m11, m02, m12, m03, m13);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public Half MinElement => Half.Min(Half.Min(Half.Min(Half.Min(Half.Min(Half.Min(Half.Min(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public Half MaxElement => Half.Max(Half.Max(Half.Max(Half.Max(Half.Max(Half.Max(Half.Max(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => (((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public Half Sum => (((m00 + m01) + (m02 + m03)) + ((m10 + m11) + (m12 + m13)));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => (((Half.Abs(m00) + Half.Abs(m01)) + (Half.Abs(m02) + Half.Abs(m03))) + ((Half.Abs(m10) + Half.Abs(m11)) + (Half.Abs(m12) + Half.Abs(m13))));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public Half NormMax => Half.Max(Half.Max(Half.Max(Half.Max(Half.Max(Half.Max(Half.Max(Half.Abs(m00), Half.Abs(m01)), Half.Abs(m02)), Half.Abs(m03)), Half.Abs(m10)), Half.Abs(m11)), Half.Abs(m12)), Half.Abs(m13));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)Half.Abs(m00), p) + Math.Pow((double)Half.Abs(m01), p)) + (Math.Pow((double)Half.Abs(m02), p) + Math.Pow((double)Half.Abs(m03), p))) + ((Math.Pow((double)Half.Abs(m10), p) + Math.Pow((double)Half.Abs(m11), p)) + (Math.Pow((double)Half.Abs(m12), p) + Math.Pow((double)Half.Abs(m13), p)))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication hmat2x4 * hmat2 -> hmat2x4.
/// </summary>
public static hmat2x4 operator*(hmat2x4 lhs, hmat2 rhs) => new hmat2x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication hmat2x4 * hmat3x2 -> hmat3x4.
/// </summary>
public static hmat3x4 operator*(hmat2x4 lhs, hmat3x2 rhs) => new hmat3x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication hmat2x4 * hmat4x2 -> hmat4.
/// </summary>
public static hmat4 operator*(hmat2x4 lhs, hmat4x2 rhs) => new hmat4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31), (lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static hvec4 operator*(hmat2x4 m, hvec2 v) => new hvec4((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y), (m.m03 * v.x + m.m13 * v.y));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static hmat2x4 CompMul(hmat2x4 A, hmat2x4 B) => new hmat2x4(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m03 * B.m03, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m13 * B.m13);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static hmat2x4 CompDiv(hmat2x4 A, hmat2x4 B) => new hmat2x4(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m03 / B.m03, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m13 / B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static hmat2x4 CompAdd(hmat2x4 A, hmat2x4 B) => new hmat2x4(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m03 + B.m03, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m13 + B.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static hmat2x4 CompSub(hmat2x4 A, hmat2x4 B) => new hmat2x4(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m03 - B.m03, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m13 - B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static hmat2x4 operator+(hmat2x4 lhs, hmat2x4 rhs) => new hmat2x4(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m03 + rhs.m03, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m13 + rhs.m13);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static hmat2x4 operator+(hmat2x4 lhs, Half rhs) => new hmat2x4(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m03 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m13 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static hmat2x4 operator+(Half lhs, hmat2x4 rhs) => new hmat2x4(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m03, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static hmat2x4 operator-(hmat2x4 lhs, hmat2x4 rhs) => new hmat2x4(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m03 - rhs.m03, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m13 - rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static hmat2x4 operator-(hmat2x4 lhs, Half rhs) => new hmat2x4(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m03 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m13 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static hmat2x4 operator-(Half lhs, hmat2x4 rhs) => new hmat2x4(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m03, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m13);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static hmat2x4 operator/(hmat2x4 lhs, Half rhs) => new hmat2x4(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m03 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m13 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static hmat2x4 operator/(Half lhs, hmat2x4 rhs) => new hmat2x4(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m03, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m13);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static hmat2x4 operator*(hmat2x4 lhs, Half rhs) => new hmat2x4(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m03 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static hmat2x4 operator*(Half lhs, hmat2x4 rhs) => new hmat2x4(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m03, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m13);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat2x4 operator<(hmat2x4 lhs, hmat2x4 rhs) => new bmat2x4(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m03 < rhs.m03, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m13 < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(hmat2x4 lhs, Half rhs) => new bmat2x4(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m03 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m13 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(Half lhs, hmat2x4 rhs) => new bmat2x4(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m03, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat2x4 operator<=(hmat2x4 lhs, hmat2x4 rhs) => new bmat2x4(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m03 <= rhs.m03, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m13 <= rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(hmat2x4 lhs, Half rhs) => new bmat2x4(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m03 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m13 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(Half lhs, hmat2x4 rhs) => new bmat2x4(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m03, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat2x4 operator>(hmat2x4 lhs, hmat2x4 rhs) => new bmat2x4(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m03 > rhs.m03, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m13 > rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(hmat2x4 lhs, Half rhs) => new bmat2x4(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m03 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m13 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(Half lhs, hmat2x4 rhs) => new bmat2x4(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m03, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat2x4 operator>=(hmat2x4 lhs, hmat2x4 rhs) => new bmat2x4(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m03 >= rhs.m03, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m13 >= rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(hmat2x4 lhs, Half rhs) => new bmat2x4(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m03 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m13 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(Half lhs, hmat2x4 rhs) => new bmat2x4(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m03, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m13);
}
}
| |
#region copyright
// -----------------------------------------------------------------------
// <copyright file="TypeEx.cs" company="Akka.NET Team">
// Copyright (C) 2015-2016 AsynkronIT <https://github.com/AsynkronIT>
// Copyright (C) 2016-2016 Akka.NET Team <https://github.com/akkadotnet>
// </copyright>
// -----------------------------------------------------------------------
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Hyperion.Internal;
namespace Hyperion.Extensions
{
internal static class TypeEx
{
//Why not inline typeof you ask?
//Because it actually generates calls to get the type.
//We prefetch all primitives here
public static readonly Type SystemObject = typeof(object);
public static readonly Type Int32Type = typeof(int);
public static readonly Type Int64Type = typeof(long);
public static readonly Type Int16Type = typeof(short);
public static readonly Type UInt32Type = typeof(uint);
public static readonly Type UInt64Type = typeof(ulong);
public static readonly Type UInt16Type = typeof(ushort);
public static readonly Type ByteType = typeof(byte);
public static readonly Type SByteType = typeof(sbyte);
public static readonly Type BoolType = typeof(bool);
public static readonly Type DateTimeType = typeof(DateTime);
public static readonly Type DateTimeOffsetType = typeof(DateTimeOffset);
public static readonly Type StringType = typeof(string);
public static readonly Type GuidType = typeof(Guid);
public static readonly Type FloatType = typeof(float);
public static readonly Type DoubleType = typeof(double);
public static readonly Type DecimalType = typeof(decimal);
public static readonly Type CharType = typeof(char);
public static readonly Type ByteArrayType = typeof(byte[]);
public static readonly Type TypeType = typeof(Type);
public static readonly Type RuntimeType = Type.GetType("System.RuntimeType");
private static readonly ReadOnlyCollection<string> UnsafeTypesDenySet =
new ReadOnlyCollection<string>(new[]
{
"System.Security.Claims.ClaimsIdentity",
"System.Windows.Forms.AxHost.State",
"System.Windows.Data.ObjectDataProvider",
"System.Management.Automation.PSObject",
"System.Web.Security.RolePrincipal",
"System.IdentityModel.Tokens.SessionSecurityToken",
"SessionViewStateHistoryItem",
"TextFormattingRunProperties",
"ToolboxItemContainer",
"System.Security.Principal.WindowsClaimsIdentity",
"System.Security.Principal.WindowsIdentity",
"System.Security.Principal.WindowsPrincipal",
"System.CodeDom.Compiler.TempFileCollection",
"System.IO.FileSystemInfo",
"System.Activities.Presentation.WorkflowDesigner",
"System.Windows.ResourceDictionary",
"System.Windows.Forms.BindingSource",
"Microsoft.Exchange.Management.SystemManager.WinForms.ExchangeSettingsProvider",
"System.Diagnostics.Process",
"System.Management.IWbemClassObjectFreeThreaded"
});
public static bool IsHyperionPrimitive(this Type type)
{
return type == Int32Type ||
type == Int64Type ||
type == Int16Type ||
type == UInt32Type ||
type == UInt64Type ||
type == UInt16Type ||
type == ByteType ||
type == SByteType ||
type == DateTimeType ||
type == DateTimeOffsetType ||
type == BoolType ||
type == StringType ||
type == GuidType ||
type == FloatType ||
type == DoubleType ||
type == DecimalType ||
type == CharType;
//add TypeSerializer with null support
}
#if NETSTANDARD16
//HACK: IsValueType does not exist for netstandard1.6
private static bool IsValueType(this Type type)
=> type.IsSubclassOf(typeof(ValueType));
private static bool IsSubclassOf(this Type p, Type c)
=> c.IsAssignableFrom(p);
//HACK: the GetUnitializedObject actually exists in .NET Core, its just not public
private static readonly Func<Type, object> GetUninitializedObjectDelegate = (Func<Type, object>)
typeof(string)
.GetTypeInfo()
.Assembly
.GetType("System.Runtime.Serialization.FormatterServices")
?.GetTypeInfo()
?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
?.CreateDelegate(typeof(Func<Type, object>));
public static object GetEmptyObject(this Type type)
{
return GetUninitializedObjectDelegate(type);
}
#else
public static object GetEmptyObject(this Type type) => System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
#endif
public static bool IsOneDimensionalArray(this Type type)
{
return type.IsArray && type.GetArrayRank() == 1;
}
public static bool IsOneDimensionalPrimitiveArray(this Type type)
{
return type.IsArray && type.GetArrayRank() == 1 && type.GetElementType().IsHyperionPrimitive();
}
private static readonly ConcurrentDictionary<ByteArrayKey, Type> TypeNameLookup =
new ConcurrentDictionary<ByteArrayKey, Type>(ByteArrayKeyComparer.Instance);
public static byte[] GetTypeManifest(IReadOnlyCollection<byte[]> fieldNames)
{
IEnumerable<byte> result = new[] { (byte)fieldNames.Count };
foreach (var name in fieldNames)
{
var encodedLength = BitConverter.GetBytes(name.Length);
result = result.Concat(encodedLength);
result = result.Concat(name);
}
var versionTolerantHeader = result.ToArray();
return versionTolerantHeader;
}
private static Type GetTypeFromManifestName(Stream stream, DeserializerSession session)
{
var bytes = stream.ReadLengthEncodedByteArray(session);
var byteArr = ByteArrayKey.Create(bytes);
return TypeNameLookup.GetOrAdd(byteArr, b =>
{
var shortName = StringEx.FromUtf8Bytes(b.Bytes, 0, b.Bytes.Length);
var overrides = session.Serializer.Options.CrossFrameworkPackageNameOverrides;
var oldName = shortName;
foreach (var adapter in overrides)
{
shortName = adapter(shortName);
if (!ReferenceEquals(oldName, shortName))
break;
}
var options = session.Serializer.Options;
return LoadTypeByName(shortName, options.DisallowUnsafeTypes, options.TypeFilter);
});
}
private static bool UnsafeInheritanceCheck(Type type)
{
#if NETSTANDARD1_6
if (type.IsValueType())
return false;
var currentBase = type.DeclaringType;
#else
if (type.IsValueType)
return false;
var currentBase = type.BaseType;
#endif
while (currentBase != null)
{
if (UnsafeTypesDenySet.Any(r => currentBase.FullName?.Contains(r) ?? false))
return true;
#if NETSTANDARD1_6
currentBase = currentBase.DeclaringType;
#else
currentBase = currentBase.BaseType;
#endif
}
return false;
}
public static Type LoadTypeByName(string name, bool disallowUnsafeTypes, ITypeFilter typeFilter)
{
if (disallowUnsafeTypes)
{
if(UnsafeTypesDenySet.Any(name.Contains))
throw new EvilDeserializationException("Unsafe Type Deserialization Detected!", name);
if(!typeFilter.IsAllowed(name))
throw new UserEvilDeserializationException("Unsafe Type Deserialization Detected!", name);
}
try
{
// Try to load type name using strict version to avoid possible conflicts
// i.e. if there are different version available in GAC and locally
var typename = ToQualifiedAssemblyName(name, ignoreAssemblyVersion: false);
var type = Type.GetType(typename, true);
if (UnsafeInheritanceCheck(type))
throw new EvilDeserializationException(
"Unsafe Type Deserialization Detected!", name);
return type;
}
catch (IOException)
{
var typename = ToQualifiedAssemblyName(name, ignoreAssemblyVersion: true);
var type = Type.GetType(typename, true);
if (UnsafeInheritanceCheck(type))
throw new EvilDeserializationException(
"Unsafe Type Deserialization Detected!", name);
return type;
}
}
public static Type GetTypeFromManifestFull(Stream stream, DeserializerSession session)
{
var type = GetTypeFromManifestName(stream, session);
session.TrackDeserializedType(type);
return type;
}
public static Type GetTypeFromManifestVersion(Stream stream, DeserializerSession session)
{
var type = GetTypeFromManifestName(stream, session);
var fieldCount = stream.ReadByte();
for (var i = 0; i < fieldCount; i++)
{
var fieldName = stream.ReadLengthEncodedByteArray(session);
}
session.TrackDeserializedTypeWithVersion(type, null);
return type;
}
public static Type GetTypeFromManifestIndex(int typeId, DeserializerSession session)
{
var type = session.GetTypeFromTypeId(typeId);
return type;
}
public static bool IsNullable(this Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static Type GetNullableElement(this Type type)
{
return type.GetTypeInfo().GetGenericArguments()[0];
}
public static bool IsFixedSizeType(this Type type)
{
return type == Int16Type ||
type == Int32Type ||
type == Int64Type ||
type == BoolType ||
type == UInt16Type ||
type == UInt32Type ||
type == UInt64Type ||
type == CharType;
}
public static int GetTypeSize(this Type type)
{
if (type == Int16Type)
return sizeof(short);
if (type == Int32Type)
return sizeof (int);
if (type == Int64Type)
return sizeof (long);
if (type == BoolType)
return sizeof (bool);
if (type == UInt16Type)
return sizeof (ushort);
if (type == UInt32Type)
return sizeof (uint);
if (type == UInt64Type)
return sizeof (ulong);
if (type == CharType)
return sizeof(char);
throw new NotSupportedException();
}
private static readonly string CoreAssemblyQualifiedName = 1.GetType().AssemblyQualifiedName;
private static readonly string CoreAssemblyName = GetCoreAssemblyName();
private static readonly Regex cleanAssemblyVersionRegex = new Regex(
"(, Version=([\\d\\.]+))?(, Culture=[^,\\] \\t]+)?(, PublicKeyToken=(null|[\\da-f]+))?",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private static string GetCoreAssemblyName()
{
var part = CoreAssemblyQualifiedName.Substring(CoreAssemblyQualifiedName.IndexOf(", Version", StringComparison.Ordinal));
return part;
}
public static string GetShortAssemblyQualifiedName(this Type self)
{
var name = self.AssemblyQualifiedName;
name = name.Replace(CoreAssemblyName, ",%core%");
name = cleanAssemblyVersionRegex.Replace(name, string.Empty);
return name;
}
public static string ToQualifiedAssemblyName(string shortName, bool ignoreAssemblyVersion)
{
// Strip out assembly version, if specified
if (ignoreAssemblyVersion)
{
shortName = cleanAssemblyVersionRegex.Replace(shortName, string.Empty);
}
var res = shortName.Replace(",%core%", CoreAssemblyName);
return res;
}
/// <summary>
/// Search for a method by name, parameter types, and binding flags.
/// Unlike GetMethod(), does 'loose' matching on generic
/// parameter types, and searches base interfaces.
/// </summary>
/// <exception cref="AmbiguousMatchException"/>
public static MethodInfo GetMethodExt(this Type thisType,
string name,
BindingFlags bindingFlags,
params Type[] parameterTypes)
{
MethodInfo matchingMethod = null;
// Check all methods with the specified name, including in base classes
GetMethodExt(ref matchingMethod, thisType, name, bindingFlags, parameterTypes);
// If we're searching an interface, we have to manually search base interfaces
if (matchingMethod == null && thisType.GetTypeInfo().IsInterface)
{
foreach (Type interfaceType in thisType.GetInterfaces())
GetMethodExt(ref matchingMethod,
interfaceType,
name,
bindingFlags,
parameterTypes);
}
return matchingMethod;
}
private static void GetMethodExt(ref MethodInfo matchingMethod,
Type type,
string name,
BindingFlags bindingFlags,
params Type[] parameterTypes)
{
// Check all methods with the specified name, including in base classes
foreach (MethodInfo methodInfo in type.GetTypeInfo().GetMember(name,
MemberTypes.Method,
bindingFlags))
{
// Check that the parameter counts and types match,
// with 'loose' matching on generic parameters
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
if (parameterInfos.Length == parameterTypes.Length)
{
int i = 0;
for (; i < parameterInfos.Length; ++i)
{
if (!parameterInfos[i].ParameterType
.IsSimilarType(parameterTypes[i]))
break;
}
if (i == parameterInfos.Length)
{
if (matchingMethod == null)
matchingMethod = methodInfo;
else
throw new AmbiguousMatchException(
"More than one matching method found!");
}
}
}
}
/// <summary>
/// Special type used to match any generic parameter type in GetMethodExt().
/// </summary>
public class T
{ }
/// <summary>
/// Determines if the two types are either identical, or are both generic
/// parameters or generic types with generic parameters in the same
/// locations (generic parameters match any other generic paramter,
/// and concrete types).
/// </summary>
private static bool IsSimilarType(this Type thisType, Type type)
{
if (thisType == null && type == null)
return true;
if (thisType == null || type == null)
return false;
// Ignore any 'ref' types
if (thisType.IsByRef)
thisType = thisType.GetElementType();
if (type.IsByRef)
type = type.GetElementType();
// Handle array types
if (thisType.IsArray && type.IsArray)
return thisType.GetElementType().IsSimilarType(type.GetElementType());
// If the types are identical, or they're both generic parameters
// or the special 'T' type, treat as a match
if (thisType == type || thisType.IsGenericParameter || thisType == typeof(T) || type.IsGenericParameter || type == typeof(T))
return true;
// Handle any generic arguments
if (thisType.GetTypeInfo().IsGenericType && type.GetTypeInfo().IsGenericType)
{
Type[] thisArguments = thisType.GetGenericArguments();
Type[] arguments = type.GetGenericArguments();
if (thisArguments.Length == arguments.Length)
{
for (int i = 0; i < thisArguments.Length; ++i)
{
if (!thisArguments[i].IsSimilarType(arguments[i]))
return false;
}
return true;
}
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using DbLocalizationProvider.Queries;
using DbLocalizationProvider.Refactoring;
using DbLocalizationProvider.Sync;
using Xunit;
namespace DbLocalizationProvider.Tests.Refactoring
{
public class RefactoredResourceTests
{
private readonly TypeDiscoveryHelper _sut;
public RefactoredResourceTests()
{
var state = new ScanState();
var keyBuilder = new ResourceKeyBuilder(state);
var oldKeyBuilder = new OldResourceKeyBuilder(keyBuilder);
var ctx = new ConfigurationContext();
ctx.TypeFactory.ForQuery<DetermineDefaultCulture.Query>().SetHandler<DetermineDefaultCulture.Handler>();
ctx.CustomAttributes.Add<AdditionalDataAttribute>();
var queryExecutor = new QueryExecutor(ctx.TypeFactory);
var translationBuilder = new DiscoveredTranslationBuilder(queryExecutor);
_sut = new TypeDiscoveryHelper(new List<IResourceTypeScanner>
{
new LocalizedModelTypeScanner(keyBuilder, oldKeyBuilder, state, ctx, translationBuilder),
new LocalizedResourceTypeScanner(keyBuilder, oldKeyBuilder, state, ctx, translationBuilder),
new LocalizedEnumTypeScanner(keyBuilder, translationBuilder),
new LocalizedForeignResourceTypeScanner(keyBuilder, oldKeyBuilder, state, ctx, translationBuilder)
}, ctx);
}
[Theory]
[InlineData(typeof(RenamedResourceClass),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClass.NewResourceKey",
"OldResourceClass",
null,
"DbLocalizationProvider.Tests.Refactoring.OldResourceClass.NewResourceKey")]
[InlineData(typeof(RenamedResourceNamespace),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceNamespace.NewResourceKey",
null,
"In.Galaxy.Far.Far.Away",
"In.Galaxy.Far.Far.Away.RenamedResourceNamespace.NewResourceKey")]
[InlineData(typeof(RenamedResourceClassAndNamespace),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClassAndNamespace.NewResourceKey",
"OldResourceClassAndNamespace",
"In.Galaxy.Far.Far.Away",
"In.Galaxy.Far.Far.Away.OldResourceClassAndNamespace.NewResourceKey")]
[InlineData(typeof(RenamedResourceKey),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceKey.NewResourceKey",
"OldResourceKey",
null,
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceKey.OldResourceKey")]
[InlineData(typeof(RenamedResourceClassAndKey),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClassAndKey.NewResourceKey",
"OldResourceKey",
null,
"DbLocalizationProvider.Tests.Refactoring.OldResourceClass.OldResourceKey")]
[InlineData(typeof(RenamedResourceClassAndKeyAndNamespace),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClassAndKeyAndNamespace.NewResourceKey",
"OldResourceKey",
"In.Galaxy.Far.Far.Away",
"In.Galaxy.Far.Far.Away.OldResourceClassAndKeyAndNamespace.OldResourceKey")]
public void ProperRenameDiscoveryTests(Type target, string resourceKey, string oldTypeName, string typeOldNamespace, string oldResourceKey)
{
var result = _sut.ScanResources(target);
Assert.NotEmpty(result);
var discoveredResource = result.First();
Assert.Equal(resourceKey, discoveredResource.Key);
Assert.Equal(oldTypeName, discoveredResource.TypeOldName);
Assert.Equal(typeOldNamespace, discoveredResource.TypeOldNamespace);
Assert.Equal(oldResourceKey, discoveredResource.OldResourceKey);
}
[Theory]
[InlineData(typeof(ParentContainerClass.RenamedNestedResourceClass),
"DbLocalizationProvider.Tests.Refactoring.ParentContainerClass+RenamedNestedResourceClass.NewResourceKey",
"OldNestedResourceClass",
null,
"DbLocalizationProvider.Tests.Refactoring.ParentContainerClass+OldNestedResourceClass.NewResourceKey")]
[InlineData(typeof(ParentContainerClass.RenamedNestedResourceProperty),
"DbLocalizationProvider.Tests.Refactoring.ParentContainerClass+RenamedNestedResourceProperty.NewResourceKey",
"OldProperty",
null,
"DbLocalizationProvider.Tests.Refactoring.ParentContainerClass+RenamedNestedResourceProperty.OldProperty")]
[InlineData(typeof(ParentContainerClass.RenamedNestedResourceClassAndProperty),
"DbLocalizationProvider.Tests.Refactoring.ParentContainerClass+RenamedNestedResourceClassAndProperty.NewResourceKey",
"OldProperty",
null,
"DbLocalizationProvider.Tests.Refactoring.ParentContainerClass+OldNestedResourceClassAndProperty.OldProperty")]
[InlineData(typeof(ParentContainerClass.RenamedNestedResourceClassAndNamespace),
"DbLocalizationProvider.Tests.Refactoring.ParentContainerClass+RenamedNestedResourceClassAndNamespace.NewResourceKey",
"OldNestedResourceClass",
"In.Galaxy.Far.Far.Away",
"In.Galaxy.Far.Far.Away.ParentContainerClass+OldNestedResourceClass.NewResourceKey")]
[InlineData(typeof(ParentContainerClass.RenamedNestedResourceNamespace),
"DbLocalizationProvider.Tests.Refactoring.ParentContainerClass+RenamedNestedResourceNamespace.NewResourceKey",
null,
"In.Galaxy.Far.Far.Away",
"In.Galaxy.Far.Far.Away.ParentContainerClass+RenamedNestedResourceNamespace.NewResourceKey")]
[InlineData(typeof(RenamedParentContainerClass.RenamedNestedResourceClass),
"DbLocalizationProvider.Tests.Refactoring.RenamedParentContainerClass+RenamedNestedResourceClass.NewResourceKey",
"OldNestedResourceClass",
null,
"DbLocalizationProvider.Tests.Refactoring.OldParentContainerClass+OldNestedResourceClass.NewResourceKey")]
[InlineData(typeof(RenamedParentContainerClass.RenamedNestedResourceClassAndProperty),
"DbLocalizationProvider.Tests.Refactoring.RenamedParentContainerClass+RenamedNestedResourceClassAndProperty.NewResourceKey",
"OldResourceKey",
null,
"DbLocalizationProvider.Tests.Refactoring.OldParentContainerClass+OldNestedResourceClassAndProperty.OldResourceKey")]
[InlineData(typeof(RenamedParentContainerClassAndNamespace.RenamedNestedResourceClass),
"DbLocalizationProvider.Tests.Refactoring.RenamedParentContainerClassAndNamespace+RenamedNestedResourceClass.NewResourceKey",
"OldNestedResourceClass",
null,
"In.Galaxy.Far.Far.Away.OldParentContainerClassAndNamespace+OldNestedResourceClass.NewResourceKey")]
[InlineData(typeof(RenamedParentContainerClassAndNamespace.RenamedNestedResourceClassAndProperty),
"DbLocalizationProvider.Tests.Refactoring.RenamedParentContainerClassAndNamespace+RenamedNestedResourceClassAndProperty.NewResourceKey",
"OldResourceKey",
null,
"In.Galaxy.Far.Far.Away.OldParentContainerClassAndNamespace+OldNestedResourceClass.OldResourceKey")]
public void NestedResourceProperRenameDiscoveryTests(Type target, string resourceKey, string oldTypeName, string typeOldNamespace, string oldResourceKey)
{
var result = _sut.ScanResources(target);
Assert.NotEmpty(result);
var discoveredResource = result.First();
Assert.Equal(resourceKey, discoveredResource.Key);
Assert.Equal(oldTypeName, discoveredResource.TypeOldName);
Assert.Equal(typeOldNamespace, discoveredResource.TypeOldNamespace);
Assert.Equal(oldResourceKey, discoveredResource.OldResourceKey);
}
[Theory]
[InlineData(typeof(RenamedModelClass),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelClass.NewProperty",
"OldModelClass",
null,
"DbLocalizationProvider.Tests.Refactoring.OldModelClass.NewProperty")]
[InlineData(typeof(RenamedModelClassAndNamespace),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelClassAndNamespace.NewProperty",
"OldModelClassAndNamespace",
"In.Galaxy.Far.Far.Away",
"In.Galaxy.Far.Far.Away.OldModelClassAndNamespace.NewProperty")]
[InlineData(typeof(RenamedModelNamespace),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelNamespace.NewProperty",
null,
"In.Galaxy.Far.Far.Away",
"In.Galaxy.Far.Far.Away.RenamedModelNamespace.NewProperty")]
[InlineData(typeof(RenamedModelProperty),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelProperty.NewProperty",
"OldProperty",
null,
"DbLocalizationProvider.Tests.Refactoring.RenamedModelProperty.OldProperty")]
[InlineData(typeof(RenamedModelClassAndProperty),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelClassAndProperty.NewProperty",
"OldProperty",
null,
"DbLocalizationProvider.Tests.Refactoring.OldModelClassAndProperty.OldProperty")]
[InlineData(typeof(RenamedModelClassAndNamespaceAndProperty),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelClassAndNamespaceAndProperty.NewProperty",
"OldProperty",
"In.Galaxy.Far.Far.Away",
"In.Galaxy.Far.Far.Away.OldModelClassAndNamespaceAndProperty.OldProperty")]
public void ModelProperRenameDiscoveryTests(Type target, string resourceKey, string oldTypeName, string typeOldNamespace, string oldResourceKey)
{
var result = _sut.ScanResources(target);
Assert.NotEmpty(result);
var discoveredResource = result.First();
Assert.Equal(resourceKey, discoveredResource.Key);
Assert.Equal(oldTypeName, discoveredResource.TypeOldName);
Assert.Equal(typeOldNamespace, discoveredResource.TypeOldNamespace);
Assert.Equal(oldResourceKey, discoveredResource.OldResourceKey);
}
[Theory]
[InlineData(typeof(RenamedModelWithValidationClass),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationClass.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationClass.NewProperty-Required",
"DbLocalizationProvider.Tests.Refactoring.OldModelWithValidationClass.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.OldModelWithValidationClass.NewProperty-Required")]
[InlineData(typeof(RenamedModelWithDisplayProperty),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithDisplayProperty.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithDisplayProperty.NewProperty-Description",
"DbLocalizationProvider.Tests.Refactoring.OldModelWithDisplayProperty.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.OldModelWithDisplayProperty.NewProperty-Description")]
[InlineData(typeof(RenamedModelWithValidationClassAndNamespace),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationClassAndNamespace.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationClassAndNamespace.NewProperty-Required",
"In.Galaxy.Far.Far.Away.OldModelWithValidationClassAndNamespace.NewProperty",
"In.Galaxy.Far.Far.Away.OldModelWithValidationClassAndNamespace.NewProperty-Required")]
[InlineData(typeof(RenamedModelWithValidationAndNamespace),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationAndNamespace.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationAndNamespace.NewProperty-Required",
"In.Galaxy.Far.Far.Away.RenamedModelWithValidationAndNamespace.NewProperty",
"In.Galaxy.Far.Far.Away.RenamedModelWithValidationAndNamespace.NewProperty-Required")]
[InlineData(typeof(RenamedModelWithValidationProperty),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationProperty.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationProperty.NewProperty-Required",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationProperty.OldProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationProperty.OldProperty-Required")]
[InlineData(typeof(RenamedModelWithDescriptionProperty),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithDescriptionProperty.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithDescriptionProperty.NewProperty-Description",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithDescriptionProperty.OldProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithDescriptionProperty.OldProperty-Description")]
[InlineData(typeof(RenamedModelClassWithValidationProperty),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelClassWithValidationProperty.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelClassWithValidationProperty.NewProperty-Required",
"DbLocalizationProvider.Tests.Refactoring.OldModelClassWithValidationProperty.OldProperty",
"DbLocalizationProvider.Tests.Refactoring.OldModelClassWithValidationProperty.OldProperty-Required")]
[InlineData(typeof(RenamedModelClassWithValidationPropertyAndNamespace),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelClassWithValidationPropertyAndNamespace.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelClassWithValidationPropertyAndNamespace.NewProperty-Required",
"In.Galaxy.Far.Far.Away.OldModelClassWithValidationPropertyAndNamespace.OldProperty",
"In.Galaxy.Far.Far.Away.OldModelClassWithValidationPropertyAndNamespace.OldProperty-Required")]
[InlineData(typeof(RenamedModelWithValidationPropertyAndNamespace),
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationPropertyAndNamespace.NewProperty",
"DbLocalizationProvider.Tests.Refactoring.RenamedModelWithValidationPropertyAndNamespace.NewProperty-Required",
"In.Galaxy.Far.Far.Away.RenamedModelWithValidationPropertyAndNamespace.OldProperty",
"In.Galaxy.Far.Far.Away.RenamedModelWithValidationPropertyAndNamespace.OldProperty-Required")]
public void ModelAdditionalResourceProperRenameDiscoveryTests(Type target, string resourceKey, string secondResourceKey, string oldResourceKey, string oldSecondResourceKey)
{
var result = _sut.ScanResources(target);
Assert.NotEmpty(result);
Assert.Equal(2, result.Count());
var discoveredResource = result.First(dr => dr.Key == resourceKey);
var secondDiscoveredResource = result.First(dr => dr.Key == secondResourceKey);
Assert.Equal(resourceKey, discoveredResource.Key);
Assert.Equal(oldResourceKey, discoveredResource.OldResourceKey);
Assert.Equal(secondResourceKey, secondDiscoveredResource.Key);
Assert.Equal(oldSecondResourceKey, secondDiscoveredResource.OldResourceKey);
}
[Theory]
[InlineData(typeof(RenamedResourceClassWithAdditionalAttribute),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClassWithAdditionalAttribute.NewResourceKey",
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClassWithAdditionalAttribute.NewResourceKey-AdditionalData",
"DbLocalizationProvider.Tests.Refactoring.OldResourceClassWithAdditionalAttribute.NewResourceKey",
"DbLocalizationProvider.Tests.Refactoring.OldResourceClassWithAdditionalAttribute.NewResourceKey-AdditionalData")]
[InlineData(typeof(RenamedResourceKeyWithAdditionalAttribute),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceKeyWithAdditionalAttribute.NewResourceKey",
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceKeyWithAdditionalAttribute.NewResourceKey-AdditionalData",
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceKeyWithAdditionalAttribute.OldResourceKey",
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceKeyWithAdditionalAttribute.OldResourceKey-AdditionalData")]
[InlineData(typeof(RenamedResourceClassAndKeyWithAdditionalAttribute),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClassAndKeyWithAdditionalAttribute.NewResourceKey",
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClassAndKeyWithAdditionalAttribute.NewResourceKey-AdditionalData",
"DbLocalizationProvider.Tests.Refactoring.OldResourceClassAndKeyWithAdditionalAttribute.OldResourceKey",
"DbLocalizationProvider.Tests.Refactoring.OldResourceClassAndKeyWithAdditionalAttribute.OldResourceKey-AdditionalData")]
[InlineData(typeof(RenamedResourceClassAndKeyAndNamespaceWithAdditionalAttribute),
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClassAndKeyAndNamespaceWithAdditionalAttribute.NewResourceKey",
"DbLocalizationProvider.Tests.Refactoring.RenamedResourceClassAndKeyAndNamespaceWithAdditionalAttribute.NewResourceKey-AdditionalData",
"In.Galaxy.Far.Far.Away.OldResourceClassAndKeyAndNamespaceWithAdditionalAttribute.OldResourceKey",
"In.Galaxy.Far.Far.Away.OldResourceClassAndKeyAndNamespaceWithAdditionalAttribute.OldResourceKey-AdditionalData")]
public void ModelCustomAttributesResourceProperRenameDiscoveryTests(
Type target,
string resourceKey,
string secondResourceKey,
string oldResourceKey,
string oldSecondResourceKey)
{
var result = _sut.ScanResources(target);
Assert.NotEmpty(result);
Assert.Equal(2, result.Count());
var discoveredResource = result.First(dr => dr.Key.EndsWith("NewResourceKey"));
var secondDiscoveredResource = result.First(dr => dr.Key.EndsWith("AdditionalData"));
Assert.Equal(resourceKey, discoveredResource.Key);
Assert.Equal(oldResourceKey, discoveredResource.OldResourceKey);
Assert.Equal(secondResourceKey, secondDiscoveredResource.Key);
Assert.Equal(oldSecondResourceKey, secondDiscoveredResource.OldResourceKey);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using Prism.Properties;
using System;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Prism.Commands
{
/// <summary>
/// An <see cref="ICommand"/> whose delegates can be attached for <see cref="Execute"/> and <see cref="CanExecute"/>.
/// </summary>
/// <typeparam name="T">Parameter type.</typeparam>
/// <remarks>
/// The constructor deliberately prevents the use of value types.
/// Because ICommand takes an object, having a value type for T would cause unexpected behavior when CanExecute(null) is called during XAML initialization for command bindings.
/// Using default(T) was considered and rejected as a solution because the implementor would not be able to distinguish between a valid and defaulted values.
/// <para/>
/// Instead, callers should support a value type by using a nullable value type and checking the HasValue property before using the Value property.
/// <example>
/// <code>
/// public MyClass()
/// {
/// this.submitCommand = new DelegateCommand<int?>(this.Submit, this.CanSubmit);
/// }
///
/// private bool CanSubmit(int? customerId)
/// {
/// return (customerId.HasValue && customers.Contains(customerId.Value));
/// }
/// </code>
/// </example>
/// </remarks>
public class DelegateCommand<T> : DelegateCommandBase
{
/// <summary>
/// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
/// </summary>
/// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <remarks><see cref="CanExecute"/> will always return true.</remarks>
public DelegateCommand(Action<T> executeMethod)
: this(executeMethod, (o) => true)
{
}
/// <summary>
/// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
/// </summary>
/// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param>
/// <exception cref="ArgumentNullException">When both <paramref name="executeMethod"/> and <paramref name="canExecuteMethod"/> ar <see langword="null" />.</exception>
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
: base((o) => executeMethod((T)o), (o) => canExecuteMethod((T)o))
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException("executeMethod", Resources.DelegateCommandDelegatesCannotBeNull);
TypeInfo genericTypeInfo = typeof(T).GetTypeInfo();
// DelegateCommand allows object or Nullable<>.
// note: Nullable<> is a struct so we cannot use a class constraint.
if (genericTypeInfo.IsValueType)
{
if ((!genericTypeInfo.IsGenericType) || (!typeof(Nullable<>).GetTypeInfo().IsAssignableFrom(genericTypeInfo.GetGenericTypeDefinition().GetTypeInfo())))
{
throw new InvalidCastException(Resources.DelegateCommandInvalidGenericPayloadType);
}
}
}
/// <summary>
/// Factory method to create a new instance of <see cref="DelegateCommand{T}"/> from an awaitable handler method.
/// </summary>
/// <param name="executeMethod">Delegate to execute when Execute is called on the command.</param>
/// <returns>Constructed instance of <see cref="DelegateCommand{T}"/></returns>
public static DelegateCommand<T> FromAsyncHandler(Func<T, Task> executeMethod)
{
return new DelegateCommand<T>(executeMethod);
}
/// <summary>
/// Factory method to create a new instance of <see cref="DelegateCommand{T}"/> from an awaitable handler method.
/// </summary>
/// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param>
/// <returns>Constructed instance of <see cref="DelegateCommand{T}"/></returns>
public static DelegateCommand<T> FromAsyncHandler(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod)
{
return new DelegateCommand<T>(executeMethod, canExecuteMethod);
}
///<summary>
///Determines if the command can execute by invoked the <see cref="Func{T,Bool}"/> provided during construction.
///</summary>
///<param name="parameter">Data used by the command to determine if it can execute.</param>
///<returns>
///<see langword="true" /> if this command can be executed; otherwise, <see langword="false" />.
///</returns>
public virtual bool CanExecute(T parameter)
{
return base.CanExecute(parameter);
}
///<summary>
///Executes the command and invokes the <see cref="Action{T}"/> provided during construction.
///</summary>
///<param name="parameter">Data used by the command.</param>
public virtual async Task Execute(T parameter)
{
await base.Execute(parameter);
}
private DelegateCommand(Func<T, Task> executeMethod)
: this(executeMethod, (o) => true)
{
}
private DelegateCommand(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod)
: base((o) => executeMethod((T)o), (o) => canExecuteMethod((T)o))
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException("executeMethod", Resources.DelegateCommandDelegatesCannotBeNull);
}
}
/// <summary>
/// An <see cref="ICommand"/> whose delegates do not take any parameters for <see cref="Execute"/> and <see cref="CanExecute"/>.
/// </summary>
/// <see cref="DelegateCommandBase"/>
/// <see cref="DelegateCommand{T}"/>
public class DelegateCommand : DelegateCommandBase
{
/// <summary>
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Action"/> to invoke on execution.
/// </summary>
/// <param name="executeMethod">The <see cref="Action"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
public DelegateCommand(Action executeMethod)
: this(executeMethod, () => true)
{
}
/// <summary>
/// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Action"/> to invoke on execution
/// and a <see langword="Func" /> to query for determining if the command can execute.
/// </summary>
/// <param name="executeMethod">The <see cref="Action"/> to invoke when <see cref="ICommand.Execute"/> is called.</param>
/// <param name="canExecuteMethod">The <see cref="Func{TResult}"/> to invoke when <see cref="ICommand.CanExecute"/> is called</param>
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
: base((o) => executeMethod(), (o) => canExecuteMethod())
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException("executeMethod", Resources.DelegateCommandDelegatesCannotBeNull);
}
/// <summary>
/// Factory method to create a new instance of <see cref="DelegateCommand"/> from an awaitable handler method.
/// </summary>
/// <param name="executeMethod">Delegate to execute when Execute is called on the command.</param>
/// <returns>Constructed instance of <see cref="DelegateCommand"/></returns>
public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod)
{
return new DelegateCommand(executeMethod);
}
/// <summary>
/// Factory method to create a new instance of <see cref="DelegateCommand"/> from an awaitable handler method.
/// </summary>
/// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param>
/// <returns>Constructed instance of <see cref="DelegateCommand"/></returns>
public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod, Func<bool> canExecuteMethod)
{
return new DelegateCommand(executeMethod, canExecuteMethod);
}
///<summary>
/// Executes the command.
///</summary>
public virtual async Task Execute()
{
await Execute(null);
}
/// <summary>
/// Determines if the command can be executed.
/// </summary>
/// <returns>Returns <see langword="true"/> if the command can execute, otherwise returns <see langword="false"/>.</returns>
public virtual bool CanExecute()
{
return CanExecute(null);
}
private DelegateCommand(Func<Task> executeMethod)
: this(executeMethod, () => true)
{
}
private DelegateCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod)
: base((o) => executeMethod(), (o) => canExecuteMethod())
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException("executeMethod", Resources.DelegateCommandDelegatesCannotBeNull);
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit;
namespace Revit.SDK.Samples.CurtainWallGrid.CS
{
/// <summary>
/// the class manages the creation operation for the curtain wall
/// </summary>
public class WallGeometry
{
#region Fields
// the document of this sample
MyDocument m_myDocument;
// the refferred drawing class for the curtain wall
private WallDrawing m_drawing;
// the selected ViewPlan used for curtain wall creation
Autodesk.Revit.DB.ViewPlan m_selectedView;
// the selected wall type
WallType m_selectedWallType;
// store the start point of baseline (in PointD format)
PointD m_startPointD;
//store the start point of baseline (in Autodesk.Revit.DB.XYZ format)
Autodesk.Revit.DB.XYZ m_startXYZ;
// store the end point of baseline (in PointD format)
PointD m_endPointD;
//store the end point of baseline (in Autodesk.Revit.DB.XYZ format)
Autodesk.Revit.DB.XYZ m_endXYZ;
#endregion
#region Properties
/// <summary>
/// the document of this sample
/// </summary>
public MyDocument MyDocument
{
get
{
return m_myDocument;
}
}
/// <summary>
/// the refferred drawing class for the curtain wall
/// </summary>
public WallDrawing Drawing
{
get
{
return m_drawing;
}
}
/// <summary>
/// the selected ViewPlan used for curtain wall creation
/// </summary>
public Autodesk.Revit.DB.ViewPlan SelectedView
{
get
{
return m_selectedView;
}
set
{
m_selectedView = value;
}
}
/// <summary>
/// the selected wall type
/// </summary>
public WallType SelectedWallType
{
get
{
return m_selectedWallType;
}
set
{
m_selectedWallType = value;
}
}
/// <summary>
/// store the start point of baseline (in PointD format)
/// </summary>
public PointD StartPointD
{
get
{
return m_startPointD;
}
set
{
m_startPointD = value;
}
}
/// <summary>
/// Get start point of baseline
/// </summary>
public Autodesk.Revit.DB.XYZ StartXYZ
{
get
{
return m_startXYZ;
}
set
{
m_startXYZ = value;
}
}
/// <summary>
/// store the end point of baseline (in PointD format)
/// </summary>
public PointD EndPointD
{
get
{
return m_endPointD;
}
set
{
m_endPointD = value;
}
}
/// <summary>
/// Get end point of baseline
/// </summary>
public Autodesk.Revit.DB.XYZ EndXYZ
{
get
{
return m_endXYZ;
}
set
{
m_endXYZ = value;
}
}
#endregion
#region Constructors
/// <summary>
/// default constructor
/// </summary>
/// <param name="myDoc">
/// the document of the sample
/// </param>
public WallGeometry(MyDocument myDoc)
{
m_myDocument = myDoc;
m_drawing = new WallDrawing(this);
}
#endregion
#region Public methods
/// <summary>
/// create the curtain wall to the active document of Revit
/// </summary>
/// <returns>
/// the created curtain wall
/// </returns>
public Wall CreateCurtainWall()
{
if (null == m_selectedWallType || null == m_selectedView)
{
return null;
}
Autodesk.Revit.Creation.Document createDoc = m_myDocument.Document.Create;
Autodesk.Revit.Creation.Application createApp = m_myDocument.CommandData.Application.Application.Create;
//baseline
System.Drawing.Point point0 = m_drawing.WallLine2D.StartPoint;
System.Drawing.Point point1 = m_drawing.WallLine2D.EndPoint;
//new baseline and transform coordinate on windows UI to Revit UI
m_startXYZ = new Autodesk.Revit.DB.XYZ(m_startPointD.X, m_startPointD.Y, 0);
m_endXYZ = new Autodesk.Revit.DB.XYZ(m_endPointD.X, m_endPointD.Y, 0);
Autodesk.Revit.DB.Line baseline = null;
try
{
baseline = createApp.NewLineBound(m_startXYZ, m_endXYZ);
}
catch (System.ArgumentException)
{
MessageBox.Show("The start point and the end point of the line are too close, please re-draw it.");
}
Transaction act = new Transaction(m_myDocument.Document);
act.Start(Guid.NewGuid().GetHashCode().ToString());
Wall wall = createDoc.NewWall(baseline, m_selectedWallType,
m_selectedView.GenLevel, 20, 0, false, false);
act.Commit();
Transaction act2 = new Transaction(m_myDocument.Document);
act2.Start(Guid.NewGuid().GetHashCode().ToString());
m_myDocument.UIDocument.ShowElements(wall);
act2.Commit();
return wall;
}
#endregion
}// end of class
}
| |
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using FlagsAttribute = Lucene.Net.Analysis.TokenAttributes.FlagsAttribute;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// An <see cref="AttributeSource"/> contains a list of different <see cref="Attribute"/>s,
/// and methods to add and get them. There can only be a single instance
/// of an attribute in the same <see cref="AttributeSource"/> instance. This is ensured
/// by passing in the actual type of the <see cref="IAttribute"/> to
/// the <see cref="AddAttribute{T}"/>, which then checks if an instance of
/// that type is already present. If yes, it returns the instance, otherwise
/// it creates a new instance and returns it.
/// </summary>
public class AttributeSource
{
/// <summary>
/// An <see cref="AttributeFactory"/> creates instances of <see cref="Attribute"/>s.
/// </summary>
public abstract class AttributeFactory // LUCENENET TODO: API - de-nest
{
/// <summary>
/// returns an <see cref="Attribute"/> for the supplied <see cref="IAttribute"/> interface.
/// </summary>
public abstract Attribute CreateAttributeInstance<T>() where T : IAttribute;
/// <summary>
/// This is the default factory that creates <see cref="Attribute"/>s using the
/// <see cref="Type"/> of the supplied <see cref="IAttribute"/> interface by removing the <code>I</code> from the prefix.
/// </summary>
public static readonly AttributeFactory DEFAULT_ATTRIBUTE_FACTORY = new DefaultAttributeFactory();
private sealed class DefaultAttributeFactory : AttributeFactory
{
// LUCENENET: Using ConditionalWeakTable instead of WeakIdentityMap. A Type IS an
// identity for a class, so there is no need for an identity wrapper for it.
private static readonly ConditionalWeakTable<Type, WeakReference<Type>> attClassImplMap =
new ConditionalWeakTable<Type, WeakReference<Type>>();
private static readonly object attClassImplMapLock = new object();
internal DefaultAttributeFactory()
{
}
public override Attribute CreateAttributeInstance<S>()
{
try
{
Type attributeType = GetClassForInterface<S>();
// LUCENENET: Optimize for creating instances of the most common attributes
// directly rather than using Activator.CreateInstance()
return CreateInstance(attributeType) ?? (Attribute)Activator.CreateInstance(attributeType);
}
catch (Exception e)
{
throw new ArgumentException("Could not instantiate implementing class for " + typeof(S).FullName, e);
}
}
// LUCENENET: optimize known creation of built-in types
private Attribute CreateInstance(Type attributeType)
{
if (ReferenceEquals(typeof(CharTermAttribute), attributeType))
return new CharTermAttribute();
if (ReferenceEquals(typeof(FlagsAttribute), attributeType))
return new FlagsAttribute();
if (ReferenceEquals(typeof(OffsetAttribute), attributeType))
return new OffsetAttribute();
if (ReferenceEquals(typeof(PayloadAttribute), attributeType))
return new PayloadAttribute();
if (ReferenceEquals(typeof(PositionIncrementAttribute), attributeType))
return new PositionIncrementAttribute();
if (ReferenceEquals(typeof(PositionLengthAttribute), attributeType))
return new PositionLengthAttribute();
if (ReferenceEquals(typeof(TypeAttribute), attributeType))
return new TypeAttribute();
return null;
}
internal static Type GetClassForInterface<T>() where T : IAttribute
{
var attClass = typeof(T);
Type clazz;
// LUCENENET: If the weakreference is dead, we need to explicitly update its key.
// We synchronize on attClassImplMapLock to make the operation atomic.
lock (attClassImplMapLock)
{
if (!attClassImplMap.TryGetValue(attClass, out var @ref) || !@ref.TryGetTarget(out clazz))
{
#if FEATURE_CONDITIONALWEAKTABLE_ADDORUPDATE
attClassImplMap.AddOrUpdate(attClass, CreateAttributeWeakReference(attClass, out clazz));
#else
attClassImplMap.Remove(attClass);
attClassImplMap.Add(attClass, CreateAttributeWeakReference(attClass, out clazz));
#endif
}
}
return clazz;
}
// LUCENENET specific - factored this out so we can reuse
private static WeakReference<Type> CreateAttributeWeakReference(Type attributeInterfaceType, out Type clazz)
{
try
{
string name = ConvertAttributeInterfaceToClassName(attributeInterfaceType);
return new WeakReference<Type>(clazz = attributeInterfaceType.Assembly.GetType(name, true));
}
catch (Exception e)
{
throw new ArgumentException("Could not find implementing class for " + attributeInterfaceType.Name, e);
}
}
private static string ConvertAttributeInterfaceToClassName(Type attributeInterfaceType)
{
int lastPlus = attributeInterfaceType.FullName.LastIndexOf('+');
if (lastPlus == -1)
{
return string.Concat(
attributeInterfaceType.Namespace,
".",
attributeInterfaceType.Name.Substring(1));
}
else
{
return string.Concat(
attributeInterfaceType.FullName.Substring(0, lastPlus + 1),
attributeInterfaceType.Name.Substring(1));
}
}
}
}
/// <summary>
/// This class holds the state of an <see cref="AttributeSource"/>. </summary>
/// <seealso cref="CaptureState()"/>
/// <seealso cref="RestoreState(State)"/>
public sealed class State
#if FEATURE_CLONEABLE
: System.ICloneable
#endif
{
internal Attribute attribute;
internal State next;
public object Clone()
{
State clone = new State();
clone.attribute = (Attribute)attribute.Clone();
if (next != null)
{
clone.next = (State)next.Clone();
}
return clone;
}
}
// These two maps must always be in sync!!!
// So they are private, final and read-only from the outside (read-only iterators)
private readonly IDictionary<Type, Util.Attribute> attributes;
private readonly IDictionary<Type, Util.Attribute> attributeImpls;
private readonly State[] currentState;
private readonly AttributeFactory factory;
/// <summary>
/// An <see cref="AttributeSource"/> using the default attribute factory <see cref="AttributeSource.AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY"/>.
/// </summary>
public AttributeSource()
: this(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY)
{
}
/// <summary>
/// An <see cref="AttributeSource"/> that uses the same attributes as the supplied one.
/// </summary>
public AttributeSource(AttributeSource input)
{
if (input == null)
{
throw new ArgumentException("input AttributeSource must not be null");
}
this.attributes = input.attributes;
this.attributeImpls = input.attributeImpls;
this.currentState = input.currentState;
this.factory = input.factory;
}
/// <summary>
/// An <see cref="AttributeSource"/> using the supplied <see cref="AttributeFactory"/> for creating new <see cref="IAttribute"/> instances.
/// </summary>
public AttributeSource(AttributeFactory factory)
{
this.attributes = new JCG.LinkedDictionary<Type, Util.Attribute>();
this.attributeImpls = new JCG.LinkedDictionary<Type, Util.Attribute>();
this.currentState = new State[1];
this.factory = factory;
}
/// <summary>
/// Returns the used <see cref="AttributeFactory"/>.
/// </summary>
public AttributeFactory GetAttributeFactory()
{
return this.factory;
}
/// <summary>
/// Returns a new iterator that iterates the attribute classes
/// in the same order they were added in.
/// </summary>
public IEnumerator<Type> GetAttributeClassesEnumerator()
{
return attributes.Keys.GetEnumerator();
}
/// <summary>
/// Returns a new iterator that iterates all unique <see cref="IAttribute"/> implementations.
/// This iterator may contain less entries than <see cref="GetAttributeClassesEnumerator()"/>,
/// if one instance implements more than one <see cref="IAttribute"/> interface.
/// </summary>
public IEnumerator<Attribute> GetAttributeImplsEnumerator()
{
State initState = GetCurrentState();
if (initState != null)
{
return new IteratorAnonymousInnerClassHelper(initState);
}
else
{
return Collections.EmptySet<Attribute>().GetEnumerator();
}
}
private class IteratorAnonymousInnerClassHelper : IEnumerator<Attribute>
{
public IteratorAnonymousInnerClassHelper(AttributeSource.State initState)
{
state = initState;
}
private Attribute current;
private State state;
//public virtual void Remove() // LUCENENET specific - not used
//{
// throw new NotSupportedException();
//}
public void Dispose()
{
}
public bool MoveNext()
{
if (state == null)
{
return false;
}
Attribute att = state.attribute;
state = state.next;
current = att;
return true;
}
public void Reset()
{
throw new NotSupportedException();
}
public Attribute Current => current;
object IEnumerator.Current => current;
}
/// <summary>
/// A cache that stores all interfaces for known implementation classes for performance (slow reflection) </summary>
// LUCENENET: Using ConditionalWeakTable instead of WeakIdentityMap. A Type IS an
// identity for a class, so there is no need for an identity wrapper for it.
private static readonly ConditionalWeakTable<Type, LinkedList<WeakReference<Type>>> knownImplClasses =
new ConditionalWeakTable<Type, LinkedList<WeakReference<Type>>>();
internal static LinkedList<WeakReference<Type>> GetAttributeInterfaces(Type clazz)
{
return knownImplClasses.GetValue(clazz, (key) =>
{
LinkedList<WeakReference<Type>> foundInterfaces = new LinkedList<WeakReference<Type>>();
// find all interfaces that this attribute instance implements
// and that extend the Attribute interface
Type actClazz = clazz;
do
{
foreach (Type curInterface in actClazz.GetInterfaces())
{
if (curInterface != typeof(IAttribute) && typeof(IAttribute).IsAssignableFrom(curInterface))
{
foundInterfaces.AddLast(new WeakReference<Type>(curInterface));
}
}
actClazz = actClazz.BaseType;
} while (actClazz != null);
return foundInterfaces;
});
}
/// <summary>
/// <b>Expert:</b> Adds a custom <see cref="Attribute"/> instance with one or more <see cref="IAttribute"/> interfaces.
/// <para><font color="red"><b>Please note:</b> It is not guaranteed, that <paramref name="att"/> is added to
/// the <see cref="AttributeSource"/>, because the provided attributes may already exist.
/// You should always retrieve the wanted attributes using <see cref="GetAttribute{T}"/> after adding
/// with this method and cast to your <see cref="Type"/>.
/// The recommended way to use custom implementations is using an <see cref="AttributeFactory"/>.
/// </font></para>
/// </summary>
public void AddAttributeImpl(Attribute att)
{
Type clazz = att.GetType();
if (attributeImpls.ContainsKey(clazz))
{
return;
}
LinkedList<WeakReference<Type>> foundInterfaces = GetAttributeInterfaces(clazz);
// add all interfaces of this Attribute to the maps
foreach (var curInterfaceRef in foundInterfaces)
{
curInterfaceRef.TryGetTarget(out Type curInterface);
if (Debugging.AssertsEnabled) Debugging.Assert(curInterface != null, "We have a strong reference on the class holding the interfaces, so they should never get evicted");
// Attribute is a superclass of this interface
if (!attributes.ContainsKey(curInterface))
{
// invalidate state to force recomputation in captureState()
this.currentState[0] = null;
attributes.Add(curInterface, att);
if (!attributeImpls.ContainsKey(clazz))
{
attributeImpls.Add(clazz, att);
}
}
}
}
/// <summary>
/// The caller must pass in an interface type that extends <see cref="IAttribute"/>.
/// This method first checks if an instance of the corresponding class is
/// already in this <see cref="AttributeSource"/> and returns it. Otherwise a
/// new instance is created, added to this <see cref="AttributeSource"/> and returned.
/// </summary>
public T AddAttribute<T>()
where T : IAttribute
{
var attClass = typeof(T);
// LUCENENET: Eliminated exception and used TryGetValue
if (!attributes.TryGetValue(attClass, out var result))
{
if (!(attClass.IsInterface && typeof(IAttribute).IsAssignableFrom(attClass)))
{
throw new ArgumentException("AddAttribute() only accepts an interface that extends IAttribute, but " + attClass.FullName + " does not fulfil this contract.");
}
result = this.factory.CreateAttributeInstance<T>();
AddAttributeImpl(result);
}
return (T)(IAttribute)result;
}
/// <summary>
/// Returns <c>true</c>, if this <see cref="AttributeSource"/> has any attributes </summary>
public bool HasAttributes => this.attributes.Count > 0;
/// <summary>
/// The caller must pass in an interface type that extends <see cref="IAttribute"/>.
/// Returns <c>true</c>, if this <see cref="AttributeSource"/> contains the corrsponding <see cref="Attribute"/>.
/// </summary>
public bool HasAttribute<T>() where T : IAttribute
{
var attClass = typeof(T);
return this.attributes.ContainsKey(attClass);
}
/// <summary>
/// The caller must pass in an interface type that extends <see cref="IAttribute"/>.
/// Returns the instance of the corresponding <see cref="Attribute"/> contained in this <see cref="AttributeSource"/>
/// </summary>
/// <exception cref="ArgumentException"> if this <see cref="AttributeSource"/> does not contain the
/// <see cref="Attribute"/>. It is recommended to always use <see cref="AddAttribute{T}()"/> even in consumers
/// of <see cref="Analysis.TokenStream"/>s, because you cannot know if a specific <see cref="Analysis.TokenStream"/> really uses
/// a specific <see cref="Attribute"/>. <see cref="AddAttribute{T}()"/> will automatically make the attribute
/// available. If you want to only use the attribute, if it is available (to optimize
/// consuming), use <see cref="HasAttribute{T}()"/>. </exception>
public virtual T GetAttribute<T>() where T : IAttribute
{
var attClass = typeof(T);
if (!attributes.TryGetValue(attClass, out var result))
{
throw new ArgumentException($"this AttributeSource does not have the attribute '{attClass.Name}'.");
}
return (T)(IAttribute)result;
}
private State GetCurrentState()
{
State s = currentState[0];
if (s != null || !HasAttributes)
{
return s;
}
var c = s = currentState[0] = new State();
using (var it = attributeImpls.Values.GetEnumerator())
{
it.MoveNext();
c.attribute = it.Current;
while (it.MoveNext())
{
c.next = new State();
c = c.next;
c.attribute = it.Current;
}
return s;
}
}
/// <summary>
/// Resets all <see cref="Attribute"/>s in this <see cref="AttributeSource"/> by calling
/// <see cref="Attribute.Clear()"/> on each <see cref="IAttribute"/> implementation.
/// </summary>
public void ClearAttributes()
{
for (State state = GetCurrentState(); state != null; state = state.next)
{
state.attribute.Clear();
}
}
/// <summary>
/// Captures the state of all <see cref="Attribute"/>s. The return value can be passed to
/// <see cref="RestoreState(State)"/> to restore the state of this or another <see cref="AttributeSource"/>.
/// </summary>
public virtual State CaptureState()
{
State state = this.GetCurrentState();
return (state == null) ? null : (State)state.Clone();
}
/// <summary>
/// Restores this state by copying the values of all attribute implementations
/// that this state contains into the attributes implementations of the targetStream.
/// The targetStream must contain a corresponding instance for each argument
/// contained in this state (e.g. it is not possible to restore the state of
/// an <see cref="AttributeSource"/> containing a <see cref="Analysis.TokenAttributes.ICharTermAttribute"/> into a <see cref="AttributeSource"/> using
/// a <see cref="Analysis.Token"/> instance as implementation).
/// <para/>
/// Note that this method does not affect attributes of the targetStream
/// that are not contained in this state. In other words, if for example
/// the targetStream contains an <see cref="Analysis.TokenAttributes.IOffsetAttribute"/>, but this state doesn't, then
/// the value of the <see cref="Analysis.TokenAttributes.IOffsetAttribute"/> remains unchanged. It might be desirable to
/// reset its value to the default, in which case the caller should first
/// call <see cref="AttributeSource.ClearAttributes()"/> (<c>TokenStream.ClearAttributes()</c> on the targetStream.
/// </summary>
public void RestoreState(State state)
{
if (state == null)
{
return;
}
do
{
if (!attributeImpls.ContainsKey(state.attribute.GetType()))
{
throw new ArgumentException("State contains Attribute of type " + state.attribute.GetType().Name + " that is not in in this AttributeSource");
}
state.attribute.CopyTo(attributeImpls[state.attribute.GetType()]);
state = state.next;
} while (state != null);
}
public override int GetHashCode()
{
int code = 0;
for (State state = GetCurrentState(); state != null; state = state.next)
{
code = code * 31 + state.attribute.GetHashCode();
}
return code;
}
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
if (obj is AttributeSource other)
{
if (HasAttributes)
{
if (!other.HasAttributes)
{
return false;
}
if (this.attributeImpls.Count != other.attributeImpls.Count)
{
return false;
}
// it is only equal if all attribute impls are the same in the same order
State thisState = this.GetCurrentState();
State otherState = other.GetCurrentState();
while (thisState != null && otherState != null)
{
if (otherState.attribute.GetType() != thisState.attribute.GetType() || !otherState.attribute.Equals(thisState.attribute))
{
return false;
}
thisState = thisState.next;
otherState = otherState.next;
}
return true;
}
else
{
return !other.HasAttributes;
}
}
else
{
return false;
}
}
/// <summary>
/// This method returns the current attribute values as a string in the following format
/// by calling the <see cref="ReflectWith(IAttributeReflector)"/> method:
///
/// <list type="bullet">
/// <item><term>if <paramref name="prependAttClass"/>=true:</term> <description> <c>"AttributeClass.Key=value,AttributeClass.Key=value"</c> </description></item>
/// <item><term>if <paramref name="prependAttClass"/>=false:</term> <description> <c>"key=value,key=value"</c> </description></item>
/// </list>
/// </summary>
/// <seealso cref="ReflectWith(IAttributeReflector)"/>
public string ReflectAsString(bool prependAttClass)
{
StringBuilder buffer = new StringBuilder();
ReflectWith(new AttributeReflectorAnonymousInnerClassHelper(this, prependAttClass, buffer));
return buffer.ToString();
}
private class AttributeReflectorAnonymousInnerClassHelper : IAttributeReflector
{
private readonly AttributeSource outerInstance;
private bool prependAttClass;
private StringBuilder buffer;
public AttributeReflectorAnonymousInnerClassHelper(AttributeSource outerInstance, bool prependAttClass, StringBuilder buffer)
{
this.outerInstance = outerInstance;
this.prependAttClass = prependAttClass;
this.buffer = buffer;
}
public void Reflect<T>(string key, object value)
where T : IAttribute
{
Reflect(typeof(T), key, value);
}
public void Reflect(Type attClass, string key, object value)
{
if (buffer.Length > 0)
{
buffer.Append(',');
}
if (prependAttClass)
{
buffer.Append(attClass.Name).Append('#');
}
buffer.Append(key).Append('=').Append(object.ReferenceEquals(value, null) ? "null" : value);
}
}
/// <summary>
/// This method is for introspection of attributes, it should simply
/// add the key/values this <see cref="AttributeSource"/> holds to the given <see cref="IAttributeReflector"/>.
///
/// <para>This method iterates over all <see cref="IAttribute"/> implementations and calls the
/// corresponding <see cref="Attribute.ReflectWith(IAttributeReflector)"/> method.</para>
/// </summary>
/// <seealso cref="Attribute.ReflectWith(IAttributeReflector)"/>
public void ReflectWith(IAttributeReflector reflector)
{
for (State state = GetCurrentState(); state != null; state = state.next)
{
state.attribute.ReflectWith(reflector);
}
}
/// <summary>
/// Performs a clone of all <see cref="Attribute"/> instances returned in a new
/// <see cref="AttributeSource"/> instance. This method can be used to e.g. create another <see cref="Analysis.TokenStream"/>
/// with exactly the same attributes (using <see cref="AttributeSource(AttributeSource)"/>).
/// You can also use it as a (non-performant) replacement for <see cref="CaptureState()"/>, if you need to look
/// into / modify the captured state.
/// </summary>
public AttributeSource CloneAttributes()
{
AttributeSource clone = new AttributeSource(this.factory);
if (HasAttributes)
{
// first clone the impls
for (State state = GetCurrentState(); state != null; state = state.next)
{
//clone.AttributeImpls[state.attribute.GetType()] = state.attribute.Clone();
var impl = (Attribute)state.attribute.Clone();
if (!clone.attributeImpls.ContainsKey(impl.GetType()))
{
clone.attributeImpls.Add(impl.GetType(), impl);
}
}
// now the interfaces
foreach (var entry in this.attributes)
{
clone.attributes.Add(entry.Key, clone.attributeImpls[entry.Value.GetType()]);
}
}
return clone;
}
/// <summary>
/// Copies the contents of this <see cref="AttributeSource"/> to the given target <see cref="AttributeSource"/>.
/// The given instance has to provide all <see cref="IAttribute"/>s this instance contains.
/// The actual attribute implementations must be identical in both <see cref="AttributeSource"/> instances;
/// ideally both <see cref="AttributeSource"/> instances should use the same <see cref="AttributeFactory"/>.
/// You can use this method as a replacement for <see cref="RestoreState(State)"/>, if you use
/// <see cref="CloneAttributes()"/> instead of <see cref="CaptureState()"/>.
/// </summary>
public void CopyTo(AttributeSource target)
{
for (State state = GetCurrentState(); state != null; state = state.next)
{
Attribute targetImpl = target.attributeImpls[state.attribute.GetType()];
if (targetImpl == null)
{
throw new ArgumentException("this AttributeSource contains Attribute of type " + state.attribute.GetType().Name + " that is not in the target");
}
state.attribute.CopyTo(targetImpl);
}
}
/// <summary>
/// Returns a string consisting of the class's simple name, the hex representation of the identity hash code,
/// and the current reflection of all attributes. </summary>
/// <seealso cref="ReflectAsString(bool)"/>
public override string ToString()
{
return this.GetType().Name + '@' + RuntimeHelpers.GetHashCode(this).ToString("x") + " " + ReflectAsString(false);
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cairo;
using Rectangle = Gdk.Rectangle;
namespace Pinta.Core
{
public abstract class GradientRenderer
{
private BinaryPixelOp normalBlendOp;
private ColorBgra startColor;
private ColorBgra endColor;
private PointD startPoint;
private PointD endPoint;
private bool alphaBlending;
private bool alphaOnly;
private bool lerpCacheIsValid = false;
private byte[] lerpAlphas;
private ColorBgra[] lerpColors;
public ColorBgra StartColor {
get { return this.startColor; }
set {
if (this.startColor != value) {
this.startColor = value;
this.lerpCacheIsValid = false;
}
}
}
public ColorBgra EndColor {
get { return this.endColor; }
set {
if (this.endColor != value) {
this.endColor = value;
this.lerpCacheIsValid = false;
}
}
}
public PointD StartPoint {
get { return this.startPoint; }
set { this.startPoint = value; }
}
public PointD EndPoint {
get { return this.endPoint; }
set { this.endPoint = value; }
}
public bool AlphaBlending {
get { return this.alphaBlending; }
set { this.alphaBlending = value; }
}
public bool AlphaOnly {
get { return this.alphaOnly; }
set { this.alphaOnly = value; }
}
public virtual void BeforeRender ()
{
if (!this.lerpCacheIsValid) {
byte startAlpha;
byte endAlpha;
if (this.alphaOnly) {
ComputeAlphaOnlyValuesFromColors (this.startColor, this.endColor, out startAlpha, out endAlpha);
} else {
startAlpha = this.startColor.A;
endAlpha = this.endColor.A;
}
this.lerpAlphas = new byte[256];
this.lerpColors = new ColorBgra[256];
for (int i = 0; i < 256; ++i) {
byte a = (byte)i;
this.lerpColors[a] = ColorBgra.Blend (this.startColor, this.endColor, a);
this.lerpAlphas[a] = (byte)(startAlpha + ((endAlpha - startAlpha) * a) / 255);
}
this.lerpCacheIsValid = true;
}
}
public abstract byte ComputeByteLerp(int x, int y);
public virtual void AfterRender ()
{
}
private static void ComputeAlphaOnlyValuesFromColors (ColorBgra startColor, ColorBgra endColor, out byte startAlpha, out byte endAlpha)
{
startAlpha = startColor.A;
endAlpha = (byte)(255 - endColor.A);
}
unsafe public void Render (ImageSurface surface, Gdk.Rectangle[] rois)
{
byte startAlpha;
byte endAlpha;
if (this.alphaOnly) {
ComputeAlphaOnlyValuesFromColors (this.startColor, this.endColor, out startAlpha, out endAlpha);
} else {
startAlpha = this.startColor.A;
endAlpha = this.endColor.A;
}
surface.Flush ();
ColorBgra* src_data_ptr = (ColorBgra*)surface.DataPtr;
int src_width = surface.Width;
for (int ri = 0; ri < rois.Length; ++ri) {
Gdk.Rectangle rect = rois[ri];
if (this.startPoint.X == this.endPoint.X && this.startPoint.Y == this.endPoint.Y) {
// Start and End point are the same ... fill with solid color.
for (int y = rect.Top; y <= rect.GetBottom (); ++y) {
ColorBgra* pixelPtr = surface.GetPointAddress(rect.Left, y);
for (int x = rect.Left; x <= rect.GetRight (); ++x) {
ColorBgra result;
if (this.alphaOnly && this.alphaBlending) {
byte resultAlpha = (byte)Utility.FastDivideShortByByte ((ushort)(pixelPtr->A * endAlpha), 255);
result = *pixelPtr;
result.A = resultAlpha;
} else if (this.alphaOnly && !this.alphaBlending) {
result = *pixelPtr;
result.A = endAlpha;
} else if (!this.alphaOnly && this.alphaBlending) {
result = this.normalBlendOp.Apply (*pixelPtr, this.endColor);
//if (!this.alphaOnly && !this.alphaBlending)
} else {
result = this.endColor;
}
*pixelPtr = result;
++pixelPtr;
}
}
} else {
var mainrect = rect;
Parallel.ForEach(Enumerable.Range (rect.Top, rect.GetBottom () + 1),
(y) => ProcessGradientLine(startAlpha, endAlpha, y, mainrect, surface, src_data_ptr, src_width));
}
}
surface.MarkDirty ();
AfterRender ();
}
private unsafe bool ProcessGradientLine (byte startAlpha, byte endAlpha, int y, Rectangle rect, ImageSurface surface, ColorBgra* src_data_ptr, int src_width)
{
var pixelPtr = surface.GetPointAddressUnchecked(src_data_ptr, src_width, rect.Left, y);
var right = rect.GetRight ();
if (alphaOnly && alphaBlending)
{
for (var x = rect.Left; x <= right; ++x)
{
var lerpByte = ComputeByteLerp(x, y);
var lerpAlpha = lerpAlphas[lerpByte];
var resultAlpha = Utility.FastScaleByteByByte(pixelPtr->A, lerpAlpha);
pixelPtr->A = resultAlpha;
++pixelPtr;
}
}
else if (alphaOnly && !alphaBlending)
{
for (var x = rect.Left; x <= right; ++x)
{
var lerpByte = ComputeByteLerp(x, y);
var lerpAlpha = lerpAlphas[lerpByte];
pixelPtr->A = lerpAlpha;
++pixelPtr;
}
}
else if (!alphaOnly && (alphaBlending && (startAlpha != 255 || endAlpha != 255)))
{
// If we're doing all color channels, and we're doing alpha blending, and if alpha blending is necessary
for (var x = rect.Left; x <= right; ++x)
{
var lerpByte = ComputeByteLerp(x, y);
var lerpColor = lerpColors[lerpByte];
var result = normalBlendOp.Apply(*pixelPtr, lerpColor);
*pixelPtr = result;
++pixelPtr;
}
//if (!this.alphaOnly && !this.alphaBlending) // or sC.A == 255 && eC.A == 255
}
else
{
for (var x = rect.Left; x <= right; ++x)
{
var lerpByte = ComputeByteLerp(x, y);
var lerpColor = lerpColors[lerpByte];
*pixelPtr = lerpColor;
++pixelPtr;
}
}
return true;
}
protected internal GradientRenderer (bool alphaOnly, BinaryPixelOp normalBlendOp)
{
this.normalBlendOp = normalBlendOp;
this.alphaOnly = alphaOnly;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyString
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// EnumModel operations.
/// </summary>
public partial class EnumModel : IServiceOperations<AutoRestSwaggerBATService>, IEnumModel
{
/// <summary>
/// Initializes a new instance of the EnumModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public EnumModel(AutoRestSwaggerBATService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATService
/// </summary>
public AutoRestSwaggerBATService Client { get; private set; }
/// <summary>
/// Get enum value 'red color' from enumeration of 'red color', 'green-color',
/// 'blue_color'.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Colors?>> GetNotExpandableWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNotExpandable", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Colors?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Colors?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Sends value 'red color' from enumeration of 'red color', 'green-color',
/// 'blue_color'
/// </summary>
/// <param name='stringBody'>
/// Possible values include: 'red color', 'green-color', 'blue_color'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutNotExpandableWithHttpMessagesAsync(Colors stringBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("stringBody", stringBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutNotExpandable", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection.Emit;
namespace System
{
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MulticastDelegate : Delegate
{
// This is set under 3 circumstances
// 1. Multicast delegate
// 2. Secure/Wrapper delegate
// 3. Inner delegate of secure delegate where the secure delegate security context is a collectible method
private Object _invocationList;
private IntPtr _invocationCount;
// This constructor is called from the class generated by the
// compiler generated code (This must match the constructor
// in Delegate
protected MulticastDelegate(Object target, String method) : base(target, method)
{
}
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
protected MulticastDelegate(Type target, String method) : base(target, method)
{
}
internal bool IsUnmanagedFunctionPtr()
{
return (_invocationCount == (IntPtr)(-1));
}
internal bool InvocationListLogicallyNull()
{
return (_invocationList == null) || (_invocationList is LoaderAllocator) || (_invocationList is DynamicResolver);
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new SerializationException(SR.Serialization_DelegatesNotSupported);
}
// equals returns true IIF the delegate is not null and has the
// same target, method and invocation list as this object
public override sealed bool Equals(Object obj)
{
if (obj == null)
return false;
if (object.ReferenceEquals(this, obj))
return true;
if (!InternalEqualTypes(this, obj))
return false;
// Since this is a MulticastDelegate and we know
// the types are the same, obj should also be a
// MulticastDelegate
Debug.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
var d = JitHelpers.UnsafeCast<MulticastDelegate>(obj);
if (_invocationCount != (IntPtr)0)
{
// there are 4 kind of delegate kinds that fall into this bucket
// 1- Multicast (_invocationList is Object[])
// 2- Secure/Wrapper (_invocationList is Delegate)
// 3- Unmanaged FntPtr (_invocationList == null)
// 4- Open virtual (_invocationCount == MethodDesc of target, _invocationList == null, LoaderAllocator, or DynamicResolver)
if (InvocationListLogicallyNull())
{
if (IsUnmanagedFunctionPtr())
{
if (!d.IsUnmanagedFunctionPtr())
return false;
return CompareUnmanagedFunctionPtrs(this, d);
}
// now we know 'this' is not a special one, so we can work out what the other is
if ((d._invocationList as Delegate) != null)
// this is a secure/wrapper delegate so we need to unwrap and check the inner one
return Equals(d._invocationList);
return base.Equals(obj);
}
else
{
if ((_invocationList as Delegate) != null)
{
// this is a secure/wrapper delegate so we need to unwrap and check the inner one
return _invocationList.Equals(obj);
}
else
{
Debug.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
return InvocationListEquals(d);
}
}
}
else
{
// among the several kind of delegates falling into this bucket one has got a non
// empty _invocationList (open static with special sig)
// to be equals we need to check that _invocationList matches (both null is fine)
// and call the base.Equals()
if (!InvocationListLogicallyNull())
{
if (!_invocationList.Equals(d._invocationList))
return false;
return base.Equals(d);
}
// now we know 'this' is not a special one, so we can work out what the other is
if ((d._invocationList as Delegate) != null)
// this is a secure/wrapper delegate so we need to unwrap and check the inner one
return Equals(d._invocationList);
// now we can call on the base
return base.Equals(d);
}
}
// Recursive function which will check for equality of the invocation list.
private bool InvocationListEquals(MulticastDelegate d)
{
Debug.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison");
Object[] invocationList = _invocationList as Object[];
if (d._invocationCount != _invocationCount)
return false;
int invocationCount = (int)_invocationCount;
for (int i = 0; i < invocationCount; i++)
{
Delegate dd = (Delegate)invocationList[i];
Object[] dInvocationList = d._invocationList as Object[];
if (!dd.Equals(dInvocationList[i]))
return false;
}
return true;
}
private bool TrySetSlot(Object[] a, int index, Object o)
{
if (a[index] == null && System.Threading.Interlocked.CompareExchange<Object>(ref a[index], o, null) == null)
return true;
// The slot may be already set because we have added and removed the same method before.
// Optimize this case, because it's cheaper than copying the array.
if (a[index] != null)
{
MulticastDelegate d = (MulticastDelegate)o;
MulticastDelegate dd = (MulticastDelegate)a[index];
if (dd._methodPtr == d._methodPtr &&
dd._target == d._target &&
dd._methodPtrAux == d._methodPtrAux)
{
return true;
}
}
return false;
}
private MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount, bool thisIsMultiCastAlready)
{
// First, allocate a new multicast delegate just like this one, i.e. same type as the this object
MulticastDelegate result = (MulticastDelegate)InternalAllocLike(this);
// Performance optimization - if this already points to a true multicast delegate,
// copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them
if (thisIsMultiCastAlready)
{
result._methodPtr = this._methodPtr;
result._methodPtrAux = this._methodPtrAux;
}
else
{
result._methodPtr = GetMulticastInvoke();
result._methodPtrAux = GetInvokeMethod();
}
result._target = result;
result._invocationList = invocationList;
result._invocationCount = (IntPtr)invocationCount;
return result;
}
internal MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount)
{
return NewMulticastDelegate(invocationList, invocationCount, false);
}
internal void StoreDynamicMethod(MethodInfo dynamicMethod)
{
if (_invocationCount != (IntPtr)0)
{
Debug.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
// must be a secure/wrapper one, unwrap and save
MulticastDelegate d = (MulticastDelegate)_invocationList;
d._methodBase = dynamicMethod;
}
else
_methodBase = dynamicMethod;
}
// This method will combine this delegate with the passed delegate
// to form a new delegate.
protected override sealed Delegate CombineImpl(Delegate follow)
{
if ((Object)follow == null) // cast to object for a more efficient test
return this;
// Verify that the types are the same...
if (!InternalEqualTypes(this, follow))
throw new ArgumentException(SR.Arg_DlgtTypeMis);
MulticastDelegate dFollow = (MulticastDelegate)follow;
Object[] resultList;
int followCount = 1;
Object[] followList = dFollow._invocationList as Object[];
if (followList != null)
followCount = (int)dFollow._invocationCount;
int resultCount;
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
resultCount = 1 + followCount;
resultList = new Object[resultCount];
resultList[0] = this;
if (followList == null)
{
resultList[1] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[1 + i] = followList[i];
}
return NewMulticastDelegate(resultList, resultCount);
}
else
{
int invocationCount = (int)_invocationCount;
resultCount = invocationCount + followCount;
resultList = null;
if (resultCount <= invocationList.Length)
{
resultList = invocationList;
if (followList == null)
{
if (!TrySetSlot(resultList, invocationCount, dFollow))
resultList = null;
}
else
{
for (int i = 0; i < followCount; i++)
{
if (!TrySetSlot(resultList, invocationCount + i, followList[i]))
{
resultList = null;
break;
}
}
}
}
if (resultList == null)
{
int allocCount = invocationList.Length;
while (allocCount < resultCount)
allocCount *= 2;
resultList = new Object[allocCount];
for (int i = 0; i < invocationCount; i++)
resultList[i] = invocationList[i];
if (followList == null)
{
resultList[invocationCount] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[invocationCount + i] = followList[i];
}
}
return NewMulticastDelegate(resultList, resultCount, true);
}
}
private Object[] DeleteFromInvocationList(Object[] invocationList, int invocationCount, int deleteIndex, int deleteCount)
{
Object[] thisInvocationList = _invocationList as Object[];
int allocCount = thisInvocationList.Length;
while (allocCount / 2 >= invocationCount - deleteCount)
allocCount /= 2;
Object[] newInvocationList = new Object[allocCount];
for (int i = 0; i < deleteIndex; i++)
newInvocationList[i] = invocationList[i];
for (int i = deleteIndex + deleteCount; i < invocationCount; i++)
newInvocationList[i - deleteCount] = invocationList[i];
return newInvocationList;
}
private bool EqualInvocationLists(Object[] a, Object[] b, int start, int count)
{
for (int i = 0; i < count; i++)
{
if (!(a[start + i].Equals(b[i])))
return false;
}
return true;
}
// This method currently looks backward on the invocation list
// for an element that has Delegate based equality with value. (Doesn't
// look at the invocation list.) If this is found we remove it from
// this list and return a new delegate. If its not found a copy of the
// current list is returned.
protected override sealed Delegate RemoveImpl(Delegate value)
{
// There is a special case were we are removing using a delegate as
// the value we need to check for this case
//
MulticastDelegate v = value as MulticastDelegate;
if (v == null)
return this;
if (v._invocationList as Object[] == null)
{
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
// they are both not real Multicast
if (this.Equals(value))
return null;
}
else
{
int invocationCount = (int)_invocationCount;
for (int i = invocationCount; --i >= 0;)
{
if (value.Equals(invocationList[i]))
{
if (invocationCount == 2)
{
// Special case - only one value left, either at the beginning or the end
return (Delegate)invocationList[1 - i];
}
else
{
Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1);
return NewMulticastDelegate(list, invocationCount - 1, true);
}
}
}
}
}
else
{
Object[] invocationList = _invocationList as Object[];
if (invocationList != null)
{
int invocationCount = (int)_invocationCount;
int vInvocationCount = (int)v._invocationCount;
for (int i = invocationCount - vInvocationCount; i >= 0; i--)
{
if (EqualInvocationLists(invocationList, v._invocationList as Object[], i, vInvocationCount))
{
if (invocationCount - vInvocationCount == 0)
{
// Special case - no values left
return null;
}
else if (invocationCount - vInvocationCount == 1)
{
// Special case - only one value left, either at the beginning or the end
return (Delegate)invocationList[i != 0 ? 0 : invocationCount - 1];
}
else
{
Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount);
return NewMulticastDelegate(list, invocationCount - vInvocationCount, true);
}
}
}
}
}
return this;
}
// This method returns the Invocation list of this multicast delegate.
public override sealed Delegate[] GetInvocationList()
{
Contract.Ensures(Contract.Result<Delegate[]>() != null);
Delegate[] del;
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
del = new Delegate[1];
del[0] = this;
}
else
{
// Create an array of delegate copies and each
// element into the array
del = new Delegate[(int)_invocationCount];
for (int i = 0; i < del.Length; i++)
del[i] = (Delegate)invocationList[i];
}
return del;
}
public static bool operator ==(MulticastDelegate d1, MulticastDelegate d2)
{
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
public static bool operator !=(MulticastDelegate d1, MulticastDelegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
public override sealed int GetHashCode()
{
if (IsUnmanagedFunctionPtr())
return ValueType.GetHashCodeOfPtr(_methodPtr) ^ ValueType.GetHashCodeOfPtr(_methodPtrAux);
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
return base.GetHashCode();
}
else
{
int hash = 0;
for (int i = 0; i < (int)_invocationCount; i++)
{
hash = hash * 33 + invocationList[i].GetHashCode();
}
return hash;
}
}
internal override Object GetTarget()
{
if (_invocationCount != (IntPtr)0)
{
// _invocationCount != 0 we are in one of these cases:
// - Multicast -> return the target of the last delegate in the list
// - Secure/wrapper delegate -> return the target of the inner delegate
// - unmanaged function pointer - return null
// - virtual open delegate - return null
if (InvocationListLogicallyNull())
{
// both open virtual and ftn pointer return null for the target
return null;
}
else
{
Object[] invocationList = _invocationList as Object[];
if (invocationList != null)
{
int invocationCount = (int)_invocationCount;
return ((Delegate)invocationList[invocationCount - 1]).GetTarget();
}
else
{
Delegate receiver = _invocationList as Delegate;
if (receiver != null)
return receiver.GetTarget();
}
}
}
return base.GetTarget();
}
protected override MethodInfo GetMethodImpl()
{
if (_invocationCount != (IntPtr)0 && _invocationList != null)
{
// multicast case
Object[] invocationList = _invocationList as Object[];
if (invocationList != null)
{
int index = (int)_invocationCount - 1;
return ((Delegate)invocationList[index]).Method;
}
MulticastDelegate innerDelegate = _invocationList as MulticastDelegate;
if (innerDelegate != null)
{
// must be a secure/wrapper delegate
return innerDelegate.GetMethodImpl();
}
}
else if (IsUnmanagedFunctionPtr())
{
// we handle unmanaged function pointers here because the generic ones (used for WinRT) would otherwise
// be treated as open delegates by the base implementation, resulting in failure to get the MethodInfo
if ((_methodBase == null) || !(_methodBase is MethodInfo))
{
IRuntimeMethodInfo method = FindMethodHandle();
RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method);
// need a proper declaring type instance method on a generic type
if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType))
{
// we are returning the 'Invoke' method of this delegate so use this.GetType() for the exact type
RuntimeType reflectedType = GetType() as RuntimeType;
declaringType = reflectedType;
}
_methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
}
return (MethodInfo)_methodBase;
}
// Otherwise, must be an inner delegate of a SecureDelegate of an open virtual method. In that case, call base implementation
return base.GetMethodImpl();
}
// this should help inlining
[System.Diagnostics.DebuggerNonUserCode]
private void ThrowNullThisInDelegateToInstance()
{
throw new ArgumentException(SR.Arg_DlgtNullInst);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorClosed(Object target, IntPtr methodPtr)
{
if (target == null)
ThrowNullThisInDelegateToInstance();
this._target = target;
this._methodPtr = methodPtr;
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorClosedStatic(Object target, IntPtr methodPtr)
{
this._target = target;
this._methodPtr = methodPtr;
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorRTClosed(Object target, IntPtr methodPtr)
{
this._target = target;
this._methodPtr = AdjustTarget(target, methodPtr);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk)
{
this._target = this;
this._methodPtr = shuffleThunk;
this._methodPtrAux = methodPtr;
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAllocLike(this);
realDelegate.CtorClosed(target, methodPtr);
_invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
_invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureClosedStatic(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAllocLike(this);
realDelegate.CtorClosedStatic(target, methodPtr);
_invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
_invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureRTClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
realDelegate.CtorRTClosed(target, methodPtr);
_invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
_invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
realDelegate.CtorOpened(target, methodPtr, shuffleThunk);
_invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
_invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk)
{
this._target = this;
this._methodPtr = shuffleThunk;
this._methodPtrAux = GetCallStub(methodPtr);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
realDelegate.CtorVirtualDispatch(target, methodPtr, shuffleThunk);
_invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
_invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleClosedStatic(Object target, IntPtr methodPtr, IntPtr gchandle)
{
this._target = target;
this._methodPtr = methodPtr;
this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle)
{
this._target = this;
this._methodPtr = shuffleThunk;
this._methodPtrAux = methodPtr;
this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle)
{
this._target = this;
this._methodPtr = shuffleThunk;
this._methodPtrAux = GetCallStub(methodPtr);
this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
}
}
}
| |
// 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.Runtime.InteropServices.Marshal.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.Runtime.InteropServices
{
static public partial class Marshal
{
#region Methods and constructors
public static int AddRef(IntPtr pUnk)
{
return default(int);
}
public static IntPtr AllocCoTaskMem(int cb)
{
return default(IntPtr);
}
public static IntPtr AllocHGlobal(int cb)
{
return default(IntPtr);
}
public static IntPtr AllocHGlobal(IntPtr cb)
{
return default(IntPtr);
}
public static bool AreComObjectsAvailableForCleanup()
{
return default(bool);
}
public static Object BindToMoniker(string monikerName)
{
return default(Object);
}
public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak)
{
}
public static void CleanupUnusedObjectsInCurrentContext()
{
}
public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
{
}
public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
{
}
public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
{
}
public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
{
}
public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
{
}
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
{
}
public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
{
}
public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
{
}
public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
{
}
public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
{
}
public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
{
}
public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
{
}
public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
{
}
public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
{
}
public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
{
}
public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
{
}
public static IntPtr CreateAggregatedObject(IntPtr pOuter, Object o)
{
return default(IntPtr);
}
public static Object CreateWrapperOfType(Object o, Type t)
{
return default(Object);
}
public static void DestroyStructure(IntPtr ptr, Type structuretype)
{
}
public static int FinalReleaseComObject(Object o)
{
Contract.Ensures(Contract.Result<int>() == 0);
return default(int);
}
public static void FreeBSTR(IntPtr ptr)
{
}
public static void FreeCoTaskMem(IntPtr ptr)
{
}
public static void FreeHGlobal(IntPtr hglobal)
{
}
public static Guid GenerateGuidForType(Type type)
{
return default(Guid);
}
public static string GenerateProgIdForType(Type type)
{
return default(string);
}
public static Object GetActiveObject(string progID)
{
return default(Object);
}
public static IntPtr GetComInterfaceForObject(Object o, Type T)
{
return default(IntPtr);
}
public static IntPtr GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode)
{
return default(IntPtr);
}
public static IntPtr GetComInterfaceForObjectInContext(Object o, Type t)
{
return default(IntPtr);
}
public static Object GetComObjectData(Object obj, Object key)
{
return default(Object);
}
public static int GetComSlotForMethodInfo(System.Reflection.MemberInfo m)
{
Contract.Requires(m.DeclaringType != null);
return default(int);
}
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
{
return default(Delegate);
}
public static int GetEndComSlot(Type t)
{
return default(int);
}
public static int GetExceptionCode()
{
return default(int);
}
public static Exception GetExceptionForHR(int errorCode)
{
return default(Exception);
}
public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
{
return default(Exception);
}
public static IntPtr GetExceptionPointers()
{
return default(IntPtr);
}
public static IntPtr GetFunctionPointerForDelegate(Delegate d)
{
return default(IntPtr);
}
public static IntPtr GetHINSTANCE(System.Reflection.Module m)
{
return default(IntPtr);
}
public static int GetHRForException(Exception e)
{
return default(int);
}
public static int GetHRForLastWin32Error()
{
Contract.Ensures(-2147024896 <= Contract.Result<int>());
return default(int);
}
public static IntPtr GetIDispatchForObject(Object o)
{
return default(IntPtr);
}
public static IntPtr GetIDispatchForObjectInContext(Object o)
{
return default(IntPtr);
}
public static IntPtr GetITypeInfoForType(Type t)
{
return default(IntPtr);
}
public static IntPtr GetIUnknownForObject(Object o)
{
return default(IntPtr);
}
public static IntPtr GetIUnknownForObjectInContext(Object o)
{
return default(IntPtr);
}
public static int GetLastWin32Error()
{
return default(int);
}
public static IntPtr GetManagedThunkForUnmanagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
{
return default(IntPtr);
}
public static System.Reflection.MemberInfo GetMethodInfoForComSlot(Type t, int slot, ref ComMemberType memberType)
{
return default(System.Reflection.MemberInfo);
}
public static void GetNativeVariantForObject(Object obj, IntPtr pDstNativeVariant)
{
}
public static Object GetObjectForIUnknown(IntPtr pUnk)
{
return default(Object);
}
public static Object GetObjectForNativeVariant(IntPtr pSrcNativeVariant)
{
return default(Object);
}
public static Object[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars)
{
return default(Object[]);
}
public static int GetStartComSlot(Type t)
{
return default(int);
}
public static System.Threading.Thread GetThreadFromFiberCookie(int cookie)
{
return default(System.Threading.Thread);
}
public static Object GetTypedObjectForIUnknown(IntPtr pUnk, Type t)
{
return default(Object);
}
public static Type GetTypeForITypeInfo(IntPtr piTypeInfo)
{
return default(Type);
}
public static string GetTypeInfoName(UCOMITypeInfo pTI)
{
return default(string);
}
public static string GetTypeInfoName(System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo)
{
return default(string);
}
public static Guid GetTypeLibGuid(System.Runtime.InteropServices.ComTypes.ITypeLib typelib)
{
return default(Guid);
}
public static Guid GetTypeLibGuid(UCOMITypeLib pTLB)
{
return default(Guid);
}
public static Guid GetTypeLibGuidForAssembly(System.Reflection.Assembly asm)
{
return default(Guid);
}
public static int GetTypeLibLcid(System.Runtime.InteropServices.ComTypes.ITypeLib typelib)
{
return default(int);
}
public static int GetTypeLibLcid(UCOMITypeLib pTLB)
{
return default(int);
}
public static string GetTypeLibName(System.Runtime.InteropServices.ComTypes.ITypeLib typelib)
{
return default(string);
}
public static string GetTypeLibName(UCOMITypeLib pTLB)
{
return default(string);
}
public static void GetTypeLibVersionForAssembly(System.Reflection.Assembly inputAssembly, out int majorVersion, out int minorVersion)
{
majorVersion = default(int);
minorVersion = default(int);
}
public static Object GetUniqueObjectForIUnknown(IntPtr unknown)
{
return default(Object);
}
public static IntPtr GetUnmanagedThunkForManagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
{
return default(IntPtr);
}
public static bool IsComObject(Object o)
{
return default(bool);
}
public static bool IsTypeVisibleFromCom(Type t)
{
return default(bool);
}
public static int NumParamBytes(System.Reflection.MethodInfo m)
{
return default(int);
}
public static IntPtr OffsetOf(Type t, string fieldName)
{
return default(IntPtr);
}
public static void Prelink(System.Reflection.MethodInfo m)
{
}
public static void PrelinkAll(Type c)
{
}
public static string PtrToStringAnsi(IntPtr ptr)
{
return default(string);
}
public static string PtrToStringAnsi(IntPtr ptr, int len)
{
return default(string);
}
public static string PtrToStringAuto(IntPtr ptr, int len)
{
return default(string);
}
public static string PtrToStringAuto(IntPtr ptr)
{
return default(string);
}
public static string PtrToStringBSTR(IntPtr ptr)
{
return default(string);
}
public static string PtrToStringUni(IntPtr ptr)
{
return default(string);
}
public static string PtrToStringUni(IntPtr ptr, int len)
{
return default(string);
}
public static void PtrToStructure(IntPtr ptr, Object structure)
{
}
public static Object PtrToStructure(IntPtr ptr, Type structureType)
{
return default(Object);
}
public static int QueryInterface(IntPtr pUnk, ref Guid iid, out IntPtr ppv)
{
ppv = default(IntPtr);
return default(int);
}
public static byte ReadByte(IntPtr ptr, int ofs)
{
return default(byte);
}
public static byte ReadByte(Object ptr, int ofs)
{
return default(byte);
}
public static byte ReadByte(IntPtr ptr)
{
return default(byte);
}
public static short ReadInt16(IntPtr ptr, int ofs)
{
return default(short);
}
public static short ReadInt16(IntPtr ptr)
{
return default(short);
}
public static short ReadInt16(Object ptr, int ofs)
{
return default(short);
}
public static int ReadInt32(Object ptr, int ofs)
{
return default(int);
}
public static int ReadInt32(IntPtr ptr, int ofs)
{
return default(int);
}
public static int ReadInt32(IntPtr ptr)
{
return default(int);
}
public static long ReadInt64(Object ptr, int ofs)
{
return default(long);
}
public static long ReadInt64(IntPtr ptr, int ofs)
{
return default(long);
}
public static long ReadInt64(IntPtr ptr)
{
return default(long);
}
public static IntPtr ReadIntPtr(IntPtr ptr)
{
return default(IntPtr);
}
public static IntPtr ReadIntPtr(Object ptr, int ofs)
{
return default(IntPtr);
}
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
return default(IntPtr);
}
public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
{
return default(IntPtr);
}
public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
{
return default(IntPtr);
}
public static int Release(IntPtr pUnk)
{
return default(int);
}
public static int ReleaseComObject(Object o)
{
Contract.Requires(o != null);
return default(int);
}
public static void ReleaseThreadCache()
{
}
public static IntPtr SecureStringToBSTR(System.Security.SecureString s)
{
return default(IntPtr);
}
public static IntPtr SecureStringToCoTaskMemAnsi(System.Security.SecureString s)
{
return default(IntPtr);
}
public static IntPtr SecureStringToCoTaskMemUnicode(System.Security.SecureString s)
{
return default(IntPtr);
}
public static IntPtr SecureStringToGlobalAllocAnsi(System.Security.SecureString s)
{
return default(IntPtr);
}
public static IntPtr SecureStringToGlobalAllocUnicode(System.Security.SecureString s)
{
return default(IntPtr);
}
public static bool SetComObjectData(Object obj, Object key, Object data)
{
return default(bool);
}
public static int SizeOf(Object structure)
{
return default(int);
}
public static int SizeOf(Type t)
{
return default(int);
}
public static IntPtr StringToBSTR(string s)
{
return default(IntPtr);
}
public static IntPtr StringToCoTaskMemAnsi(string s)
{
return default(IntPtr);
}
public static IntPtr StringToCoTaskMemAuto(string s)
{
return default(IntPtr);
}
public static IntPtr StringToCoTaskMemUni(string s)
{
return default(IntPtr);
}
public static IntPtr StringToHGlobalAnsi(string s)
{
return default(IntPtr);
}
public static IntPtr StringToHGlobalAuto(string s)
{
return default(IntPtr);
}
public static IntPtr StringToHGlobalUni(string s)
{
return default(IntPtr);
}
public static void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld)
{
}
public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
{
}
public static void ThrowExceptionForHR(int errorCode)
{
}
public static IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
{
return default(IntPtr);
}
public static void WriteByte(IntPtr ptr, int ofs, byte val)
{
}
public static void WriteByte(Object ptr, int ofs, byte val)
{
}
public static void WriteByte(IntPtr ptr, byte val)
{
}
public static void WriteInt16(Object ptr, int ofs, short val)
{
}
public static void WriteInt16(IntPtr ptr, int ofs, short val)
{
}
public static void WriteInt16(IntPtr ptr, short val)
{
}
public static void WriteInt16(IntPtr ptr, int ofs, char val)
{
}
public static void WriteInt16(IntPtr ptr, char val)
{
}
public static void WriteInt16(Object ptr, int ofs, char val)
{
}
public static void WriteInt32(IntPtr ptr, int val)
{
}
public static void WriteInt32(IntPtr ptr, int ofs, int val)
{
}
public static void WriteInt32(Object ptr, int ofs, int val)
{
}
public static void WriteInt64(IntPtr ptr, int ofs, long val)
{
}
public static void WriteInt64(Object ptr, int ofs, long val)
{
}
public static void WriteInt64(IntPtr ptr, long val)
{
}
public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
{
}
public static void WriteIntPtr(Object ptr, int ofs, IntPtr val)
{
}
public static void WriteIntPtr(IntPtr ptr, IntPtr val)
{
}
public static void ZeroFreeBSTR(IntPtr s)
{
}
public static void ZeroFreeCoTaskMemAnsi(IntPtr s)
{
}
public static void ZeroFreeCoTaskMemUnicode(IntPtr s)
{
}
public static void ZeroFreeGlobalAllocAnsi(IntPtr s)
{
}
public static void ZeroFreeGlobalAllocUnicode(IntPtr s)
{
}
#endregion
#region Fields
public readonly static int SystemDefaultCharSize;
public readonly static int SystemMaxDBCSCharSize;
#endregion
}
}
| |
//Used with permission: http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx
using System;
namespace CSharpVitamins
{
/// <summary>
/// Represents a globally unique identifier (GUID) with a
/// shorter string value. Sguid
/// </summary>
public struct ShortGuid
{
#region Static
/// <summary>
/// A read-only instance of the ShortGuid class whose value
/// is guaranteed to be all zeroes.
/// </summary>
public static readonly ShortGuid Empty = new ShortGuid(Guid.Empty);
#endregion
#region Fields
Guid _guid;
string _value;
#endregion
#region Contructors
/// <summary>
/// Creates a ShortGuid from a base64 encoded string
/// </summary>
/// <param name="value">The encoded guid as a
/// base64 string</param>
public ShortGuid(string value)
{
_value = value;
_guid = Decode(value);
}
/// <summary>
/// Creates a ShortGuid from a Guid
/// </summary>
/// <param name="guid">The Guid to encode</param>
public ShortGuid(Guid guid)
{
_value = Encode(guid);
_guid = guid;
}
#endregion
#region Properties
/// <summary>
/// Gets/sets the underlying Guid
/// </summary>
public Guid Guid
{
get { return _guid; }
set
{
if (value != _guid)
{
_guid = value;
_value = Encode(value);
}
}
}
/// <summary>
/// Gets/sets the underlying base64 encoded string
/// </summary>
public string Value
{
get { return _value; }
set
{
if (value != _value)
{
_value = value;
_guid = Decode(value);
}
}
}
#endregion
#region ToString
/// <summary>
/// Returns the base64 encoded guid as a string
/// </summary>
/// <returns></returns>
public override string ToString()
{
return _value;
}
#endregion
#region Equals
/// <summary>
/// Returns a value indicating whether this instance and a
/// specified Object represent the same type and value.
/// </summary>
/// <param name="obj">The object to compare</param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj is ShortGuid)
return _guid.Equals(((ShortGuid)obj)._guid);
if (obj is Guid)
return _guid.Equals((Guid)obj);
if (obj is string)
return _guid.Equals(((ShortGuid)obj)._guid);
return false;
}
#endregion
#region GetHashCode
/// <summary>
/// Returns the HashCode for underlying Guid.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return _guid.GetHashCode();
}
#endregion
#region NewGuid
/// <summary>
/// Initialises a new instance of the ShortGuid class
/// </summary>
/// <returns></returns>
public static ShortGuid NewGuid()
{
return new ShortGuid(Guid.NewGuid());
}
#endregion
#region Encode
/// <summary>
/// Creates a new instance of a Guid using the string value,
/// then returns the base64 encoded version of the Guid.
/// </summary>
/// <param name="value">An actual Guid string (i.e. not a ShortGuid)</param>
/// <returns></returns>
public static string Encode(string value)
{
Guid guid = new Guid(value);
return Encode(guid);
}
/// <summary>
/// Encodes the given Guid as a base64 string that is 22
/// characters long.
/// </summary>
/// <param name="guid">The Guid to encode</param>
/// <returns></returns>
public static string Encode(Guid guid)
{
string encoded = Convert.ToBase64String(guid.ToByteArray());
encoded = encoded
.Replace("/", "_")
.Replace("+", "-");
return encoded.Substring(0, 22);
}
#endregion
#region Decode
/// <summary>
/// Decodes the given base64 string
/// </summary>
/// <param name="value">The base64 encoded string of a Guid</param>
/// <returns>A new Guid</returns>
public static Guid Decode(string value)
{
value = value
.Replace("_", "/")
.Replace("-", "+");
byte[] buffer = Convert.FromBase64String(value + "==");
return new Guid(buffer);
}
#endregion
#region Operators
/// <summary>
/// Determines if both ShortGuids have the same underlying
/// Guid value.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static bool operator ==(ShortGuid x, ShortGuid y)
{
if ((object)x == null) return (object)y == null;
return x._guid == y._guid;
}
/// <summary>
/// Determines if both ShortGuids do not have the
/// same underlying Guid value.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static bool operator !=(ShortGuid x, ShortGuid y)
{
return !(x == y);
}
/// <summary>
/// Implicitly converts the ShortGuid to it's string equivilent
/// </summary>
/// <param name="shortGuid"></param>
/// <returns></returns>
public static implicit operator string(ShortGuid shortGuid)
{
return shortGuid._value;
}
/// <summary>
/// Implicitly converts the ShortGuid to it's Guid equivilent
/// </summary>
/// <param name="shortGuid"></param>
/// <returns></returns>
public static implicit operator Guid(ShortGuid shortGuid)
{
return shortGuid._guid;
}
/// <summary>
/// Implicitly converts the string to a ShortGuid
/// </summary>
/// <param name="shortGuid"></param>
/// <returns></returns>
public static implicit operator ShortGuid(string shortGuid)
{
return new ShortGuid(shortGuid);
}
/// <summary>
/// Implicitly converts the Guid to a ShortGuid
/// </summary>
/// <param name="guid"></param>
/// <returns></returns>
public static implicit operator ShortGuid(Guid guid)
{
return new ShortGuid(guid);
}
#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.Buffers;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Text.Unicode.Tests
{
public class Utf16UtilityTests
{
private unsafe delegate char* GetPointerToFirstInvalidCharDel(char* pInputBuffer, int inputLength, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment);
private static readonly Lazy<GetPointerToFirstInvalidCharDel> _getPointerToFirstInvalidCharFn = CreateGetPointerToFirstInvalidCharFn();
[Theory]
[InlineData("", 0, 0)] // empty string is OK
[InlineData("X", 1, 1)]
[InlineData("XY", 2, 2)]
[InlineData("XYZ", 3, 3)]
[InlineData("<EACU>", 1, 2)]
[InlineData("X<EACU>", 2, 3)]
[InlineData("<EACU>X", 2, 3)]
[InlineData("<EURO>", 1, 3)]
[InlineData("<GRIN>", 1, 4)]
[InlineData("X<GRIN>Z", 3, 6)]
[InlineData("X<0000>Z", 3, 3)] // null chars are allowed
public void GetIndexOfFirstInvalidUtf16Sequence_WithSmallValidBuffers(string unprocessedInput, int expectedRuneCount, int expectedUtf8ByteCount)
{
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(unprocessedInput, -1 /* expectedIdxOfFirstInvalidChar */, expectedRuneCount, expectedUtf8ByteCount);
}
[Theory]
[InlineData("<DC00>", 0, 0, 0)] // standalone low surrogate (at beginning of sequence)
[InlineData("X<DC00>", 1, 1, 1)] // standalone low surrogate (preceded by valid ASCII data)
[InlineData("<EURO><DC00>", 1, 1, 3)] // standalone low surrogate (preceded by valid non-ASCII data)
[InlineData("<D800>", 0, 0, 0)] // standalone high surrogate (missing follow-up low surrogate)
[InlineData("<D800>Y", 0, 0, 0)] // standalone high surrogate (followed by ASCII char)
[InlineData("<D800><D800>", 0, 0, 0)] // standalone high surrogate (followed by high surrogate)
[InlineData("<D800><EURO>", 0, 0, 0)] // standalone high surrogate (followed by valid non-ASCII char)
[InlineData("<DC00><DC00>", 0, 0, 0)] // standalone low surrogate (not preceded by a high surrogate)
[InlineData("<DC00><D800>", 0, 0, 0)] // standalone low surrogate (not preceded by a high surrogate)
[InlineData("<GRIN><DC00><DC00>", 2, 1, 4)] // standalone low surrogate (preceded by a valid surrogate pair)
[InlineData("<GRIN><DC00><D800>", 2, 1, 4)] // standalone low surrogate (preceded by a valid surrogate pair)
[InlineData("<GRIN><0000><DC00><D800>", 3, 2, 5)] // standalone low surrogate (preceded by a valid null char)
public void GetIndexOfFirstInvalidUtf16Sequence_WithSmallInvalidBuffers(string unprocessedInput, int idxOfFirstInvalidChar, int expectedRuneCount, int expectedUtf8ByteCount)
{
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(unprocessedInput, idxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount);
}
[Theory] // chars below presented as hex since Xunit doesn't like invalid UTF-16 string literals
[InlineData("<2BB4><218C><1BC0><613F><F9E9><B740><DE38><E689>", 6, 6, 18)]
[InlineData("<1854><C980><012C><4797><DD5A><41D0><A104><5464>", 4, 4, 11)]
[InlineData("<F1AF><8BD3><5037><BE29><DEFF><3E3A><DD71><6336>", 4, 4, 12)]
[InlineData("<B978><0F25><DC23><D3BB><7352><4025><0B93><4107>", 2, 2, 6)]
[InlineData("<887C><C980><012C><4797><DD5A><41D0><A104><5464>", 4, 4, 11)]
public void GetIndexOfFirstInvalidUtf16Sequence_WithEightRandomCharsContainingUnpairedSurrogates(string unprocessedInput, int idxOfFirstInvalidChar, int expectedRuneCount, int expectedUtf8ByteCount)
{
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(unprocessedInput, idxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount);
}
[Fact]
public void GetIndexOfFirstInvalidUtf16Sequence_WithInvalidSurrogateSequences()
{
// All ASCII
char[] chars = Enumerable.Repeat('x', 128).ToArray();
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 128, expectedUtf8ByteCount: 128);
// Throw a surrogate pair at the beginning
chars[0] = '\uD800';
chars[1] = '\uDFFF';
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 127, expectedUtf8ByteCount: 130);
// Throw a surrogate pair near the end
chars[124] = '\uD800';
chars[125] = '\uDFFF';
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 126, expectedUtf8ByteCount: 132);
// Throw a standalone surrogate code point at the *very* end
chars[127] = '\uD800'; // high surrogate
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, 127, expectedRuneCount: 125, expectedUtf8ByteCount: 131);
chars[127] = '\uDFFF'; // low surrogate
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, 127, expectedRuneCount: 125, expectedUtf8ByteCount: 131);
// Make the final surrogate pair valid
chars[126] = '\uD800'; // high surrogate
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 125, expectedUtf8ByteCount: 134);
// Throw an invalid surrogate sequence in the middle (straddles a vector boundary)
chars[12] = '\u0080'; // 2-byte UTF-8 sequence
chars[13] = '\uD800'; // high surrogate
chars[14] = '\uD800'; // high surrogate
chars[15] = '\uDFFF'; // low surrogate
chars[16] = '\uDFFF'; // low surrogate
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, 13, expectedRuneCount: 12, expectedUtf8ByteCount: 16);
// Correct the surrogate sequence we just added
chars[14] = '\uDC00'; // low surrogate
chars[15] = '\uDBFF'; // high surrogate
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 123, expectedUtf8ByteCount: 139);
// Corrupt the surrogate pair that's split across a vector boundary
chars[16] = 'x'; // ASCII char (remember.. chars[15] is a high surrogate char)
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, 15, expectedRuneCount: 13, expectedUtf8ByteCount: 20);
}
[Fact]
public void GetIndexOfFirstInvalidUtf16Sequence_WithStandaloneLowSurrogateCharAtStart()
{
// The input stream will be a vector's worth of ASCII chars, followed by a single standalone low
// surrogate char, then padded with U+0000 until it's a multiple of the vector size.
// Using Vector<ushort>.Count here as a stand-in for Vector<char>.Count.
char[] chars = new char[Vector<ushort>.Count * 2];
for (int i = 0; i < Vector<ushort>.Count; i++)
{
chars[i] = 'x'; // ASCII char
}
chars[Vector<ushort>.Count] = '\uDEAD'; // standalone low surrogate char
for (int i = 0; i <= Vector<ushort>.Count; i++)
{
// Expect all ASCII chars to be consumed, low surrogate char to be marked invalid.
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars[(Vector<ushort>.Count - i)..], i, i, i);
}
}
private static void GetIndexOfFirstInvalidUtf16Sequence_Test_Core(string unprocessedInput, int expectedIdxOfFirstInvalidChar, int expectedRuneCount, long expectedUtf8ByteCount)
{
char[] processedInput = ProcessInput(unprocessedInput).ToCharArray();
// Run the test normally
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount);
// Put a bunch of ASCII data at the beginning (to test the call to ASCIIUtility at method entry)
processedInput = Enumerable.Repeat('x', 128).Concat(processedInput).ToArray();
if (expectedIdxOfFirstInvalidChar >= 0)
{
expectedIdxOfFirstInvalidChar += 128;
}
expectedRuneCount += 128;
expectedUtf8ByteCount += 128;
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount);
// Change the first few chars to a mixture of 2-byte and 3-byte UTF-8 sequences
// This makes sure the vectorized code paths can properly handle these.
processedInput[0] = '\u0080'; // 2-byte UTF-8 sequence
processedInput[1] = '\u0800'; // 3-byte UTF-8 sequence
processedInput[2] = '\u0080'; // 2-byte UTF-8 sequence
processedInput[3] = '\u0800'; // 3-byte UTF-8 sequence
processedInput[4] = '\u0080'; // 2-byte UTF-8 sequence
processedInput[5] = '\u0800'; // 3-byte UTF-8 sequence
processedInput[6] = '\u0080'; // 2-byte UTF-8 sequence
processedInput[7] = '\u0800'; // 3-byte UTF-8 sequence
expectedUtf8ByteCount += 12;
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount);
// Throw some surrogate pairs into the mix to make sure they're also handled properly
// by the vectorized code paths.
processedInput[8] = '\u0080'; // 2-byte UTF-8 sequence
processedInput[9] = '\u0800'; // 3-byte UTF-8 sequence
processedInput[10] = '\u0080'; // 2-byte UTF-8 sequence
processedInput[11] = '\u0800'; // 3-byte UTF-8 sequence
processedInput[12] = '\u0080'; // 2-byte UTF-8 sequence
processedInput[13] = '\uD800'; // high surrogate
processedInput[14] = '\uDC00'; // low surrogate
processedInput[15] = 'z'; // ASCII char
expectedRuneCount--;
expectedUtf8ByteCount += 9;
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount);
// Split the next surrogate pair across the vector boundary (so that we
// don't inadvertently treat this as a standalone surrogate sequence).
processedInput[15] = '\uDBFF'; // high surrogate
processedInput[16] = '\uDFFF'; // low surrogate
expectedRuneCount--;
expectedUtf8ByteCount += 2;
GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount);
}
private static unsafe void GetIndexOfFirstInvalidUtf16Sequence_Test_Core(char[] input, int expectedRetVal, int expectedRuneCount, long expectedUtf8ByteCount)
{
// Arrange
using BoundedMemory<char> boundedMemory = BoundedMemory.AllocateFromExistingData(input);
boundedMemory.MakeReadonly();
// Act
int actualRetVal;
long actualUtf8CodeUnitCount;
int actualRuneCount;
fixed (char* pInputBuffer = &MemoryMarshal.GetReference(boundedMemory.Span))
{
char* pFirstInvalidChar = _getPointerToFirstInvalidCharFn.Value(pInputBuffer, input.Length, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment);
long ptrDiff = pFirstInvalidChar - pInputBuffer;
Assert.True((ulong)ptrDiff <= (uint)input.Length, "ptrDiff was outside expected range.");
Assert.True(utf8CodeUnitCountAdjustment >= 0, "UTF-16 code unit count adjustment must be non-negative.");
Assert.True(scalarCountAdjustment <= 0, "Scalar count adjustment must be 0 or negative.");
actualRetVal = (ptrDiff == input.Length) ? -1 : (int)ptrDiff;
// The last two 'out' parameters are:
// a) The number to be added to the "chars processed" return value to come up with the total UTF-8 code unit count, and
// b) The number to be added to the "total UTF-16 code unit count" value to come up with the total scalar count.
actualUtf8CodeUnitCount = ptrDiff + utf8CodeUnitCountAdjustment;
actualRuneCount = (int)ptrDiff + scalarCountAdjustment;
}
// Assert
Assert.Equal(expectedRetVal, actualRetVal);
Assert.Equal(expectedRuneCount, actualRuneCount);
Assert.Equal(actualUtf8CodeUnitCount, expectedUtf8ByteCount);
}
private static Lazy<GetPointerToFirstInvalidCharDel> CreateGetPointerToFirstInvalidCharFn()
{
return new Lazy<GetPointerToFirstInvalidCharDel>(() =>
{
Type utf16UtilityType = typeof(Utf8).Assembly.GetType("System.Text.Unicode.Utf16Utility");
if (utf16UtilityType is null)
{
throw new Exception("Couldn't find Utf16Utility type in System.Private.CoreLib.");
}
MethodInfo methodInfo = utf16UtilityType.GetMethod("GetPointerToFirstInvalidChar", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (methodInfo is null)
{
throw new Exception("Couldn't find GetPointerToFirstInvalidChar method on Utf8Utility.");
}
return (GetPointerToFirstInvalidCharDel)methodInfo.CreateDelegate(typeof(GetPointerToFirstInvalidCharDel));
});
}
private static string ProcessInput(string input)
{
input = input.Replace("<EACU>", "\u00E9", StringComparison.Ordinal); // U+00E9 LATIN SMALL LETTER E WITH ACUTE
input = input.Replace("<EURO>", "\u20AC", StringComparison.Ordinal); // U+20AC EURO SIGN
input = input.Replace("<GRIN>", "\U0001F600", StringComparison.Ordinal); // U+1F600 GRINNING FACE
// Replace <ABCD> with \uABCD. This allows us to flow potentially malformed
// UTF-16 strings without Xunit. (The unit testing framework gets angry when
// we try putting invalid UTF-16 data as inline test data.)
int idx;
while ((idx = input.IndexOf('<')) >= 0)
{
input = input[..idx] + (char)ushort.Parse(input.Substring(idx + 1, 4), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture) + input[(idx + 6)..];
}
return input;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Authentication;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.Configuration;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
{
internal class ConfigurationReader
{
private const string ProtocolsKey = "Protocols";
private const string CertificatesKey = "Certificates";
private const string CertificateKey = "Certificate";
private const string SslProtocolsKey = "SslProtocols";
private const string EndpointDefaultsKey = "EndpointDefaults";
private const string EndpointsKey = "Endpoints";
private const string UrlKey = "Url";
private const string ClientCertificateModeKey = "ClientCertificateMode";
private const string SniKey = "Sni";
private readonly IConfiguration _configuration;
private IDictionary<string, CertificateConfig>? _certificates;
private EndpointDefaults? _endpointDefaults;
private IEnumerable<EndpointConfig>? _endpoints;
public ConfigurationReader(IConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public IDictionary<string, CertificateConfig> Certificates => _certificates ??= ReadCertificates();
public EndpointDefaults EndpointDefaults => _endpointDefaults ??= ReadEndpointDefaults();
public IEnumerable<EndpointConfig> Endpoints => _endpoints ??= ReadEndpoints();
private IDictionary<string, CertificateConfig> ReadCertificates()
{
var certificates = new Dictionary<string, CertificateConfig>(0, StringComparer.OrdinalIgnoreCase);
var certificatesConfig = _configuration.GetSection(CertificatesKey).GetChildren();
foreach (var certificateConfig in certificatesConfig)
{
certificates.Add(certificateConfig.Key, new CertificateConfig(certificateConfig));
}
return certificates;
}
// "EndpointDefaults": {
// "Protocols": "Http1AndHttp2",
// "SslProtocols": [ "Tls11", "Tls12", "Tls13"],
// "ClientCertificateMode" : "NoCertificate"
// }
private EndpointDefaults ReadEndpointDefaults()
{
var configSection = _configuration.GetSection(EndpointDefaultsKey);
return new EndpointDefaults
{
Protocols = ParseProtocols(configSection[ProtocolsKey]),
SslProtocols = ParseSslProcotols(configSection.GetSection(SslProtocolsKey)),
ClientCertificateMode = ParseClientCertificateMode(configSection[ClientCertificateModeKey]),
};
}
private IEnumerable<EndpointConfig> ReadEndpoints()
{
var endpoints = new List<EndpointConfig>();
var endpointsConfig = _configuration.GetSection(EndpointsKey).GetChildren();
foreach (var endpointConfig in endpointsConfig)
{
// "EndpointName": {
// "Url": "https://*:5463",
// "Protocols": "Http1AndHttp2",
// "SslProtocols": [ "Tls11", "Tls12", "Tls13"],
// "Certificate": {
// "Path": "testCert.pfx",
// "Password": "testPassword"
// },
// "ClientCertificateMode" : "NoCertificate",
// "Sni": {
// "a.example.org": {
// "Certificate": {
// "Path": "testCertA.pfx",
// "Password": "testPassword"
// }
// },
// "*.example.org": {
// "Protocols": "Http1",
// }
// }
// }
var url = endpointConfig[UrlKey];
if (string.IsNullOrEmpty(url))
{
throw new InvalidOperationException(CoreStrings.FormatEndpointMissingUrl(endpointConfig.Key));
}
var endpoint = new EndpointConfig(
endpointConfig.Key,
url,
ReadSni(endpointConfig.GetSection(SniKey), endpointConfig.Key),
endpointConfig)
{
Protocols = ParseProtocols(endpointConfig[ProtocolsKey]),
SslProtocols = ParseSslProcotols(endpointConfig.GetSection(SslProtocolsKey)),
ClientCertificateMode = ParseClientCertificateMode(endpointConfig[ClientCertificateModeKey]),
Certificate = new CertificateConfig(endpointConfig.GetSection(CertificateKey))
};
endpoints.Add(endpoint);
}
return endpoints;
}
private static Dictionary<string, SniConfig> ReadSni(IConfigurationSection sniConfig, string endpointName)
{
var sniDictionary = new Dictionary<string, SniConfig>(0, StringComparer.OrdinalIgnoreCase);
foreach (var sniChild in sniConfig.GetChildren())
{
// "Sni": {
// "a.example.org": {
// "Protocols": "Http1",
// "SslProtocols": [ "Tls11", "Tls12", "Tls13"],
// "Certificate": {
// "Path": "testCertA.pfx",
// "Password": "testPassword"
// },
// "ClientCertificateMode" : "NoCertificate"
// },
// "*.example.org": {
// "Certificate": {
// "Path": "testCertWildcard.pfx",
// "Password": "testPassword"
// }
// }
// // The following should work once https://github.com/dotnet/runtime/issues/40218 is resolved
// "*": {}
// }
if (string.IsNullOrEmpty(sniChild.Key))
{
throw new InvalidOperationException(CoreStrings.FormatSniNameCannotBeEmpty(endpointName));
}
var sni = new SniConfig
{
Certificate = new CertificateConfig(sniChild.GetSection(CertificateKey)),
Protocols = ParseProtocols(sniChild[ProtocolsKey]),
SslProtocols = ParseSslProcotols(sniChild.GetSection(SslProtocolsKey)),
ClientCertificateMode = ParseClientCertificateMode(sniChild[ClientCertificateModeKey])
};
sniDictionary.Add(sniChild.Key, sni);
}
return sniDictionary;
}
private static ClientCertificateMode? ParseClientCertificateMode(string? clientCertificateMode)
{
if (Enum.TryParse<ClientCertificateMode>(clientCertificateMode, ignoreCase: true, out var result))
{
return result;
}
return null;
}
private static HttpProtocols? ParseProtocols(string? protocols)
{
if (Enum.TryParse<HttpProtocols>(protocols, ignoreCase: true, out var result))
{
return result;
}
return null;
}
private static SslProtocols? ParseSslProcotols(IConfigurationSection sslProtocols)
{
var stringProtocols = sslProtocols.Get<string[]>();
return stringProtocols?.Aggregate(SslProtocols.None, (acc, current) =>
{
if (Enum.TryParse(current, ignoreCase: true, out SslProtocols parsed))
{
return acc | parsed;
}
return acc;
});
}
internal static void ThrowIfContainsHttpsOnlyConfiguration(EndpointConfig endpoint)
{
if (endpoint.Certificate != null && (endpoint.Certificate.IsFileCert || endpoint.Certificate.IsStoreCert))
{
throw new InvalidOperationException(CoreStrings.FormatEndpointHasUnusedHttpsConfig(endpoint.Name, CertificateKey));
}
if (endpoint.ClientCertificateMode.HasValue)
{
throw new InvalidOperationException(CoreStrings.FormatEndpointHasUnusedHttpsConfig(endpoint.Name, ClientCertificateModeKey));
}
if (endpoint.SslProtocols.HasValue)
{
throw new InvalidOperationException(CoreStrings.FormatEndpointHasUnusedHttpsConfig(endpoint.Name, SslProtocolsKey));
}
if (endpoint.Sni.Count > 0)
{
throw new InvalidOperationException(CoreStrings.FormatEndpointHasUnusedHttpsConfig(endpoint.Name, SniKey));
}
}
}
// "EndpointDefaults": {
// "Protocols": "Http1AndHttp2",
// "SslProtocols": [ "Tls11", "Tls12", "Tls13"],
// "ClientCertificateMode" : "NoCertificate"
// }
internal class EndpointDefaults
{
public HttpProtocols? Protocols { get; set; }
public SslProtocols? SslProtocols { get; set; }
public ClientCertificateMode? ClientCertificateMode { get; set; }
}
// "EndpointName": {
// "Url": "https://*:5463",
// "Protocols": "Http1AndHttp2",
// "SslProtocols": [ "Tls11", "Tls12", "Tls13"],
// "Certificate": {
// "Path": "testCert.pfx",
// "Password": "testPassword"
// },
// "ClientCertificateMode" : "NoCertificate",
// "Sni": {
// "a.example.org": {
// "Certificate": {
// "Path": "testCertA.pfx",
// "Password": "testPasswordA"
// }
// },
// "*.example.org": {
// "Protocols": "Http1",
// }
// }
// }
internal class EndpointConfig
{
private readonly ConfigSectionClone _configSectionClone;
public EndpointConfig(
string name,
string url,
Dictionary<string, SniConfig> sni,
IConfigurationSection configSection)
{
Name = name;
Url = url;
Sni = sni;
// Compare config sections because it's accessible to app developers via an Action<EndpointConfiguration> callback.
// We cannot rely entirely on comparing config sections for equality, because KestrelConfigurationLoader.Reload() sets
// EndpointConfig properties to their default values. If a default value changes, the properties would no longer be equal,
// but the config sections could still be equal.
ConfigSection = configSection;
// The IConfigrationSection will mutate, so we need to take a snapshot to compare against later and check for changes.
_configSectionClone = new ConfigSectionClone(configSection);
}
public string Name { get; }
public string Url { get; }
public Dictionary<string, SniConfig> Sni { get; }
public IConfigurationSection ConfigSection { get; }
public HttpProtocols? Protocols { get; set; }
public SslProtocols? SslProtocols { get; set; }
public CertificateConfig? Certificate { get; set; }
public ClientCertificateMode? ClientCertificateMode { get; set; }
public override bool Equals(object? obj) =>
obj is EndpointConfig other &&
Name == other.Name &&
Url == other.Url &&
(Protocols ?? ListenOptions.DefaultHttpProtocols) == (other.Protocols ?? ListenOptions.DefaultHttpProtocols) &&
(SslProtocols ?? System.Security.Authentication.SslProtocols.None) == (other.SslProtocols ?? System.Security.Authentication.SslProtocols.None) &&
Certificate == other.Certificate &&
(ClientCertificateMode ?? Https.ClientCertificateMode.NoCertificate) == (other.ClientCertificateMode ?? Https.ClientCertificateMode.NoCertificate) &&
CompareSniDictionaries(Sni, other.Sni) &&
_configSectionClone == other._configSectionClone;
public override int GetHashCode() => HashCode.Combine(Name, Url,
Protocols ?? ListenOptions.DefaultHttpProtocols, SslProtocols ?? System.Security.Authentication.SslProtocols.None,
Certificate, ClientCertificateMode ?? Https.ClientCertificateMode.NoCertificate, Sni.Count, _configSectionClone);
public static bool operator ==(EndpointConfig? lhs, EndpointConfig? rhs) => lhs is null ? rhs is null : lhs.Equals(rhs);
public static bool operator !=(EndpointConfig? lhs, EndpointConfig? rhs) => !(lhs == rhs);
private static bool CompareSniDictionaries(Dictionary<string, SniConfig> lhs, Dictionary<string, SniConfig> rhs)
{
if (lhs.Count != rhs.Count)
{
return false;
}
foreach (var (lhsName, lhsSniConfig) in lhs)
{
if (!rhs.TryGetValue(lhsName, out var rhsSniConfig) || lhsSniConfig != rhsSniConfig)
{
return false;
}
}
return true;
}
}
internal class SniConfig
{
public HttpProtocols? Protocols { get; set; }
public SslProtocols? SslProtocols { get; set; }
public CertificateConfig? Certificate { get; set; }
public ClientCertificateMode? ClientCertificateMode { get; set; }
public override bool Equals(object? obj) =>
obj is SniConfig other &&
(Protocols ?? ListenOptions.DefaultHttpProtocols) == (other.Protocols ?? ListenOptions.DefaultHttpProtocols) &&
(SslProtocols ?? System.Security.Authentication.SslProtocols.None) == (other.SslProtocols ?? System.Security.Authentication.SslProtocols.None) &&
Certificate == other.Certificate &&
(ClientCertificateMode ?? Https.ClientCertificateMode.NoCertificate) == (other.ClientCertificateMode ?? Https.ClientCertificateMode.NoCertificate);
public override int GetHashCode() => HashCode.Combine(
Protocols ?? ListenOptions.DefaultHttpProtocols, SslProtocols ?? System.Security.Authentication.SslProtocols.None,
Certificate, ClientCertificateMode ?? Https.ClientCertificateMode.NoCertificate);
public static bool operator ==(SniConfig lhs, SniConfig rhs) => lhs is null ? rhs is null : lhs.Equals(rhs);
public static bool operator !=(SniConfig lhs, SniConfig rhs) => !(lhs == rhs);
}
// "CertificateName": {
// "Path": "testCert.pfx",
// "Password": "testPassword"
// }
internal class CertificateConfig
{
public CertificateConfig(IConfigurationSection configSection)
{
ConfigSection = configSection;
// Bind explictly to preserve linkability
Path = configSection[nameof(Path)];
KeyPath = configSection[nameof(KeyPath)];
Password = configSection[nameof(Password)];
Subject = configSection[nameof(Subject)];
Store = configSection[nameof(Store)];
Location = configSection[nameof(Location)];
if (bool.TryParse(configSection[nameof(AllowInvalid)], out var value))
{
AllowInvalid = value;
}
}
// For testing
internal CertificateConfig()
{
}
public IConfigurationSection? ConfigSection { get; }
// File
public bool IsFileCert => !string.IsNullOrEmpty(Path);
public string? Path { get; set; }
public string? KeyPath { get; set; }
public string? Password { get; set; }
// Cert store
public bool IsStoreCert => !string.IsNullOrEmpty(Subject);
public string? Subject { get; set; }
public string? Store { get; set; }
public string? Location { get; set; }
public bool? AllowInvalid { get; set; }
public override bool Equals(object? obj) =>
obj is CertificateConfig other &&
Path == other.Path &&
KeyPath == other.KeyPath &&
Password == other.Password &&
Subject == other.Subject &&
Store == other.Store &&
Location == other.Location &&
(AllowInvalid ?? false) == (other.AllowInvalid ?? false);
public override int GetHashCode() => HashCode.Combine(Path, KeyPath, Password, Subject, Store, Location, AllowInvalid ?? false);
public static bool operator ==(CertificateConfig? lhs, CertificateConfig? rhs) => lhs is null ? rhs is null : lhs.Equals(rhs);
public static bool operator !=(CertificateConfig? lhs, CertificateConfig? rhs) => !(lhs == rhs);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.Sys.MaxPath; } }
public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } }
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None))
using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, FileStream.DefaultBufferSize, FileOptions.None))
{
Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle));
}
}
public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors)
{
// Copy the destination file to a backup.
if (destBackupFullPath != null)
{
CopyFile(destFullPath, destBackupFullPath, overwrite: true);
}
// Then copy the contents of the source file to the destination file.
CopyFile(sourceFullPath, destFullPath, overwrite: true);
// Finally, delete the source file.
DeleteFile(sourceFullPath);
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
// The desired behavior for Move(source, dest) is to not overwrite the destination file
// if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
// link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move
// as a Creation and Deletion instead of a Rename and thus differ from Windows.
if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)
{
// If link fails, we can fall back to doing a full copy, but we'll only do so for
// cases where we expect link could fail but such a copy could succeed. We don't
// want to do so for all errors, because the copy could incur a lot of cost
// even if we know it'll eventually fail, e.g. EROFS means that the source file
// system is read-only and couldn't support the link being added, but if it's
// read-only, then the move should fail any way due to an inability to delete
// the source file.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EXDEV || // rename fails across devices / mount points
errorInfo.Error == Interop.Error.EPERM || // permissions might not allow creating hard links even if a copy would work
errorInfo.Error == Interop.Error.EOPNOTSUPP || // links aren't supported by the source file system
errorInfo.Error == Interop.Error.EMLINK) // too many hard links to the source file
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
}
else
{
// The operation failed. Within reason, try to determine which path caused the problem
// so we can throw a detailed exception.
string path = null;
bool isDirectory = false;
if (errorInfo.Error == Interop.Error.ENOENT)
{
if (!Directory.Exists(Path.GetDirectoryName(destFullPath)))
{
// The parent directory of destFile can't be found.
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
path = destFullPath;
isDirectory = true;
}
else
{
path = sourceFullPath;
}
}
else if (errorInfo.Error == Interop.Error.EEXIST)
{
path = destFullPath;
}
throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory);
}
}
DeleteFile(sourceFullPath);
}
public override void DeleteFile(string fullPath)
{
if (Interop.Sys.Unlink(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// ENOENT means it already doesn't exist; nop
if (errorInfo.Error != Interop.Error.ENOENT)
{
if (errorInfo.Error == Interop.Error.EISDIR)
errorInfo = Interop.Error.EACCES.Info();
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= MaxDirectoryPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
// The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).
// We do the same.
result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask);
if (result < 0 && firstError.Error == 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errorInfo.Error != Interop.Error.EEXIST)
{
firstError = errorInfo;
}
else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errorInfo;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError.Error != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
var di = new DirectoryInfo(fullPath);
if (!di.Exists)
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
RemoveDirectoryInternal(di, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if ((directory.Attributes & FileAttributes.ReparsePoint) != 0)
{
DeleteFile(directory.FullName);
return;
}
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(directory.FullName, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
var childDirectory = new DirectoryInfo(item);
if (childDirectory.Exists)
{
RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
if (Interop.Sys.RmDir(directory.FullName) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES:
case Interop.Error.EPERM:
case Interop.Error.EROFS:
case Interop.Error.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName)); // match Win32 exception
case Interop.Error.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
Interop.ErrorInfo ignored;
return DirectoryExists(fullPath, out ignored);
}
private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)
{
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo);
}
public override bool FileExists(string fullPath)
{
Interop.ErrorInfo ignored;
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFREG, out ignored);
}
private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)
{
Debug.Assert(fileType == Interop.Sys.FileTypes.S_IFREG || fileType == Interop.Sys.FileTypes.S_IFDIR);
Interop.Sys.FileStatus fileinfo;
errorInfo = default(Interop.ErrorInfo);
// First use stat, as we want to follow symlinks. If that fails, it could be because the symlink
// is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate
// based on the symlink itself.
if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 &&
Interop.Sys.LStat(fullPath, out fileinfo) < 0)
{
errorInfo = Interop.Sys.GetLastErrorInfo();
return false;
}
// Something exists at this path. If the caller is asking for a directory, return true if it's
// a directory and false for everything else. If the caller is asking for a file, return false for
// a directory and true for everything else.
return
(fileType == Interop.Sys.FileTypes.S_IFDIR) ==
((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR);
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new FileInfo(path, null));
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new DirectoryInfo(path, null));
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
(FileSystemInfo)new DirectoryInfo(path, null) :
(FileSystemInfo)new FileInfo(path, null));
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
Interop.Sys.DirectoryEntry dirent;
while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0)
{
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory.
bool isDir;
if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR)
{
// We know it's a directory.
isDir = true;
}
else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN)
{
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g. symlink to a file, broken symlink, etc.), we'll just treat it as a file.
Interop.ErrorInfo errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored);
}
else
{
// Otherwise, treat it as a file. This includes regular files, FIFOs, etc.
isDir = false;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(dirent.InodeName))
{
string userPath = null;
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
userPath = Path.Combine(dirPath.UserPath, dirent.InodeName);
toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName)));
}
if (_includeDirectories &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true);
}
}
}
else if (_includeFiles &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath)
{
Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.Sys.GetCwd();
}
public override void SetCurrentDirectory(string fullPath)
{
Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath, isDirectory:true);
}
public override FileAttributes GetAttributes(string fullPath)
{
return new FileInfo(fullPath, null).Attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new FileInfo(fullPath, null).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new FileInfo(fullPath, null).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new FileInfo(fullPath, null).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new FileInfo(fullPath, null).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
}
public override string[] GetLogicalDrives()
{
return DriveInfoInternal.GetLogicalDrives();
}
}
}
| |
namespace AdMaiora.Bugghy
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Media;
using AdMaiora.AppKit.UI;
using AdMaiora.AppKit.UI.App;
using AdMaiora.Bugghy.Api;
using AdMaiora.Bugghy.Model;
#pragma warning disable CS4014
public class ChatFragment : AdMaiora.AppKit.UI.App.Fragment
{
#region Inner Classes
class ChatAdapter : ItemRecyclerAdapter<ChatAdapter.ChatViewHolder, Model.Message>
{
#region Inner Classes
public class ChatViewHolder : ItemViewHolder
{
[Widget]
public RelativeLayout CalloutLayout;
[Widget]
public TextView SenderLabel;
[Widget]
public TextView MessageLabel;
[Widget]
public TextView DateLabel;
public ChatViewHolder(View itemView)
: base(itemView)
{
}
}
#endregion
#region Costants and Fields
private string _currentUser;
private Random _rnd;
private List<string> _palette;
private Dictionary<string, string> _colors;
#endregion
#region Constructors
public ChatAdapter(AdMaiora.AppKit.UI.App.Fragment context, IEnumerable<Model.Message> source)
: base(context, Resource.Layout.CellChat, source)
{
_currentUser = AppController.Settings.LastLoginUsernameUsed;
_rnd = new Random(DateTime.Now.Second);
_palette = new List<string>
{
"C3BEF7", "8A4FFF", "273C2C", "626868", "80727B", "62929E",
"F79256", "66101F", "DB995A", "654236", "6369D1", "22181C ",
"998FC7", "5B2333", "564D4A"
};
_colors = new Dictionary<string, string>();
}
#endregion
#region Public Methods
public override void GetView(int postion, ChatViewHolder holder, View view, Model.Message item)
{
bool isYours = _currentUser == item.Sender;
bool isSending = item.PostDate == null;
bool isSent = item.PostDate.GetValueOrDefault() != DateTime.MinValue;
if (!isYours && !_colors.ContainsKey(item.Sender))
_colors.Add(item.Sender, _palette[_rnd.Next(_palette.Count)]);
((RelativeLayout)view).SetGravity(isYours ? GravityFlags.Right : GravityFlags.Left);
holder.CalloutLayout.Background.SetColorFilter(
ViewBuilder.ColorFromARGB(isYours ? AppController.Colors.PapayaWhip : _colors[item.Sender]),
PorterDuff.Mode.SrcIn);
holder.CalloutLayout.Alpha = isSent ? 1 : .35f;
holder.SenderLabel.Text = String.Concat(isYours ? "YOU" : item.Sender.Split('@')[0], " ");
holder.SenderLabel.SetTextColor(ViewBuilder.ColorFromARGB(isYours ? AppController.Colors.Jet : AppController.Colors.White));
holder.MessageLabel.Text = String.Concat(item.Content, " ");
holder.MessageLabel.SetTextColor(ViewBuilder.ColorFromARGB(isYours ? AppController.Colors.Jet : AppController.Colors.White));
holder.DateLabel.Text = isSent ? String.Format(" sent @ {0:G}", item.PostDate) : String.Empty;
holder.DateLabel.SetTextColor(ViewBuilder.ColorFromARGB(isYours ? AppController.Colors.Jet : AppController.Colors.White));
}
public void Insert(Model.Message message)
{
this.SourceItems.Add(message);
this.SourceItems = this.SourceItems.OrderBy(x => x.PostDate).ToList();
}
public void Refresh(IEnumerable<Model.Message> items)
{
this.SourceItems.Clear();
this.SourceItems.AddRange(items);
}
#endregion
}
#endregion
#region Constants and Fields
private int _gimmickId;
private int _userId;
private Issue _issue;
private ChatAdapter _adapter;
// This flag check if we are already calling the send message REST service
private bool _isSendingMessage;
// This cancellation token is used to cancel the rest send message request
private CancellationTokenSource _cts0;
// This flag check if we are already calling the refersh message REST service
private bool _isRefreshingMessage;
// This cancellation token is used to cancel the rest refresh messages request
private CancellationTokenSource _cts1;
#endregion
#region Widgets
[Widget]
private RelativeLayout HeaderLayout;
[Widget]
private ImageView TypeImage;
[Widget]
private TextView TitleLabel;
[Widget]
private TextView StatusLabel;
[Widget]
private ItemRecyclerView MessageList;
[Widget]
private RelativeLayout InputLayout;
[Widget]
private EditText MessageText;
[Widget]
private ImageButton SendButton;
#endregion
#region Constructors
public ChatFragment()
{
}
#endregion
#region Properties
#endregion
#region Fragment Methods
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
_gimmickId = this.Arguments.GetInt("GimmickId");
_userId = AppController.Settings.LastLoginUserIdUsed;
_issue = this.Arguments.GetObject<Issue>("Issue");
_adapter = new ChatAdapter(this, new Model.Message[0]);
}
public override void OnCreateView(LayoutInflater inflater, ViewGroup container)
{
base.OnCreateView(inflater, container);
#region Desinger Stuff
SetContentView(Resource.Layout.FragmentChat, inflater, container);
ResizeToShowKeyboard();
this.HasOptionsMenu = true;
#endregion
this.Title = "Chat";
this.ActionBar.Show();
this.HeaderLayout.Clickable = true;
this.HeaderLayout.SetOnTouchListener(GestureListener.ForSingleTapUp(this.Activity,
(e) =>
{
var f = new IssueFragment();
f.Arguments = new Bundle();
f.Arguments.PutInt("GimmickId", _gimmickId);
f.Arguments.PutObject<Issue>("Issue", _issue);
this.FragmentManager.BeginTransaction()
.AddToBackStack("BeforeIssueFragment")
.Replace(Resource.Id.ContentLayout, f, "IssueFragment")
.Commit();
}));
this.MessageList.SetAdapter(_adapter);
this.SendButton.Click += SendButton_Click;
if(_issue != null)
LoadIssue();
RefreshMessages();
}
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
base.OnCreateOptionsMenu(menu, inflater);
menu.Clear();
menu.Add(0, 1, 0, "Refresh").SetShowAsAction(ShowAsAction.Always);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch(item.ItemId)
{
case 1:
RefreshMessages();
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
public override void OnDestroyView()
{
base.OnDestroyView();
if (_cts0 != null)
_cts0.Cancel();
if (_cts1 != null)
_cts1.Cancel();
this.SendButton.Click -= SendButton_Click;
}
#endregion
#region Public Methods
#endregion
#region Methods
private void LoadIssue()
{
this.TitleLabel.Text = _issue.Title;
DateTime? statusDate = null;
switch(_issue.Status)
{
case IssueStatus.Opened:
statusDate = _issue.CreationDate;
break;
case IssueStatus.Evaluating:
case IssueStatus.Working:
statusDate = _issue.ReplyDate;
break;
case IssueStatus.Resolved:
case IssueStatus.Rejected:
case IssueStatus.Closed:
statusDate = _issue.ClosedDate;
break;
}
this.StatusLabel.Text = String.Format("{0} @ {1:G}",
_issue.Status.ToString(),
statusDate.GetValueOrDefault());
}
private void PostMessage()
{
if (_isSendingMessage)
return;
string content = this.MessageText.Text;
if (String.IsNullOrWhiteSpace(content))
return;
_isSendingMessage = true;
((MainActivity)this.Activity).BlockUI();
_cts0 = new CancellationTokenSource();
AppController.PostMessage(_cts0,
_issue.IssueId,
_userId,
content,
(message) =>
{
if (_adapter != null)
{
_adapter.Insert(message);
this.MessageList.ReloadData();
this.MessageList.Visibility = ViewStates.Visible;
this.MessageText.Text = String.Empty;
}
},
(error) =>
{
Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show();
},
() =>
{
_isSendingMessage = false;
((MainActivity)this.Activity).UnblockUI();
});
}
private void RefreshMessages()
{
if (_isRefreshingMessage)
return;
this.MessageList.Visibility = ViewStates.Gone;
_isRefreshingMessage = true;
((MainActivity)this.Activity).BlockUI();
Model.Message[] messages = null;
_cts1 = new CancellationTokenSource();
AppController.RefreshMessages(_cts1,
_issue.IssueId,
(newMessages) =>
{
messages = newMessages;
},
(error) =>
{
Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show();
},
() =>
{
if (messages != null)
{
LoadMessages(messages);
if (_adapter?.ItemCount > 0)
this.MessageList.Visibility = ViewStates.Visible;
_isRefreshingMessage = false;
((MainActivity)this.Activity).UnblockUI();
}
else
{
AppController.Utility.ExecuteOnAsyncTask(_cts1.Token,
() =>
{
messages = AppController.GetMessages(_issue.IssueId);
},
() =>
{
LoadMessages(messages);
if (_adapter?.ItemCount > 0)
this.MessageList.Visibility = ViewStates.Visible;
_isRefreshingMessage = false;
((MainActivity)this.Activity).UnblockUI();
});
}
});
}
private void LoadMessages(IEnumerable<Model.Message> messages)
{
if (messages == null)
return;
// Sort desc by creation date
messages = messages.OrderBy(x => x.PostDate);
if (_adapter == null)
{
_adapter = new ChatAdapter(this, messages);
this.MessageList.SetAdapter(_adapter);
}
else
{
_adapter.Refresh(messages);
this.MessageList.ReloadData();
}
}
private void SetIssueTypeImage(IssueType type)
{
string[] typeImages = new[] { "image_gear", "image_issue_crash", "image_issue_blocking", "image_issue_nblocking" };
this.TypeImage.SetImageResource(typeImages[(int)type]);
}
#endregion
#region Event Handlers
private void SendButton_Click(object sender, EventArgs e)
{
DismissKeyboard();
PostMessage();
}
#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.Reflection;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Runtime.Serialization;
namespace System.Text
{
// Our input file data structures look like:
//
// Header structure looks like:
// struct NLSPlusHeader
// {
// WORD[16] filename; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3, 2, 0, 0
// WORD count; // 2 bytes = 42 // Number of code page indexes that will follow
// }
//
// Each code page section looks like:
// struct NLSCodePageIndex
// {
// WORD[16] codePageName; // 32 bytes
// WORD codePage; // +2 bytes = 34
// WORD byteCount; // +2 bytes = 36
// DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE.
// }
//
// Each code page then has its own header
// struct NLSCodePage
// {
// WORD[16] codePageName; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // e.g.: 3.2.0.0
// WORD codePage; // 2 bytes = 42
// WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS)
// WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character
// WORD byteReplace; // 2 bytes = 48 // default replacement byte(s)
// BYTE[] data; // data section
// }
internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable
{
internal const string CODE_PAGE_DATA_FILE_NAME = "codepages.nlp";
protected int dataTableCodePage;
// Variables to help us allocate/mark our memory section correctly
protected int iExtraBytes = 0;
// Our private unicode-to-bytes best-fit-array, and vice versa.
protected char[] arrayUnicodeBestFit = null;
protected char[] arrayBytesBestFit = null;
internal BaseCodePageEncoding(int codepage)
: this(codepage, codepage)
{
}
internal BaseCodePageEncoding(int codepage, int dataCodePage)
: base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null))
{
SetFallbackEncoding();
// Remember number of code pages that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec)
: base(codepage, enc, dec)
{
// Remember number of code pages that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
// Just a helper as we cannot use 'this' when calling 'base(...)'
private void SetFallbackEncoding()
{
(EncoderFallback as InternalEncoderBestFitFallback).encoding = this;
(DecoderFallback as InternalDecoderBestFitFallback).encoding = this;
}
//
// This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME.
//
// Explicit layout is used here since a syntax like char[16] can not be used in sequential layout.
[StructLayout(LayoutKind.Explicit)]
internal struct CodePageDataFileHeader
{
[FieldOffset(0)]
internal char TableName; // WORD[16]
[FieldOffset(0x20)]
internal ushort Version; // WORD[4]
[FieldOffset(0x28)]
internal short CodePageCount; // WORD
[FieldOffset(0x2A)]
internal short unused1; // Add an unused WORD so that CodePages is aligned with DWORD boundary.
}
private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44;
[StructLayout(LayoutKind.Explicit, Pack = 2)]
internal unsafe struct CodePageIndex
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal short CodePage; // WORD
[FieldOffset(0x22)]
internal short ByteCount; // WORD
[FieldOffset(0x24)]
internal int Offset; // DWORD
}
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct CodePageHeader
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal ushort VersionMajor; // WORD
[FieldOffset(0x22)]
internal ushort VersionMinor; // WORD
[FieldOffset(0x24)]
internal ushort VersionRevision; // WORD
[FieldOffset(0x26)]
internal ushort VersionBuild; // WORD
[FieldOffset(0x28)]
internal short CodePage; // WORD
[FieldOffset(0x2a)]
internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS)
[FieldOffset(0x2c)]
internal char UnicodeReplace; // WORD // default replacement unicode character
[FieldOffset(0x2e)]
internal ushort ByteReplace; // WORD // default replacement bytes
}
private const int CODEPAGE_HEADER_SIZE = 48;
// Initialize our global stuff
private static readonly byte[] s_codePagesDataHeader = new byte[CODEPAGE_DATA_FILE_HEADER_SIZE];
protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream(CODE_PAGE_DATA_FILE_NAME);
protected static readonly object s_streamLock = new object(); // this lock used when reading from s_codePagesEncodingDataStream
// Real variables
protected byte[] m_codePageHeader = new byte[CODEPAGE_HEADER_SIZE];
protected int m_firstDataWordOffset;
protected int m_dataSize;
// Safe handle wrapper around section map view
protected SafeAllocHHandle safeNativeMemoryHandle = null;
internal static Stream GetEncodingDataStream(string tableName)
{
Debug.Assert(tableName != null, "table name can not be null");
// NOTE: We must reflect on a public type that is exposed in the contract here
// (i.e. CodePagesEncodingProvider), otherwise we will not get a reference to
// the right assembly.
Stream stream = typeof(CodePagesEncodingProvider).GetTypeInfo().Assembly.GetManifestResourceStream(tableName);
if (stream == null)
{
// We can not continue if we can't get the resource.
throw new InvalidOperationException();
}
// Read the header
stream.Read(s_codePagesDataHeader, 0, s_codePagesDataHeader.Length);
return stream;
}
// We need to load tables for our code page
private unsafe void LoadCodePageTables()
{
if (!FindCodePage(dataTableCodePage))
{
// Didn't have one
throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage));
}
// We had it, so load it
LoadManagedCodePage();
}
// Look up the code page pointer
private unsafe bool FindCodePage(int codePage)
{
Debug.Assert(m_codePageHeader != null && m_codePageHeader.Length == CODEPAGE_HEADER_SIZE, "m_codePageHeader expected to match in size the struct CodePageHeader");
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = &s_codePagesDataHeader[0])
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = &codePageIndex[0])
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
// Found it!
long position = s_codePagesEncodingDataStream.Position;
s_codePagesEncodingDataStream.Seek((long)pCodePageIndex->Offset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(m_codePageHeader, 0, m_codePageHeader.Length);
m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; // stream now pointing to the codepage data
if (i == codePagesCount - 1) // last codepage
{
m_dataSize = (int)(s_codePagesEncodingDataStream.Length - pCodePageIndex->Offset - m_codePageHeader.Length);
}
else
{
// Read Next codepage data to get the offset and then calculate the size
s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin);
int currentOffset = pCodePageIndex->Offset;
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
m_dataSize = pCodePageIndex->Offset - currentOffset - m_codePageHeader.Length;
}
return true;
}
}
}
}
// Couldn't find it
return false;
}
// Get our code page byte count
internal static unsafe int GetCodePageByteSize(int codePage)
{
// Loop through all of the m_pCodePageIndex[] items to find our code page
byte[] codePageIndex = new byte[sizeof(CodePageIndex)];
lock (s_streamLock)
{
// seek to the first CodePageIndex entry
s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin);
int codePagesCount;
fixed (byte* pBytes = &s_codePagesDataHeader[0])
{
CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes;
codePagesCount = pDataHeader->CodePageCount;
}
fixed (byte* pBytes = &codePageIndex[0])
{
CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes;
for (int i = 0; i < codePagesCount; i++)
{
s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length);
if (pCodePageIndex->CodePage == codePage)
{
Debug.Assert(pCodePageIndex->ByteCount == 1 || pCodePageIndex->ByteCount == 2,
"[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePageIndex->ByteCount + ") in table");
// Return what it says for byte count
return pCodePageIndex->ByteCount;
}
}
}
}
// Couldn't find it
return 0;
}
// We have a managed code page entry, so load our tables
protected abstract unsafe void LoadManagedCodePage();
// Allocate memory to load our code page
protected unsafe byte* GetNativeMemory(int iSize)
{
if (safeNativeMemoryHandle == null)
{
byte* pNativeMemory = (byte*)Marshal.AllocHGlobal(iSize);
Debug.Assert(pNativeMemory != null);
safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)pNativeMemory);
}
return (byte*)safeNativeMemoryHandle.DangerousGetHandle();
}
protected abstract unsafe void ReadBestFitTable();
internal char[] GetBestFitUnicodeToBytesData()
{
// Read in our best fit table if necessary
if (arrayUnicodeBestFit == null) ReadBestFitTable();
Debug.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
// Normally we don't have any best fit data.
return arrayUnicodeBestFit;
}
internal char[] GetBestFitBytesToUnicodeData()
{
// Read in our best fit table if necessary
if (arrayBytesBestFit == null) ReadBestFitTable();
Debug.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
// Normally we don't have any best fit data.
return arrayBytesBestFit;
}
// During the AppDomain shutdown the Encoding class may have already finalized, making the memory section
// invalid. We detect that by validating the memory section handle then re-initializing the memory
// section by calling LoadManagedCodePage() method and eventually the mapped file handle and
// the memory section pointer will get finalized one more time.
internal unsafe void CheckMemorySection()
{
if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero)
{
LoadManagedCodePage();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public struct ValueTuple
: IEquatable<ValueTuple>, Collections.IStructuralEquatable, Collections.IStructuralComparable, IComparable, IComparable<ValueTuple>
{
public override bool Equals(object obj) { throw null; }
public bool Equals(ValueTuple other) { throw null; }
bool Collections.IStructuralEquatable.Equals(object other, Collections.IEqualityComparer comparer) { throw null; }
int IComparable.CompareTo(object other) { throw null; }
public int CompareTo(ValueTuple other) { throw null; }
int Collections.IStructuralComparable.CompareTo(object other, Collections.IComparer comparer) { throw null; }
public override int GetHashCode() { throw null; }
int Collections.IStructuralEquatable.GetHashCode(Collections.IEqualityComparer comparer) { throw null; }
public override string ToString() { throw null; }
public static ValueTuple Create() { throw null; }
public static ValueTuple<T1> Create<T1>(T1 item1) { throw null; }
public static ValueTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { throw null; }
public static ValueTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { throw null; }
public static ValueTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) { throw null; }
public static ValueTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { throw null; }
public static ValueTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { throw null; }
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { throw null; }
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { throw null; }
}
public struct ValueTuple<T1>
: IEquatable<ValueTuple<T1>>, Collections.IStructuralEquatable, Collections.IStructuralComparable, IComparable, IComparable<ValueTuple<T1>>
{
public T1 Item1;
public ValueTuple(T1 item1) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(ValueTuple<T1> other) { throw null; }
bool Collections.IStructuralEquatable.Equals(object other, Collections.IEqualityComparer comparer) { throw null; }
int IComparable.CompareTo(object other) { throw null; }
public int CompareTo(ValueTuple<T1> other) { throw null; }
int Collections.IStructuralComparable.CompareTo(object other, Collections.IComparer comparer) { throw null; }
public override int GetHashCode() { throw null; }
int Collections.IStructuralEquatable.GetHashCode(Collections.IEqualityComparer comparer) { throw null; }
public override string ToString() { throw null; }
}
[Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)]
public struct ValueTuple<T1, T2>
: IEquatable<ValueTuple<T1, T2>>, Collections.IStructuralEquatable, Collections.IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2>>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(ValueTuple<T1, T2> other) { throw null; }
bool Collections.IStructuralEquatable.Equals(object other, Collections.IEqualityComparer comparer) { throw null; }
int IComparable.CompareTo(object other) { throw null; }
public int CompareTo(ValueTuple<T1, T2> other) { throw null; }
int Collections.IStructuralComparable.CompareTo(object other, Collections.IComparer comparer) { throw null; }
public override int GetHashCode() { throw null; }
int Collections.IStructuralEquatable.GetHashCode(Collections.IEqualityComparer comparer) { throw null; }
public override string ToString() { throw null; }
}
[Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3>
: IEquatable<ValueTuple<T1, T2, T3>>, Collections.IStructuralEquatable, Collections.IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3>>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public ValueTuple(T1 item1, T2 item2, T3 item3) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(ValueTuple<T1, T2, T3> other) { throw null; }
bool Collections.IStructuralEquatable.Equals(object other, Collections.IEqualityComparer comparer) { throw null; }
int IComparable.CompareTo(object other) { throw null; }
public int CompareTo(ValueTuple<T1, T2, T3> other) { throw null; }
int Collections.IStructuralComparable.CompareTo(object other, Collections.IComparer comparer) { throw null; }
public override int GetHashCode() { throw null; }
int Collections.IStructuralEquatable.GetHashCode(Collections.IEqualityComparer comparer) { throw null; }
public override string ToString() { throw null; }
}
[Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4>
: IEquatable<ValueTuple<T1, T2, T3, T4>>, Collections.IStructuralEquatable, Collections.IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4>>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(ValueTuple<T1, T2, T3, T4> other) { throw null; }
bool Collections.IStructuralEquatable.Equals(object other, Collections.IEqualityComparer comparer) { throw null; }
int IComparable.CompareTo(object other) { throw null; }
public int CompareTo(ValueTuple<T1, T2, T3, T4> other) { throw null; }
int Collections.IStructuralComparable.CompareTo(object other, Collections.IComparer comparer) { throw null; }
public override int GetHashCode() { throw null; }
int Collections.IStructuralEquatable.GetHashCode(Collections.IEqualityComparer comparer) { throw null; }
public override string ToString() { throw null; }
}
[Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5>>, Collections.IStructuralEquatable, Collections.IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5>>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
public T5 Item5;
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(ValueTuple<T1, T2, T3, T4, T5> other) { throw null; }
bool Collections.IStructuralEquatable.Equals(object other, Collections.IEqualityComparer comparer) { throw null; }
int IComparable.CompareTo(object other) { throw null; }
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5> other) { throw null; }
int Collections.IStructuralComparable.CompareTo(object other, Collections.IComparer comparer) { throw null; }
public override int GetHashCode() { throw null; }
int Collections.IStructuralEquatable.GetHashCode(Collections.IEqualityComparer comparer) { throw null; }
public override string ToString() { throw null; }
}
[Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6>>, Collections.IStructuralEquatable, Collections.IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6>>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
public T5 Item5;
public T6 Item6;
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6> other) { throw null; }
bool Collections.IStructuralEquatable.Equals(object other, Collections.IEqualityComparer comparer) { throw null; }
int IComparable.CompareTo(object other) { throw null; }
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6> other) { throw null; }
int Collections.IStructuralComparable.CompareTo(object other, Collections.IComparer comparer) { throw null; }
public override int GetHashCode() { throw null; }
int Collections.IStructuralEquatable.GetHashCode(Collections.IEqualityComparer comparer) { throw null; }
public override string ToString() { throw null; }
}
[Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, Collections.IStructuralEquatable, Collections.IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
public T5 Item5;
public T6 Item6;
public T7 Item7;
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other) { throw null; }
bool Collections.IStructuralEquatable.Equals(object other, Collections.IEqualityComparer comparer) { throw null; }
int IComparable.CompareTo(object other) { throw null; }
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other) { throw null; }
int Collections.IStructuralComparable.CompareTo(object other, Collections.IComparer comparer) { throw null; }
public override int GetHashCode() { throw null; }
int Collections.IStructuralEquatable.GetHashCode(Collections.IEqualityComparer comparer) { throw null; }
public override string ToString() { throw null; }
}
[Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, Collections.IStructuralEquatable, Collections.IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>
where TRest : struct
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
public T5 Item5;
public T6 Item6;
public T7 Item7;
public TRest Rest;
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other) { throw null; }
bool Collections.IStructuralEquatable.Equals(object other, Collections.IEqualityComparer comparer) { throw null; }
int IComparable.CompareTo(object other) { throw null; }
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other) { throw null; }
int Collections.IStructuralComparable.CompareTo(object other, Collections.IComparer comparer) { throw null; }
public override int GetHashCode() { throw null; }
int Collections.IStructuralEquatable.GetHashCode(Collections.IEqualityComparer comparer) { throw null; }
public override string ToString() { throw null; }
}
}
namespace System
{
using System.ComponentModel;
public static class TupleExtensions
{
#region Deconstruct
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1>(
this Tuple<T1> value,
out T1 item1)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2>(
this Tuple<T1, T2> value,
out T1 item1, out T2 item2)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3>(
this Tuple<T1, T2, T3> value,
out T1 item1, out T2 item2, out T3 item3)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4>(
this Tuple<T1, T2, T3, T4> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5>(
this Tuple<T1, T2, T3, T4, T5> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6>(
this Tuple<T1, T2, T3, T4, T5, T6> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7>(
this Tuple<T1, T2, T3, T4, T5, T6, T7> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15>>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16>>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17>>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18>>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19>>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20>>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19, out T20 item20)
{
throw null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20, T21>>> value,
out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19, out T20 item20, out T21 item21)
{
throw null;
}
#endregion
#region ToValueTuple
public static ValueTuple<T1>
ToValueTuple<T1>(
this Tuple<T1> value)
{
throw null;
}
public static ValueTuple<T1, T2>
ToValueTuple<T1, T2>(
this Tuple<T1, T2> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3>
ToValueTuple<T1, T2, T3>(
this Tuple<T1, T2, T3> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4>
ToValueTuple<T1, T2, T3, T4>(
this Tuple<T1, T2, T3, T4> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5>
ToValueTuple<T1, T2, T3, T4, T5>(
this Tuple<T1, T2, T3, T4, T5> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6>
ToValueTuple<T1, T2, T3, T4, T5, T6>(
this Tuple<T1, T2, T3, T4, T5, T6> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7>(
this Tuple<T1, T2, T3, T4, T5, T6, T7> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15>>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15>>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16>>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16>>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17>>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17>>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18>>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18>>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19>>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19>>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20>>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20>>> value)
{
throw null;
}
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20, T21>>>
ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(
this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20, T21>>> value)
{
throw null;
}
#endregion
#region ToTuple
public static Tuple<T1>
ToTuple<T1>(
this ValueTuple<T1> value)
{
throw null;
}
public static Tuple<T1, T2>
ToTuple<T1, T2>(
this ValueTuple<T1, T2> value)
{
throw null;
}
public static Tuple<T1, T2, T3>
ToTuple<T1, T2, T3>(
this ValueTuple<T1, T2, T3> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4>
ToTuple<T1, T2, T3, T4>(
this ValueTuple<T1, T2, T3, T4> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5>
ToTuple<T1, T2, T3, T4, T5>(
this ValueTuple<T1, T2, T3, T4, T5> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6>
ToTuple<T1, T2, T3, T4, T5, T6>(
this ValueTuple<T1, T2, T3, T4, T5, T6> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7>
ToTuple<T1, T2, T3, T4, T5, T6, T7>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15>>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15>>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16>>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16>>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17>>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17>>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18>>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18>>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19>>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19>>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20>>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20>>> value)
{
throw null;
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20, T21>>>
ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(
this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20, T21>>> value)
{
throw null;
}
#endregion
private static ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLong<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) where TRest : struct =>
new ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest);
private static Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLongRef<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) =>
new Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest);
}
}
namespace System.Runtime.CompilerServices
{
using System.Collections.Generic;
[CLSCompliant(false)]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event)]
public sealed class TupleElementNamesAttribute : Attribute
{
public TupleElementNamesAttribute(string[] transformNames) { throw null; }
public IList<string> TransformNames { get { throw null; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace Nest
{
[JsonConverter(typeof(VerbatimDictionaryKeysJsonConverter))]
public class AggregationDictionary : IsADictionaryBase<string, IAggregationContainer>
{
public AggregationDictionary() : base() { }
public AggregationDictionary(IDictionary<string, IAggregationContainer> container) : base(container) { }
public AggregationDictionary(Dictionary<string, AggregationContainer> container)
: base(container.Select(kv => kv).ToDictionary(kv => kv.Key, kv => (IAggregationContainer)kv.Value))
{ }
public static implicit operator AggregationDictionary(Dictionary<string, IAggregationContainer> container) =>
new AggregationDictionary(container);
public static implicit operator AggregationDictionary(Dictionary<string, AggregationContainer> container) =>
new AggregationDictionary(container);
public static implicit operator AggregationDictionary(AggregationBase aggregator)
{
IAggregation b;
var combinator = aggregator as AggregationCombinator;
if (combinator != null)
{
var dict = new Dictionary<string, AggregationContainer>();
foreach (var agg in combinator.Aggregations)
{
b = agg;
if (b.Name.IsNullOrEmpty())
throw new ArgumentException($"{aggregator.GetType().Name} .Name is not set!");
dict.Add(b.Name, agg);
}
return dict;
}
b = aggregator;
if (b.Name.IsNullOrEmpty())
throw new ArgumentException($"{aggregator.GetType().Name} .Name is not set!");
return new Dictionary<string, AggregationContainer> { { b.Name, aggregator } };
}
}
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(ReadAsTypeJsonConverter<AggregationContainer>))]
public interface IAggregationContainer
{
[JsonProperty("meta")]
[JsonConverter(typeof(VerbatimDictionaryKeysJsonConverter))]
IDictionary<string, object> Meta { get; set; }
[JsonProperty("avg")]
IAverageAggregation Average { get; set; }
[JsonProperty("date_histogram")]
IDateHistogramAggregation DateHistogram { get; set; }
[JsonProperty("percentiles")]
IPercentilesAggregation Percentiles { get; set; }
[JsonProperty("date_range")]
IDateRangeAggregation DateRange { get; set; }
[JsonProperty("extended_stats")]
IExtendedStatsAggregation ExtendedStats { get; set; }
[JsonProperty("filter")]
IFilterAggregation Filter { get; set; }
[JsonProperty("filters")]
IFiltersAggregation Filters { get; set; }
[JsonProperty("geo_distance")]
IGeoDistanceAggregation GeoDistance { get; set; }
[JsonProperty("geohash_grid")]
IGeoHashGridAggregation GeoHash { get; set; }
[JsonProperty("geo_bounds")]
IGeoBoundsAggregation GeoBounds { get; set; }
[JsonProperty("histogram")]
IHistogramAggregation Histogram { get; set; }
[JsonProperty("global")]
IGlobalAggregation Global { get; set; }
[JsonProperty("ip_range")]
IIpRangeAggregation IpRange { get; set; }
[JsonProperty("max")]
IMaxAggregation Max { get; set; }
[JsonProperty("min")]
IMinAggregation Min { get; set; }
[JsonProperty("cardinality")]
ICardinalityAggregation Cardinality { get; set; }
[JsonProperty("missing")]
IMissingAggregation Missing { get; set; }
[JsonProperty("nested")]
INestedAggregation Nested { get; set; }
[JsonProperty("reverse_nested")]
IReverseNestedAggregation ReverseNested { get; set; }
[JsonProperty("range")]
IRangeAggregation Range { get; set; }
[JsonProperty("stats")]
IStatsAggregator Stats { get; set; }
[JsonProperty("sum")]
ISumAggregation Sum { get; set; }
[JsonProperty("terms")]
ITermsAggregation Terms { get; set; }
[JsonProperty("significant_terms")]
ISignificantTermsAggregation SignificantTerms { get; set; }
[JsonProperty("value_count")]
IValueCountAggregation ValueCount { get; set; }
[JsonProperty("percentile_ranks")]
IPercentileRanksAggregation PercentileRanks { get; set; }
[JsonProperty("top_hits")]
ITopHitsAggregation TopHits { get; set; }
[JsonProperty("children")]
IChildrenAggregation Children { get; set; }
[JsonProperty("scripted_metric")]
IScriptedMetricAggregation ScriptedMetric { get; set; }
[JsonProperty("avg_bucket")]
IAverageBucketAggregation AverageBucket { get; set; }
[JsonProperty("derivative")]
IDerivativeAggregation Derivative { get; set; }
[JsonProperty("max_bucket")]
IMaxBucketAggregation MaxBucket { get; set; }
[JsonProperty("min_bucket")]
IMinBucketAggregation MinBucket { get; set; }
[JsonProperty("sum_bucket")]
ISumBucketAggregation SumBucket { get; set; }
[JsonProperty("stats_bucket")]
IStatsBucketAggregation StatsBucket { get; set; }
[JsonProperty("extended_stats_bucket")]
IExtendedStatsBucketAggregation ExtendedStatsBucket { get; set; }
[JsonProperty("percentiles_bucket")]
IPercentilesBucketAggregation PercentilesBucket { get; set; }
[JsonProperty("moving_avg")]
IMovingAverageAggregation MovingAverage { get; set; }
[JsonProperty("cumulative_sum")]
ICumulativeSumAggregation CumulativeSum { get; set; }
[JsonProperty("serial_diff")]
ISerialDifferencingAggregation SerialDifferencing { get; set; }
[JsonProperty("bucket_script")]
IBucketScriptAggregation BucketScript { get; set; }
[JsonProperty("bucket_selector")]
IBucketSelectorAggregation BucketSelector { get; set; }
[JsonProperty("sampler")]
ISamplerAggregation Sampler { get; set; }
[JsonProperty("aggs")]
AggregationDictionary Aggregations { get; set; }
void Accept(IAggregationVisitor visitor);
}
public class AggregationContainer : IAggregationContainer
{
public IDictionary<string, object> Meta { get; set; }
public IAverageAggregation Average { get; set; }
public IValueCountAggregation ValueCount { get; set; }
public IMaxAggregation Max { get; set; }
public IMinAggregation Min { get; set; }
public IStatsAggregator Stats { get; set; }
public ISumAggregation Sum { get; set; }
public IExtendedStatsAggregation ExtendedStats { get; set; }
public IDateHistogramAggregation DateHistogram { get; set; }
public IPercentilesAggregation Percentiles { get; set; }
public IDateRangeAggregation DateRange { get; set; }
public IFilterAggregation Filter { get; set; }
public IFiltersAggregation Filters { get; set; }
public IGeoDistanceAggregation GeoDistance { get; set; }
public IGeoHashGridAggregation GeoHash { get; set; }
public IGeoBoundsAggregation GeoBounds { get; set; }
public IHistogramAggregation Histogram { get; set; }
public IGlobalAggregation Global { get; set; }
public IIpRangeAggregation IpRange { get; set; }
public ICardinalityAggregation Cardinality { get; set; }
public IMissingAggregation Missing { get; set; }
public INestedAggregation Nested { get; set; }
public IReverseNestedAggregation ReverseNested { get; set; }
public IRangeAggregation Range { get; set; }
public ITermsAggregation Terms { get; set; }
public ISignificantTermsAggregation SignificantTerms { get; set; }
public IPercentileRanksAggregation PercentileRanks { get; set; }
public ITopHitsAggregation TopHits { get; set; }
public IChildrenAggregation Children { get; set; }
public IScriptedMetricAggregation ScriptedMetric { get; set; }
public IAverageBucketAggregation AverageBucket { get; set; }
public IDerivativeAggregation Derivative { get; set; }
public IMaxBucketAggregation MaxBucket { get; set; }
public IMinBucketAggregation MinBucket { get; set; }
public ISumBucketAggregation SumBucket { get; set; }
public IStatsBucketAggregation StatsBucket { get; set; }
public IExtendedStatsBucketAggregation ExtendedStatsBucket { get; set; }
public IPercentilesBucketAggregation PercentilesBucket { get; set; }
public IMovingAverageAggregation MovingAverage { get; set; }
public ICumulativeSumAggregation CumulativeSum { get; set; }
public ISerialDifferencingAggregation SerialDifferencing { get; set; }
public IBucketScriptAggregation BucketScript { get; set; }
public IBucketSelectorAggregation BucketSelector { get; set; }
public ISamplerAggregation Sampler { get; set; }
public AggregationDictionary Aggregations { get; set; }
public static implicit operator AggregationContainer(AggregationBase aggregator)
{
if (aggregator == null) return null;
var container = new AggregationContainer();
aggregator.WrapInContainer(container);
var bucket = aggregator as BucketAggregationBase;
container.Aggregations = bucket?.Aggregations;
container.Meta = aggregator.Meta;
return container;
}
public void Accept(IAggregationVisitor visitor)
{
if (visitor.Scope == AggregationVisitorScope.Unknown) visitor.Scope = AggregationVisitorScope.Aggregation;
new AggregationWalker().Walk(this, visitor);
}
}
public class AggregationContainerDescriptor<T> : DescriptorBase<AggregationContainerDescriptor<T>, IAggregationContainer>, IAggregationContainer
where T : class
{
IDictionary<string, object> IAggregationContainer.Meta { get; set; }
AggregationDictionary IAggregationContainer.Aggregations { get; set; }
IAverageAggregation IAggregationContainer.Average { get; set; }
IDateHistogramAggregation IAggregationContainer.DateHistogram { get; set; }
IPercentilesAggregation IAggregationContainer.Percentiles { get; set; }
IDateRangeAggregation IAggregationContainer.DateRange { get; set; }
IExtendedStatsAggregation IAggregationContainer.ExtendedStats { get; set; }
IFilterAggregation IAggregationContainer.Filter { get; set; }
IFiltersAggregation IAggregationContainer.Filters { get; set; }
IGeoDistanceAggregation IAggregationContainer.GeoDistance { get; set; }
IGeoHashGridAggregation IAggregationContainer.GeoHash { get; set; }
IGeoBoundsAggregation IAggregationContainer.GeoBounds { get; set; }
IHistogramAggregation IAggregationContainer.Histogram { get; set; }
IGlobalAggregation IAggregationContainer.Global { get; set; }
IIpRangeAggregation IAggregationContainer.IpRange { get; set; }
IMaxAggregation IAggregationContainer.Max { get; set; }
IMinAggregation IAggregationContainer.Min { get; set; }
ICardinalityAggregation IAggregationContainer.Cardinality { get; set; }
IMissingAggregation IAggregationContainer.Missing { get; set; }
INestedAggregation IAggregationContainer.Nested { get; set; }
IReverseNestedAggregation IAggregationContainer.ReverseNested { get; set; }
IRangeAggregation IAggregationContainer.Range { get; set; }
IStatsAggregator IAggregationContainer.Stats { get; set; }
ISumAggregation IAggregationContainer.Sum { get; set; }
IValueCountAggregation IAggregationContainer.ValueCount { get; set; }
ISignificantTermsAggregation IAggregationContainer.SignificantTerms { get; set; }
IPercentileRanksAggregation IAggregationContainer.PercentileRanks { get; set; }
ITermsAggregation IAggregationContainer.Terms { get; set; }
ITopHitsAggregation IAggregationContainer.TopHits { get; set; }
IChildrenAggregation IAggregationContainer.Children { get; set; }
IScriptedMetricAggregation IAggregationContainer.ScriptedMetric { get; set; }
IAverageBucketAggregation IAggregationContainer.AverageBucket { get; set; }
IDerivativeAggregation IAggregationContainer.Derivative { get; set; }
IMaxBucketAggregation IAggregationContainer.MaxBucket { get; set; }
IMinBucketAggregation IAggregationContainer.MinBucket { get; set; }
ISumBucketAggregation IAggregationContainer.SumBucket { get; set; }
IStatsBucketAggregation IAggregationContainer.StatsBucket { get; set; }
IExtendedStatsBucketAggregation IAggregationContainer.ExtendedStatsBucket { get; set; }
IPercentilesBucketAggregation IAggregationContainer.PercentilesBucket { get; set; }
IMovingAverageAggregation IAggregationContainer.MovingAverage { get; set; }
ICumulativeSumAggregation IAggregationContainer.CumulativeSum { get; set; }
ISerialDifferencingAggregation IAggregationContainer.SerialDifferencing { get; set; }
IBucketScriptAggregation IAggregationContainer.BucketScript { get; set; }
IBucketSelectorAggregation IAggregationContainer.BucketSelector { get; set; }
ISamplerAggregation IAggregationContainer.Sampler { get; set; }
public AggregationContainerDescriptor<T> Average(string name,
Func<AverageAggregationDescriptor<T>, IAverageAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Average = d);
public AggregationContainerDescriptor<T> DateHistogram(string name,
Func<DateHistogramAggregationDescriptor<T>, IDateHistogramAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.DateHistogram = d);
public AggregationContainerDescriptor<T> Percentiles(string name,
Func<PercentilesAggregationDescriptor<T>, IPercentilesAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Percentiles = d);
public AggregationContainerDescriptor<T> PercentileRanks(string name,
Func<PercentileRanksAggregationDescriptor<T>, IPercentileRanksAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.PercentileRanks = d);
public AggregationContainerDescriptor<T> DateRange(string name,
Func<DateRangeAggregationDescriptor<T>, IDateRangeAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.DateRange = d);
public AggregationContainerDescriptor<T> ExtendedStats(string name,
Func<ExtendedStatsAggregationDescriptor<T>, IExtendedStatsAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.ExtendedStats = d);
public AggregationContainerDescriptor<T> Filter(string name,
Func<FilterAggregationDescriptor<T>, IFilterAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Filter = d);
public AggregationContainerDescriptor<T> Filters(string name,
Func<FiltersAggregationDescriptor<T>, IFiltersAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Filters = d);
public AggregationContainerDescriptor<T> GeoDistance(string name,
Func<GeoDistanceAggregationDescriptor<T>, IGeoDistanceAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.GeoDistance = d);
public AggregationContainerDescriptor<T> GeoHash(string name,
Func<GeoHashGridAggregationDescriptor<T>, IGeoHashGridAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.GeoHash = d);
public AggregationContainerDescriptor<T> GeoBounds(string name,
Func<GeoBoundsAggregationDescriptor<T>, IGeoBoundsAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.GeoBounds = d);
public AggregationContainerDescriptor<T> Histogram(string name,
Func<HistogramAggregationDescriptor<T>, IHistogramAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Histogram = d);
public AggregationContainerDescriptor<T> Global(string name,
Func<GlobalAggregationDescriptor<T>, IGlobalAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Global = d);
public AggregationContainerDescriptor<T> IpRange(string name,
Func<IpRangeAggregationDescriptor<T>, IIpRangeAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.IpRange = d);
public AggregationContainerDescriptor<T> Max(string name,
Func<MaxAggregationDescriptor<T>, IMaxAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Max = d);
public AggregationContainerDescriptor<T> Min(string name,
Func<MinAggregationDescriptor<T>, IMinAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Min = d);
public AggregationContainerDescriptor<T> Cardinality(string name,
Func<CardinalityAggregationDescriptor<T>, ICardinalityAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Cardinality = d);
public AggregationContainerDescriptor<T> Missing(string name,
Func<MissingAggregationDescriptor<T>, IMissingAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Missing = d);
public AggregationContainerDescriptor<T> Nested(string name,
Func<NestedAggregationDescriptor<T>, INestedAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Nested = d);
public AggregationContainerDescriptor<T> ReverseNested(string name,
Func<ReverseNestedAggregationDescriptor<T>, IReverseNestedAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.ReverseNested = d);
public AggregationContainerDescriptor<T> Range(string name,
Func<RangeAggregationDescriptor<T>, IRangeAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Range = d);
public AggregationContainerDescriptor<T> Stats(string name,
Func<StatsAggregationDescriptor<T>, IStatsAggregator> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Stats = d);
public AggregationContainerDescriptor<T> Sum(string name,
Func<SumAggregationDescriptor<T>, ISumAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Sum = d);
public AggregationContainerDescriptor<T> Terms(string name,
Func<TermsAggregationDescriptor<T>, ITermsAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Terms = d);
public AggregationContainerDescriptor<T> SignificantTerms(string name,
Func<SignificantTermsAggregationDescriptor<T>, ISignificantTermsAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.SignificantTerms = d);
public AggregationContainerDescriptor<T> ValueCount(string name,
Func<ValueCountAggregationDescriptor<T>, IValueCountAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.ValueCount = d);
public AggregationContainerDescriptor<T> TopHits(string name,
Func<TopHitsAggregationDescriptor<T>, ITopHitsAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.TopHits = d);
public AggregationContainerDescriptor<T> Children<TChild>(string name,
Func<ChildrenAggregationDescriptor<TChild>, IChildrenAggregation> selector) where TChild : class =>
_SetInnerAggregation(name, selector, (a, d) => a.Children = d);
public AggregationContainerDescriptor<T> ScriptedMetric(string name,
Func<ScriptedMetricAggregationDescriptor<T>, IScriptedMetricAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.ScriptedMetric = d);
public AggregationContainerDescriptor<T> AverageBucket(string name,
Func<AverageBucketAggregationDescriptor, IAverageBucketAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.AverageBucket = d);
public AggregationContainerDescriptor<T> Derivative(string name,
Func<DerivativeAggregationDescriptor, IDerivativeAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Derivative = d);
public AggregationContainerDescriptor<T> MaxBucket(string name,
Func<MaxBucketAggregationDescriptor, IMaxBucketAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.MaxBucket = d);
public AggregationContainerDescriptor<T> MinBucket(string name,
Func<MinBucketAggregationDescriptor, IMinBucketAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.MinBucket = d);
public AggregationContainerDescriptor<T> SumBucket(string name,
Func<SumBucketAggregationDescriptor, ISumBucketAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.SumBucket = d);
public AggregationContainerDescriptor<T> StatsBucket(string name,
Func<StatsBucketAggregationDescriptor, IStatsBucketAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.StatsBucket = d);
public AggregationContainerDescriptor<T> ExtendedStatsBucket(string name,
Func<ExtendedStatsBucketAggregationDescriptor, IExtendedStatsBucketAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.ExtendedStatsBucket = d);
public AggregationContainerDescriptor<T> PercentilesBucket(string name,
Func<PercentilesBucketAggregationDescriptor, IPercentilesBucketAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.PercentilesBucket = d);
public AggregationContainerDescriptor<T> MovingAverage(string name,
Func<MovingAverageAggregationDescriptor, IMovingAverageAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.MovingAverage = d);
public AggregationContainerDescriptor<T> CumulativeSum(string name,
Func<CumulativeSumAggregationDescriptor, ICumulativeSumAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.CumulativeSum = d);
public AggregationContainerDescriptor<T> SerialDifferencing(string name,
Func<SerialDifferencingAggregationDescriptor, ISerialDifferencingAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.SerialDifferencing = d);
public AggregationContainerDescriptor<T> BucketScript(string name,
Func<BucketScriptAggregationDescriptor, IBucketScriptAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.BucketScript = d);
public AggregationContainerDescriptor<T> BucketSelector(string name,
Func<BucketSelectorAggregationDescriptor, IBucketSelectorAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.BucketSelector = d);
public AggregationContainerDescriptor<T> Sampler(string name,
Func<SamplerAggregationDescriptor<T>, ISamplerAggregation> selector) =>
_SetInnerAggregation(name, selector, (a, d) => a.Sampler = d);
/// <summary>
/// Fluent methods do not assign to properties on `this` directly but on IAggregationContainers inside `this.Aggregations[string, IContainer]
/// </summary>
private AggregationContainerDescriptor<T> _SetInnerAggregation<TAggregator, TAggregatorInterface>(
string key,
Func<TAggregator, TAggregatorInterface> selector
, Action<IAggregationContainer, TAggregatorInterface> assignToProperty
)
where TAggregator : IAggregation, TAggregatorInterface, new()
where TAggregatorInterface : IAggregation
{
var aggregator = selector(new TAggregator());
//create new isolated container for new aggregator and assign to the right property
var container = new AggregationContainer() { Meta = aggregator.Meta };
assignToProperty(container, aggregator);
//create aggregations dictionary on `this` if it does not exist already
IAggregationContainer self = this;
if (self.Aggregations == null) self.Aggregations = new Dictionary<string, IAggregationContainer>();
//if the aggregator is a bucket aggregator (meaning it contains nested aggregations);
var bucket = aggregator as IBucketAggregation;
if (bucket != null && bucket.Aggregations.HasAny())
{
//make sure we copy those aggregations to the isolated container's
//own .Aggregations container (the one that gets serialized to "aggs")
IAggregationContainer d = container;
d.Aggregations = bucket.Aggregations;
}
//assign the aggregations container under Aggregations ("aggs" in the json)
self.Aggregations[key] = container;
return this;
}
public void Accept(IAggregationVisitor visitor)
{
if (visitor.Scope == AggregationVisitorScope.Unknown) visitor.Scope = AggregationVisitorScope.Aggregation;
new AggregationWalker().Walk(this, visitor);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using S7.Net.Types;
namespace S7.Net
{
/// <summary>
/// Creates an instance of S7.Net driver
/// </summary>
public partial class Plc : IDisposable
{
private const int CONNECTION_TIMED_OUT_ERROR_CODE = 10060;
//TCP connection to device
private TcpClient tcpClient;
private NetworkStream stream;
private int readTimeout = System.Threading.Timeout.Infinite;
private int writeTimeout = System.Threading.Timeout.Infinite;
/// <summary>
/// IP address of the PLC
/// </summary>
public string IP { get; private set; }
/// <summary>
/// PORT Number of the PLC, default is 102
/// </summary>
public int Port { get; private set; }
/// <summary>
/// CPU type of the PLC
/// </summary>
public CpuType CPU { get; private set; }
/// <summary>
/// Rack of the PLC
/// </summary>
public Int16 Rack { get; private set; }
/// <summary>
/// Slot of the CPU of the PLC
/// </summary>
public Int16 Slot { get; private set; }
/// <summary>
/// Max PDU size this cpu supports
/// </summary>
public Int16 MaxPDUSize { get; set; }
/// <summary>Gets or sets the amount of time that a read operation blocks waiting for data from PLC.</summary>
/// <returns>A <see cref="T:System.Int32" /> that specifies the amount of time, in milliseconds, that will elapse before a read operation fails. The default value, <see cref="F:System.Threading.Timeout.Infinite" />, specifies that the read operation does not time out.</returns>
public int ReadTimeout
{
get => readTimeout;
set
{
readTimeout = value;
if (tcpClient != null) tcpClient.ReceiveTimeout = readTimeout;
}
}
/// <summary>Gets or sets the amount of time that a write operation blocks waiting for data to PLC. </summary>
/// <returns>A <see cref="T:System.Int32" /> that specifies the amount of time, in milliseconds, that will elapse before a write operation fails. The default value, <see cref="F:System.Threading.Timeout.Infinite" />, specifies that the write operation does not time out.</returns>
public int WriteTimeout
{
get => writeTimeout;
set
{
writeTimeout = value;
if (tcpClient != null) tcpClient.SendTimeout = writeTimeout;
}
}
/// <summary>
/// Returns true if a connection to the PLC can be established
/// </summary>
public bool IsAvailable
{
//TODO: Fix This
get
{
try
{
Connect();
return true;
}
catch
{
return false;
}
}
}
/// <summary>
/// Checks if the socket is connected and polls the other peer (the PLC) to see if it's connected.
/// This is the variable that you should continously check to see if the communication is working
/// See also: http://stackoverflow.com/questions/2661764/how-to-check-if-a-socket-is-connected-disconnected-in-c
/// </summary>
public bool IsConnected
{
get
{
try
{
if (tcpClient == null)
return false;
//TODO: Actually check communication by sending an empty TPDU
return tcpClient.Connected;
}
catch { return false; }
}
}
/// <summary>
/// Creates a PLC object with all the parameters needed for connections.
/// For S7-1200 and S7-1500, the default is rack = 0 and slot = 0.
/// You need slot > 0 if you are connecting to external ethernet card (CP).
/// For S7-300 and S7-400 the default is rack = 0 and slot = 2.
/// </summary>
/// <param name="cpu">CpuType of the PLC (select from the enum)</param>
/// <param name="ip">Ip address of the PLC</param>
/// <param name="port">Port address of the PLC, default 102</param>
/// <param name="rack">rack of the PLC, usually it's 0, but check in the hardware configuration of Step7 or TIA portal</param>
/// <param name="slot">slot of the CPU of the PLC, usually it's 2 for S7300-S7400, 0 for S7-1200 and S7-1500.
/// If you use an external ethernet card, this must be set accordingly.</param>
public Plc(CpuType cpu, string ip, int port, Int16 rack, Int16 slot)
{
if (!Enum.IsDefined(typeof(CpuType), cpu))
throw new ArgumentException($"The value of argument '{nameof(cpu)}' ({cpu}) is invalid for Enum type '{typeof(CpuType).Name}'.", nameof(cpu));
if (string.IsNullOrEmpty(ip))
throw new ArgumentException("IP address must valid.", nameof(ip));
CPU = cpu;
IP = ip;
Port = port;
Rack = rack;
Slot = slot;
MaxPDUSize = 240;
}
/// <summary>
/// Creates a PLC object with all the parameters needed for connections.
/// For S7-1200 and S7-1500, the default is rack = 0 and slot = 0.
/// You need slot > 0 if you are connecting to external ethernet card (CP).
/// For S7-300 and S7-400 the default is rack = 0 and slot = 2.
/// </summary>
/// <param name="cpu">CpuType of the PLC (select from the enum)</param>
/// <param name="ip">Ip address of the PLC</param>
/// <param name="rack">rack of the PLC, usually it's 0, but check in the hardware configuration of Step7 or TIA portal</param>
/// <param name="slot">slot of the CPU of the PLC, usually it's 2 for S7300-S7400, 0 for S7-1200 and S7-1500.
/// If you use an external ethernet card, this must be set accordingly.</param>
public Plc(CpuType cpu, string ip, Int16 rack, Int16 slot)
{
if (!Enum.IsDefined(typeof(CpuType), cpu))
throw new ArgumentException($"The value of argument '{nameof(cpu)}' ({cpu}) is invalid for Enum type '{typeof(CpuType).Name}'.", nameof(cpu));
if (string.IsNullOrEmpty(ip))
throw new ArgumentException("IP address must valid.", nameof(ip));
CPU = cpu;
IP = ip;
Port = 102;
Rack = rack;
Slot = slot;
MaxPDUSize = 240;
}
/// <summary>
/// Close connection to PLC
/// </summary>
public void Close()
{
if (tcpClient != null)
{
if (tcpClient.Connected) tcpClient.Close();
}
}
private void AssertPduSizeForRead(ICollection<DataItem> dataItems)
{
// 12 bytes of header data, 12 bytes of parameter data for each dataItem
if ((dataItems.Count + 1) * 12 > MaxPDUSize) throw new Exception("Too many vars requested for read");
// 14 bytes of header data, 4 bytes of result data for each dataItem and the actual data
if (GetDataLength(dataItems) + dataItems.Count * 4 + 14 > MaxPDUSize) throw new Exception("Too much data requested for read");
}
private void AssertPduSizeForWrite(ICollection<DataItem> dataItems)
{
// 12 bytes of header data, 18 bytes of parameter data for each dataItem
if (dataItems.Count * 18 + 12 > MaxPDUSize) throw new Exception("Too many vars supplied for write");
// 12 bytes of header data, 16 bytes of data for each dataItem and the actual data
if (GetDataLength(dataItems) + dataItems.Count * 16 + 12 > MaxPDUSize)
throw new Exception("Too much data supplied for write");
}
private void ConfigureConnection()
{
if (tcpClient == null)
{
return;
}
tcpClient.ReceiveTimeout = ReadTimeout;
tcpClient.SendTimeout = WriteTimeout;
}
private int GetDataLength(IEnumerable<DataItem> dataItems)
{
// Odd length variables are 0-padded
return dataItems.Select(di => VarTypeToByteLength(di.VarType, di.Count))
.Sum(len => (len & 1) == 1 ? len + 1 : len);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
/// <summary>
/// Dispose Plc Object
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
Close();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~Plc() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
void IDisposable.Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Com.Aspose.Barcode.Model;
namespace Com.Aspose.Barcode
{
public struct FileInfo
{
public string Name;
public string MimeType;
public byte[] file;
}
public class ApiInvoker
{
private static readonly ApiInvoker _instance = new ApiInvoker();
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
public string appSid { set; get; }
public string apiKey { set; get; }
public static ApiInvoker GetInstance()
{
return _instance;
}
public void addDefaultHeader(string key, string value)
{
defaultHeaderMap.Add(key, value);
}
public string escapeString(string str)
{
return str;
}
public static object deserialize(string json, Type type)
{
try
{
if (json.StartsWith("{") || json.StartsWith("["))
return JsonConvert.DeserializeObject(json, type);
else
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(json);
return JsonConvert.SerializeXmlNode(xmlDoc);
}
}
catch (IOException e)
{
throw new ApiException(500, e.Message);
}
catch (JsonSerializationException jse)
{
throw new ApiException(500, jse.Message);
}
catch (System.Xml.XmlException xmle)
{
throw new ApiException(500, xmle.Message);
}
}
public static object deserialize(byte[] BinaryData, Type type)
{
try
{
return new ResponseMessage(BinaryData, 200, "Ok");
}
catch (IOException e)
{
throw new ApiException(500, e.Message);
}
}
private static string Sign(string url, string appKey)
{
UriBuilder uriBuilder = new UriBuilder(url);
// Remove final slash here as it can be added automatically.
uriBuilder.Path = uriBuilder.Path.TrimEnd('/');
// Compute the hash.
byte[] privateKey = Encoding.UTF8.GetBytes(appKey);
HMACSHA1 algorithm = new HMACSHA1(privateKey);
byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri);
byte[] hash = algorithm.ComputeHash(sequence);
string signature = Convert.ToBase64String(hash);
// Remove invalid symbols.
signature = signature.TrimEnd('=');
//signature = HttpUtility.UrlEncode(signature);
// Convert codes to upper case as they can be updated automatically.
signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
// Add the signature to query string.
return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature);
}
public static string serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string;
}
public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, string body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string;
}
public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[];
}
public static void CopyTo(Stream source, Stream destination, int bufferSize)
{
byte[] array = new byte[bufferSize];
int count;
while ((count = source.Read(array, 0, array.Length)) != 0)
{
destination.Write(array, 0, count);
}
}
private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
path = path.Replace("{appSid}", this.appSid);
path = Regex.Replace(path, @"{.+?}", "");
//var b = new StringBuilder();
host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
path = Sign(host + path, this.apiKey);
var client = WebRequest.Create(path);
client.Method = method;
byte[] formData = null;
if (formParams.Count > 0)
{
if (formParams.Count > 1)
{
string formDataBoundary = String.Format("Somthing");
client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
formData = GetMultipartFormData(formParams, formDataBoundary);
}
else
{
client.ContentType = "multipart/form-data";
formData = GetMultipartFormData(formParams, "");
}
client.ContentLength = formData.Length;
}
else
{
client.ContentType = "application/json";
}
foreach (var headerParamsItem in headerParams)
{
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
}
foreach (var defaultHeaderMapItem in defaultHeaderMap)
{
if (!headerParams.ContainsKey(defaultHeaderMapItem.Key))
{
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
}
}
//byte[] toBytes = Encoding.ASCII.GetBytes(body.ToString());
//client.ContentLength = toBytes.Length;
switch (method)
{
case "GET":
break;
case "POST":
case "PUT":
case "DELETE":
using (Stream requestStream = client.GetRequestStream())
{
if (formData != null)
{
requestStream.Write(formData, 0, formData.Length);
}
if (body != null)
{
//requestStream.Write(toBytes, 0, toBytes.Length);
var swRequestWriter = new StreamWriter(requestStream);
swRequestWriter.Write(serialize(body));
swRequestWriter.Close();
}
}
break;
default:
throw new ApiException(500, "unknown method type " + method);
}
try
{
var webResponse = (HttpWebResponse)client.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
webResponse.Close();
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
}
if (binaryResponse)
{
using (var memoryStream = new MemoryStream())
{
CopyTo(webResponse.GetResponseStream(), memoryStream, 81920);
return memoryStream.ToArray();
}
}
else
{
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
{
var responseData = responseReader.ReadToEnd();
return responseData;
}
}
}
catch (WebException ex)
{
var response = ex.Response as HttpWebResponse;
int statusCode = 0;
if (response != null)
{
statusCode = (int)response.StatusCode;
response.Close();
}
throw new ApiException(statusCode, ex.Message);
}
}
private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, string body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams)
{
path = path.Replace("{appSid}", this.appSid);
path = Regex.Replace(path, @"{.+?}", "");
//var b = new StringBuilder();
host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
path = Sign(host + path, this.apiKey);
var client = WebRequest.Create(path);
client.Method = method;
byte[] formData = null;
if (formParams.Count > 0)
{
if (formParams.Count > 1)
{
string formDataBoundary = String.Format("Somthing");
client.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
formData = GetMultipartFormData(formParams, formDataBoundary);
}
else
{
client.ContentType = "multipart/form-data";
formData = GetMultipartFormData(formParams, "");
}
client.ContentLength = formData.Length;
}
else
{
client.ContentType = "application/json";
}
foreach (var headerParamsItem in headerParams)
{
client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
}
foreach (var defaultHeaderMapItem in defaultHeaderMap)
{
if (!headerParams.ContainsKey(defaultHeaderMapItem.Key))
{
client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
}
}
byte[] toBytes = Encoding.ASCII.GetBytes(body);
client.ContentLength = toBytes.Length;
switch (method)
{
case "GET":
break;
case "POST":
case "PUT":
case "DELETE":
using (Stream requestStream = client.GetRequestStream())
{
if (formData != null)
{
requestStream.Write(formData, 0, formData.Length);
}
if (body != null)
{
requestStream.Write(toBytes, 0, toBytes.Length);
//var swRequestWriter = new StreamWriter(requestStream);
//swRequestWriter.Write(serialize(body));
//swRequestWriter.Close();
}
}
break;
default:
throw new ApiException(500, "unknown method type " + method);
}
try
{
var webResponse = (HttpWebResponse)client.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
webResponse.Close();
throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
}
if (binaryResponse)
{
using (var memoryStream = new MemoryStream())
{
CopyTo(webResponse.GetResponseStream(), memoryStream, 81920);
return memoryStream.ToArray();
}
}
else
{
using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
{
var responseData = responseReader.ReadToEnd();
return responseData;
}
}
}
catch (WebException ex)
{
var response = ex.Response as HttpWebResponse;
int statusCode = 0;
if (response != null)
{
statusCode = (int)response.StatusCode;
response.Close();
}
throw new ApiException(statusCode, ex.Message);
}
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
if (postParameters.Count > 1)
{
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
needsCLRF = true;
var fileInfo = (FileInfo)param.Value;
if (param.Value is FileInfo)
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
boundary,
param.Key,
fileInfo.MimeType);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
fileInfo.file);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
}
else
{
foreach (var param in postParameters)
{
var fileInfo = (FileInfo)param.Value;
if (param.Value is FileInfo)
{
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length);
}
else
{
string postData = (string)param.Value;
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
}
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
/**
* Overloaded method for returning the path value
* For a string value an empty value is returned if the value is null
* @param value
* @return
*/
public String ToPathValue(String value)
{
return (value == null) ? "" : value;
}
public String ToPathValue(int value)
{
return value.ToString();
}
public String ToPathValue(int? value)
{
return value.ToString();
}
public String ToPathValue(float value)
{
return value.ToString();
}
public String ToPathValue(float? value)
{
return value.ToString();
}
public String ToPathValue(long value)
{
return value.ToString();
}
public String ToPathValue(long? value)
{
return value.ToString();
}
public String ToPathValue(bool value)
{
return value.ToString();
}
public String ToPathValue(bool? value)
{
return value.ToString();
}
public String ToPathValue(double value)
{
return value.ToString();
}
public String ToPathValue(double? value)
{
return value.ToString();
}
}
}
| |
//-----------------------------------------------------------------------------
//Cortex
//Copyright (c) 2010-2015, Joshua Scoggins
//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 Cortex 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 Joshua Scoggins BE LIABLE FOR ANY
//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Cortex.Collections
{
/*
A Multicell is a cell that stores cells
this allows for techniques such as the principle of
locality and a segmented memory model to take place
as each cell can be located in different areas of memory
and the reference is stored in the given area.
The super type of a multi cell is cell and operating on the
super type will allow one to modify the cells instead of the
data they store.
A multicell must shadow:
- indexer operator
- the length property
- the count property
- the IsFull property
- the Expand method
- the GetEnumerator method to return IEnumerable<T>
instead of R
It must add the following as well
- A consolidate operator to covert the multiple cells into
a single large cell
- a new Add method for data elements of type t
- a new Remove method for data elements of type t
- the Exists method for data elements of type t
- the indexof method for data elements of type T
- a new contains method for data elements of type T
Prototype interface
--------------------------
public interface IMultiCell<R, T> : ICell<R>, IEnumerable<T>
where R : ICell<T>
{
new T this[int index] { get; }
new int Length { get; }
new int Count { get; }
new bool IsFull { get; }
new void Expand(int newSize);
new IEnumerator<T> GetEnumerator();
Cell<T> Consolidate();
bool Add(T value);
bool Remove(T value);
int IndexOf(T value);
bool Exists(Predicate<T> predicate);
bool Contains(T value);
}
*/
public class MultiCell<R, T> : Cell<R> , IEnumerable<T>
where R : Cell<T>
{
protected Func<int, R> ctor;
private int lastCell, defaultCellSize, numElements, capacity;
public int DefaultCellSize { get { return defaultCellSize; } set { defaultCellSize = value; } }
public int CurrentCell { get { return lastCell; } protected set { lastCell = value; } }
public new int Length { get { return capacity; } protected set { capacity = value; } }
public new int Count { get { return numElements; } protected set { numElements = value; } }
public int CellCount { get { return base.Count; } protected set { base.Count = value; } }
public int CellLength { get { return base.Length; } }
public new bool IsFull { get { return Count == Length; } }
public Func<int, R> CellConstructor { get { return ctor; } protected set { ctor = value; } }
public MultiCell(Func<int, R> ctor, int size, int defaultCellSize)
: base(size)
{
this.defaultCellSize = defaultCellSize;
lastCell = 0;
this.ctor = ctor;
base.Add(ctor(defaultCellSize));
Length = backingStore[0].Length;
}
public MultiCell(Func<int, R> ctor, int size)
: this(ctor, size, DEFAULT_CAPACITY)
{
}
public MultiCell(Func<int, R> ctor)
: this(ctor, DEFAULT_CAPACITY)
{
}
public MultiCell(MultiCell<R, T> cell)
: base(cell.Length)
{
this.ctor = cell.ctor;
this.defaultCellSize = cell.defaultCellSize;
this.lastCell = cell.lastCell;
for(int i = 0; i < cell.Length; i++)
this.backingStore[i] = (R)cell.backingStore[i].Clone();
}
public bool AddRange(IEnumerable<T> elements)
{
foreach(T v in elements)
if(!Add(v))
return false;
return true;
}
public bool Add(T value)
{
//this can fail horribly
if(lastCell >= base.Count)
return false;
bool result = backingStore[lastCell].Add(value);
if(result)
{
numElements++;
return true;
}
else
{
lastCell++;
return Add(value);
}
}
public new bool Remove(R value)
{
bool result = base.Remove(value);
if(result)
{
Length -= value.Length;
Count -= value.Count;
}
return result;
}
public bool Remove(T value)
{
int index = IndexOf(value);
bool result = (index == -1);
if(!result)
{
R target = base[index];
result = target.Remove(value);
if(result)
Count--;
if(target.Count == 0 && lastCell > 0)
lastCell--; //go to the previous one so that if the removal continues we can properly handle this
}
return result;
}
public int IndexOf(T value)
{
int index = 0;
Predicate<T> subElement = (y) =>
{
bool result = y.Equals(value);
if(!result)
index++;
return result;
};
Predicate<R> p = (x) => x.Exists(subElement);
return Exists(p) ? index : -1;
}
protected object compressionLock = new object();
public new T[] ToArray()
{
List<T> elements = new List<T>();
for(int i = 0; i < base.Count; i++)
{
R value = base[i];
for(int j = 0; j < value.Count; j++)
elements.Add(value[j]);
}
return elements.ToArray();
}
public void PerformFullCompression()
{
lock(compressionLock)
{
T[] newElements = ToArray();
Clear();
AddRange(newElements);
}
}
public new void Expand(int newSize)
{
if(newSize < Length)
throw new ArgumentException("Given new cell count is smaller than current count");
else if(newSize == Length)
return;
else
{
int increase = newSize - Length;
R newCell = ctor(increase);
bool result = Add(newCell);
if(!result)
{
base.Expand(base.Length + 2);
Add(newCell);
}
Length += increase;
}
}
public override object Clone()
{
return new MultiCell<R, T>(this);
}
public new void Clear()
{
CellCount = 0;
lastCell = 0;
Count = 0;
Length = 0;
for(int i = 0; i < CellLength; i++)
base[i].Clear();
}
public void ExpandCells(int newCellCount)
{
if (newCellCount < base.Length)
throw new ArgumentException("Given new size is smaller than current size");
else if (newCellCount == base.Length)
return;
else
base.Expand(newCellCount);
}
public bool Exists(Predicate<T> pred)
{
Predicate<R> pr = (y) => y.Exists(pred);
return Exists(pr);
}
public bool Contains(T value)
{
Predicate<T> pred = (x) => x.Equals(value);
return Exists(pred);
}
/*
When overloading this[int index] its important to convert the
index so that it spans across the different cells automatically
*/
public new T this[int index]
{
get
{
KeyValuePair<int, int> relativePos = TranslateIndex(index);
if(relativePos.Key == -1 && relativePos.Value == -1)
return default(T);
else
return backingStore[relativePos.Key][relativePos.Value];
}
set
{
KeyValuePair<int, int> relativePos = TranslateIndex(index);
if(relativePos.Key != -1 && relativePos.Value != -1)
backingStore[relativePos.Key][relativePos.Value] = value;
}
}
public T this[int cellNumber, int index]
{
get
{
return base[cellNumber][index];
}
set
{
base[cellNumber][index] = value;
}
}
public KeyValuePair<int, int> TranslateIndex(int index)
{
//Alright here is what we do... we start at the current
for(int i = 0; i < base.Count; i++)
{
R value = base[i];
if(index < value.Count)
return new KeyValuePair<int, int>(i, index);
else
index = index - value.Count;
}
return new KeyValuePair<int, int>(-1, -1);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public new IEnumerator<T> GetEnumerator()
{
return new MultiCellEnumerator(this);
}
public class MultiCellEnumerator : IEnumerator<T>
{
private R[] backingElements;
private int count, bIndex;
private IEnumerator<T> current;
public MultiCellEnumerator(MultiCell<R, T> mc)
{
backingElements = mc.backingStore;
count = mc.CellCount;
bIndex = -1;
}
object IEnumerator.Current { get { return Current; } }
public T Current { get { return current.Current; } }
public bool MoveNext()
{
if(bIndex == -1)
{
bIndex++;
if(bIndex < count)
current = backingElements[bIndex].GetEnumerator();
return current.MoveNext();
}
else
{
bool result = current.MoveNext();
if(result)
return result;
else
{
bIndex++;
bool result2 = bIndex < count;
if(result2)
{
current = backingElements[bIndex].GetEnumerator();
return current.MoveNext();
}
return result2;
}
}
}
public void Reset()
{
bIndex = -1;
}
public void Dispose()
{
if(current != null)
current.Dispose();
backingElements = null;
}
}
}
public class MultiCell<T> : MultiCell<Cell<T>, T>
{
public MultiCell(int numCells, int defaultCellSize) : base((x) => new Cell<T>(x), numCells, defaultCellSize) { }
public MultiCell(int numCells) : base((x) => new Cell<T>(x), numCells, DEFAULT_CAPACITY) { }
public MultiCell() : base((x) => new Cell<T>(x), DEFAULT_CAPACITY) { }
public MultiCell(MultiCell<T> cells) : base(cells) { }
public override object Clone()
{
return new MultiCell<T>(this);
}
}
}
| |
using System;
using System.Xml;
using System.Data;
using System.Data.OleDb;
using System.Runtime.InteropServices;
namespace MyMeta
{
#if ENTERPRISE
using System.Runtime.InteropServices;
[ComVisible(false), ClassInterface(ClassInterfaceType.AutoDual)]
#endif
public class Column : Single, IColumn, INameValueItem
{
public Column()
{
}
virtual internal Column Clone()
{
Column c = (Column)this.dbRoot.ClassFactory.CreateColumn();
c.dbRoot = this.dbRoot;
c.Columns = this.Columns;
c._row = this._row;
c._foreignKeys = Column._emptyForeignKeys;
return c;
}
#region Objects
public ITable Table
{
get
{
ITable theTable = null;
if(null != Columns.Table)
{
theTable = Columns.Table;
}
else if(null != Columns.Index)
{
theTable = Columns.Index.Indexes.Table;
}
else if(null != Columns.ForeignKey)
{
theTable = Columns.ForeignKey.ForeignKeys.Table;
}
return theTable;
}
}
public IView View
{
get
{
IView theView = null;
if(null != Columns.View)
{
theView = Columns.View;
}
return theView;
}
}
public IDomain Domain
{
get
{
IDomain theDomain = null;
if(this.HasDomain)
{
theDomain = this.Columns.GetDatabase().Domains[this.DomainName];
}
return theDomain;
}
}
#endregion
#region Properties
[DispId(0)]
override public string Alias
{
get
{
XmlNode node = null;
if(this.GetXmlNode(out node, false))
{
string niceName = null;
if(this.GetUserData(node, "n", out niceName))
{
if(string.Empty != niceName)
return niceName;
}
}
// There was no nice name
return this.Name;
}
set
{
XmlNode node = null;
if(this.GetXmlNode(out node, true))
{
this.SetUserData(node, "n", value);
}
}
}
override public string Name
{
get
{
return this.GetString(Columns.f_Name);
}
}
virtual public Guid Guid
{
get
{
return this.GetGuid(Columns.f_Guid);
}
}
virtual public System.Int32 PropID
{
get
{
return this.GetInt32(Columns.f_PropID);
}
}
virtual public System.Int32 Ordinal
{
get
{
return this.GetInt32(Columns.f_Ordinal);
}
}
virtual public System.Boolean HasDefault
{
get
{
return this.GetBool(Columns.f_HasDefault);
}
}
virtual public string Default
{
get
{
return this.GetString(Columns.f_Default);
}
}
virtual public System.Int32 Flags
{
get
{
return this.GetInt32(Columns.f_Flags);
}
}
virtual public System.Boolean IsNullable
{
get
{
return this.GetBool(Columns.f_IsNullable);
}
}
virtual public System.Int32 DataType
{
get
{
return this.GetInt32(Columns.f_DataType);
}
}
virtual public Guid TypeGuid
{
get
{
return this.GetGuid(Columns.f_TypeGuid);
}
}
virtual public System.Int32 CharacterMaxLength
{
get
{
return this.GetInt32(Columns.f_MaxLength);
}
}
virtual public System.Int32 CharacterOctetLength
{
get
{
return this.GetInt32(Columns.f_OctetLength);
}
}
virtual public System.Int32 NumericPrecision
{
get
{
return this.GetInt32(Columns.f_NumericPrecision);
}
}
virtual public System.Int32 NumericScale
{
get
{
return this.GetInt32(Columns.f_NumericScale);
}
}
virtual public System.Int32 DateTimePrecision
{
get
{
return this.GetInt32(Columns.f_DatetimePrecision);
}
}
virtual public string CharacterSetCatalog
{
get
{
return this.GetString(Columns.f_CharSetCatalog);
}
}
virtual public string CharacterSetSchema
{
get
{
return this.GetString(Columns.f_CharSetSchema);
}
}
virtual public string CharacterSetName
{
get
{
return this.GetString(Columns.f_CharSetName);
}
}
virtual public string DomainCatalog
{
get
{
return this.GetString(Columns.f_DomainCatalog);
}
}
virtual public string DomainSchema
{
get
{
return this.GetString(Columns.f_DomainSchema);
}
}
virtual public string DomainName
{
get
{
return this.GetString(Columns.f_DomainName);
}
}
virtual public string Description
{
get
{
return this.GetString(Columns.f_Description);
}
}
virtual public System.Int32 LCID
{
get
{
return this.GetInt32(Columns.f_LCID);
}
}
virtual public System.Int32 CompFlags
{
get
{
return this.GetInt32(Columns.f_CompFlags);
}
}
virtual public System.Int32 SortID
{
get
{
return this.GetInt32(Columns.f_SortID);
}
}
virtual public System.Byte[] TDSCollation
{
get
{
return this.GetByteArray(Columns.f_TDSCollation);
}
}
virtual public System.Boolean IsComputed
{
get
{
return this.GetBool(Columns.f_IsComputed);
}
}
virtual public System.Boolean IsInPrimaryKey
{
get
{
bool isPrimaryKey = false;
if(null != Columns.Table)
{
IColumns keys = Columns.Table.PrimaryKeys;
foreach (IColumn key in keys)
{
if (key != null)
{
if (key.Name == this.Name)
{
isPrimaryKey = true;
break;
}
}
}
}
return isPrimaryKey;
}
}
virtual public System.Boolean IsAutoKey
{
get
{
return this.GetBool(Columns.f_IsAutoKey);
}
}
virtual public string DataTypeName
{
get
{
if(this.dbRoot.DomainOverride)
{
if(this.HasDomain)
{
if(this.Domain != null)
{
return this.Domain.DataTypeName;
}
}
}
return this.GetString(null);
}
}
virtual public string LanguageType
{
get
{
if(this.dbRoot.DomainOverride)
{
if(this.HasDomain)
{
if(this.Domain != null)
{
return this.Domain.LanguageType;
}
}
}
if(dbRoot.LanguageNode != null)
{
string xPath = @"./Type[@From='" + this.DataTypeName + "']";
XmlNode node = dbRoot.LanguageNode.SelectSingleNode(xPath, null);
if(node != null)
{
string languageType = "";
if(this.GetUserData(node, "To", out languageType))
{
return languageType;
}
}
}
return "Unknown";
}
}
virtual public string DbTargetType
{
get
{
if(this.dbRoot.DomainOverride)
{
if(this.HasDomain)
{
if(this.Domain != null)
{
return this.Domain.DbTargetType;
}
}
}
if(dbRoot.DbTargetNode != null)
{
string xPath = @"./Type[@From='" + this.DataTypeName + "']";
XmlNode node = dbRoot.DbTargetNode.SelectSingleNode(xPath, null);
if(node != null)
{
string driverType = "";
if(this.GetUserData(node, "To", out driverType))
{
return driverType;
}
}
}
return "Unknown";
}
}
virtual public string DataTypeNameComplete
{
get
{
if(this.dbRoot.DomainOverride)
{
if(this.HasDomain)
{
if(this.Domain != null)
{
return this.Domain.DataTypeNameComplete;
}
}
}
return "Unknown";
}
}
virtual public System.Boolean IsInForeignKey
{
get
{
if(this.ForeignKeys == Column._emptyForeignKeys)
return true;
else
return this.ForeignKeys.Count > 0 ? true : false;
}
}
virtual public System.Int32 AutoKeySeed
{
get
{
return this.GetInt32(Columns.f_AutoKeySeed);
}
}
virtual public System.Int32 AutoKeyIncrement
{
get
{
return this.GetInt32(Columns.f_AutoKeyIncrement);
}
}
virtual public System.Boolean HasDomain
{
get
{
if(this._row.Table.Columns.Contains("DOMAIN_NAME"))
{
object o = this._row["DOMAIN_NAME"];
if(o != null && o != DBNull.Value)
{
return true;
}
}
return false;
}
}
#endregion
#region Collections
public IForeignKeys ForeignKeys
{
get
{
if(null == _foreignKeys)
{
_foreignKeys = (ForeignKeys)this.dbRoot.ClassFactory.CreateForeignKeys();
_foreignKeys.dbRoot = this.dbRoot;
if(this.Columns.Table != null)
{
IForeignKeys fk = this.Columns.Table.ForeignKeys;
}
}
return _foreignKeys;
}
}
virtual public IPropertyCollection GlobalProperties
{
get
{
Database db = this.Columns.GetDatabase() as Database;
if(null == db._columnProperties)
{
db._columnProperties = new PropertyCollection();
db._columnProperties.Parent = this;
string xPath = this.GlobalUserDataXPath;
XmlNode xmlNode = this.dbRoot.UserData.SelectSingleNode(xPath, null);
if(xmlNode == null)
{
XmlNode parentNode = db.CreateGlobalXmlNode();
xmlNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Column", null);
parentNode.AppendChild(xmlNode);
}
db._columnProperties.LoadAllGlobal(xmlNode);
}
return db._columnProperties;
}
}
virtual public IPropertyCollection AllProperties
{
get
{
if(null == _allProperties)
{
_allProperties = new PropertyCollectionAll();
_allProperties.Load(this.Properties, this.GlobalProperties);
}
return _allProperties;
}
}
protected internal virtual void AddForeignKey(ForeignKey fk)
{
if(null == _foreignKeys)
{
_foreignKeys = (ForeignKeys)this.dbRoot.ClassFactory.CreateForeignKeys();
_foreignKeys.dbRoot = this.dbRoot;
}
this._foreignKeys.AddForeignKey(fk);
}
internal PropertyCollectionAll _allProperties = null;
#endregion
#region XML User Data
[ComVisible(false)]
override public string UserDataXPath
{
get
{
return Columns.UserDataXPath + @"/Column[@p='" + this.Name + "']";
}
}
[ComVisible(false)]
override public string GlobalUserDataXPath
{
get
{
return ((Database)this.Columns.GetDatabase()).GlobalUserDataXPath + "/Column";
}
}
[ComVisible(false)]
override internal bool GetXmlNode(out XmlNode node, bool forceCreate)
{
node = null;
bool success = false;
if(null == _xmlNode)
{
// Get the parent node
XmlNode parentNode = null;
if(this.Columns.GetXmlNode(out parentNode, forceCreate))
{
// See if our user data already exists
string xPath = @"./Column[@p='" + this.Name + "']";
if(!GetUserData(xPath, parentNode, out _xmlNode) && forceCreate)
{
// Create it, and try again
this.CreateUserMetaData(parentNode);
GetUserData(xPath, parentNode, out _xmlNode);
}
}
}
if(null != _xmlNode)
{
node = _xmlNode;
success = true;
}
return success;
}
[ComVisible(false)]
override public void CreateUserMetaData(XmlNode parentNode)
{
XmlNode myNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Column", null);
parentNode.AppendChild(myNode);
XmlAttribute attr;
attr = parentNode.OwnerDocument.CreateAttribute("p");
attr.Value = this.Name;
myNode.Attributes.Append(attr);
attr = parentNode.OwnerDocument.CreateAttribute("n");
attr.Value = "";
myNode.Attributes.Append(attr);
}
#endregion
#region INameValueCollection Members
public string ItemName
{
get
{
return this.Name;
}
}
public string ItemValue
{
get
{
return this.Name;
}
}
#endregion
internal Columns Columns = null;
protected ForeignKeys _foreignKeys = null;
static private ForeignKeys _emptyForeignKeys = new ForeignKeys();
#region IEquatable<IColumn> Members
public bool Equals(IColumn other) {
if (other == null)
return false;
var o = other as Column;
if (o == null)
throw new NotImplementedException();
return this.dbRoot == o.dbRoot
&& this.Columns == o.Columns
&& this._row == o._row;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
/// <summary>
/// A tag span interval tree represents an ordered tree data structure to store tag spans in. It
/// allows you to efficiently find all tag spans that intersect a provided span. Tag spans are
/// tracked. That way you can query for intersecting/overlapping spans in a different snapshot
/// than the one for the tag spans that were added.
/// </summary>
internal partial class TagSpanIntervalTree<TTag> where TTag : ITag
{
private readonly IntervalTree<TagNode> _tree;
private readonly ITextBuffer _textBuffer;
private readonly SpanTrackingMode _spanTrackingMode;
public TagSpanIntervalTree(ITextBuffer textBuffer,
SpanTrackingMode trackingMode,
IEnumerable<ITagSpan<TTag>> values = null)
{
_textBuffer = textBuffer;
_spanTrackingMode = trackingMode;
var nodeValues = values == null
? null
: values.Select(ts => new TagNode(ts, trackingMode));
var introspector = new IntervalIntrospector(textBuffer.CurrentSnapshot);
_tree = IntervalTree.Create(introspector, nodeValues);
}
public ITextBuffer Buffer
{
get
{
return _textBuffer;
}
}
public SpanTrackingMode SpanTrackingMode
{
get
{
return _spanTrackingMode;
}
}
public IList<ITagSpan<TTag>> GetIntersectingSpans(SnapshotSpan snapshotSpan)
{
var snapshot = snapshotSpan.Snapshot;
Contract.Requires(snapshot.TextBuffer == _textBuffer);
var introspector = new IntervalIntrospector(snapshot);
var intersectingIntervals = _tree.GetIntersectingIntervals(snapshotSpan.Start, snapshotSpan.Length, introspector);
List<ITagSpan<TTag>> result = null;
foreach (var tagNode in intersectingIntervals)
{
result = result ?? new List<ITagSpan<TTag>>();
result.Add(new TagSpan<TTag>(tagNode.Span.GetSpan(snapshot), tagNode.Tag));
}
return result ?? SpecializedCollections.EmptyList<ITagSpan<TTag>>();
}
public void GetNonIntersectingSpans(SnapshotSpan snapshotSpan, List<ITagSpan<TTag>> beforeSpans, List<ITagSpan<TTag>> afterSpans)
{
var snapshot = snapshotSpan.Snapshot;
Contract.Requires(snapshot.TextBuffer == _textBuffer);
var introspector = new IntervalIntrospector(snapshot);
var beforeSpan = new SnapshotSpan(snapshot, 0, snapshotSpan.Start);
AddNonIntersectingSpans(beforeSpan, introspector, beforeSpans);
var afterSpan = new SnapshotSpan(snapshot, snapshotSpan.End, snapshot.Length - snapshotSpan.End);
AddNonIntersectingSpans(afterSpan, introspector, afterSpans);
}
private void AddNonIntersectingSpans(
SnapshotSpan span, IntervalIntrospector introspector, List<ITagSpan<TTag>> spans)
{
var snapshot = span.Snapshot;
foreach (var tagNode in _tree.GetIntersectingIntervals(span.Start, span.Length, introspector))
{
var tagNodeSpan = tagNode.Span.GetSpan(snapshot);
if (span.Contains(tagNodeSpan))
{
spans.Add(new TagSpan<TTag>(tagNodeSpan, tagNode.Tag));
}
}
}
public IEnumerable<ITagSpan<TTag>> GetSpans(ITextSnapshot snapshot)
{
return _tree.Select(tn => new TagSpan<TTag>(tn.Span.GetSpan(snapshot), tn.Tag));
}
public bool IsEmpty()
{
return _tree.IsEmpty();
}
public IEnumerable<ITagSpan<TTag>> GetIntersectingTagSpans(NormalizedSnapshotSpanCollection requestedSpans)
{
var result = GetIntersectingTagSpansWorker(requestedSpans);
DebugVerifyTags(requestedSpans, result);
return result;
}
[Conditional("DEBUG")]
private static void DebugVerifyTags(NormalizedSnapshotSpanCollection requestedSpans, IEnumerable<ITagSpan<TTag>> tags)
{
if (tags == null)
{
return;
}
foreach (var tag in tags)
{
var span = tag.Span;
if (!requestedSpans.Any(s => s.IntersectsWith(span)))
{
Contract.Fail(tag + " doesn't intersects with any requested span");
}
}
}
private IEnumerable<ITagSpan<TTag>> GetIntersectingTagSpansWorker(NormalizedSnapshotSpanCollection requestedSpans)
{
const int MaxNumberOfRequestedSpans = 100;
// Special case the case where there is only one requested span. In that case, we don't
// need to allocate any intermediate collections
return requestedSpans.Count == 1
? GetIntersectingSpans(requestedSpans[0])
: requestedSpans.Count < MaxNumberOfRequestedSpans
? GetTagsForSmallNumberOfSpans(requestedSpans)
: GetTagsForLargeNumberOfSpans(requestedSpans);
}
private IEnumerable<ITagSpan<TTag>> GetTagsForSmallNumberOfSpans(NormalizedSnapshotSpanCollection requestedSpans)
{
var result = new List<ITagSpan<TTag>>();
foreach (var s in requestedSpans)
{
result.AddRange(GetIntersectingSpans(s));
}
return result;
}
private IEnumerable<ITagSpan<TTag>> GetTagsForLargeNumberOfSpans(NormalizedSnapshotSpanCollection requestedSpans)
{
// we are asked with bunch of spans. rather than asking same question again and again, ask once with big span
// which will return superset of what we want. and then filter them out in O(m+n) cost.
// m == number of requested spans, n = number of returned spans
var mergedSpan = new SnapshotSpan(requestedSpans[0].Start, requestedSpans[requestedSpans.Count - 1].End);
var result = GetIntersectingSpans(mergedSpan);
int requestIndex = 0;
var enumerator = result.GetEnumerator();
try
{
if (!enumerator.MoveNext())
{
return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>();
}
var hashSet = new HashSet<ITagSpan<TTag>>();
while (true)
{
var currentTag = enumerator.Current;
var currentRequestSpan = requestedSpans[requestIndex];
var currentTagSpan = currentTag.Span;
if (currentRequestSpan.Start > currentTagSpan.End)
{
if (!enumerator.MoveNext())
{
break;
}
}
else if (currentTagSpan.Start > currentRequestSpan.End)
{
requestIndex++;
if (requestIndex >= requestedSpans.Count)
{
break;
}
}
else
{
if (currentTagSpan.Length > 0)
{
hashSet.Add(currentTag);
}
if (!enumerator.MoveNext())
{
break;
}
}
}
return hashSet;
}
finally
{
enumerator.Dispose();
}
}
}
}
| |
/*=================================\
* PlotterControl\Form_Dialog_EditGraph.cs
*
* The Coestaris licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
*
* Created: 27.11.2017 14:04
* Last Edited: 27.11.2017 14:04:46
*=================================*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace CnC_WFA
{
public partial class Form_Dialog_EditGraph : Form
{
public Form_Dialog_EditGraph()
{
InitializeComponent();
}
private Graph Object;
private List<string> GlobalErrors, GlobalErrorsLims, GlobalErrorsPeriod;
private string CurrentCompString;
private DateTime startTime, endTime, startTimePeriod, endTimePeriod;
private string CurrentCompStringLow, CurrentCompStringHigh;
public Form_Graph FormParent { get; internal set; }
private Button[] Buttons;
private Color SelectedButtonColor = Color.FromArgb(5, 92, 199);
private Color DefaultButtonColor = Color.FromArgb(4, 60, 130);
public Form_Dialog_EditGraph(Graph editing)
{
InitializeComponent();
Object = editing;
Text = string.Format(TB.L.Phrase["Form_Graph.Editing"], Object.Name);
}
private void Form_Dialog_EditGraph_Load(object sender, EventArgs e)
{
Buttons = new Button[]
{
button_data,
button_display,
button_markers
};
textBox_name.Text = Object.Name;
if (Object.DataSource.GetType() == typeof(FormulaDataSource))
{
radioButton_data_formula.Checked = true;
var ds = Object.DataSource as FormulaDataSource;
textBox_data_formula_formula.Text = ds.Formula;
textBox_data_formula_start.Text = ds.LowLimFormula;
textBox_data_formula_end.Text = ds.HighLimFormula;
CurrentCompString = ds.Formula;
CurrentCompStringHigh = ds.HighLimFormula;
CurrentCompStringLow = ds.LowLimFormula;
}
comboBox_display_penstyle.Items.AddRange(Enum.GetNames(typeof(PenStyles)));
comboBox_display_penstyle.Text = Object.PStyle.ToString();
checkBox_display_display.Checked = Object.Display;
textBox_display_width.Text = Object.MainPen.Width.ToString();
colorDialog1.Color = Object.MainPen.Color;
checkBox_markers_use.Checked = Object.Markers.Use;
radioButton_markers_period.Checked = Object.Markers.UsePeriodic;
radioButton_markers_inpoints.Checked = !Object.Markers.UsePeriodic;
comboBox_markers_type.Items.AddRange(Enum.GetNames(typeof(MarkerType)));
comboBox_markers_type.Text = Object.Markers.Type.ToString();
colorDialog2.Color = Object.Markers.Color;
textBox_markers_size.Text = Object.Markers.Size.ToString();
checkBox_markers_period.Checked = Object.Markers.AutoLims;
textBox_markers_period.Text = Object.Markers.PeriodFormula;
textBox_markers_period_start.Text = Object.Markers.LowLimFormula;
textBox_markers_period_end.Text = Object.Markers.HighLimFormula;
colorDialog1.Color = Object.MainPen.Color;
SetDisplayColorProbe();
SetMarkerColorProbe();
if (!checkBox_markers_period.Checked)
{
textBox_markers_period_start.Text = textBox_data_formula_start.Text;
textBox_markers_period_end.Text = textBox_data_formula_end.Text;
}
}
private void SetDisplayColorProbe()
{
Bitmap bmp = new Bitmap(50, 50);
using (Graphics gr = Graphics.FromImage(bmp)) gr.FillRectangle(new SolidBrush(colorDialog1.Color), new RectangleF(0, 0, 50, 50));
Image img = pictureBox_display_color.Image;
pictureBox_display_color.Image = bmp;
if (img != null) img.Dispose();
}
private void SetMarkerColorProbe()
{
Bitmap bmp = new Bitmap(50, 50);
using (Graphics gr = Graphics.FromImage(bmp)) gr.FillRectangle(new SolidBrush(colorDialog2.Color), new RectangleF(0, 0, 50, 50));
Image img = pictureBox_markers_color.Image;
pictureBox_markers_color.Image = bmp;
if (img != null) img.Dispose();
}
private void button_data_formula_compile_Click(object sender, EventArgs e)
{
var ds = Object.DataSource as FormulaDataSource;
string LastCompString = ds.Formula;
string LastCompStringLow = ds.LowLimFormula;
string LastCompStringHigh = ds.HighLimFormula;
ds.Formula = CurrentCompString;
ds.HighLimFormula = CurrentCompStringHigh;
ds.LowLimFormula = CurrentCompStringLow;
startTime = DateTime.Now;
GlobalErrors = ds.Compile();
GlobalErrorsLims = ds.CompileRange();
if (GlobalErrorsLims !=null || GlobalErrors != null)
{
panel_data_formula_status.Visible = true;
panel_data_formula_status.BackColor = Color.FromArgb(255, 74, 74);
label_data_formula_status.Text = string.Format(TB.L.Phrase["Form_Dialog_EditElement.FoundErrors"], (GlobalErrors?.Count == null ? 0 : GlobalErrors?.Count) + (GlobalErrorsLims?.Count == null ? 0 : GlobalErrorsLims?.Count));
button_data_formula_status_more.Visible = true;
ds.Formula = LastCompString;
ds.Formula = LastCompString;
ds.LowLimFormula = LastCompStringLow;
ds.HighLimFormula = LastCompStringHigh;
ds.Compile();
ds.CompileRange();
endTime = DateTime.Now;
}
else
{
panel_data_formula_status.Visible = true;
panel_data_formula_status.BackColor = Color.FromArgb(0, 255, 0);
label_data_formula_status.Text = string.Format(TB.L.Phrase["Form_Dialog_EditElement.OKBuiltIn"], (DateTime.Now - startTime).TotalMilliseconds);
button_data_formula_status_more.Visible = false;
Object.ResetPreRender();
if (Object.Markers.UsePeriodic && Object.Markers.AutoLims)
{
Object.Markers.LowLimFormula = ds.LowLimFormula;
Object.Markers.HighLimFormula = ds.HighLimFormula;
textBox_markers_period.Text = Object.Markers.PeriodFormula;
textBox_markers_period_start.Text = Object.Markers.LowLimFormula;
}
}
timer_data_forumla_expire.Enabled = true;
Object.DataSource = ds;
}
private void button_data_formula_status_more_Click(object sender, EventArgs e)
{
var ds = Object.DataSource as FormulaDataSource;
string[] messages = new string[] {
TB.L.Phrase["Form_Graph.Log.1"],
TB.L.Phrase["Form_Graph.Log.2"],
TB.L.Phrase["Form_Graph.Log.3"],
TB.L.Phrase["Form_Graph.Log.4"],
TB.L.Phrase["Form_Graph.Log.5"]
}; ;
string res = "";
res += string.Format(messages[0], startTime, endTime, (endTime - startTime).TotalSeconds, (GlobalErrors?.Count == null ? 0 : GlobalErrors?.Count) + (GlobalErrorsLims?.Count == null ? 0 : GlobalErrorsLims?.Count));
if (GlobalErrors == null) res += messages[1];
else res += string.Format(messages[2], GlobalErrors.Count, CurrentCompString, string.Join("\n", GlobalErrors.Select(p => " - " + p)), ds.Formula);
if (GlobalErrorsLims == null)
{
res += string.Format(messages[3], TB.L.Phrase["Form_Dialog_EditElement.Word.Bottom"], 2);
res += string.Format(messages[3], TB.L.Phrase["Form_Dialog_EditElement.Word.Upper"], 3);
}
else
{
if (GlobalErrorsLims.FindAll(p => p.StartsWith("/")).Count() == 0) res += string.Format(messages[3], TB.L.Phrase["Form_Dialog_EditElement.Word.Bottom"], 2);
else
{
var a = GlobalErrorsLims.FindAll(p => p.StartsWith("/")).ToArray();
res += string.Format(messages[4], a.Length, TB.L.Phrase["Form_Dialog_EditElement.Word.Bottom"], CurrentCompStringLow, string.Join("\n", a.Select(p => " - " + p.Trim('/'))), ds.LowLimFormula, 2);
}
if (GlobalErrorsLims.FindAll(p => p.StartsWith("\\")).Count() == 0) res += string.Format(messages[3], TB.L.Phrase["Form_Dialog_EditElement.Word.Upper"], 3);
else
{
var a = GlobalErrorsLims.FindAll(p => p.StartsWith("\\")).ToArray();
res += string.Format(messages[4], a.Length, TB.L.Phrase["Form_Dialog_EditElement.Word.Upper"], CurrentCompStringLow, string.Join("\n", a.Select(p => " - " + p.Trim('\\'))), ds.HighLimFormula, 3);
}
}
MessageBox.Show(res, TB.L.Phrase["Form_Dialog_EditElement.Report"], MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void timer_data_forumla_expire_Tick(object sender, EventArgs e)
{
timer_data_forumla_expire.Enabled = false;
panel_data_formula_status.Visible = false;
button_data_formula_status_more.Visible = false;
}
private void button_data_formula_expand_Click(object sender, EventArgs e)
{
if (!richTextBox_data_formula_add.Visible)
{
richTextBox_data_formula_add.Visible = true;
richTextBox_data_formula_add.Text = textBox_data_formula_formula.Text;
} else
{
richTextBox_data_formula_add.Visible = false;
textBox_data_formula_formula.Text = richTextBox_data_formula_add.Text;
}
}
private void button4_Click(object sender, EventArgs e) => Close();
private void textBox_name_TextChanged(object sender, EventArgs e)
{
Object.Name = textBox_name.Text;
Text = string.Format(TB.L.Phrase["Form_Graph.Editing"], Object.Name);
}
private void HighLightButton(int index)
{
for (int i = 0; i < Buttons.Length; i++)
Buttons[i].BackColor = i == index ? SelectedButtonColor : DefaultButtonColor;
tabControl_main.SelectedIndex = index;
}
private void Form_Dialog_EditGraph_FormClosing(object sender, FormClosingEventArgs e)
{
if (Object.DataSource.GetType() == typeof(FormulaDataSource))
{
var ds = Object.DataSource as FormulaDataSource;
string res = "";
if (CurrentCompString != ds.Formula) res += string.Format(TB.L.Phrase["Form_Graph.ExitLog.1"], CurrentCompString, ds.Formula);
if (CurrentCompStringHigh != ds.HighLimFormula) res += string.Format(TB.L.Phrase["Form_Graph.ExitLog.2"], CurrentCompStringLow, ds.HighLimFormula);
if (CurrentCompStringLow != ds.LowLimFormula) res += string.Format(TB.L.Phrase["Form_Graph.ExitLog.3"], CurrentCompStringHigh, ds.LowLimFormula);
if (textBox_markers_period.Text != Object.Markers.PeriodFormula) res += string.Format(TB.L.Phrase["Form_Graph.ExitLog.4"], textBox_markers_period.Text, Object.Markers.PeriodFormula);
if (textBox_markers_period_start.Text != Object.Markers.LowLimFormula) res += string.Format(TB.L.Phrase["Form_Graph.ExitLog.5"], textBox_markers_period_start.Text, Object.Markers.LowLimFormula);
if (textBox_markers_period_end.Text != Object.Markers.HighLimFormula) res += string.Format(TB.L.Phrase["Form_Graph.ExitLog.6"], textBox_markers_period_end.Text, Object.Markers.HighLimFormula);
if(res.Length != 0) MessageBox.Show(res, TB.L.Phrase["Form_Graph.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error);
Object.DataSource = ds;
}
Object.MainPen = new Pen(colorDialog1.Color, float.Parse(textBox_display_width.Text));
Object.Display = checkBox_display_display.Checked;
Object.PStyle = (PenStyles)Enum.Parse(typeof(PenStyles), comboBox_display_penstyle.Text);
Object.ResetPreRender();
Object.Markers.GetPoints();
}
private void button_display_color_Click(object sender, EventArgs e)
{
if(colorDialog1.ShowDialog() == DialogResult.OK)
{
SetDisplayColorProbe();
label_display_color_rgb.Text = string.Format(TB.L.Phrase["Form_Dialog_EditElement.RGB"], colorDialog1.Color.R, colorDialog1.Color.G, colorDialog1.Color.B);
}
}
private void checkBox_markers_period_CheckedChanged(object sender, EventArgs e)
{
Object.Markers.AutoLims = checkBox_markers_period.Checked;
textBox_markers_period_start.Enabled = !checkBox_markers_period.Checked;
textBox_markers_period_end.Enabled = !checkBox_markers_period.Checked;
if(!checkBox_markers_period.Checked)
{
textBox_markers_period_start.Text = textBox_data_formula_start.Text;
textBox_markers_period_end.Text = textBox_data_formula_end.Text;
}
}
private void checkBox_markers_use_CheckedChanged(object sender, EventArgs e)
{
Object.Markers.Use = checkBox_markers_use.Checked;
groupBox_markers_display.Enabled = checkBox_markers_use.Checked;
groupBox_markers_params.Enabled = checkBox_markers_use.Checked;
}
private void button_markers_status_Click(object sender, EventArgs e)
{
var periodErrors = GlobalErrorsPeriod.FindAll(p => p.StartsWith("|"));
var highErrors = GlobalErrorsPeriod.FindAll(p => p.StartsWith("\\"));
var lowErrors = GlobalErrorsPeriod.FindAll(p => p.StartsWith("/"));
var ds = Object.DataSource as FormulaDataSource;
string[] messages = new string[] {
TB.L.Phrase["Form_Graph.Log1.1"],
TB.L.Phrase["Form_Graph.Log1.2"],
TB.L.Phrase["Form_Graph.Log1.3"],
TB.L.Phrase["Form_Graph.Log1.4"],
TB.L.Phrase["Form_Graph.Log1.5"]
};
string res = "";
res += string.Format(messages[0], startTimePeriod, endTimePeriod, (endTimePeriod - startTimePeriod).TotalSeconds, GlobalErrorsPeriod.Count);
if (periodErrors.Count == 0) res += messages[1];
else res += string.Format(messages[2], periodErrors.Count, textBox_markers_period.Text, string.Join("\n", periodErrors.Select(p => " - " + p.Trim('|'))), Object.Markers.PeriodFormula);
if (lowErrors.Count == 0) res += string.Format(messages[3], TB.L.Phrase["Form_Dialog_EditElement.Word.Bottom"], 2);
else res += string.Format(messages[4], lowErrors.Count, TB.L.Phrase["Form_Dialog_EditElement.Word.Bottom"], textBox_markers_period_end.Text, string.Join("\n", lowErrors.Select(p => " - " + p.Trim('/'))), Object.Markers.LowLimFormula, 2);
if (highErrors.Count == 0) res += string.Format(messages[3], TB.L.Phrase["Form_Dialog_EditElement.Word.Upper"], 3);
else res += string.Format(messages[4], highErrors.Count, TB.L.Phrase["Form_Dialog_EditElement.Word.Upper"], textBox_markers_period_start.Text, string.Join("\n", highErrors.Select(p => " - " + p.Trim('\\'))), Object.Markers.HighLimFormula, 3);
MessageBox.Show(res, TB.L.Phrase["Form_Dialog_EditElement.Report"], MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void timer_markers_expire_Tick(object sender, EventArgs e)
{
panel_markers_status.Visible = false;
timer_markers_expire.Enabled = false;
}
private void radioButton_markers_period_CheckedChanged(object sender, EventArgs e)
{
groupBox_period.Enabled = radioButton_markers_period.Checked;
groupBox_points.Enabled = !radioButton_markers_period.Checked;
}
private void button_markers_compile_Click(object sender, EventArgs e)
{
startTimePeriod = DateTime.Now;
if (Object.Markers.UsePeriodic)
{
string LowCompString = Object.Markers.LowLimFormula;
string HighCompString = Object.Markers.HighLimFormula;
string PeriodCompString = Object.Markers.PeriodFormula;
Object.Markers.LowLimFormula = textBox_markers_period_start.Text;
Object.Markers.HighLimFormula = textBox_markers_period_end.Text;
Object.Markers.PeriodFormula = textBox_markers_period.Text;
GlobalErrorsPeriod = Object.Markers.CompilePeriod();
if (GlobalErrorsPeriod != null)
{
panel_markers_status.Visible = true;
panel_markers_status.BackColor = Color.FromArgb(255, 74, 74);
label_markers_status.Text = string.Format(TB.L.Phrase["Form_Dialog_EditElement.FoundErrors"], (GlobalErrorsPeriod?.Count == null ? 0 : GlobalErrorsPeriod?.Count));
button_markers_status.Visible = true;
Object.Markers.LowLimFormula = LowCompString;
Object.Markers.HighLimFormula = HighCompString;
Object.Markers.PeriodFormula = PeriodCompString;
Object.Markers.CompilePeriod();
endTimePeriod = DateTime.Now;
}
else
{
panel_markers_status.Visible = true;
panel_markers_status.BackColor = Color.FromArgb(0, 255, 0);
label_markers_status.Text = string.Format(TB.L.Phrase["Form_Dialog_EditElement.OKBuiltIn"], (DateTime.Now - startTimePeriod).TotalMilliseconds);
button_markers_status.Visible = false;
Object.Markers.CompilePeriod();
}
timer_markers_expire.Enabled = true;
}
}
private void button_data_Click(object sender, EventArgs e) => HighLightButton(0);
private void button_display_Click(object sender, EventArgs e) => HighLightButton(1);
private void button_markers_Click(object sender, EventArgs e) => HighLightButton(2);
private void textBox_markers_period_TextChanged(object sender, EventArgs e) => Object.Markers.PeriodFormula = textBox_markers_period.Text;
private void textBox_markers_end_TextChanged(object sender, EventArgs e) => Object.Markers.HighLimFormula = textBox_markers_period_end.Text;
private void textBox_markers_period_start_TextChanged(object sender, EventArgs e) => Object.Markers.LowLimFormula = textBox_markers_period_start.Text;
private void checkBox_display_display_CheckedChanged(object sender, EventArgs e) => groupBox1.Enabled = checkBox_display_display.Checked;
private void textBox_data_formula_start_TextChanged(object sender, EventArgs e) => CurrentCompStringLow = textBox_data_formula_start.Text;
private void textBox_data_formula_end_TextChanged(object sender, EventArgs e) => CurrentCompStringHigh = textBox_data_formula_end.Text;
private void textBox_data_formula_formula_TextChanged(object sender, EventArgs e) => CurrentCompString = textBox_data_formula_formula.Text;
private void richTextBox_data_formula_add_TextChanged(object sender, EventArgs e) => CurrentCompString = richTextBox_data_formula_add.Text;
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Authorization.Roles;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using Abp.Zero;
using Abp.Zero.Configuration;
using Microsoft.AspNet.Identity;
namespace Abp.Authorization.Users
{
/// <summary>
/// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework.
/// </summary>
public abstract class AbpUserManager<TRole, TUser>
: UserManager<TUser, long>,
IDomainService
where TRole : AbpRole<TUser>, new()
where TUser : AbpUser<TUser>
{
protected IUserPermissionStore<TUser> UserPermissionStore
{
get
{
if (!(Store is IUserPermissionStore<TUser>))
{
throw new AbpException("Store is not IUserPermissionStore");
}
return Store as IUserPermissionStore<TUser>;
}
}
public ILocalizationManager LocalizationManager { get; }
public IAbpSession AbpSession { get; set; }
public FeatureDependencyContext FeatureDependencyContext { get; set; }
protected AbpRoleManager<TRole, TUser> RoleManager { get; }
public AbpUserStore<TRole, TUser> AbpStore { get; }
public IMultiTenancyConfig MultiTenancy { get; set; }
private readonly IPermissionManager _permissionManager;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly ICacheManager _cacheManager;
private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
private readonly IOrganizationUnitSettings _organizationUnitSettings;
private readonly ISettingManager _settingManager;
protected AbpUserManager(
AbpUserStore<TRole, TUser> userStore,
AbpRoleManager<TRole, TUser> roleManager,
IPermissionManager permissionManager,
IUnitOfWorkManager unitOfWorkManager,
ICacheManager cacheManager,
IRepository<OrganizationUnit, long> organizationUnitRepository,
IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
IOrganizationUnitSettings organizationUnitSettings,
ILocalizationManager localizationManager,
IdentityEmailMessageService emailService,
ISettingManager settingManager,
IUserTokenProviderAccessor userTokenProviderAccessor)
: base(userStore)
{
AbpStore = userStore;
RoleManager = roleManager;
LocalizationManager = localizationManager;
_settingManager = settingManager;
_permissionManager = permissionManager;
_unitOfWorkManager = unitOfWorkManager;
_cacheManager = cacheManager;
_organizationUnitRepository = organizationUnitRepository;
_userOrganizationUnitRepository = userOrganizationUnitRepository;
_organizationUnitSettings = organizationUnitSettings;
AbpSession = NullAbpSession.Instance;
UserLockoutEnabledByDefault = true;
DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
MaxFailedAccessAttemptsBeforeLockout = 5;
EmailService = emailService;
UserTokenProvider = userTokenProviderAccessor.GetUserTokenProviderOrNull<TUser>();
}
public override async Task<IdentityResult> CreateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
var tenantId = GetCurrentTenantId();
if (tenantId.HasValue && !user.TenantId.HasValue)
{
user.TenantId = tenantId.Value;
}
return await base.CreateAsync(user);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permissionName">Permission name</param>
public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName)
{
return await IsGrantedAsync(
userId,
_permissionManager.GetPermission(permissionName)
);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission)
{
return IsGrantedAsync(user.Id, permission);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permission">Permission</param>
public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission)
{
//Check for multi-tenancy side
if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide()))
{
return false;
}
//Check for depended features
if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant)
{
if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext))
{
return false;
}
}
//Get cached user permissions
var cacheItem = await GetUserPermissionCacheItemAsync(userId);
if (cacheItem == null)
{
return false;
}
//Check for user-specific value
if (cacheItem.GrantedPermissions.Contains(permission.Name))
{
return true;
}
if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
{
return false;
}
//Check for roles
foreach (var roleId in cacheItem.RoleIds)
{
if (await RoleManager.IsGrantedAsync(roleId, permission))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets granted permissions for a user.
/// </summary>
/// <param name="user">Role</param>
/// <returns>List of granted permissions</returns>
public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user)
{
var permissionList = new List<Permission>();
foreach (var permission in _permissionManager.GetAllPermissions())
{
if (await IsGrantedAsync(user.Id, permission))
{
permissionList.Add(permission);
}
}
return permissionList;
}
/// <summary>
/// Sets all granted permissions of a user at once.
/// Prohibits all other permissions.
/// </summary>
/// <param name="user">The user</param>
/// <param name="permissions">Permissions</param>
public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions)
{
var oldPermissions = await GetGrantedPermissionsAsync(user);
var newPermissions = permissions.ToArray();
foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p)))
{
await ProhibitPermissionAsync(user, permission);
}
foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p)))
{
await GrantPermissionAsync(user, permission);
}
}
/// <summary>
/// Prohibits all permissions for a user.
/// </summary>
/// <param name="user">User</param>
public async Task ProhibitAllPermissionsAsync(TUser user)
{
foreach (var permission in _permissionManager.GetAllPermissions())
{
await ProhibitPermissionAsync(user, permission);
}
}
/// <summary>
/// Resets all permission settings for a user.
/// It removes all permission settings for the user.
/// User will have permissions according to his roles.
/// This method does not prohibit all permissions.
/// For that, use <see cref="ProhibitAllPermissionsAsync"/>.
/// </summary>
/// <param name="user">User</param>
public async Task ResetAllPermissionsAsync(TUser user)
{
await UserPermissionStore.RemoveAllPermissionSettingsAsync(user);
}
/// <summary>
/// Grants a permission for a user if not already granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task GrantPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
if (await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
}
/// <summary>
/// Prohibits a permission for a user if it's granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
if (!await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
}
public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
{
return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress);
}
public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
{
return AbpStore.FindAllAsync(login);
}
/// <summary>
/// Gets a user by given id.
/// Throws exception if no user found with given id.
/// </summary>
/// <param name="userId">User id</param>
/// <returns>User</returns>
/// <exception cref="AbpException">Throws exception if no user found with given id</exception>
public virtual async Task<TUser> GetUserByIdAsync(long userId)
{
var user = await FindByIdAsync(userId);
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
return user;
}
public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)
{
var identity = await base.CreateIdentityAsync(user, authenticationType);
if (user.TenantId.HasValue)
{
identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture)));
}
return identity;
}
public async override Task<IdentityResult> UpdateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
//Admin user's username can not be changed!
if (user.UserName != AbpUser<TUser>.AdminUserName)
{
if ((await GetOldUserNameAsync(user.Id)) == AbpUser<TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TUser>.AdminUserName));
}
}
return await base.UpdateAsync(user);
}
public async override Task<IdentityResult> DeleteAsync(TUser user)
{
if (user.UserName == AbpUser<TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TUser>.AdminUserName));
}
return await base.DeleteAsync(user);
}
public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword)
{
var result = await PasswordValidator.ValidateAsync(newPassword);
if (!result.Succeeded)
{
return result;
}
await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword));
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
{
var user = (await FindByNameAsync(userName));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateUserName"), userName));
}
user = (await FindByEmailAsync(emailAddress));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress));
}
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames)
{
//Remove from removed roles
foreach (var userRole in user.Roles.ToList())
{
var role = await RoleManager.FindByIdAsync(userRole.RoleId);
if (roleNames.All(roleName => role.Name != roleName))
{
var result = await RemoveFromRoleAsync(user.Id, role.Name);
if (!result.Succeeded)
{
return result;
}
}
}
//Add to added roles
foreach (var roleName in roleNames)
{
var role = await RoleManager.GetRoleByNameAsync(roleName);
if (user.Roles.All(ur => ur.RoleId != role.Id))
{
var result = await AddToRoleAsync(user.Id, roleName);
if (!result.Succeeded)
{
return result;
}
}
}
return IdentityResult.Success;
}
public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId)
{
return await IsInOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
return await _userOrganizationUnitRepository.CountAsync(uou =>
uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id
) > 0;
}
public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId)
{
await AddToOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
var currentOus = await GetOrganizationUnitsAsync(user);
if (currentOus.Any(cou => cou.Id == ou.Id))
{
return;
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1);
await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id));
}
public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId)
{
await RemoveFromOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id);
}
public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds)
{
await SetOrganizationUnitsAsync(
await GetUserByIdAsync(userId),
organizationUnitIds
);
}
private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount)
{
var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId);
if (requestedCount > maxCount)
{
throw new AbpException(string.Format("Can not set more than {0} organization unit for a user!", maxCount));
}
}
public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds)
{
if (organizationUnitIds == null)
{
organizationUnitIds = new long[0];
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length);
var currentOus = await GetOrganizationUnitsAsync(user);
//Remove from removed OUs
foreach (var currentOu in currentOus)
{
if (!organizationUnitIds.Contains(currentOu.Id))
{
await RemoveFromOrganizationUnitAsync(user, currentOu);
}
}
//Add to added OUs
foreach (var organizationUnitId in organizationUnitIds)
{
if (currentOus.All(ou => ou.Id != organizationUnitId))
{
await AddToOrganizationUnitAsync(
user,
await _organizationUnitRepository.GetAsync(organizationUnitId)
);
}
}
}
[UnitOfWork]
public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where uou.UserId == user.Id
select ou;
return Task.FromResult(query.ToList());
}
[UnitOfWork]
public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false)
{
if (!includeChildren)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
where uou.OrganizationUnitId == organizationUnit.Id
select user;
return Task.FromResult(query.ToList());
}
else
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where ou.Code.StartsWith(organizationUnit.Code)
select user;
return Task.FromResult(query.ToList());
}
}
public virtual void RegisterTwoFactorProviders(int? tenantId)
{
TwoFactorProviders.Clear();
if (!IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, tenantId))
{
return;
}
if (EmailService != null &&
IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, tenantId))
{
RegisterTwoFactorProvider(
L("Email"),
new EmailTokenProvider<TUser, long>
{
Subject = L("EmailSecurityCodeSubject"),
BodyFormat = L("EmailSecurityCodeBody")
}
);
}
if (SmsService != null &&
IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, tenantId))
{
RegisterTwoFactorProvider(
L("Sms"),
new PhoneNumberTokenProvider<TUser, long>
{
MessageFormat = L("SmsSecurityCodeMessage")
}
);
}
}
public virtual void InitializeLockoutSettings(int? tenantId)
{
UserLockoutEnabledByDefault = IsTrue(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId);
DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId));
MaxFailedAccessAttemptsBeforeLockout = GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId);
}
public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(long userId)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.GetValidTwoFactorProvidersAsync(userId);
}
public override async Task<IdentityResult> NotifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.NotifyTwoFactorTokenAsync(userId, twoFactorProvider, token);
}
public override async Task<string> GenerateTwoFactorTokenAsync(long userId, string twoFactorProvider)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.GenerateTwoFactorTokenAsync(userId, twoFactorProvider);
}
public override async Task<bool> VerifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.VerifyTwoFactorTokenAsync(userId, twoFactorProvider, token);
}
protected virtual Task<string> GetOldUserNameAsync(long userId)
{
return AbpStore.GetUserNameFromDatabaseAsync(userId);
}
private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId)
{
var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0);
return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () =>
{
var user = await FindByIdAsync(userId);
if (user == null)
{
return null;
}
var newCacheItem = new UserPermissionCacheItem(userId);
foreach (var roleName in await GetRolesAsync(userId))
{
newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id);
}
foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId))
{
if (permissionInfo.IsGranted)
{
newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
}
else
{
newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
}
}
return newCacheItem;
});
}
private bool IsTrue(string settingName, int? tenantId)
{
return GetSettingValue<bool>(settingName, tenantId);
}
private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct
{
return tenantId == null
? _settingManager.GetSettingValueForApplication<T>(settingName)
: _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value);
}
private string L(string name)
{
return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
}
private int? GetCurrentTenantId()
{
if (_unitOfWorkManager.Current != null)
{
return _unitOfWorkManager.Current.GetTenantId();
}
return AbpSession.TenantId;
}
private MultiTenancySides GetCurrentMultiTenancySide()
{
if (_unitOfWorkManager.Current != null)
{
return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue
? MultiTenancySides.Host
: MultiTenancySides.Tenant;
}
return AbpSession.MultiTenancySide;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal abstract class CType : ITypeOrNamespace
{
private TypeKind _typeKind;
private Name _pName;
private bool _fHasErrors; // Whether anyituents have errors. This is immutable.
private bool _fUnres; // Whether anyituents are unresolved. This is immutable.
private bool _isBogus; // can't be used in our language -- unsupported type(s)
private bool _checkedBogus; // Have we checked a method args/return for bogus types
// Is and As methods.
public AggregateType AsAggregateType() { return this as AggregateType; }
public ErrorType AsErrorType() { return this as ErrorType; }
public ArrayType AsArrayType() { return this as ArrayType; }
public PointerType AsPointerType() { return this as PointerType; }
public ParameterModifierType AsParameterModifierType() { return this as ParameterModifierType; }
public NullableType AsNullableType() { return this as NullableType; }
public TypeParameterType AsTypeParameterType() { return this as TypeParameterType; }
public bool IsAggregateType() { return this is AggregateType; }
public bool IsVoidType() { return this is VoidType; }
public bool IsNullType() { return this is NullType; }
public bool IsOpenTypePlaceholderType() { return this is OpenTypePlaceholderType; }
public bool IsBoundLambdaType() { return this is BoundLambdaType; }
public bool IsMethodGroupType() { return this is MethodGroupType; }
public bool IsErrorType() { return this is ErrorType; }
public bool IsArrayType() { return this is ArrayType; }
public bool IsPointerType() { return this is PointerType; }
public bool IsParameterModifierType() { return this is ParameterModifierType; }
public bool IsNullableType() { return this is NullableType; }
public bool IsTypeParameterType() { return this is TypeParameterType; }
public bool IsWindowsRuntimeType()
{
return (AssociatedSystemType.Attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime;
}
public bool IsCollectionType()
{
if ((AssociatedSystemType.IsGenericType &&
(AssociatedSystemType.GetGenericTypeDefinition() == typeof(IList<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(ICollection<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IEnumerable<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IReadOnlyList<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IReadOnlyCollection<>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IDictionary<,>) ||
AssociatedSystemType.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>))) ||
AssociatedSystemType == typeof(System.Collections.IList) ||
AssociatedSystemType == typeof(System.Collections.ICollection) ||
AssociatedSystemType == typeof(System.Collections.IEnumerable) ||
AssociatedSystemType == typeof(System.Collections.Specialized.INotifyCollectionChanged) ||
AssociatedSystemType == typeof(System.ComponentModel.INotifyPropertyChanged))
{
return true;
}
return false;
}
// API similar to System.Type
public bool IsGenericParameter
{
get { return IsTypeParameterType(); }
}
private Type _associatedSystemType;
public Type AssociatedSystemType
{
get
{
if (_associatedSystemType == null)
{
_associatedSystemType = CalculateAssociatedSystemType(this);
}
return _associatedSystemType;
}
}
private static Type CalculateAssociatedSystemType(CType src)
{
Type result = null;
switch (src.GetTypeKind())
{
case TypeKind.TK_ArrayType:
ArrayType a = src.AsArrayType();
Type elementType = a.GetElementType().AssociatedSystemType;
if (a.rank == 1)
{
result = elementType.MakeArrayType();
}
else
{
result = elementType.MakeArrayType(a.rank);
}
break;
case TypeKind.TK_NullableType:
NullableType n = src.AsNullableType();
Type underlyingType = n.GetUnderlyingType().AssociatedSystemType;
result = typeof(Nullable<>).MakeGenericType(underlyingType);
break;
case TypeKind.TK_PointerType:
PointerType p = src.AsPointerType();
Type referentType = p.GetReferentType().AssociatedSystemType;
result = referentType.MakePointerType();
break;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType r = src.AsParameterModifierType();
Type parameterType = r.GetParameterType().AssociatedSystemType;
result = parameterType.MakeByRefType();
break;
case TypeKind.TK_AggregateType:
result = CalculateAssociatedSystemTypeForAggregate(src.AsAggregateType());
break;
case TypeKind.TK_TypeParameterType:
TypeParameterType t = src.AsTypeParameterType();
if (t.IsMethodTypeParameter())
{
MethodInfo meth = t.GetOwningSymbol().AsMethodSymbol().AssociatedMemberInfo as MethodInfo;
result = meth.GetGenericArguments()[t.GetIndexInOwnParameters()];
}
else
{
Type parentType = t.GetOwningSymbol().AsAggregateSymbol().AssociatedSystemType;
result = parentType.GetGenericArguments()[t.GetIndexInOwnParameters()];
}
break;
case TypeKind.TK_ArgumentListType:
case TypeKind.TK_BoundLambdaType:
case TypeKind.TK_ErrorType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_NaturalIntegerType:
case TypeKind.TK_NullType:
case TypeKind.TK_OpenTypePlaceholderType:
case TypeKind.TK_UnboundLambdaType:
case TypeKind.TK_VoidType:
default:
break;
}
Debug.Assert(result != null || src.GetTypeKind() == TypeKind.TK_AggregateType);
return result;
}
private static Type CalculateAssociatedSystemTypeForAggregate(AggregateType aggtype)
{
AggregateSymbol agg = aggtype.GetOwningAggregate();
TypeArray typeArgs = aggtype.GetTypeArgsAll();
List<Type> list = new List<Type>();
// Get each type arg.
for (int i = 0; i < typeArgs.size; i++)
{
// Unnamed type parameter types are just placeholders.
if (typeArgs.Item(i).IsTypeParameterType() && typeArgs.Item(i).AsTypeParameterType().GetTypeParameterSymbol().name == null)
{
return null;
}
list.Add(typeArgs.Item(i).AssociatedSystemType);
}
Type[] systemTypeArgs = list.ToArray();
Type uninstantiatedType = agg.AssociatedSystemType;
if (uninstantiatedType.IsGenericType)
{
try
{
return uninstantiatedType.MakeGenericType(systemTypeArgs);
}
catch (ArgumentException)
{
// If the constraints don't work, just return the type without substituting it.
return uninstantiatedType;
}
}
return uninstantiatedType;
}
// ITypeOrNamespace
public bool IsType() { return true; }
public bool IsNamespace() { return false; }
public AssemblyQualifiedNamespaceSymbol AsNamespace() { throw Error.InternalCompilerError(); }
public CType AsType() { return this; }
public TypeKind GetTypeKind() { return _typeKind; }
public void SetTypeKind(TypeKind kind) { _typeKind = kind; }
public Name GetName() { return _pName; }
public void SetName(Name pName) { _pName = pName; }
public bool checkBogus() { return _isBogus; }
public bool getBogus() { return _isBogus; }
public bool hasBogus() { return _checkedBogus; }
public void setBogus(bool isBogus)
{
_isBogus = isBogus;
_checkedBogus = true;
}
public bool computeCurrentBogusState()
{
if (hasBogus())
{
return checkBogus();
}
bool fBogus = false;
switch (GetTypeKind())
{
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
if (GetBaseOrParameterOrElementType() != null)
{
fBogus = GetBaseOrParameterOrElementType().computeCurrentBogusState();
}
break;
case TypeKind.TK_ErrorType:
setBogus(false);
break;
case TypeKind.TK_AggregateType:
fBogus = AsAggregateType().getAggregate().computeCurrentBogusState();
for (int i = 0; !fBogus && i < AsAggregateType().GetTypeArgsAll().size; i++)
{
fBogus |= AsAggregateType().GetTypeArgsAll().Item(i).computeCurrentBogusState();
}
break;
case TypeKind.TK_TypeParameterType:
case TypeKind.TK_VoidType:
case TypeKind.TK_NullType:
case TypeKind.TK_OpenTypePlaceholderType:
case TypeKind.TK_ArgumentListType:
case TypeKind.TK_NaturalIntegerType:
setBogus(false);
break;
default:
throw Error.InternalCompilerError();
//setBogus(false);
//break;
}
if (fBogus)
{
// Only set this if at least 1 declared thing is bogus
setBogus(fBogus);
}
return hasBogus() && checkBogus();
}
// This call switches on the kind and dispatches accordingly. This should really only be
// used when dereferencing TypeArrays. We should consider refactoring our code to not
// need this type of thing - strongly typed handling of TypeArrays would be much better.
public CType GetBaseOrParameterOrElementType()
{
switch (GetTypeKind())
{
case TypeKind.TK_ArrayType:
return AsArrayType().GetElementType();
case TypeKind.TK_PointerType:
return AsPointerType().GetReferentType();
case TypeKind.TK_ParameterModifierType:
return AsParameterModifierType().GetParameterType();
case TypeKind.TK_NullableType:
return AsNullableType().GetUnderlyingType();
default:
return null;
}
}
public void InitFromParent()
{
Debug.Assert(!IsAggregateType());
CType typePar = null;
if (IsErrorType())
{
typePar = AsErrorType().GetTypeParent();
}
else
{
typePar = GetBaseOrParameterOrElementType();
}
_fHasErrors = typePar.HasErrors();
_fUnres = typePar.IsUnresolved();
#if CSEE
this.typeRes = this;
if (!this.fUnres)
this.tsRes = ktsImportMax;
this.fDirty = typePar.fDirty;
this.tsDirty = typePar.tsDirty;
#endif // CSEE
}
public bool HasErrors()
{
return _fHasErrors;
}
public void SetErrors(bool fHasErrors)
{
_fHasErrors = fHasErrors;
}
public bool IsUnresolved()
{
return _fUnres;
}
public void SetUnresolved(bool fUnres)
{
_fUnres = fUnres;
}
////////////////////////////////////////////////////////////////////////////////
// Given a symbol, determine its fundamental type. This is the type that
// indicate how the item is stored and what instructions are used to reference
// if. The fundamental types are:
// one of the integral/float types (includes enums with that underlying type)
// reference type
// struct/value type
public FUNDTYPE fundType()
{
switch (GetTypeKind())
{
case TypeKind.TK_AggregateType:
{
AggregateSymbol sym = AsAggregateType().getAggregate();
// Treat enums like their underlying types.
if (sym.IsEnum())
{
sym = sym.GetUnderlyingType().getAggregate();
}
if (sym.IsStruct())
{
// Struct type could be predefined (int, long, etc.) or some other struct.
if (sym.IsPredefined())
return PredefinedTypeFacts.GetFundType(sym.GetPredefType());
return FUNDTYPE.FT_STRUCT;
}
return FUNDTYPE.FT_REF; // Interfaces, classes, delegates are reference types.
}
case TypeKind.TK_TypeParameterType:
return FUNDTYPE.FT_VAR;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullType:
return FUNDTYPE.FT_REF;
case TypeKind.TK_PointerType:
return FUNDTYPE.FT_PTR;
case TypeKind.TK_NullableType:
return FUNDTYPE.FT_STRUCT;
default:
return FUNDTYPE.FT_NONE;
}
}
public ConstValKind constValKind()
{
if (isPointerLike())
{
return ConstValKind.IntPtr;
}
switch (fundType())
{
case FUNDTYPE.FT_I8:
case FUNDTYPE.FT_U8:
return ConstValKind.Long;
case FUNDTYPE.FT_STRUCT:
// Here we can either have a decimal type, or an enum
// whose fundamental type is decimal.
Debug.Assert((getAggregate().IsEnum() && getAggregate().GetUnderlyingType().getPredefType() == PredefinedType.PT_DECIMAL)
|| (isPredefined() && getPredefType() == PredefinedType.PT_DATETIME)
|| (isPredefined() && getPredefType() == PredefinedType.PT_DECIMAL));
if (isPredefined() && getPredefType() == PredefinedType.PT_DATETIME)
{
return ConstValKind.Long;
}
return ConstValKind.Decimal;
case FUNDTYPE.FT_REF:
if (isPredefined() && getPredefType() == PredefinedType.PT_STRING)
{
return ConstValKind.String;
}
else
{
return ConstValKind.IntPtr;
}
case FUNDTYPE.FT_R4:
return ConstValKind.Float;
case FUNDTYPE.FT_R8:
return ConstValKind.Double;
case FUNDTYPE.FT_I1:
return ConstValKind.Boolean;
default:
return ConstValKind.Int;
}
}
public CType underlyingType()
{
if (IsAggregateType() && getAggregate().IsEnum())
return getAggregate().GetUnderlyingType();
return this;
}
////////////////////////////////////////////////////////////////////////////////
// Strips off ArrayType, ParameterModifierType, PointerType, PinnedType and optionally NullableType
// and returns the result.
public CType GetNakedType(bool fStripNub)
{
for (CType type = this; ;)
{
switch (type.GetTypeKind())
{
default:
return type;
case TypeKind.TK_NullableType:
if (!fStripNub)
return type;
type = type.GetBaseOrParameterOrElementType();
break;
case TypeKind.TK_ArrayType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
break;
}
}
}
public AggregateSymbol GetNakedAgg()
{
return GetNakedAgg(false);
}
private AggregateSymbol GetNakedAgg(bool fStripNub)
{
CType type = GetNakedType(fStripNub);
if (type != null && type.IsAggregateType())
return type.AsAggregateType().getAggregate();
return null;
}
public AggregateSymbol getAggregate()
{
Debug.Assert(IsAggregateType());
return AsAggregateType().GetOwningAggregate();
}
public CType StripNubs()
{
CType type;
for (type = this; type.IsNullableType(); type = type.AsNullableType().GetUnderlyingType())
;
return type;
}
public CType StripNubs(out int pcnub)
{
pcnub = 0;
CType type;
for (type = this; type.IsNullableType(); type = type.AsNullableType().GetUnderlyingType())
(pcnub)++;
return type;
}
public bool isDelegateType()
{
return (IsAggregateType() && getAggregate().IsDelegate());
}
////////////////////////////////////////////////////////////////////////////////
// A few types are considered "simple" types for purposes of conversions and so
// on. They are the fundamental types the compiler knows about for operators and
// conversions.
public bool isSimpleType()
{
return (isPredefined() &&
PredefinedTypeFacts.IsSimpleType(getPredefType()));
}
public bool isSimpleOrEnum()
{
return isSimpleType() || isEnumType();
}
public bool isSimpleOrEnumOrString()
{
return isSimpleType() || isPredefType(PredefinedType.PT_STRING) || isEnumType();
}
private bool isPointerLike()
{
return IsPointerType() || isPredefType(PredefinedType.PT_INTPTR) || isPredefType(PredefinedType.PT_UINTPTR);
}
////////////////////////////////////////////////////////////////////////////////
// A few types are considered "numeric" types. They are the fundamental number
// types the compiler knows about for operators and conversions.
public bool isNumericType()
{
return (isPredefined() &&
PredefinedTypeFacts.IsNumericType(getPredefType()));
}
public bool isStructOrEnum()
{
return (IsAggregateType() && (getAggregate().IsStruct() || getAggregate().IsEnum())) || IsNullableType();
}
public bool isStructType()
{
return IsAggregateType() && getAggregate().IsStruct() || IsNullableType();
}
public bool isEnumType()
{
return (IsAggregateType() && getAggregate().IsEnum());
}
public bool isInterfaceType()
{
return (IsAggregateType() && getAggregate().IsInterface());
}
public bool isClassType()
{
return (IsAggregateType() && getAggregate().IsClass());
}
public AggregateType underlyingEnumType()
{
Debug.Assert(isEnumType());
return getAggregate().GetUnderlyingType();
}
public bool isUnsigned()
{
if (IsAggregateType())
{
AggregateType sym = AsAggregateType();
if (sym.isEnumType())
{
sym = sym.underlyingEnumType();
}
if (sym.isPredefined())
{
PredefinedType pt = sym.getPredefType();
return pt == PredefinedType.PT_UINTPTR || pt == PredefinedType.PT_BYTE || (pt >= PredefinedType.PT_USHORT && pt <= PredefinedType.PT_ULONG);
}
else
{
return false;
}
}
else
{
return IsPointerType();
}
}
public bool isUnsafe()
{
// Pointer types are the only unsafe types.
// Note that generics may not be instantiated with pointer types
return (this != null && (IsPointerType() || (IsArrayType() && AsArrayType().GetElementType().isUnsafe())));
}
public bool isPredefType(PredefinedType pt)
{
if (IsAggregateType())
return AsAggregateType().getAggregate().IsPredefined() && AsAggregateType().getAggregate().GetPredefType() == pt;
return (IsVoidType() && pt == PredefinedType.PT_VOID);
}
public bool isPredefined()
{
return IsAggregateType() && getAggregate().IsPredefined();
}
public PredefinedType getPredefType()
{
//ASSERT(isPredefined());
return getAggregate().GetPredefType();
}
////////////////////////////////////////////////////////////////////////////////
// Is this type System.TypedReference or System.ArgIterator?
// (used for errors because these types can't go certain places)
public bool isSpecialByRefType()
{
// ArgIterator, TypedReference and RuntimeArgumentHandle are not supported.
return false;
}
public bool isStaticClass()
{
AggregateSymbol agg = GetNakedAgg(false);
if (agg == null)
return false;
if (!agg.IsStatic())
return false;
return true;
}
public bool computeManagedType(SymbolLoader symbolLoader)
{
if (IsVoidType())
return false;
switch (fundType())
{
case FUNDTYPE.FT_NONE:
case FUNDTYPE.FT_REF:
case FUNDTYPE.FT_VAR:
return true;
case FUNDTYPE.FT_STRUCT:
if (IsNullableType())
{
return true;
}
else
{
AggregateSymbol aggT = getAggregate();
// See if we already know.
if (aggT.IsKnownManagedStructStatus())
{
return aggT.IsManagedStruct();
}
// Generics are always managed.
if (aggT.GetTypeVarsAll().size > 0)
{
aggT.SetManagedStruct(true);
return true;
}
// If the struct layout has an error, don't recurse its children.
if (aggT.IsLayoutError())
{
aggT.SetUnmanagedStruct(true);
return false;
}
// at this point we can only determine the managed status
// if we have members defined, otherwise we don't know the result
if (symbolLoader != null)
{
for (Symbol ps = aggT.firstChild; ps != null; ps = ps.nextChild)
{
if (ps.IsFieldSymbol() && !ps.AsFieldSymbol().isStatic)
{
CType type = ps.AsFieldSymbol().GetType();
if (type.computeManagedType(symbolLoader))
{
aggT.SetManagedStruct(true);
return true;
}
}
}
aggT.SetUnmanagedStruct(true);
}
return false;
}
default:
return false;
}
}
public CType GetDelegateTypeOfPossibleExpression()
{
if (isPredefType(PredefinedType.PT_G_EXPRESSION))
{
return AsAggregateType().GetTypeArgsThis().Item(0);
}
return this;
}
// These check for AGGTYPESYMs, TYVARSYMs and others as appropriate.
public bool IsValType()
{
switch (GetTypeKind())
{
case TypeKind.TK_TypeParameterType:
return AsTypeParameterType().IsValueType();
case TypeKind.TK_AggregateType:
return AsAggregateType().getAggregate().IsValueType();
case TypeKind.TK_NullableType:
return true;
default:
return false;
}
}
public bool IsNonNubValType()
{
switch (GetTypeKind())
{
case TypeKind.TK_TypeParameterType:
return AsTypeParameterType().IsNonNullableValueType();
case TypeKind.TK_AggregateType:
return AsAggregateType().getAggregate().IsValueType();
case TypeKind.TK_NullableType:
return false;
default:
return false;
}
}
public bool IsRefType()
{
switch (GetTypeKind())
{
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullType:
return true;
case TypeKind.TK_TypeParameterType:
return AsTypeParameterType().IsReferenceType();
case TypeKind.TK_AggregateType:
return AsAggregateType().getAggregate().IsRefType();
default:
return false;
}
}
// A few types can be the same pointer value and not actually
// be equivalent or convertible (like ANONMETHSYMs)
public bool IsNeverSameType()
{
return IsBoundLambdaType() || IsMethodGroupType() || (IsErrorType() && !AsErrorType().HasParent());
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="VB6.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.VisualStudio
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.Build.Framework;
using MSBuild.ExtensionPack.VisualStudio.Extended;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>Build</i> (<b>Required: </b> Projects <b>Optional: </b>VB6Path, StopOnError)</para>
/// <para><b>Remote Execution Support:</b> NA</para>
/// <para/>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <ItemGroup>
/// <ProjectsToBuild Include="C:\MyVB6Project.vbp">
/// <OutDir>c:\output</OutDir>
/// <!-- Note the special use of ChgPropVBP metadata to change project properties at Build Time -->
/// <ChgPropVBP>RevisionVer=4;CompatibleMode="0"</ChgPropVBP>
/// </ProjectsToBuild>
/// <ProjectsToBuild Include="C:\MyVB6Project2.vbp"/>
/// </ItemGroup>
/// <Target Name="Default">
/// <!-- Build a collection of VB6 projects -->
/// <MSBuild.ExtensionPack.VisualStudio.VB6 TaskAction="Build" Projects="@(ProjectsToBuild)"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class VB6 : BaseTask
{
private const char Separator = ';';
/// <summary>
/// Sets the VB6Path. Default is [Program Files]\Microsoft Visual Studio\VB98\VB6.exe
/// </summary>
public string VB6Path { get; set; }
/// <summary>
/// Set to true to stop processing when a project in the Projects collection fails to compile. Default is false.
/// </summary>
public bool StopOnError { get; set; }
/// <summary>
/// Sets the projects. Use an 'OutDir' metadata item to specify the output directory. The OutDir will be created if it does not exist.
/// </summary>
[Required]
public ITaskItem[] Projects { get; set; }
protected override void InternalExecute()
{
if (!this.TargetingLocalMachine())
{
return;
}
if (string.IsNullOrEmpty(this.VB6Path))
{
string programFilePath = Environment.GetEnvironmentVariable("ProgramFiles");
if (string.IsNullOrEmpty(programFilePath))
{
Log.LogError("Failed to read a value from the ProgramFiles Environment Variable");
return;
}
if (File.Exists(programFilePath + @"\Microsoft Visual Studio\VB98\VB6.exe"))
{
this.VB6Path = programFilePath + @"\Microsoft Visual Studio\VB98\VB6.exe";
}
else
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "VB6.exe was not found in the default location. Use VB6Path to specify it. Searched at: {0}", programFilePath + @"\Microsoft Visual Studio\VB98\VB6.exe"));
return;
}
}
switch (this.TaskAction)
{
case "Build":
this.Build();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void Build()
{
if (this.Projects == null)
{
Log.LogError("The collection passed to Projects is empty");
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Building Projects Collection: {0} projects", this.Projects.Length));
if (this.Projects.Any(project => !this.BuildProject(project) && this.StopOnError))
{
this.LogTaskMessage("BuildVB6 Task Execution Failed [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "] Stopped by StopOnError set on true");
return;
}
this.LogTaskMessage("BuildVB6 Task Execution Completed [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "]");
}
private bool BuildProject(ITaskItem project)
{
using (Process proc = new Process())
{
// start changing properties
if (!string.IsNullOrEmpty(project.GetMetadata("ChgPropVBP")))
{
this.LogTaskMessage("START - Changing Properties VBP");
VBPProject projectVBP = new VBPProject(project.ItemSpec);
if (projectVBP.Load())
{
string[] linesProperty = project.GetMetadata("ChgPropVBP").Split(Separator);
string[] keyProperty = new string[linesProperty.Length];
string[] valueProperty = new string[linesProperty.Length];
int index;
for (index = 0; index <= linesProperty.Length - 1; index++)
{
if (linesProperty[index].IndexOf("=", StringComparison.OrdinalIgnoreCase) != -1)
{
keyProperty[index] = linesProperty[index].Substring(0, linesProperty[index].IndexOf("=", StringComparison.OrdinalIgnoreCase));
valueProperty[index] = linesProperty[index].Substring(linesProperty[index].IndexOf("=", StringComparison.OrdinalIgnoreCase) + 1);
}
if (!string.IsNullOrEmpty(keyProperty[index]) && !string.IsNullOrEmpty(valueProperty[index]))
{
this.LogTaskMessage(keyProperty[index] + " -> New value: " + valueProperty[index]);
projectVBP.SetProjectProperty(keyProperty[index], valueProperty[index], false);
}
}
projectVBP.Save();
}
this.LogTaskMessage("END - Changing Properties VBP");
}
// end changing properties
proc.StartInfo.FileName = this.VB6Path;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
if (string.IsNullOrEmpty(project.GetMetadata("OutDir")))
{
proc.StartInfo.Arguments = @"/MAKE /OUT " + @"""" + project.ItemSpec + ".log" + @""" " + @"""" + project.ItemSpec + @"""";
}
else
{
if (!Directory.Exists(project.GetMetadata("OutDir")))
{
Directory.CreateDirectory(project.GetMetadata("OutDir"));
}
proc.StartInfo.Arguments = @"/MAKE /OUT " + @"""" + project.ItemSpec + ".log" + @""" " + @"""" + project.ItemSpec + @"""" + " /outdir " + @"""" + project.GetMetadata("OutDir") + @"""";
}
// start the process
this.LogTaskMessage("Running " + proc.StartInfo.FileName + " " + proc.StartInfo.Arguments);
proc.Start();
string outputStream = proc.StandardOutput.ReadToEnd();
if (outputStream.Length > 0)
{
this.LogTaskMessage(outputStream);
}
string errorStream = proc.StandardError.ReadToEnd();
if (errorStream.Length > 0)
{
Log.LogError(errorStream);
}
proc.WaitForExit();
if (proc.ExitCode != 0)
{
Log.LogError("Non-zero exit code from VB6.exe: " + proc.ExitCode);
try
{
using (FileStream myStreamFile = new FileStream(project.ItemSpec + ".log", FileMode.Open))
{
System.IO.StreamReader myStream = new System.IO.StreamReader(myStreamFile);
string myBuffer = myStream.ReadToEnd();
Log.LogError(myBuffer);
}
}
catch (Exception ex)
{
Log.LogError(string.Format(CultureInfo.CurrentUICulture, "Unable to open log file: '{0}'. Exception: {1}", project.ItemSpec + ".log", ex.Message));
}
return false;
}
return true;
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the RisComiteEtica class.
/// </summary>
[Serializable]
public partial class RisComiteEticaCollection : ActiveList<RisComiteEtica, RisComiteEticaCollection>
{
public RisComiteEticaCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>RisComiteEticaCollection</returns>
public RisComiteEticaCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
RisComiteEtica o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the RIS_ComiteEtica table.
/// </summary>
[Serializable]
public partial class RisComiteEtica : ActiveRecord<RisComiteEtica>, IActiveRecord
{
#region .ctors and Default Settings
public RisComiteEtica()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public RisComiteEtica(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public RisComiteEtica(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public RisComiteEtica(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("RIS_ComiteEtica", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdComiteEtica = new TableSchema.TableColumn(schema);
colvarIdComiteEtica.ColumnName = "idComiteEtica";
colvarIdComiteEtica.DataType = DbType.Int32;
colvarIdComiteEtica.MaxLength = 0;
colvarIdComiteEtica.AutoIncrement = true;
colvarIdComiteEtica.IsNullable = false;
colvarIdComiteEtica.IsPrimaryKey = true;
colvarIdComiteEtica.IsForeignKey = false;
colvarIdComiteEtica.IsReadOnly = false;
colvarIdComiteEtica.DefaultSetting = @"";
colvarIdComiteEtica.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdComiteEtica);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.AnsiString;
colvarDescripcion.MaxLength = 100;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = false;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("RIS_ComiteEtica",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdComiteEtica")]
[Bindable(true)]
public int IdComiteEtica
{
get { return GetColumnValue<int>(Columns.IdComiteEtica); }
set { SetColumnValue(Columns.IdComiteEtica, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varDescripcion)
{
RisComiteEtica item = new RisComiteEtica();
item.Descripcion = varDescripcion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdComiteEtica,string varDescripcion)
{
RisComiteEtica item = new RisComiteEtica();
item.IdComiteEtica = varIdComiteEtica;
item.Descripcion = varDescripcion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdComiteEticaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdComiteEtica = @"idComiteEtica";
public static string Descripcion = @"descripcion";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Workspaces
{
public partial class WorkspaceTests
{
private TestWorkspace CreateWorkspace(bool disablePartialSolutions = true)
{
return new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, disablePartialSolutions: disablePartialSolutions);
}
private static async Task WaitForWorkspaceOperationsToComplete(TestWorkspace workspace)
{
var workspaceWaiter = workspace.ExportProvider
.GetExports<IAsynchronousOperationListener, FeatureMetadata>()
.First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter;
await workspaceWaiter.CreateWaitTask();
}
[Fact]
public async Task TestEmptySolutionUpdateDoesNotFireEvents()
{
using (var workspace = CreateWorkspace())
{
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
// wait for all previous operations to complete
await WaitForWorkspaceOperationsToComplete(workspace);
var solution = workspace.CurrentSolution;
bool workspaceChanged = false;
workspace.WorkspaceChanged += (s, e) => workspaceChanged = true;
// make an 'empty' update by claiming something changed, but its the same as before
workspace.OnParseOptionsChanged(project.Id, project.ParseOptions);
// wait for any new outstanding operations to complete (there shouldn't be any)
await WaitForWorkspaceOperationsToComplete(workspace);
// same solution instance == nothing changed
Assert.Equal(solution, workspace.CurrentSolution);
// no event was fired because nothing was changed
Assert.False(workspaceChanged);
}
}
[Fact]
public void TestAddProject()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
Assert.Equal(0, solution.Projects.Count());
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
solution = workspace.CurrentSolution;
Assert.Equal(1, solution.Projects.Count());
}
}
[Fact]
public void TestRemoveExistingProject1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
workspace.OnProjectRemoved(project.Id);
solution = workspace.CurrentSolution;
Assert.Equal(0, solution.Projects.Count());
}
}
[Fact]
public void TestRemoveExistingProject2()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
solution = workspace.CurrentSolution;
workspace.OnProjectRemoved(project.Id);
solution = workspace.CurrentSolution;
Assert.Equal(0, solution.Projects.Count());
}
}
[Fact]
public void TestRemoveNonAddedProject1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project = new TestHostProject(workspace);
Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project.Id));
}
}
[Fact]
public void TestRemoveNonAddedProject2()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project2.Id));
}
}
[Fact]
public async Task TestChangeOptions1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(
@"#if FOO
class C { }
#else
class D { }
#endif");
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
await VerifyRootTypeNameAsync(workspace, "D");
workspace.OnParseOptionsChanged(document.Id.ProjectId,
new CSharpParseOptions(preprocessorSymbols: new[] { "FOO" }));
await VerifyRootTypeNameAsync(workspace, "C");
}
}
[Fact]
public async Task TestChangeOptions2()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(
@"#if FOO
class C { }
#else
class D { }
#endif");
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
await VerifyRootTypeNameAsync(workspace, "D");
workspace.OnParseOptionsChanged(document.Id.ProjectId,
new CSharpParseOptions(preprocessorSymbols: new[] { "FOO" }));
await VerifyRootTypeNameAsync(workspace, "C");
workspace.OnDocumentClosed(document.Id);
}
}
[Fact]
public async void TestAddedSubmissionParseTreeHasEmptyFilePath()
{
using (var workspace = CreateWorkspace())
{
var document1 = new TestHostDocument("var x = 1;", displayName: "Sub1", sourceCodeKind: SourceCodeKind.Script);
var project1 = new TestHostProject(workspace, document1, name: "Submission");
var document2 = new TestHostDocument("var x = 2;", displayName: "Sub2", sourceCodeKind: SourceCodeKind.Script, filePath: "a.csx");
var project2 = new TestHostProject(workspace, document2, name: "Script");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.TryApplyChanges(workspace.CurrentSolution);
// Check that a parse tree for a submission has an empty file path.
SyntaxTree tree1 = await workspace.CurrentSolution
.GetProjectState(project1.Id)
.GetDocumentState(document1.Id)
.GetSyntaxTreeAsync(CancellationToken.None);
Assert.Equal("", tree1.FilePath);
// Check that a parse tree for a script does not have an empty file path.
SyntaxTree tree2 = await workspace.CurrentSolution
.GetProjectState(project2.Id)
.GetDocumentState(document2.Id)
.GetSyntaxTreeAsync(CancellationToken.None);
Assert.Equal("a.csx", tree2.FilePath);
}
}
private static async Task VerifyRootTypeNameAsync(TestWorkspace workspaceSnapshotBuilder, string typeName)
{
var currentSnapshot = workspaceSnapshotBuilder.CurrentSolution;
var type = await GetRootTypeDeclarationAsync(currentSnapshot);
Assert.Equal(type.Identifier.ValueText, typeName);
}
private static async Task<TypeDeclarationSyntax> GetRootTypeDeclarationAsync(Solution currentSnapshot)
{
var tree = await currentSnapshot.Projects.First().Documents.First().GetSyntaxTreeAsync();
var root = (CompilationUnitSyntax)tree.GetRoot();
var type = (TypeDeclarationSyntax)root.Members[0];
return type;
}
[Fact]
public void TestAddP2PReferenceFails()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id)));
}
}
[Fact]
public void TestAddP2PReference1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var reference = new ProjectReference(project2.Id);
workspace.OnProjectReferenceAdded(project1.Id, reference);
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
Assert.True(snapshot.GetProject(id1).ProjectReferences.Contains(reference), "ProjectReferences did not contain project2");
}
}
[Fact]
public void TestAddP2PReferenceTwice()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id));
Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id)));
}
}
[Fact]
public void TestRemoveP2PReference1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id));
workspace.OnProjectReferenceRemoved(project1.Id, new ProjectReference(project2.Id));
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
Assert.Equal(0, snapshot.GetProject(id1).ProjectReferences.Count());
}
}
[Fact]
public void TestAddP2PReferenceCircularity()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id));
Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project2.Id, new ProjectReference(project1.Id)));
}
}
[Fact]
public void TestRemoveProjectWithOpenedDocuments()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OnProjectRemoved(project1.Id);
Assert.False(workspace.IsDocumentOpen(document.Id));
Assert.Empty(workspace.CurrentSolution.Projects);
}
}
[Fact]
public void TestRemoveProjectWithClosedDocuments()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public void TestRemoveOpenedDocument()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
Assert.Throws<ArgumentException>(() => workspace.OnDocumentRemoved(document.Id));
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public async Task TestGetCompilation()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(@"class C { }");
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
await VerifyRootTypeNameAsync(workspace, "C");
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var compilation = await snapshot.GetProject(id1).GetCompilationAsync();
var classC = compilation.SourceModule.GlobalNamespace.GetMembers("C").Single();
}
}
[Fact]
public async Task TestGetCompilationOnDependentProject()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument(@"class D : C { }");
var project2 = new TestHostProject(workspace, document2, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
var compilation2 = await snapshot.GetProject(id2).GetCompilationAsync();
var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classC = classD.BaseType;
}
}
[Fact]
public async Task TestGetCompilationOnCrossLanguageDependentProject()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
var compilation2 = await snapshot.GetProject(id2).GetCompilationAsync();
var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classC = classD.BaseType;
}
}
[Fact]
public async Task TestGetCompilationOnCrossLanguageDependentProjectChanged()
{
using (var workspace = CreateWorkspace())
{
var solutionX = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var solutionY = workspace.CurrentSolution;
var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id;
var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id;
var compilation2 = await solutionY.GetProject(id2).GetCompilationAsync();
var errors = compilation2.GetDiagnostics();
var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classC = classD.BaseType;
Assert.NotEqual(TypeKind.Error, classC.TypeKind);
// change the class name in document1
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
var buffer1 = document1.GetTextBuffer();
// change C to X
buffer1.Replace(new Span(13, 1), "X");
// this solution should have the change
var solutionZ = workspace.CurrentSolution;
var docZ = solutionZ.GetDocument(document1.Id);
var docZText = await docZ.GetTextAsync();
var compilation2Z = await solutionZ.GetProject(id2).GetCompilationAsync();
var classDz = compilation2Z.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCz = classDz.BaseType;
Assert.Equal(TypeKind.Error, classCz.TypeKind);
}
}
[WpfFact]
public async Task TestDependentSemanticVersionChangesWhenNotOriginallyAccessed()
{
using (var workspace = CreateWorkspace(disablePartialSolutions: false))
{
var solutionX = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var solutionY = workspace.CurrentSolution;
var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id;
var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id;
var compilation2y = await solutionY.GetProject(id2).GetCompilationAsync();
var errors = compilation2y.GetDiagnostics();
var classDy = compilation2y.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCy = classDy.BaseType;
Assert.NotEqual(TypeKind.Error, classCy.TypeKind);
// open both documents so background compiler works on their compilations
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer());
// change C to X
var buffer1 = document1.GetTextBuffer();
buffer1.Replace(new Span(13, 1), "X");
for (int iter = 0; iter < 10; iter++)
{
WaitHelper.WaitForDispatchedOperationsToComplete(System.Windows.Threading.DispatcherPriority.ApplicationIdle);
Thread.Sleep(1000);
// the current solution should eventually have the change
var cs = workspace.CurrentSolution;
var doc1Z = cs.GetDocument(document1.Id);
var hasX = (await doc1Z.GetTextAsync()).ToString().Contains("X");
if (hasX)
{
var newVersion = await cs.GetProject(project1.Id).GetDependentSemanticVersionAsync();
var newVersionX = await doc1Z.Project.GetDependentSemanticVersionAsync();
Assert.NotEqual(VersionStamp.Default, newVersion);
Assert.Equal(newVersion, newVersionX);
break;
}
}
}
}
[WpfFact]
public async Task TestGetCompilationOnCrossLanguageDependentProjectChangedInProgress()
{
using (var workspace = CreateWorkspace(disablePartialSolutions: false))
{
var solutionX = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var solutionY = workspace.CurrentSolution;
var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id;
var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id;
var compilation2y = await solutionY.GetProject(id2).GetCompilationAsync();
var errors = compilation2y.GetDiagnostics();
var classDy = compilation2y.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCy = classDy.BaseType;
Assert.NotEqual(TypeKind.Error, classCy.TypeKind);
// open both documents so background compiler works on their compilations
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer());
// change C to X
var buffer1 = document1.GetTextBuffer();
buffer1.Replace(new Span(13, 1), "X");
var foundTheError = false;
for (int iter = 0; iter < 10; iter++)
{
WaitHelper.WaitForDispatchedOperationsToComplete(System.Windows.Threading.DispatcherPriority.ApplicationIdle);
Thread.Sleep(1000);
// the current solution should eventually have the change
var cs = workspace.CurrentSolution;
var doc1Z = cs.GetDocument(document1.Id);
var hasX = (await doc1Z.GetTextAsync()).ToString().Contains("X");
if (hasX)
{
var doc2Z = cs.GetDocument(document2.Id);
var partialDoc2Z = await doc2Z.WithFrozenPartialSemanticsAsync(CancellationToken.None);
var compilation2Z = await partialDoc2Z.Project.GetCompilationAsync();
var classDz = compilation2Z.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCz = classDz.BaseType;
if (classCz.TypeKind == TypeKind.Error)
{
foundTheError = true;
break;
}
}
}
Assert.True(foundTheError, "Did not find error");
}
}
[Fact]
public async Task TestOpenAndChangeDocument()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
var buffer = document.GetTextBuffer();
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
buffer.Insert(0, "class C {}");
solution = workspace.CurrentSolution;
var doc = solution.Projects.Single().Documents.First();
var syntaxTree = await doc.GetSyntaxTreeAsync(CancellationToken.None);
Assert.True(syntaxTree.GetRoot().Width() > 0, "syntaxTree.GetRoot().Width should be > 0");
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public async Task TestApplyChangesWithDocumentTextUpdated()
{
using (var workspace = CreateWorkspace())
{
var startText = "public class C { }";
var newText = "public class D { }";
var document = new TestHostDocument(startText);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
var buffer = document.GetTextBuffer();
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
// prove the document has the correct text
Assert.Equal(startText, (await workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync()).ToString());
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.WithDocumentText(document.Id, SourceText.From(newText));
// prove that current document text is unchanged
Assert.Equal(startText, (await workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync()).ToString());
// prove buffer is unchanged too
Assert.Equal(startText, buffer.CurrentSnapshot.GetText());
workspace.TryApplyChanges(newSolution);
// new text should have been pushed into buffer
Assert.Equal(newText, buffer.CurrentSnapshot.GetText());
}
}
[Fact]
public void TestApplyChangesWithDocumentAdded()
{
using (var workspace = CreateWorkspace())
{
var doc1Text = "public class C { }";
var doc2Text = "public class D { }";
var document = new TestHostDocument(doc1Text);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.AddDocument(DocumentId.CreateNewId(project1.Id), "Doc2", SourceText.From(doc2Text));
workspace.TryApplyChanges(newSolution);
// new document should have been added.
Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
}
}
[Fact]
public void TestApplyChangesWithDocumentRemoved()
{
using (var workspace = CreateWorkspace())
{
var doc1Text = "public class C { }";
var document = new TestHostDocument(doc1Text);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.RemoveDocument(document.Id);
workspace.TryApplyChanges(newSolution);
// document should have been removed
Assert.Equal(0, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
}
}
[Fact]
public async Task TestDocumentEvents()
{
using (var workspace = CreateWorkspace())
{
var doc1Text = "public class C { }";
var document = new TestHostDocument(doc1Text);
var project1 = new TestHostProject(workspace, document, name: "project1");
var longEventTimeout = TimeSpan.FromMinutes(5);
var shortEventTimeout = TimeSpan.FromSeconds(5);
workspace.AddTestProject(project1);
// Creating two waiters that will allow us to know for certain if the events have fired.
using (var closeWaiter = new EventWaiter())
using (var openWaiter = new EventWaiter())
{
// Wrapping event handlers so they can notify us on being called.
var documentOpenedEventHandler = openWaiter.Wrap<DocumentEventArgs>(
(sender, args) => Assert.True(args.Document.Id == document.Id,
"The document given to the 'DocumentOpened' event handler did not have the same id as the one created for the test."));
var documentClosedEventHandler = closeWaiter.Wrap<DocumentEventArgs>(
(sender, args) => Assert.True(args.Document.Id == document.Id,
"The document given to the 'DocumentClosed' event handler did not have the same id as the one created for the test."));
workspace.DocumentOpened += documentOpenedEventHandler;
workspace.DocumentClosed += documentClosedEventHandler;
workspace.OpenDocument(document.Id);
workspace.CloseDocument(document.Id);
// Wait for all workspace tasks to finish. After this is finished executing, all handlers should have been notified.
await WaitForWorkspaceOperationsToComplete(workspace);
// Wait to receive signal that events have fired.
Assert.True(openWaiter.WaitForEventToFire(longEventTimeout),
string.Format("event 'DocumentOpened' was not fired within {0} minutes.",
longEventTimeout.Minutes));
Assert.True(closeWaiter.WaitForEventToFire(longEventTimeout),
string.Format("event 'DocumentClosed' was not fired within {0} minutes.",
longEventTimeout.Minutes));
workspace.DocumentOpened -= documentOpenedEventHandler;
workspace.DocumentClosed -= documentClosedEventHandler;
workspace.OpenDocument(document.Id);
workspace.CloseDocument(document.Id);
// Wait for all workspace tasks to finish. After this is finished executing, all handlers should have been notified.
await WaitForWorkspaceOperationsToComplete(workspace);
// Verifying that an event has not been called is difficult to prove.
// All events should have already been called so we wait 5 seconds and then assume the event handler was removed correctly.
Assert.False(openWaiter.WaitForEventToFire(shortEventTimeout),
string.Format("event handler 'DocumentOpened' was called within {0} seconds though it was removed from the list.",
shortEventTimeout.Seconds));
Assert.False(closeWaiter.WaitForEventToFire(shortEventTimeout),
string.Format("event handler 'DocumentClosed' was called within {0} seconds though it was removed from the list.",
shortEventTimeout.Seconds));
}
}
}
[Fact]
public async Task TestAdditionalFile_Properties()
{
using (var workspace = CreateWorkspace())
{
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument("some text");
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var project = workspace.CurrentSolution.Projects.Single();
Assert.Equal(1, project.Documents.Count());
Assert.Equal(1, project.AdditionalDocuments.Count());
Assert.Equal(1, project.AdditionalDocumentIds.Count);
var doc = project.GetDocument(additionalDoc.Id);
Assert.Null(doc);
var additionalDocument = project.GetAdditionalDocument(additionalDoc.Id);
Assert.Equal("some text", (await additionalDocument.GetTextAsync()).ToString());
}
}
[Fact]
public async Task TestAdditionalFile_DocumentChanged()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var newText = @"<setting value = ""foo1""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText);
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var buffer = additionalDoc.GetTextBuffer();
workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());
var project = workspace.CurrentSolution.Projects.Single();
var oldVersion = await project.GetSemanticVersionAsync();
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.WithAdditionalDocumentText(additionalDoc.Id, SourceText.From(newText));
workspace.TryApplyChanges(newSolution);
var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);
// new text should have been pushed into buffer
Assert.Equal(newText, buffer.CurrentSnapshot.GetText());
// Text changes are considered top level changes and they change the project's semantic version.
Assert.Equal(await doc.GetTextVersionAsync(), await doc.GetTopLevelChangeTextVersionAsync());
Assert.NotEqual(oldVersion, await doc.Project.GetSemanticVersionAsync());
}
}
[Fact]
public async Task TestAdditionalFile_OpenClose()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText);
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var buffer = additionalDoc.GetTextBuffer();
var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);
var text = await doc.GetTextAsync(CancellationToken.None);
var version = await doc.GetTextVersionAsync(CancellationToken.None);
workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());
// We don't have a GetOpenAdditionalDocumentIds since we don't need it. But make sure additional documents
// don't creep into OpenDocumentIds (Bug: 1087470)
Assert.Empty(workspace.GetOpenDocumentIds());
workspace.OnAdditionalDocumentClosed(additionalDoc.Id, TextLoader.From(TextAndVersion.Create(text, version)));
// Reopen and close to make sure we are not leaking anything.
workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());
workspace.OnAdditionalDocumentClosed(additionalDoc.Id, TextLoader.From(TextAndVersion.Create(text, version)));
Assert.Empty(workspace.GetOpenDocumentIds());
}
}
[Fact]
public void TestAdditionalFile_AddRemove()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText, "original.config");
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var project = workspace.CurrentSolution.Projects.Single();
// fork the solution to introduce a change.
var newDocId = DocumentId.CreateNewId(project.Id);
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.AddAdditionalDocument(newDocId, "app.config", "text");
var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);
workspace.TryApplyChanges(newSolution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
// Now remove the newly added document
oldSolution = workspace.CurrentSolution;
newSolution = oldSolution.RemoveAdditionalDocument(newDocId);
workspace.TryApplyChanges(newSolution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
Assert.Equal("original.config", workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Single().Name);
}
}
[Fact]
public void TestAdditionalFile_AddRemove_FromProject()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText, "original.config");
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var project = workspace.CurrentSolution.Projects.Single();
// fork the solution to introduce a change.
var doc = project.AddAdditionalDocument("app.config", "text");
workspace.TryApplyChanges(doc.Project.Solution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
// Now remove the newly added document
project = workspace.CurrentSolution.Projects.Single();
workspace.TryApplyChanges(project.RemoveAdditionalDocument(doc.Id).Solution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
Assert.Equal("original.config", workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Single().Name);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
public class MessageTransferModule : ISharedRegionModule, IMessageTransferModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
protected List<Scene> m_Scenes = new List<Scene>();
protected Dictionary<UUID, UUID> m_UserRegionMap = new Dictionary<UUID, UUID>();
public event UndeliveredMessage OnUndeliveredMessage;
private IPresenceService m_PresenceService;
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
return m_PresenceService;
}
}
public virtual void Initialise(IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null && cnf.GetString(
"MessageTransferModule", "MessageTransferModule") !=
"MessageTransferModule")
{
m_log.Debug("[MESSAGE TRANSFER]: Disabled by configuration");
return;
}
m_Enabled = true;
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_log.Debug("[MESSAGE TRANSFER]: Message transfer module active");
scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene);
}
}
public virtual void PostInitialise()
{
if (!m_Enabled)
return;
MainServer.Instance.AddXmlRPCHandler(
"grid_instant_message", processXMLRPCGridInstantMessage);
}
public virtual void RegionLoaded(Scene scene)
{
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_Scenes.Remove(scene);
}
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "MessageTransferModule"; }
}
public virtual Type ReplaceableInterface
{
get { return null; }
}
public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new UUID(im.toAgentID);
// Try root avatar only first
foreach (Scene scene in m_Scenes)
{
if (scene.Entities.ContainsKey(toAgentID) &&
scene.Entities[toAgentID] is ScenePresence)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for root agent {0} in {1}",
// toAgentID.ToString(), scene.RegionInfo.RegionName);
ScenePresence user = (ScenePresence) scene.Entities[toAgentID];
if (!user.IsChildAgent)
{
// Local message
m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", user.Name, toAgentID);
user.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
}
// try child avatar second
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for child of {0} in {1}", toAgentID, scene.RegionInfo.RegionName);
if (scene.Entities.ContainsKey(toAgentID) &&
scene.Entities[toAgentID] is ScenePresence)
{
// Local message
ScenePresence user = (ScenePresence) scene.Entities[toAgentID];
m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", user.Name, toAgentID);
user.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
SendGridInstantMessageViaXMLRPC(im, result);
return;
}
private void HandleUndeliveredMessage(GridInstantMessage im, MessageResultNotification result)
{
UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage;
// If this event has handlers, then the IM will be considered
// delivered. This will suppress the error message.
//
if (handlerUndeliveredMessage != null)
{
handlerUndeliveredMessage(im);
result(true);
return;
}
//m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable");
result(false);
}
/// <summary>
/// Process a XMLRPC Grid Instant Message
/// </summary>
/// <param name="request">XMLRPC parameters
/// </param>
/// <returns>Nothing much</returns>
protected virtual XmlRpcResponse processXMLRPCGridInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient)
{
bool successful = false;
// TODO: For now, as IMs seem to be a bit unreliable on OSGrid, catch all exception that
// happen here and aren't caught and log them.
try
{
// various rational defaults
UUID fromAgentID = UUID.Zero;
UUID toAgentID = UUID.Zero;
UUID imSessionID = UUID.Zero;
uint timestamp = 0;
string fromAgentName = "";
string message = "";
byte dialog = (byte)0;
bool fromGroup = false;
byte offline = (byte)0;
uint ParentEstateID=0;
Vector3 Position = Vector3.Zero;
UUID RegionID = UUID.Zero ;
byte[] binaryBucket = new byte[0];
float pos_x = 0;
float pos_y = 0;
float pos_z = 0;
//m_log.Info("Processing IM");
Hashtable requestData = (Hashtable)request.Params[0];
// Check if it's got all the data
if (requestData.ContainsKey("from_agent_id")
&& requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id")
&& requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name")
&& requestData.ContainsKey("message") && requestData.ContainsKey("dialog")
&& requestData.ContainsKey("from_group")
&& requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id")
&& requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y")
&& requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id")
&& requestData.ContainsKey("binary_bucket"))
{
// Do the easy way of validating the UUIDs
UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID);
UUID.TryParse((string)requestData["to_agent_id"], out toAgentID);
UUID.TryParse((string)requestData["im_session_id"], out imSessionID);
UUID.TryParse((string)requestData["region_id"], out RegionID);
try
{
timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
fromAgentName = (string)requestData["from_agent_name"];
message = (string)requestData["message"];
if (message == null)
message = string.Empty;
// Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
string requestData1 = (string)requestData["dialog"];
if (string.IsNullOrEmpty(requestData1))
{
dialog = 0;
}
else
{
byte[] dialogdata = Convert.FromBase64String(requestData1);
dialog = dialogdata[0];
}
if ((string)requestData["from_group"] == "TRUE")
fromGroup = true;
string requestData2 = (string)requestData["offline"];
if (String.IsNullOrEmpty(requestData2))
{
offline = 0;
}
else
{
byte[] offlinedata = Convert.FromBase64String(requestData2);
offline = offlinedata[0];
}
try
{
ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_x = (uint)Convert.ToInt32((string)requestData["position_x"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_y = (uint)Convert.ToInt32((string)requestData["position_y"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_z = (uint)Convert.ToInt32((string)requestData["position_z"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
Position = new Vector3(pos_x, pos_y, pos_z);
string requestData3 = (string)requestData["binary_bucket"];
if (string.IsNullOrEmpty(requestData3))
{
binaryBucket = new byte[0];
}
else
{
binaryBucket = Convert.FromBase64String(requestData3);
}
// Create a New GridInstantMessageObject the the data
GridInstantMessage gim = new GridInstantMessage();
gim.fromAgentID = fromAgentID.Guid;
gim.fromAgentName = fromAgentName;
gim.fromGroup = fromGroup;
gim.imSessionID = imSessionID.Guid;
gim.RegionID = RegionID.Guid;
gim.timestamp = timestamp;
gim.toAgentID = toAgentID.Guid;
gim.message = message;
gim.dialog = dialog;
gim.offline = offline;
gim.ParentEstateID = ParentEstateID;
gim.Position = Position;
gim.binaryBucket = binaryBucket;
// Trigger the Instant message in the scene.
foreach (Scene scene in m_Scenes)
{
if (scene.Entities.ContainsKey(toAgentID) &&
scene.Entities[toAgentID] is ScenePresence)
{
ScenePresence user =
(ScenePresence)scene.Entities[toAgentID];
if (!user.IsChildAgent)
{
scene.EventManager.TriggerIncomingInstantMessage(gim);
successful = true;
}
}
}
if (!successful)
{
// If the message can't be delivered to an agent, it
// is likely to be a group IM. On a group IM, the
// imSessionID = toAgentID = group id. Raise the
// unhandled IM event to give the groups module
// a chance to pick it up. We raise that in a random
// scene, since the groups module is shared.
//
m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim);
}
}
}
catch (Exception e)
{
m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e);
successful = false;
}
//Send response back to region calling if it was successful
// calling region uses this to know when to look up a user's location again.
XmlRpcResponse resp = new XmlRpcResponse();
Hashtable respdata = new Hashtable();
if (successful)
respdata["success"] = "TRUE";
else
respdata["success"] = "FALSE";
resp.Value = respdata;
return resp;
}
/// <summary>
/// delegate for sending a grid instant message asynchronously
/// </summary>
public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID);
protected virtual void GridInstantMessageCompleted(IAsyncResult iar)
{
GridInstantMessageDelegate icon =
(GridInstantMessageDelegate)iar.AsyncState;
icon.EndInvoke(iar);
}
protected virtual void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result)
{
GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync;
d.BeginInvoke(im, result, UUID.Zero, GridInstantMessageCompleted, d);
}
/// <summary>
/// Recursive SendGridInstantMessage over XMLRPC method.
/// This is called from within a dedicated thread.
/// The first time this is called, prevRegionHandle will be 0 Subsequent times this is called from
/// itself, prevRegionHandle will be the last region handle that we tried to send.
/// If the handles are the same, we look up the user's location using the grid.
/// If the handles are still the same, we end. The send failed.
/// </summary>
/// <param name="prevRegionHandle">
/// Pass in 0 the first time this method is called. It will be called recursively with the last
/// regionhandle tried
/// </param>
protected virtual void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID)
{
UUID toAgentID = new UUID(im.toAgentID);
PresenceInfo upd = null;
bool lookupAgent = false;
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
upd = new PresenceInfo();
upd.RegionID = m_UserRegionMap[toAgentID];
// We need to compare the current regionhandle with the previous region handle
// or the recursive loop will never end because it will never try to lookup the agent again
if (prevRegionID == upd.RegionID)
{
lookupAgent = true;
}
}
else
{
lookupAgent = true;
}
}
// Are we needing to look-up an agent?
if (lookupAgent)
{
// Non-cached user agent lookup.
PresenceInfo[] presences = PresenceService.GetAgents(new string[] { toAgentID.ToString() });
if (presences != null && presences.Length > 0)
upd = presences[0];
if (upd != null)
{
// check if we've tried this before..
// This is one way to end the recursive loop
//
if (upd.RegionID == prevRegionID)
{
m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
HandleUndeliveredMessage(im, result);
return;
}
}
else
{
m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
HandleUndeliveredMessage(im, result);
return;
}
}
if (upd != null)
{
GridRegion reginfo = m_Scenes[0].GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID,
upd.RegionID);
if (reginfo != null)
{
Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im);
// Not actually used anymore, left in for compatibility
// Remove at next interface change
//
msgdata["region_handle"] = 0;
bool imresult = doIMSending(reginfo, msgdata);
if (imresult)
{
// IM delivery successful, so store the Agent's location in our local cache.
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
m_UserRegionMap[toAgentID] = upd.RegionID;
}
else
{
m_UserRegionMap.Add(toAgentID, upd.RegionID);
}
}
result(true);
}
else
{
// try again, but lookup user this time.
// Warning, this must call the Async version
// of this method or we'll be making thousands of threads
// The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
// The version that spawns the thread is SendGridInstantMessageViaXMLRPC
// This is recursive!!!!!
SendGridInstantMessageViaXMLRPCAsync(im, result,
upd.RegionID);
}
}
else
{
m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", upd.RegionID);
HandleUndeliveredMessage(im, result);
}
}
else
{
HandleUndeliveredMessage(im, result);
}
}
/// <summary>
/// This actually does the XMLRPC Request
/// </summary>
/// <param name="reginfo">RegionInfo we pull the data out of to send the request to</param>
/// <param name="xmlrpcdata">The Instant Message data Hashtable</param>
/// <returns>Bool if the message was successfully delivered at the other side.</returns>
protected virtual bool doIMSending(GridRegion reginfo, Hashtable xmlrpcdata)
{
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
XmlRpcRequest GridReq = new XmlRpcRequest("grid_instant_message", SendParams);
try
{
XmlRpcResponse GridResp = GridReq.Send("http://" + reginfo.ExternalHostName + ":" + reginfo.HttpPort, 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("success"))
{
if ((string)responseData["success"] == "TRUE")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch (WebException e)
{
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to http://{0}:{1} the host didn't respond ({2})",
reginfo.ExternalHostName, reginfo.HttpPort, e.Message);
}
return false;
}
/// <summary>
/// Get ulong region handle for region by it's Region UUID.
/// We use region handles over grid comms because there's all sorts of free and cool caching.
/// </summary>
/// <param name="regionID">UUID of region to get the region handle for</param>
/// <returns></returns>
// private virtual ulong getLocalRegionHandleFromUUID(UUID regionID)
// {
// ulong returnhandle = 0;
//
// lock (m_Scenes)
// {
// foreach (Scene sn in m_Scenes)
// {
// if (sn.RegionInfo.RegionID == regionID)
// {
// returnhandle = sn.RegionInfo.RegionHandle;
// break;
// }
// }
// }
// return returnhandle;
// }
/// <summary>
/// Takes a GridInstantMessage and converts it into a Hashtable for XMLRPC
/// </summary>
/// <param name="msg">The GridInstantMessage object</param>
/// <returns>Hashtable containing the XMLRPC request</returns>
protected virtual Hashtable ConvertGridInstantMessageToXMLRPC(GridInstantMessage msg)
{
Hashtable gim = new Hashtable();
gim["from_agent_id"] = msg.fromAgentID.ToString();
// Kept for compatibility
gim["from_agent_session"] = UUID.Zero.ToString();
gim["to_agent_id"] = msg.toAgentID.ToString();
gim["im_session_id"] = msg.imSessionID.ToString();
gim["timestamp"] = msg.timestamp.ToString();
gim["from_agent_name"] = msg.fromAgentName;
gim["message"] = msg.message;
byte[] dialogdata = new byte[1];dialogdata[0] = msg.dialog;
gim["dialog"] = Convert.ToBase64String(dialogdata,Base64FormattingOptions.None);
if (msg.fromGroup)
gim["from_group"] = "TRUE";
else
gim["from_group"] = "FALSE";
byte[] offlinedata = new byte[1]; offlinedata[0] = msg.offline;
gim["offline"] = Convert.ToBase64String(offlinedata, Base64FormattingOptions.None);
gim["parent_estate_id"] = msg.ParentEstateID.ToString();
gim["position_x"] = msg.Position.X.ToString();
gim["position_y"] = msg.Position.Y.ToString();
gim["position_z"] = msg.Position.Z.ToString();
gim["region_id"] = msg.RegionID.ToString();
gim["binary_bucket"] = Convert.ToBase64String(msg.binaryBucket,Base64FormattingOptions.None);
return gim;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using OpenSim.Framework.Communications.Messages;
using System.Threading.Tasks;
namespace OpenSim.Framework.Communications.Clients
{
public class RegionClient
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int CREATE_OBJECT_TIMEOUT = 15000; // how long the sending region waits for an object create
public const int REZ_OBJECT_TIMEOUT = 10000; // max time the receiving region can take to rez the object
public const int AGENT_UPDATE_TIMEOUT = 10000; // how long the sending region waits for an agent create
string _gridSendKey;
public RegionClient(string gridSendKey)
{
_gridSendKey = gridSendKey;
}
public bool DoCreateChildAgentCall(RegionInfo region, AgentCircuitData aCircuit, string authKey, out string reason)
{
// Eventually, we want to use a caps url instead of the agentID
string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/agent/" + aCircuit.AgentID + "/";
//Console.WriteLine(" >>> DoCreateChildAgentCall <<< " + uri);
HttpWebRequest AgentCreateRequest = (HttpWebRequest)WebRequest.Create(uri);
AgentCreateRequest.Method = "POST";
AgentCreateRequest.ContentType = "application/json";
AgentCreateRequest.Timeout = 10000;
//AgentCreateRequest.KeepAlive = false;
AgentCreateRequest.Headers["authorization"] = GenerateAuthorization();
reason = String.Empty;
// Fill it in
OSDMap args = null;
try
{
args = aCircuit.PackAgentCircuitData();
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: PackAgentCircuitData failed with exception: " + e.Message);
reason = "PackAgentCircuitData exception";
return false;
}
// Add the regionhandle of the destination region
ulong regionHandle = GetRegionHandle(region.RegionHandle);
args["destination_handle"] = OSD.FromString(regionHandle.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
UTF8Encoding str = new UTF8Encoding();
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = AgentCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
//m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
reason = "cannot contact remote region";
return false;
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
try
{
WebResponse webResponse = AgentCreateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoCreateChildAgentCall post");
reason = "response is null";
return false;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string response = sr.ReadToEnd().Trim();
sr.Close();
m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", response);
if (String.IsNullOrEmpty(response))
{
reason = "response is empty";
return false;
}
try
{
// we assume we got an OSDMap back
OSDMap r = GetOSDMap(response);
bool success = r["success"].AsBoolean();
reason = r["reason"].AsString();
return success;
}
catch (NullReferenceException e)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", e.Message);
// check for old style response
if (response.ToLower().StartsWith("true"))
return true;
reason = "null reference exception";
return false;
}
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex.Message);
reason = "web exception";
return false;
}
}
public async Task<Tuple<bool, string>> DoCreateChildAgentCallAsync(SimpleRegionInfo regionInfo, AgentCircuitData aCircuit)
{
string uri = regionInfo.InsecurePublicHTTPServerURI + "/agent/" + aCircuit.AgentID + "/";
HttpWebRequest agentCreateRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
agentCreateRequest.Method = "POST";
agentCreateRequest.ContentType = "application/json";
agentCreateRequest.Timeout = AGENT_UPDATE_TIMEOUT;
agentCreateRequest.ReadWriteTimeout = AGENT_UPDATE_TIMEOUT;
agentCreateRequest.Headers["authorization"] = GenerateAuthorization();
OSDMap args = null;
try
{
args = aCircuit.PackAgentCircuitData();
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: PackAgentCircuitData failed with exception: " + e.Message);
return Tuple.Create(false, "PackAgentCircuitData exception");
}
// Add the regionhandle of the destination region
ulong regionHandle = GetRegionHandle(regionInfo.RegionHandle);
args["destination_handle"] = OSD.FromString(regionHandle.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
UTF8Encoding str = new UTF8Encoding();
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
return Tuple.Create(false, "Exception thrown on serialization of ChildCreate");
}
try
{ // send the Post
agentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
Stream os = await agentCreateRequest.GetRequestStreamAsync();
await os.WriteAsync(buffer, 0, strBuffer.Length); //Send it
await os.FlushAsync();
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Unable to contact remote region {0}: {1}", regionInfo.RegionHandle, e.Message);
return Tuple.Create(false, "cannot contact remote region");
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
try
{
WebResponse webResponse = await agentCreateRequest.GetResponseAsync(AGENT_UPDATE_TIMEOUT);
if (webResponse == null)
{
m_log.Warn("[REST COMMS]: Null reply on DoCreateChildAgentCall post");
return Tuple.Create(false, "response from remote region was null");
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string response = await sr.ReadToEndAsync();
response.Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", response);
if (String.IsNullOrEmpty(response))
{
m_log.Info("[REST COMMS]: Empty response on DoCreateChildAgentCall post");
return Tuple.Create(false, "response from remote region was empty");
}
try
{
// we assume we got an OSDMap back
OSDMap r = GetOSDMap(response);
bool success = r["success"].AsBoolean();
string reason = r["reason"].AsString();
return Tuple.Create(success, reason);
}
catch (NullReferenceException e)
{
m_log.WarnFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", e.Message);
// check for old style response
if (response.ToLower().StartsWith("true"))
return Tuple.Create(true, "");
return Tuple.Create(false, "exception on reply of DoCreateChildAgentCall");
}
}
catch (WebException ex)
{
m_log.WarnFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex);
return Tuple.Create(false, "web exception");
}
catch (Exception ex)
{
m_log.WarnFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex);
return Tuple.Create(false, "web exception");
}
}
public bool DoChildAgentUpdateCall(RegionInfo region, IAgentData cAgentData)
{
// Eventually, we want to use a caps url instead of the agentID
string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/agent/" + cAgentData.AgentID + "/";
//Console.WriteLine(" >>> DoChildAgentUpdateCall <<< " + uri);
HttpWebRequest ChildUpdateRequest = (HttpWebRequest)WebRequest.Create(uri);
ChildUpdateRequest.Method = "PUT";
ChildUpdateRequest.ContentType = "application/json";
ChildUpdateRequest.Timeout = AGENT_UPDATE_TIMEOUT;
//ChildUpdateRequest.KeepAlive = false;
ChildUpdateRequest.Headers["authorization"] = GenerateAuthorization();
// Fill it in
OSDMap args = null;
try
{
args = cAgentData.Pack();
}
catch (Exception e)
{
m_log.Error("[REST COMMS]: PackUpdateMessage failed with exception: " + e.Message);
return false;
}
// Add the regionhandle of the destination region
ulong regionHandle = GetRegionHandle(region.RegionHandle);
args["destination_handle"] = OSD.FromString(regionHandle.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
UTF8Encoding str = new UTF8Encoding();
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.ErrorFormat("[REST COMMS]: Exception thrown on serialization of ChildUpdate: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ChildUpdateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
}
catch (WebException)
{
// Normal case of network error connecting to a region (e.g. a down one)
return false;
}
catch (Exception ex)
{
m_log.ErrorFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
return false;
}
// Let's wait for the response
// m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate");
try
{
WebResponse webResponse = ChildUpdateRequest.GetResponse();
if (webResponse != null)
{
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string reply = sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: ChildAgentUpdate reply was {0} ", reply);
bool rc = false;
if (!bool.TryParse(reply, out rc))
rc = false;
return rc;
}
m_log.Info("[REST COMMS]: Null reply on ChildAgentUpdate post");
}
catch (Exception ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of ChildAgentUpdate {0}", ex.Message);
}
return false;
}
public enum AgentUpdate2Ret
{
Ok,
Error,
NotFound,
AccessDenied
}
public AgentUpdate2Ret DoChildAgentUpdateCall2(SimpleRegionInfo regInfo, AgentData data)
{
ulong regionHandle = GetRegionHandle(regInfo.RegionHandle);
string uri = "http://" + regInfo.ExternalHostName + ":" + regInfo.HttpPort + "/agent2/" + data.AgentID + "/" + regionHandle + "/";
HttpWebRequest agentPutRequest = (HttpWebRequest)WebRequest.Create(uri);
agentPutRequest.Method = "PUT";
agentPutRequest.ContentType = "application/octet-stream";
agentPutRequest.Timeout = AGENT_UPDATE_TIMEOUT;
agentPutRequest.Headers["authorization"] = GenerateAuthorization();
AgentPutMessage message = AgentPutMessage.FromAgentData(data);
try
{
// send the Post
Stream os = agentPutRequest.GetRequestStream();
ProtoBuf.Serializer.Serialize(os, message);
os.Flush();
os.Close();
m_log.InfoFormat("[REST COMMS]: PUT DoChildAgentUpdateCall2 request to remote sim {0}", uri);
}
catch (Exception e)
{
m_log.ErrorFormat("[REST COMMS]: DoChildAgentUpdateCall2 call failed {0}", e);
return AgentUpdate2Ret.Error;
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
try
{
HttpWebResponse webResponse = (HttpWebResponse)agentPutRequest.GetResponse();
if (webResponse == null)
{
m_log.Error("[REST COMMS]: Null reply on DoChildAgentUpdateCall2 put");
return AgentUpdate2Ret.Error;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string reply = sr.ReadToEnd().Trim();
sr.Close();
//this will happen during the initial rollout and tells us we need to fall back to the
//old method
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
m_log.InfoFormat("[REST COMMS]: NotFound on reply of DoChildAgentUpdateCall2");
return AgentUpdate2Ret.NotFound;
}
else if (webResponse.StatusCode == HttpStatusCode.OK)
{
return AgentUpdate2Ret.Ok;
}
else
{
m_log.ErrorFormat("[REST COMMS]: Error on reply of DoChildAgentUpdateCall2 {0}", reply);
return AgentUpdate2Ret.Error;
}
}
catch (WebException ex)
{
HttpWebResponse webResponse = ex.Response as HttpWebResponse;
if (webResponse != null)
{
//this will happen during the initial rollout and tells us we need to fall back to the
//old method
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
m_log.InfoFormat("[REST COMMS]: NotFound on reply of DoChildAgentUpdateCall2");
return AgentUpdate2Ret.NotFound;
}
if (webResponse.StatusCode == HttpStatusCode.Forbidden)
{
m_log.InfoFormat("[REST COMMS]: Forbidden returned on reply of DoChildAgentUpdateCall2");
return AgentUpdate2Ret.AccessDenied;
}
}
m_log.ErrorFormat("[REST COMMS]: exception on reply of DoChildAgentUpdateCall2 {0} Sz {1}", ex, agentPutRequest.ContentLength);
}
return AgentUpdate2Ret.Error;
}
public bool DoRetrieveRootAgentCall(RegionInfo region, UUID id, out IAgentData agent)
{
agent = null;
// Eventually, we want to use a caps url instead of the agentID
string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/";
//Console.WriteLine(" >>> DoRetrieveRootAgentCall <<< " + uri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Timeout = 10000;
//request.Headers.Add("authorization", ""); // coming soon
request.Headers["authorization"] = GenerateAuthorization();
HttpWebResponse webResponse = null;
string reply = string.Empty;
try
{
webResponse = (HttpWebResponse)request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent get ");
return false;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
reply = sr.ReadToEnd().Trim();
sr.Close();
//Console.WriteLine("[REST COMMS]: ChildAgentUpdate reply was " + reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent get {0}", ex.Message);
// ignore, really
return false;
}
if (webResponse.StatusCode == HttpStatusCode.OK)
{
// we know it's jason
OSDMap args = GetOSDMap(reply);
if (args == null)
{
//Console.WriteLine("[REST COMMS]: Error getting OSDMap from reply");
return false;
}
agent = new CompleteAgentData();
agent.Unpack(args);
return true;
}
//Console.WriteLine("[REST COMMS]: DoRetrieveRootAgentCall returned status " + webResponse.StatusCode);
return false;
}
public bool DoReleaseAgentCall(ulong regionHandle, UUID id, string uri)
{
//m_log.Debug(" >>> DoReleaseAgentCall <<< " + uri);
WebRequest request = WebRequest.Create(uri);
request.Method = "DELETE";
request.Timeout = 10000;
request.Headers["authorization"] = GenerateAuthorization();
try
{
WebResponse webResponse = request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent delete ");
return false;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: ChildAgentUpdate reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex.Message);
}
return false;
}
public bool DoCloseAgentCall(RegionInfo region, UUID id)
{
string uri = region.InsecurePublicHTTPServerURI + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/";
WebRequest request = WebRequest.Create(uri);
request.Method = "DELETE";
request.Timeout = 10000;
request.Headers["authorization"] = GenerateAuthorization();
try
{
WebResponse webResponse = request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent delete ");
return false;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: ChildAgentUpdate reply was {0} ", reply);
return true;
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex.Message);
}
return false;
}
public async Task<bool> DoCloseAgentCallAsync(SimpleRegionInfo region, UUID id)
{
string uri = region.InsecurePublicHTTPServerURI + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "DELETE";
request.Timeout = AGENT_UPDATE_TIMEOUT;
request.ReadWriteTimeout = AGENT_UPDATE_TIMEOUT;
request.Headers["authorization"] = GenerateAuthorization();
try
{
WebResponse webResponse = await request.GetResponseAsync(AGENT_UPDATE_TIMEOUT);
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent delete ");
return false;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string response = await sr.ReadToEndAsync();
response.Trim();
sr.Close();
return true;
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex);
}
catch (Exception ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex);
}
return false;
}
public enum CreateObject2Ret
{
Ok,
Error,
NotFound,
AccessDenied
}
private string GenerateAuthorization()
{
return Util.GenerateHttpAuthorization(_gridSendKey);
}
public CreateObject2Ret DoCreateObject2Call(RegionInfo region, UUID sogId, byte[] sogBytes, bool allowScriptCrossing,
Vector3 pos, bool isAttachment, int numAvatarsToExpect, long nonceID)
{
ulong regionHandle = GetRegionHandle(region.RegionHandle);
string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/object2/" + sogId + "/" + regionHandle.ToString() + "/";
HttpWebRequest objectCreateRequest = (HttpWebRequest)WebRequest.Create(uri);
objectCreateRequest.Method = "POST";
objectCreateRequest.ContentType = "application/octet-stream";
objectCreateRequest.Timeout = CREATE_OBJECT_TIMEOUT;
objectCreateRequest.Headers["authorization"] = GenerateAuthorization();
objectCreateRequest.Headers["x-nonce-id"] = nonceID.ToString();
ObjectPostMessage message = new ObjectPostMessage { NumAvatars = numAvatarsToExpect, Pos = pos, Sog = sogBytes };
try
{
// send the Post
Stream os = objectCreateRequest.GetRequestStream();
ProtoBuf.Serializer.Serialize(os, message);
os.Flush();
os.Close();
m_log.InfoFormat("[REST COMMS]: Posted DoCreateObject2 request to remote sim {0}", uri);
}
catch (Exception e)
{
m_log.InfoFormat("[REST COMMS]: DoCreateObject2 call failed {0}", e);
return CreateObject2Ret.Error;
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
try
{
HttpWebResponse webResponse = (HttpWebResponse)objectCreateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoCreateObject2 post");
return CreateObject2Ret.Error;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string reply = sr.ReadToEnd().Trim();
sr.Close();
//this will happen during the initial rollout and tells us we need to fall back to the
//old method
if (webResponse.StatusCode == HttpStatusCode.Forbidden)
{
m_log.InfoFormat("[REST COMMS]: Entry denied on reply of DoCreateObject2");
return CreateObject2Ret.AccessDenied;
}
else if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
m_log.InfoFormat("[REST COMMS]: NotFound on reply of DoCreateObject2");
return CreateObject2Ret.NotFound;
}
else if (webResponse.StatusCode == HttpStatusCode.OK)
{
return CreateObject2Ret.Ok;
}
else
{
m_log.WarnFormat("[REST COMMS]: Error on reply of DoCreateObject2 {0}", reply);
return CreateObject2Ret.Error;
}
}
catch (WebException ex)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
if (response != null)
{
if (response.StatusCode == HttpStatusCode.Forbidden)
{
m_log.InfoFormat("[REST COMMS]: Entry denied on reply of DoCreateObject2");
return CreateObject2Ret.AccessDenied;
}
else if (response.StatusCode == HttpStatusCode.NotFound)
{
m_log.InfoFormat("[REST COMMS]: NotFound on reply of DoCreateObject2");
return CreateObject2Ret.NotFound;
}
else if (response.StatusCode == HttpStatusCode.OK)
{
return CreateObject2Ret.Ok;
}
else
{
m_log.Error("[REST COMMS]: Error on reply of DoCreateObject2: " + ex.Message);
return CreateObject2Ret.Error;
}
}
else
{
return CreateObject2Ret.Error;
}
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateObject2 {0} Sz {1}", ex, objectCreateRequest.ContentLength);
}
return CreateObject2Ret.Error;
}
public bool DoDeleteObject2Call(RegionInfo region, UUID sogId, long nonceID)
{
ulong regionHandle = GetRegionHandle(region.RegionHandle);
string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/object2/" + sogId + "/" + regionHandle.ToString() + "/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "DELETE";
request.Timeout = CREATE_OBJECT_TIMEOUT;
request.ReadWriteTimeout = CREATE_OBJECT_TIMEOUT;
request.Headers["authorization"] = GenerateAuthorization();
request.Headers["x-nonce-id"] = nonceID.ToString();
try
{
WebResponse webResponse = request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on remote object delete ");
return false;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: DoDeleteObject2Call reply was {0} ", reply);
return true;
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of remote object delete {0}", ex.Message);
}
return false;
}
public bool SendUpdateEstateInfo(RegionInfo region)
{
string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/region/" + region.RegionID + "/" + region.RegionHandle + "/UpdateEstateInfo/";
//m_log.Debug(" >>> DoSendUpdateEstateInfoCall <<< " + uri);
WebRequest sendUpdateEstateInfoRequest = WebRequest.Create(uri);
sendUpdateEstateInfoRequest.Method = "POST";
sendUpdateEstateInfoRequest.ContentType = "application/json";
sendUpdateEstateInfoRequest.Timeout = 10000;
sendUpdateEstateInfoRequest.Headers["authorization"] = GenerateAuthorization();
// Fill it in
OSDMap args = new OSDMap();
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
UTF8Encoding str = new UTF8Encoding();
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of DoSendUpdateEstateInfoCall: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
sendUpdateEstateInfoRequest.ContentLength = buffer.Length; //Count bytes to send
os = sendUpdateEstateInfoRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted DoSendUpdateEstateInfoCall request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
//m_log.InfoFormat("[REST COMMS]: Bad send on DoSendUpdateEstateInfoCall {0}", ex.Message);
return false;
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoSendUpdateEstateInfoCall");
try
{
WebResponse webResponse = sendUpdateEstateInfoRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoSendUpdateEstateInfoCall post");
return false;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: DoSendUpdateEstateInfoCall reply was {0} ", reply);
return true;
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoSendUpdateEstateInfoCall {0}", ex.Message);
}
return false;
}
#region Hyperlinks
public virtual ulong GetRegionHandle(ulong handle)
{
return handle;
}
public virtual bool IsHyperlink(ulong handle)
{
return false;
}
#endregion /* Hyperlinks */
public static OSDMap GetOSDMap(string data)
{
OSDMap args = null;
try
{
OSD buffer;
// We should pay attention to the content-type, but let's assume we know it's Json
buffer = OSDParser.DeserializeJson(data);
if (buffer.Type == OSDType.Map)
{
args = (OSDMap)buffer;
return args;
}
else
{
// uh?
System.Console.WriteLine("[REST COMMS]: Got OSD of type " + buffer.Type.ToString());
return null;
}
}
catch (Exception ex)
{
System.Console.WriteLine("[REST COMMS]: exception on parse of REST message " + ex.Message);
return null;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.