context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
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;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmVAT
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmVAT() : base()
{
FormClosed += frmVAT_FormClosed;
KeyPress += frmVAT_KeyPress;
Resize += frmVAT_Resize;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.TextBox withEventsField__txtFloat_0;
public System.Windows.Forms.TextBox _txtFloat_0 {
get { return withEventsField__txtFloat_0; }
set {
if (withEventsField__txtFloat_0 != null) {
withEventsField__txtFloat_0.Enter -= txtFloat_Enter;
withEventsField__txtFloat_0.KeyPress -= txtFloat_KeyPress;
withEventsField__txtFloat_0.Leave -= txtFloat_Leave;
}
withEventsField__txtFloat_0 = value;
if (withEventsField__txtFloat_0 != null) {
withEventsField__txtFloat_0.Enter += txtFloat_Enter;
withEventsField__txtFloat_0.KeyPress += txtFloat_KeyPress;
withEventsField__txtFloat_0.Leave += txtFloat_Leave;
}
}
}
private System.Windows.Forms.TextBox withEventsField__txtFields_0;
public System.Windows.Forms.TextBox _txtFields_0 {
get { return withEventsField__txtFields_0; }
set {
if (withEventsField__txtFields_0 != null) {
withEventsField__txtFields_0.Enter -= txtFields_Enter;
}
withEventsField__txtFields_0 = value;
if (withEventsField__txtFields_0 != null) {
withEventsField__txtFields_0.Enter += txtFields_Enter;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdCancel;
public System.Windows.Forms.Button cmdCancel {
get { return withEventsField_cmdCancel; }
set {
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click -= cmdCancel_Click;
}
withEventsField_cmdCancel = value;
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click += cmdCancel_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.Label _lblLabels_0;
public System.Windows.Forms.Label _lblLabels_38;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
public System.Windows.Forms.Label _lbl_5;
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
//Public WithEvents txtFloat As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
public RectangleShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmVAT));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this._txtFloat_0 = new System.Windows.Forms.TextBox();
this._txtFields_0 = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this._lblLabels_0 = new System.Windows.Forms.Label();
this._lblLabels_38 = new System.Windows.Forms.Label();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._lbl_5 = new System.Windows.Forms.Label();
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.txtFields = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
//Me.txtFloat = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
this.Shape1 = new RectangleShapeArray(components);
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.txtFields, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.txtFloat, System.ComponentModel.ISupportInitialize).BeginInit()
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Edit VAT Item";
this.ClientSize = new System.Drawing.Size(455, 109);
this.Location = new System.Drawing.Point(73, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmVAT";
this._txtFloat_0.AutoSize = false;
this._txtFloat_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtFloat_0.Size = new System.Drawing.Size(64, 19);
this._txtFloat_0.Location = new System.Drawing.Point(375, 66);
this._txtFloat_0.TabIndex = 3;
this._txtFloat_0.Text = "9,999.99";
this._txtFloat_0.AcceptsReturn = true;
this._txtFloat_0.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_0.CausesValidation = true;
this._txtFloat_0.Enabled = true;
this._txtFloat_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_0.HideSelection = true;
this._txtFloat_0.ReadOnly = false;
this._txtFloat_0.MaxLength = 0;
this._txtFloat_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_0.Multiline = false;
this._txtFloat_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_0.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtFloat_0.TabStop = true;
this._txtFloat_0.Visible = true;
this._txtFloat_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_0.Name = "_txtFloat_0";
this._txtFields_0.AutoSize = false;
this._txtFields_0.Size = new System.Drawing.Size(219, 19);
this._txtFields_0.Location = new System.Drawing.Point(87, 66);
this._txtFields_0.TabIndex = 1;
this._txtFields_0.AcceptsReturn = true;
this._txtFields_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this._txtFields_0.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_0.CausesValidation = true;
this._txtFields_0.Enabled = true;
this._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_0.HideSelection = true;
this._txtFields_0.ReadOnly = false;
this._txtFields_0.MaxLength = 0;
this._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_0.Multiline = false;
this._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_0.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtFields_0.TabStop = true;
this._txtFields_0.Visible = true;
this._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_0.Name = "_txtFields_0";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(455, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 6;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.Location = new System.Drawing.Point(5, 3);
this.cmdCancel.TabIndex = 5;
this.cmdCancel.TabStop = false;
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.CausesValidation = true;
this.cmdCancel.Enabled = true;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Name = "cmdCancel";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(372, 3);
this.cmdClose.TabIndex = 4;
this.cmdClose.TabStop = false;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Name = "cmdClose";
this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_0.Text = "VAT Rate:";
this._lblLabels_0.Size = new System.Drawing.Size(50, 13);
this._lblLabels_0.Location = new System.Drawing.Point(320, 69);
this._lblLabels_0.TabIndex = 2;
this._lblLabels_0.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_0.Enabled = true;
this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_0.UseMnemonic = true;
this._lblLabels_0.Visible = true;
this._lblLabels_0.AutoSize = true;
this._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_0.Name = "_lblLabels_0";
this._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_38.Text = "VAT Name:";
this._lblLabels_38.Size = new System.Drawing.Size(55, 13);
this._lblLabels_38.Location = new System.Drawing.Point(27, 69);
this._lblLabels_38.TabIndex = 0;
this._lblLabels_38.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_38.Enabled = true;
this._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_38.UseMnemonic = true;
this._lblLabels_38.Visible = true;
this._lblLabels_38.AutoSize = true;
this._lblLabels_38.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_38.Name = "_lblLabels_38";
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.Size = new System.Drawing.Size(430, 31);
this._Shape1_2.Location = new System.Drawing.Point(15, 60);
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_2.BorderWidth = 1;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_2.Visible = true;
this._Shape1_2.Name = "_Shape1_2";
this._lbl_5.BackColor = System.Drawing.Color.Transparent;
this._lbl_5.Text = "&1. General";
this._lbl_5.Size = new System.Drawing.Size(60, 13);
this._lbl_5.Location = new System.Drawing.Point(15, 45);
this._lbl_5.TabIndex = 7;
this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_5.Enabled = true;
this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_5.UseMnemonic = true;
this._lbl_5.Visible = true;
this._lbl_5.AutoSize = true;
this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_5.Name = "_lbl_5";
this.Controls.Add(_txtFloat_0);
this.Controls.Add(_txtFields_0);
this.Controls.Add(picButtons);
this.Controls.Add(_lblLabels_0);
this.Controls.Add(_lblLabels_38);
this.ShapeContainer1.Shapes.Add(_Shape1_2);
this.Controls.Add(_lbl_5);
this.Controls.Add(ShapeContainer1);
this.picButtons.Controls.Add(cmdCancel);
this.picButtons.Controls.Add(cmdClose);
//Me.lbl.SetIndex(_lbl_5, CType(5, Short))
//Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short))
//Me.lblLabels.SetIndex(_lblLabels_38, CType(38, Short))
//Me.txtFields.SetIndex(_txtFields_0, CType(0, Short))
//Me.txtFloat.SetIndex(_txtFloat_0, CType(0, Short))
this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2));
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
//CType(Me.txtFloat, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.txtFields, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using LibGit2Sharp.Core;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
namespace LibGit2Sharp.Tests
{
public class CommitFixture : BaseFixture
{
private const string sha = "8496071c1b46c854b31185ea97743be6a8774479";
private readonly List<string> expectedShas = new List<string> { "a4a7d", "c4780", "9fd73", "4a202", "5b5b0", "84960" };
[Fact]
public void CanCountCommits()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Equal(7, repo.Commits.Count());
}
}
[Fact]
public void CanCorrectlyCountCommitsWhenSwitchingToAnotherBranch()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
// Hard reset and then remove untracked files
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Commands.Checkout(repo, "test");
Assert.Equal(2, repo.Commits.Count());
Assert.Equal("e90810b8df3e80c413d903f631643c716887138d", repo.Commits.First().Id.Sha);
Commands.Checkout(repo, "master");
Assert.Equal(9, repo.Commits.Count());
Assert.Equal("32eab9cb1f450b5fe7ab663462b77d7f4b703344", repo.Commits.First().Id.Sha);
}
}
[Fact]
public void CanEnumerateCommits()
{
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits)
{
Assert.NotNull(commit);
count++;
}
}
Assert.Equal(7, count);
}
[Fact]
public void CanEnumerateCommitsInDetachedHeadState()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
ObjectId parentOfHead = repo.Head.Tip.Parents.First().Id;
repo.Refs.Add("HEAD", parentOfHead.Sha, true);
Assert.True(repo.Info.IsHeadDetached);
Assert.Equal(6, repo.Commits.Count());
}
}
[Fact]
public void DefaultOrderingWhenEnumeratingCommitsIsTimeBased()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Equal(CommitSortStrategies.Time, repo.Commits.SortedBy);
}
}
[Fact]
public void CanEnumerateCommitsFromSha()
{
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = "a4a7dce85cf63874e984719f4fdd239f5145052f" }))
{
Assert.NotNull(commit);
count++;
}
}
Assert.Equal(6, count);
}
[Fact]
public void QueryingTheCommitHistoryWithUnknownShaOrInvalidEntryPointThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = Constants.UnknownSha }).Count());
Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = "refs/heads/deadbeef" }).Count());
Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = null }).Count());
}
}
[Fact]
public void QueryingTheCommitHistoryFromACorruptedReferenceThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
CreateCorruptedDeadBeefHead(repo.Info.Path);
Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = repo.Branches["deadbeef"] }).Count());
Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = repo.Refs["refs/heads/deadbeef"] }).Count());
}
}
[Fact]
public void QueryingTheCommitHistoryWithBadParamsThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<ArgumentException>(() => repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = string.Empty }));
Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = null }));
Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(default(CommitFilter)));
}
}
[Fact]
public void CanEnumerateCommitsWithReverseTimeSorting()
{
var reversedShas = new List<string>(expectedShas);
reversedShas.Reverse();
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter
{
IncludeReachableFrom = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse
}))
{
Assert.NotNull(commit);
Assert.StartsWith(reversedShas[count], commit.Sha);
count++;
}
}
Assert.Equal(6, count);
}
[Fact]
public void CanEnumerateCommitsWithReverseTopoSorting()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
List<Commit> commits = repo.Commits.QueryBy(new CommitFilter
{
IncludeReachableFrom = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse
}).ToList();
foreach (Commit commit in commits)
{
Assert.NotNull(commit);
foreach (Commit p in commit.Parents)
{
Commit parent = commits.Single(x => x.Id == p.Id);
Assert.True(commits.IndexOf(commit) > commits.IndexOf(parent));
}
}
}
}
[Fact]
public void CanSimplifyByFirstParent()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = repo.Head, FirstParentOnly = true },
new[]
{
"4c062a6", "be3563a", "9fd738e",
"4a202b3", "5b5b025", "8496071",
});
}
[Fact]
public void CanGetParentsCount()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Single(repo.Commits.First().Parents);
}
}
[Fact]
public void CanEnumerateCommitsWithTimeSorting()
{
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter
{
IncludeReachableFrom = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Time
}))
{
Assert.NotNull(commit);
Assert.StartsWith(expectedShas[count], commit.Sha);
count++;
}
}
Assert.Equal(6, count);
}
[Fact]
public void CanEnumerateCommitsWithTopoSorting()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
List<Commit> commits = repo.Commits.QueryBy(new CommitFilter
{
IncludeReachableFrom = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Topological
}).ToList();
foreach (Commit commit in commits)
{
Assert.NotNull(commit);
foreach (Commit p in commit.Parents)
{
Commit parent = commits.Single(x => x.Id == p.Id);
Assert.True(commits.IndexOf(commit) < commits.IndexOf(parent));
}
}
}
}
[Fact]
public void CanEnumerateFromHead()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = repo.Head },
new[]
{
"4c062a6", "be3563a", "c47800c", "9fd738e",
"4a202b3", "5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateFromDetachedHead()
{
string path = SandboxStandardTestRepo();
using (var repoClone = new Repository(path))
{
// Hard reset and then remove untracked files
repoClone.Reset(ResetMode.Hard);
repoClone.RemoveUntrackedFiles();
string headSha = repoClone.Head.Tip.Sha;
Commands.Checkout(repoClone, headSha);
AssertEnumerationOfCommitsInRepo(repoClone,
repo => new CommitFilter { IncludeReachableFrom = repo.Head },
new[]
{
"32eab9c", "592d3c8", "4c062a6",
"be3563a", "c47800c", "9fd738e",
"4a202b3", "5b5b025", "8496071",
});
}
}
[Fact]
public void CanEnumerateUsingTwoHeadsAsBoundaries()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = "HEAD", ExcludeReachableFrom = "refs/heads/br2" },
new[] { "4c062a6", "be3563a" }
);
}
[Fact]
public void CanEnumerateUsingImplicitHeadAsSinceBoundary()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { ExcludeReachableFrom = "refs/heads/br2" },
new[] { "4c062a6", "be3563a" }
);
}
[Fact]
public void CanEnumerateUsingTwoAbbreviatedShasAsBoundaries()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = "a4a7dce", ExcludeReachableFrom = "4a202b3" },
new[] { "a4a7dce", "c47800c", "9fd738e" }
);
}
[Fact]
public void CanEnumerateCommitsFromTwoHeads()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = new[] { "refs/heads/br2", "refs/heads/master" } },
new[]
{
"4c062a6", "a4a7dce", "be3563a", "c47800c",
"9fd738e", "4a202b3", "5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateCommitsFromMixedStartingPoints()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = new object[] { repo.Branches["br2"],
"refs/heads/master",
new ObjectId("e90810b8df3e80c413d903f631643c716887138d") } },
new[]
{
"4c062a6", "e90810b", "6dcf9bf", "a4a7dce",
"be3563a", "c47800c", "9fd738e", "4a202b3",
"5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateCommitsUsingGlob()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = repo.Refs.FromGlob("refs/heads/*") },
new[]
{
"4c062a6", "e90810b", "6dcf9bf", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "41bc8c6", "5001298", "5b5b025", "8496071"
});
}
[Fact]
public void CanHideCommitsUsingGlob()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = "refs/heads/packed-test", ExcludeReachableFrom = repo.Refs.FromGlob("*/packed") },
new[]
{
"4a202b3", "5b5b025", "8496071"
});
}
[Fact]
public void CanEnumerateCommitsFromAnAnnotatedTag()
{
CanEnumerateCommitsFromATag(t => t);
}
[Fact]
public void CanEnumerateCommitsFromATagAnnotation()
{
CanEnumerateCommitsFromATag(t => t.Annotation);
}
private void CanEnumerateCommitsFromATag(Func<Tag, object> transformer)
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = transformer(repo.Tags["test"]) },
new[] { "e90810b", "6dcf9bf", }
);
}
[Fact]
public void CanEnumerateAllCommits()
{
AssertEnumerationOfCommits(
repo => new CommitFilter
{
IncludeReachableFrom = repo.Refs.OrderBy(r => r.CanonicalName, StringComparer.Ordinal),
},
new[]
{
"44d5d18", "bb65291", "532740a", "503a16f", "3dfd6fd",
"4409de1", "902c60b", "4c062a6", "e90810b", "6dcf9bf",
"a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3",
"41bc8c6", "5001298", "5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateCommitsFromATagWhichPointsToABlob()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { IncludeReachableFrom = repo.Tags["point_to_blob"] },
new string[] { });
}
[Fact]
public void CanEnumerateCommitsFromATagWhichPointsToATree()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
string headTreeSha = repo.Head.Tip.Tree.Sha;
Tag tag = repo.ApplyTag("point_to_tree", headTreeSha);
AssertEnumerationOfCommitsInRepo(repo,
r => new CommitFilter { IncludeReachableFrom = tag },
new string[] { });
}
}
private void AssertEnumerationOfCommits(Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds)
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
AssertEnumerationOfCommitsInRepo(repo, filterBuilder, abbrevIds);
}
}
private static void AssertEnumerationOfCommitsInRepo(IRepository repo, Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds)
{
ICommitLog commits = repo.Commits.QueryBy(filterBuilder(repo));
IEnumerable<string> commitShas = commits.Select(c => c.Id.ToString(7)).ToArray();
Assert.Equal(abbrevIds, commitShas);
}
[Fact]
public void CanLookupCommitGeneric()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>(sha);
Assert.Equal("testing\n", commit.Message);
Assert.Equal("testing", commit.MessageShort);
Assert.Equal(sha, commit.Sha);
}
}
[Fact]
public void CanReadCommitData()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
GitObject obj = repo.Lookup(sha);
Assert.NotNull(obj);
Assert.Equal(typeof(Commit), obj.GetType());
var commit = (Commit)obj;
Assert.Equal("testing\n", commit.Message);
Assert.Equal("testing", commit.MessageShort);
Assert.Equal("UTF-8", commit.Encoding);
Assert.Equal(sha, commit.Sha);
Assert.NotNull(commit.Author);
Assert.Equal("Scott Chacon", commit.Author.Name);
Assert.Equal("schacon@gmail.com", commit.Author.Email);
Assert.Equal(1273360386, commit.Author.When.ToUnixTimeSeconds());
Assert.NotNull(commit.Committer);
Assert.Equal("Scott Chacon", commit.Committer.Name);
Assert.Equal("schacon@gmail.com", commit.Committer.Email);
Assert.Equal(1273360386, commit.Committer.When.ToUnixTimeSeconds());
Assert.Equal("181037049a54a1eb5fab404658a3a250b44335d7", commit.Tree.Sha);
Assert.Empty(commit.Parents);
}
}
[Fact]
public void CanReadCommitWithMultipleParents()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("a4a7dce85cf63874e984719f4fdd239f5145052f");
Assert.Equal(2, commit.Parents.Count());
}
}
[Fact]
public void CanDirectlyAccessABlobOfTheCommit()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("4c062a6");
var blob = commit["1/branch_file.txt"].Target as Blob;
Assert.NotNull(blob);
Assert.Equal("hi\n", blob.GetContentText());
}
}
[Fact]
public void CanDirectlyAccessATreeOfTheCommit()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("4c062a6");
var tree1 = commit["1"].Target as Tree;
Assert.NotNull(tree1);
}
}
[Fact]
public void DirectlyAccessingAnUnknownTreeEntryOfTheCommitReturnsNull()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("4c062a6");
Assert.Null(commit["I-am-not-here"]);
}
}
[Fact]
public void CanCommitWithSignatureFromConfig()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
CreateConfigurationWithDummyUser(repo, Constants.Identity);
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
const string relativeFilepath = "new.txt";
string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null");
Commands.Stage(repo, relativeFilepath);
File.AppendAllText(filePath, "token\n");
Commands.Stage(repo, relativeFilepath);
Assert.Null(repo.Head[relativeFilepath]);
Signature signature = repo.Config.BuildSignature(DateTimeOffset.Now);
Commit commit = repo.Commit("Initial egotistic commit", signature, signature);
AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n");
AssertBlobContent(commit[relativeFilepath], "nulltoken\n");
AssertCommitIdentitiesAre(commit, Constants.Identity);
}
}
[Fact]
public void CommitParentsAreMergeHeads()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard, "c47800");
CreateAndStageANewFile(repo);
Touch(repo.Info.Path, "MERGE_HEAD", "9fd738e8f7967c078dceed8190330fc8648ee56a\n");
Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation);
Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);
Assert.Equal(CurrentOperation.None, repo.Info.CurrentOperation);
Assert.Equal(2, newMergedCommit.Parents.Count());
Assert.Equal("c47800c7266a2be04c571c04d5a6614691ea99bd", newMergedCommit.Parents.First().Sha);
Assert.Equal("9fd738e8f7967c078dceed8190330fc8648ee56a", newMergedCommit.Parents.Skip(1).First().Sha);
// Assert reflog entry is created
var reflogEntry = repo.Refs.Log(repo.Refs.Head).First();
Assert.Equal(repo.Head.Tip.Id, reflogEntry.To);
Assert.NotNull(reflogEntry.Committer.Email);
Assert.NotNull(reflogEntry.Committer.Name);
Assert.Equal(string.Format("commit (merge): {0}", newMergedCommit.MessageShort), reflogEntry.Message);
}
}
[Fact]
public void CommitCleansUpMergeMetadata()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
const string relativeFilepath = "new.txt";
Touch(repo.Info.WorkingDirectory, relativeFilepath, "this is a new file");
Commands.Stage(repo, relativeFilepath);
string mergeHeadPath = Touch(repo.Info.Path, "MERGE_HEAD", "abcdefabcdefabcdefabcdefabcdefabcdefabcd");
string mergeMsgPath = Touch(repo.Info.Path, "MERGE_MSG", "This is a dummy merge.\n");
string mergeModePath = Touch(repo.Info.Path, "MERGE_MODE", "no-ff");
string origHeadPath = Touch(repo.Info.Path, "ORIG_HEAD", "beefbeefbeefbeefbeefbeefbeefbeefbeefbeef");
Assert.True(File.Exists(mergeHeadPath));
Assert.True(File.Exists(mergeMsgPath));
Assert.True(File.Exists(mergeModePath));
Assert.True(File.Exists(origHeadPath));
var author = Constants.Signature;
repo.Commit("Initial egotistic commit", author, author);
Assert.False(File.Exists(mergeHeadPath));
Assert.False(File.Exists(mergeMsgPath));
Assert.False(File.Exists(mergeModePath));
Assert.True(File.Exists(origHeadPath));
}
}
[Fact]
public void CanCommitALittleBit()
{
string repoPath = InitNewRepository();
var identity = Constants.Identity;
using (var repo = new Repository(repoPath, new RepositoryOptions { Identity = identity }))
{
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
const string relativeFilepath = "new.txt";
string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null");
Commands.Stage(repo, relativeFilepath);
File.AppendAllText(filePath, "token\n");
Commands.Stage(repo, relativeFilepath);
Assert.Null(repo.Head[relativeFilepath]);
var author = Constants.Signature;
const string shortMessage = "Initial egotistic commit";
const string commitMessage = shortMessage + "\n\nOnly the coolest commits from us";
var before = DateTimeOffset.Now.TruncateMilliseconds();
Commit commit = repo.Commit(commitMessage, author, author);
AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n");
AssertBlobContent(commit[relativeFilepath], "nulltoken\n");
Assert.Empty(commit.Parents);
Assert.False(repo.Info.IsHeadUnborn);
// Assert a reflog entry is created on HEAD
Assert.Single(repo.Refs.Log("HEAD"));
var reflogEntry = repo.Refs.Log("HEAD").First();
Assert.Equal(identity.Name, reflogEntry.Committer.Name);
Assert.Equal(identity.Email, reflogEntry.Committer.Email);
var now = DateTimeOffset.Now;
Assert.InRange(reflogEntry.Committer.When, before, now);
Assert.Equal(commit.Id, reflogEntry.To);
Assert.Equal(ObjectId.Zero, reflogEntry.From);
Assert.Equal(string.Format("commit (initial): {0}", shortMessage), reflogEntry.Message);
// Assert a reflog entry is created on HEAD target
var targetCanonicalName = repo.Refs.Head.TargetIdentifier;
Assert.Single(repo.Refs.Log(targetCanonicalName));
Assert.Equal(commit.Id, repo.Refs.Log(targetCanonicalName).First().To);
File.WriteAllText(filePath, "nulltoken commits!\n");
Commands.Stage(repo, relativeFilepath);
var author2 = new Signature(author.Name, author.Email, author.When.AddSeconds(5));
Commit commit2 = repo.Commit("Are you trying to fork me?", author2, author2);
AssertBlobContent(repo.Head[relativeFilepath], "nulltoken commits!\n");
AssertBlobContent(commit2[relativeFilepath], "nulltoken commits!\n");
Assert.Single(commit2.Parents);
Assert.Equal(commit.Id, commit2.Parents.First().Id);
// Assert the reflog is shifted
Assert.Equal(2, repo.Refs.Log("HEAD").Count());
Assert.Equal(reflogEntry.To, repo.Refs.Log("HEAD").First().From);
Branch firstCommitBranch = repo.CreateBranch("davidfowl-rules", commit);
Commands.Checkout(repo, firstCommitBranch);
File.WriteAllText(filePath, "davidfowl commits!\n");
var author3 = new Signature("David Fowler", "david.fowler@microsoft.com", author.When.AddSeconds(2));
Commands.Stage(repo, relativeFilepath);
Commit commit3 = repo.Commit("I'm going to branch you backwards in time!", author3, author3);
AssertBlobContent(repo.Head[relativeFilepath], "davidfowl commits!\n");
AssertBlobContent(commit3[relativeFilepath], "davidfowl commits!\n");
Assert.Single(commit3.Parents);
Assert.Equal(commit.Id, commit3.Parents.First().Id);
AssertBlobContent(firstCommitBranch[relativeFilepath], "nulltoken\n");
}
}
private static void AssertBlobContent(TreeEntry entry, string expectedContent)
{
Assert.Equal(TreeEntryTargetType.Blob, entry.TargetType);
Assert.Equal(expectedContent, ((Blob)(entry.Target)).GetContentText());
}
private static void AddCommitToRepo(string path)
{
using (var repo = new Repository(path))
{
const string relativeFilepath = "test.txt";
Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n");
Commands.Stage(repo, relativeFilepath);
var author = new Signature("nulltoken", "emeric.fermas@gmail.com", DateTimeOffset.Parse("Wed, Dec 14 2011 08:29:03 +0100"));
repo.Commit("Initial commit", author, author);
}
}
[Fact]
public void CanGeneratePredictableObjectShas()
{
string repoPath = InitNewRepository();
AddCommitToRepo(repoPath);
using (var repo = new Repository(repoPath))
{
Commit commit = repo.Commits.Single();
Assert.Equal("1fe3126578fc4eca68c193e4a3a0a14a0704624d", commit.Sha);
Tree tree = commit.Tree;
Assert.Equal("2b297e643c551e76cfa1f93810c50811382f9117", tree.Sha);
GitObject blob = tree.Single().Target;
Assert.IsAssignableFrom<Blob>(blob);
Assert.Equal("9daeafb9864cf43055ae93beb0afd6c7d144bfa4", blob.Sha);
}
}
[Fact]
public void CanAmendARootCommit()
{
string repoPath = InitNewRepository();
AddCommitToRepo(repoPath);
using (var repo = new Repository(repoPath))
{
Assert.Single(repo.Head.Commits);
Commit originalCommit = repo.Head.Tip;
Assert.Empty(originalCommit.Parents);
CreateAndStageANewFile(repo);
Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true });
Assert.Single(repo.Head.Commits);
AssertCommitHasBeenAmended(repo, amendedCommit, originalCommit);
}
}
[Fact]
public void CanAmendACommitWithMoreThanOneParent()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path, new RepositoryOptions { Identity = Constants.Identity }))
{
var mergedCommit = repo.Lookup<Commit>("be3563a");
Assert.NotNull(mergedCommit);
Assert.Equal(2, mergedCommit.Parents.Count());
repo.Reset(ResetMode.Soft, mergedCommit.Sha);
CreateAndStageANewFile(repo);
const string commitMessage = "I'm rewriting the history!";
var before = DateTimeOffset.Now.TruncateMilliseconds();
Commit amendedCommit = repo.Commit(commitMessage, Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true });
AssertCommitHasBeenAmended(repo, amendedCommit, mergedCommit);
AssertRefLogEntry(repo, "HEAD",
string.Format("commit (amend): {0}", commitMessage),
mergedCommit.Id,
amendedCommit.Id,
Constants.Identity, before);
}
}
private static void CreateAndStageANewFile(IRepository repo)
{
string relativeFilepath = string.Format("new-file-{0}.txt", Path.GetRandomFileName());
Touch(repo.Info.WorkingDirectory, relativeFilepath, "brand new content\n");
Commands.Stage(repo, relativeFilepath);
}
private static void AssertCommitHasBeenAmended(IRepository repo, Commit amendedCommit, Commit originalCommit)
{
Commit headCommit = repo.Head.Tip;
Assert.Equal(amendedCommit, headCommit);
Assert.NotEqual(originalCommit.Sha, amendedCommit.Sha);
Assert.Equal(originalCommit.Parents, amendedCommit.Parents);
}
[Fact]
public void CanNotAmendAnEmptyRepository()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Assert.Throws<UnbornBranchException>(() =>
repo.Commit("I can not amend anything !:(", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true }));
}
}
[Fact]
public void CanRetrieveChildrenOfASpecificCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
const string parentSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644";
var filter = new CommitFilter
{
/* Revwalk from all the refs (git log --all) ... */
IncludeReachableFrom = repo.Refs,
/* ... and stop when the parent is reached */
ExcludeReachableFrom = parentSha
};
var commits = repo.Commits.QueryBy(filter);
var children = from c in commits
from p in c.Parents
let pId = p.Id
where pId.Sha == parentSha
select c;
var expectedChildren = new[] { "c47800c7266a2be04c571c04d5a6614691ea99bd",
"4a202b346bb0fb0db7eff3cffeb3c70babbd2045" };
Assert.Equal(expectedChildren, children.Select(c => c.Id.Sha));
}
}
[Fact]
public void CanCorrectlyDistinguishAuthorFromCommitter()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
var author = new Signature("Wilbert van Dolleweerd", "getit@xs4all.nl",
DateTimeOffset.FromUnixTimeSeconds(1244187936).ToOffset(TimeSpan.FromMinutes(120)));
var committer = new Signature("Henk Westhuis", "Henk_Westhuis@hotmail.com",
DateTimeOffset.FromUnixTimeSeconds(1244286496).ToOffset(TimeSpan.FromMinutes(120)));
Commit c = repo.Commit("I can haz an author and a committer!", author, committer);
Assert.Equal(author, c.Author);
Assert.Equal(committer, c.Committer);
}
}
[Fact]
public void CanCommitOnOrphanedBranch()
{
string newBranchName = "refs/heads/newBranch";
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
// Set Head to point to branch other than master
repo.Refs.UpdateTarget("HEAD", newBranchName);
Assert.Equal(newBranchName, repo.Head.CanonicalName);
const string relativeFilepath = "test.txt";
Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n");
Commands.Stage(repo, relativeFilepath);
repo.Commit("Initial commit", Constants.Signature, Constants.Signature);
Assert.Single(repo.Head.Commits);
}
}
[Fact]
public void CanNotCommitAnEmptyCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature));
}
}
[Fact]
public void CanCommitAnEmptyCommitWhenForced()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AllowEmptyCommit = true });
}
}
[Fact]
public void CanNotAmendAnEmptyCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AllowEmptyCommit = true });
Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true }));
}
}
[Fact]
public void CanAmendAnEmptyCommitWhenForced()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Commit emptyCommit = repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AllowEmptyCommit = true });
Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true, AllowEmptyCommit = true });
AssertCommitHasBeenAmended(repo, amendedCommit, emptyCommit);
}
}
[Fact]
public void CanCommitAnEmptyCommitWhenMerging()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");
Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation);
Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);
Assert.Equal(2, newMergedCommit.Parents.Count());
Assert.Equal("32eab9cb1f450b5fe7ab663462b77d7f4b703344", newMergedCommit.Parents.First().Sha);
Assert.Equal("f705abffe7015f2beacf2abe7a36583ebee3487e", newMergedCommit.Parents.Skip(1).First().Sha);
}
}
[Fact]
public void CanAmendAnEmptyMergeCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");
Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);
Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true });
AssertCommitHasBeenAmended(repo, amendedCommit, newMergedCommit);
}
}
[Fact]
public void CanNotAmendACommitInAWayThatWouldLeadTheNewCommitToBecomeEmpty()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Touch(repo.Info.WorkingDirectory, "test.txt", "test\n");
Commands.Stage(repo, "test.txt");
repo.Commit("Initial commit", Constants.Signature, Constants.Signature);
Touch(repo.Info.WorkingDirectory, "new.txt", "content\n");
Commands.Stage(repo, "new.txt");
repo.Commit("One commit", Constants.Signature, Constants.Signature);
Commands.Remove(repo, "new.txt");
Assert.Throws<EmptyCommitException>(() => repo.Commit("Oops", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true }));
}
}
[Fact]
public void CanPrettifyAMessage()
{
string input = "# Comment\nA line that will remain\n# And another character\n\n\n";
string expected = "A line that will remain\n";
Assert.Equal(expected, Commit.PrettifyMessage(input, '#'));
Assert.Equal(expected, Commit.PrettifyMessage(input.Replace('#', ';'), ';'));
}
private readonly string signedCommit =
"tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n" +
"parent 8496071c1b46c854b31185ea97743be6a8774479\n" +
"author Ben Burkert <ben@benburkert.com> 1358451456 -0800\n" +
"committer Ben Burkert <ben@benburkert.com> 1358451456 -0800\n" +
"gpgsig -----BEGIN PGP SIGNATURE-----\n" +
" Version: GnuPG v1.4.12 (Darwin)\n" +
" \n" +
" iQIcBAABAgAGBQJQ+FMIAAoJEH+LfPdZDSs1e3EQAJMjhqjWF+WkGLHju7pTw2al\n" +
" o6IoMAhv0Z/LHlWhzBd9e7JeCnanRt12bAU7yvYp9+Z+z+dbwqLwDoFp8LVuigl8\n" +
" JGLcnwiUW3rSvhjdCp9irdb4+bhKUnKUzSdsR2CK4/hC0N2i/HOvMYX+BRsvqweq\n" +
" AsAkA6dAWh+gAfedrBUkCTGhlNYoetjdakWqlGL1TiKAefEZrtA1TpPkGn92vbLq\n" +
" SphFRUY9hVn1ZBWrT3hEpvAIcZag3rTOiRVT1X1flj8B2vGCEr3RrcwOIZikpdaW\n" +
" who/X3xh/DGbI2RbuxmmJpxxP/8dsVchRJJzBwG+yhwU/iN3MlV2c5D69tls/Dok\n" +
" 6VbyU4lm/ae0y3yR83D9dUlkycOnmmlBAHKIZ9qUts9X7mWJf0+yy2QxJVpjaTGG\n" +
" cmnQKKPeNIhGJk2ENnnnzjEve7L7YJQF6itbx5VCOcsGh3Ocb3YR7DMdWjt7f8pu\n" +
" c6j+q1rP7EpE2afUN/geSlp5i3x8aXZPDj67jImbVCE/Q1X9voCtyzGJH7MXR0N9\n" +
" ZpRF8yzveRfMH8bwAJjSOGAFF5XkcR/RNY95o+J+QcgBLdX48h+ZdNmUf6jqlu3J\n" +
" 7KmTXXQcOVpN6dD3CmRFsbjq+x6RHwa8u1iGn+oIkX908r97ckfB/kHKH7ZdXIJc\n" +
" cpxtDQQMGYFpXK/71stq\n" +
" =ozeK\n" +
" -----END PGP SIGNATURE-----\n" +
"\n" +
"a simple commit which works\n";
private readonly string signatureData =
"-----BEGIN PGP SIGNATURE-----\n" +
"Version: GnuPG v1.4.12 (Darwin)\n" +
"\n" +
"iQIcBAABAgAGBQJQ+FMIAAoJEH+LfPdZDSs1e3EQAJMjhqjWF+WkGLHju7pTw2al\n" +
"o6IoMAhv0Z/LHlWhzBd9e7JeCnanRt12bAU7yvYp9+Z+z+dbwqLwDoFp8LVuigl8\n" +
"JGLcnwiUW3rSvhjdCp9irdb4+bhKUnKUzSdsR2CK4/hC0N2i/HOvMYX+BRsvqweq\n" +
"AsAkA6dAWh+gAfedrBUkCTGhlNYoetjdakWqlGL1TiKAefEZrtA1TpPkGn92vbLq\n" +
"SphFRUY9hVn1ZBWrT3hEpvAIcZag3rTOiRVT1X1flj8B2vGCEr3RrcwOIZikpdaW\n" +
"who/X3xh/DGbI2RbuxmmJpxxP/8dsVchRJJzBwG+yhwU/iN3MlV2c5D69tls/Dok\n" +
"6VbyU4lm/ae0y3yR83D9dUlkycOnmmlBAHKIZ9qUts9X7mWJf0+yy2QxJVpjaTGG\n" +
"cmnQKKPeNIhGJk2ENnnnzjEve7L7YJQF6itbx5VCOcsGh3Ocb3YR7DMdWjt7f8pu\n" +
"c6j+q1rP7EpE2afUN/geSlp5i3x8aXZPDj67jImbVCE/Q1X9voCtyzGJH7MXR0N9\n" +
"ZpRF8yzveRfMH8bwAJjSOGAFF5XkcR/RNY95o+J+QcgBLdX48h+ZdNmUf6jqlu3J\n" +
"7KmTXXQcOVpN6dD3CmRFsbjq+x6RHwa8u1iGn+oIkX908r97ckfB/kHKH7ZdXIJc\n" +
"cpxtDQQMGYFpXK/71stq\n" +
"=ozeK\n" +
"-----END PGP SIGNATURE-----";
private readonly string signedData =
"tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n" +
"parent 8496071c1b46c854b31185ea97743be6a8774479\n" +
"author Ben Burkert <ben@benburkert.com> 1358451456 -0800\n" +
"committer Ben Burkert <ben@benburkert.com> 1358451456 -0800\n" +
"\n" +
"a simple commit which works\n";
[Fact]
public void CanExtractSignatureFromCommit()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
var odb = repo.ObjectDatabase;
var signedId = odb.Write<Commit>(Encoding.UTF8.GetBytes(signedCommit));
// Look up the commit to make sure we wrote something valid
var commit = repo.Lookup<Commit>(signedId);
Assert.Equal("a simple commit which works\n", commit.Message);
var signatureInfo = Commit.ExtractSignature(repo, signedId, "gpgsig");
Assert.Equal(signedData, signatureInfo.SignedData);
Assert.Equal(signatureData, signatureInfo.Signature);
signatureInfo = Commit.ExtractSignature(repo, signedId);
Assert.Equal(signedData, signatureInfo.SignedData);
Assert.Equal(signatureData, signatureInfo.Signature);
}
}
[Fact]
public void CanCreateACommitString()
{
string repoPath = SandboxStandardTestRepo();
using (var repo = new Repository(repoPath))
{
var tipCommit = repo.Head.Tip;
var recreatedCommit = Commit.CreateBuffer(
tipCommit.Author,
tipCommit.Committer,
tipCommit.Message,
tipCommit.Tree,
tipCommit.Parents,
false, null);
var recreatedId = repo.ObjectDatabase.Write<Commit>(Encoding.UTF8.GetBytes(recreatedCommit));
Assert.Equal(tipCommit.Id, recreatedId);
}
}
[Fact]
public void CanCreateASignedCommit()
{
string repoPath = SandboxStandardTestRepo();
using (var repo = new Repository(repoPath))
{
var odb = repo.ObjectDatabase;
var signedId = odb.Write<Commit>(Encoding.UTF8.GetBytes(signedCommit));
var signedId2 = odb.CreateCommitWithSignature(signedData, signatureData);
Assert.Equal(signedId, signedId2);
var signatureInfo = Commit.ExtractSignature(repo, signedId2);
Assert.Equal(signedData, signatureInfo.SignedData);
Assert.Equal(signatureData, signatureInfo.Signature);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Xml.Serialization;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class contains utility methods for the MSBuild engine.
/// </summary>
/// <owner>RGoel</owner>
static public class Utilities
{
private readonly static Regex singlePropertyRegex = new Regex(@"^\$\(([^\$\(\)]*)\)$");
/// <summary>
/// Update our table which keeps track of all the properties that are referenced
/// inside of a condition and the string values that they are being tested against.
/// So, for example, if the condition was " '$(Configuration)' == 'Debug' ", we
/// would get passed in leftValue="$(Configuration)" and rightValueExpanded="Debug".
/// This call would add the string "Debug" to the list of possible values for the
/// "Configuration" property.
///
/// This method also handles the case when two or more properties are being
/// concatenated together with a vertical bar, as in '
/// $(Configuration)|$(Platform)' == 'Debug|x86'
/// </summary>
/// <param name="conditionedPropertiesTable"></param>
/// <param name="leftValue"></param>
/// <param name="rightValueExpanded"></param>
/// <owner>rgoel</owner>
internal static void UpdateConditionedPropertiesTable
(
Hashtable conditionedPropertiesTable, // Hash table containing a StringCollection
// of possible values, keyed by property name.
string leftValue, // The raw value on the left side of the operator
string rightValueExpanded // The fully expanded value on the right side
// of the operator.
)
{
if ((conditionedPropertiesTable != null) && (rightValueExpanded.Length > 0))
{
// The left side should be exactly "$(propertyname)" or "$(propertyname1)|$(propertyname2)"
// or "$(propertyname1)|$(propertyname2)|$(propertyname3)", etc. Anything else,
// and we don't touch the table.
// Split up the leftValue into pieces based on the vertical bar character.
string[] leftValuePieces = leftValue.Split(new char[]{'|'});
// Loop through each of the pieces.
for (int i = 0 ; i < leftValuePieces.Length ; i++)
{
Match singlePropertyMatch = singlePropertyRegex.Match(leftValuePieces[i]);
if (singlePropertyMatch.Success)
{
// Find the first vertical bar on the right-hand-side expression.
int indexOfVerticalBar = rightValueExpanded.IndexOf('|');
string rightValueExpandedPiece;
// If there was no vertical bar, then just use the remainder of the right-hand-side
// expression as the value of the property, and terminate the loop after this iteration.
// Also, if we're on the last segment of the left-hand-side, then use the remainder
// of the right-hand-side expression as the value of the property.
if ((indexOfVerticalBar == -1) || (i == (leftValuePieces.Length - 1)))
{
rightValueExpandedPiece = rightValueExpanded;
i = leftValuePieces.Length;
}
else
{
// If we found a vertical bar, then the portion before the vertical bar is the
// property value which we will store in our table. Then remove that portion
// from the original string so that the next iteration of the loop can easily search
// for the first vertical bar again.
rightValueExpandedPiece = rightValueExpanded.Substring(0, indexOfVerticalBar);
rightValueExpanded = rightValueExpanded.Substring(indexOfVerticalBar + 1);
}
// Capture the property name out of the regular expression.
string propertyName = singlePropertyMatch.Groups[1].ToString();
// Get the string collection for this property name, if one already exists.
StringCollection conditionedPropertyValues =
(StringCollection) conditionedPropertiesTable[propertyName];
// If this property is not already represented in the table, add a new entry
// for it.
if (conditionedPropertyValues == null)
{
conditionedPropertyValues = new StringCollection();
conditionedPropertiesTable[propertyName] = conditionedPropertyValues;
}
// If the "rightValueExpanded" is not already in the string collection
// for this property name, add it now.
if (!conditionedPropertyValues.Contains(rightValueExpandedPiece))
{
conditionedPropertyValues.Add(rightValueExpandedPiece);
}
}
}
}
}
/*
* Method: GatherReferencedPropertyNames
* Owner: DavidLe
*
* Find and record all of the properties that are referenced in the given
* condition.
*
* FUTURE: it is unfortunate that we have to completely parse+evaluate the expression
*/
internal static void GatherReferencedPropertyNames
(
string condition, // Can be null
XmlAttribute conditionAttribute, // XML attribute on which the condition is evaluated
Expander expander, // The set of properties to use for expansion
Hashtable conditionedPropertiesTable // Can be null
)
{
EvaluateCondition(condition, conditionAttribute, expander, conditionedPropertiesTable, ParserOptions.AllowProperties | ParserOptions.AllowItemLists, null, null);
}
// An array of hashtables with cached expression trees for all the combinations of condition strings
// and parser options
private static volatile Hashtable[] cachedExpressionTrees = new Hashtable[8 /* == ParserOptions.AllowAll*/]
{
new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase),
new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase),
new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase),
new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase)
};
/// <summary>
/// Evaluates a string representing a condition from a "condition" attribute.
/// If the condition is a malformed string, it throws an InvalidProjectFileException.
/// This method uses cached expression trees to avoid generating them from scratch every time it's called.
/// This method is thread safe and is called from engine and task execution module threads
/// </summary>
/// <param name="condition">Can be null</param>
/// <param name="conditionAttribute">XML attribute on which the condition is evaluated</param>
/// <param name="expander">All the data available for expanding embedded properties, metadata, and items</param>
/// <param name="itemListOptions"></param>
/// <returns>true, if the expression evaluates to true, otherwise false</returns>
internal static bool EvaluateCondition
(
string condition,
XmlAttribute conditionAttribute,
Expander expander,
ParserOptions itemListOptions,
Project parentProject
)
{
return EvaluateCondition(condition,
conditionAttribute,
expander,
parentProject.ConditionedProperties,
itemListOptions,
parentProject.ParentEngine.LoggingServices,
parentProject.ProjectBuildEventContext);
}
/// <summary>
/// Evaluates a string representing a condition from a "condition" attribute.
/// If the condition is a malformed string, it throws an InvalidProjectFileException.
/// This method uses cached expression trees to avoid generating them from scratch every time it's called.
/// This method is thread safe and is called from engine and task execution module threads
/// </summary>
/// <param name="condition">Can be null</param>
/// <param name="conditionAttribute">XML attribute on which the condition is evaluated</param>
/// <param name="expander">All the data available for expanding embedded properties, metadata, and items</param>
/// <param name="itemListOptions"></param>
/// <param name="loggingServices">Can be null</param>
/// <param name="eventContext"> contains contextual information for logging events</param>
/// <returns>true, if the expression evaluates to true, otherwise false</returns>
internal static bool EvaluateCondition
(
string condition,
XmlAttribute conditionAttribute,
Expander expander,
ParserOptions itemListOptions,
EngineLoggingServices loggingServices,
BuildEventContext buildEventContext
)
{
return EvaluateCondition(condition,
conditionAttribute,
expander,
null,
itemListOptions,
loggingServices,
buildEventContext);
}
/// <summary>
/// Evaluates a string representing a condition from a "condition" attribute.
/// If the condition is a malformed string, it throws an InvalidProjectFileException.
/// This method uses cached expression trees to avoid generating them from scratch every time it's called.
/// This method is thread safe and is called from engine and task execution module threads
/// </summary>
/// <param name="condition">Can be null</param>
/// <param name="conditionAttribute">XML attribute on which the condition is evaluated</param>
/// <param name="expander">All the data available for expanding embedded properties, metadata, and items</param>
/// <param name="conditionedPropertiesTable">Can be null</param>
/// <param name="itemListOptions"></param>
/// <param name="loggingServices">Can be null</param>
/// <param name="buildEventContext"> contains contextual information for logging events</param>
/// <returns>true, if the expression evaluates to true, otherwise false</returns>
internal static bool EvaluateCondition
(
string condition,
XmlAttribute conditionAttribute,
Expander expander,
Hashtable conditionedPropertiesTable,
ParserOptions itemListOptions,
EngineLoggingServices loggingServices,
BuildEventContext buildEventContext
)
{
ErrorUtilities.VerifyThrow((conditionAttribute != null) || (condition.Length == 0),
"If condition is non-empty, you must provide the XML node representing the condition.");
// An empty condition is equivalent to a "true" condition.
if ((null == condition) || (condition.Length == 0))
{
return true;
}
Hashtable cachedExpressionTreesForCurrentOptions = cachedExpressionTrees[(int)itemListOptions];
// Try and see if we have an expression tree for this condition already
GenericExpressionNode parsedExpression = (GenericExpressionNode) cachedExpressionTreesForCurrentOptions[condition];
if (parsedExpression == null)
{
Parser conditionParser = new Parser();
#region REMOVE_COMPAT_WARNING
conditionParser.LoggingServices = loggingServices;
conditionParser.LogBuildEventContext = buildEventContext;
#endregion
parsedExpression = conditionParser.Parse(condition, conditionAttribute, itemListOptions);
// It's possible two threads will add a different tree to the same entry in the hashtable,
// but it should be rare and it's not a problem - the previous entry will be thrown away.
// We could ensure no dupes with double check locking but it's not really necessary here.
// Also, we don't want to lock on every read.
lock (cachedExpressionTreesForCurrentOptions)
{
cachedExpressionTreesForCurrentOptions[condition] = parsedExpression;
}
}
ConditionEvaluationState state = new ConditionEvaluationState(conditionAttribute, expander, conditionedPropertiesTable, condition);
bool result;
// We are evaluating this expression now and it can cache some state for the duration,
// so we don't want multiple threads working on the same expression
lock (parsedExpression)
{
result = parsedExpression.Evaluate(state);
parsedExpression.ResetState();
}
return result;
}
/// <summary>
/// Sets the inner XML/text of the given XML node, escaping as necessary.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="node"></param>
/// <param name="s">Can be empty string, but not null.</param>
internal static void SetXmlNodeInnerContents(XmlNode node, string s)
{
ErrorUtilities.VerifyThrow(s != null, "Need value to set.");
if (s.IndexOf('<') != -1)
{
// If the value looks like it probably contains XML markup ...
try
{
// Attempt to store it verbatim as XML.
node.InnerXml = s;
return;
}
catch (XmlException)
{
// But that may fail, in the event that "s" is not really well-formed
// XML. Eat the exception and fall through below ...
}
}
// The value does not contain valid XML markup. Store it as text, so it gets
// escaped properly.
node.InnerText = s;
}
/// <summary>
/// Extracts the inner XML/text of the given XML node, unescaping as necessary.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="node"></param>
/// <returns>Inner XML/text of specified node.</returns>
internal static string GetXmlNodeInnerContents(XmlNode node)
{
// XmlNode.InnerXml gives back a string that consists of the set of characters
// in between the opening and closing elements of the XML node, without doing any
// unescaping. Any "strange" character sequences (like "<![CDATA[...]]>" will remain
// exactly so and will not be translated or interpreted. The only modification that
// .InnerXml will do is that it will normalize any Xml contained within. This means
// normalizing whitespace between XML attributes and quote characters that surround XML
// attributes. If PreserveWhitespace is false, then it will also normalize whitespace
// between elements.
//
// XmlNode.InnerText strips out any Xml contained within, and then unescapes the rest
// of the text. So if the remaining text contains certain character sequences such as
// "&" or "<![CDATA[...]]>", these will be translated into their equivalent representations.
//
// It's hard to explain, but much easier to demonstrate with examples:
//
// Original XML XmlNode.InnerText XmlNode.InnerXml
// =========================== ============================== ======================================
//
// <a><![CDATA[whatever]]></a> whatever <![CDATA[whatever]]>
//
// <a>123<MyNode/>456</a> 123456 123<MyNode />456
//
// <a>123456</a> 123456 123456
//
// <a>123<MyNode b='<'/>456</a> 123456 123<MyNode b="<" />456
//
// <a>123&456</a> 123&456 123&456
// So the trick for MSBuild when interpreting a property value is to know which one to
// use ... InnerXml or InnerText. There are two basic scenarios we care about.
//
// 1.) The first scenario is that the user is trying to create a property whose
// contents are actually XML. That is to say that the contents may be written
// to a XML file, or may be passed in as a string to XmlDocument.LoadXml.
// In this case, we would want to use XmlNode.InnerXml, because we DO NOT want
// character sequences to be unescaped. If we did unescape them, then whatever
// XML parser tried to read in the stream as XML later on would totally barf.
//
// 2.) The second scenario is the the user is trying to create a property that
// is just intended to be treated as a string. That string may be very large
// and could contain all sorts of whitespace, carriage returns, special characters,
// etc. But in the end, it's just a big string. In this case, whatever
// task is actually processing this string ... it's not going to know anything
// about character sequences such as & and <. These character sequences
// are specific to XML markup. So, here we want to use XmlNode.InnerText so that
// the character sequences get unescaped into their actual character before
// the string is passed to the task (or wherever else the property is used).
// Of course, if the string value of the property needs to contain characters
// like <, >, &, etc., then the user must XML escape these characters otherwise
// the XML parser reading the project file will croak. Or if the user doesn't
// want to escape every instance of these characters, he can surround the whole
// thing with a CDATA tag. Again, if he does this, we don't want the task to
// receive the C, D, A, T, A as part of the string ... this should be stripped off.
// Again, using XmlNode.InnerText takes care of this.
//
// 2b.) A variation of the second scenario is that the user is trying to create a property
// that is just intended to be a string, but wants to comment out part of the string.
// For example, it's a semicolon separated list that's going ultimately to end up in a list.
// eg. (DDB #56841)
//
// <BuildDirectories>
// <!--
// env\TestTools\tshell\pkg;
// -->
// ndp\fx\src\VSIP\FrameWork;
// ndp\fx\src\xmlTools;
// ddsuites\src\vs\xmlTools;
// </BuildDirectories>
//
// In this case, we want to treat the string as text, so that we don't retrieve the comment.
// We only want to retrieve the comment if there's some other XML in there. The
// mere presence of an XML comment shouldn't make us think the value is XML.
//
// Given these two scenarios, how do we know whether the user intended to treat
// a property value as XML or text? We use a simple heuristic which is that if
// XmlNode.InnerXml contains any "<" characters, then there pretty much has to be
// XML in there, so we'll just use XmlNode.InnerXml. If there are no "<" characters that aren't merely comments,
// then we assume it's to be treated as text and we use XmlNode.InnerText. Also, if
// it looks like the whole thing is one big CDATA block, then we also use XmlNode.InnerText.
// XmlNode.InnerXml is much more expensive than InnerText. Don't use it for trivial cases.
// (single child node with a trivial value or no child nodes)
if (!node.HasChildNodes)
{
return string.Empty;
}
if (node.ChildNodes.Count == 1 && (node.FirstChild.NodeType == XmlNodeType.Text || node.FirstChild.NodeType == XmlNodeType.CDATA))
{
return node.InnerText;
}
string innerXml = node.InnerXml;
// If there is no markup under the XML node (detected by the presence
// of a '<' sign
int firstLessThan = innerXml.IndexOf('<');
if (firstLessThan == -1)
{
// return the inner text so it gets properly unescaped
return node.InnerText;
}
bool containsNoTagsOtherThanComments = ContainsNoTagsOtherThanComments(innerXml, firstLessThan);
// ... or if the only XML is comments,
if (containsNoTagsOtherThanComments)
{
// return the inner text so the comments are stripped
// (this is how one might comment out part of a list in a property value)
return node.InnerText;
}
// ...or it looks like the whole thing is a big CDATA tag ...
bool startsWithCData = (innerXml.IndexOf("<![CDATA[", StringComparison.Ordinal) == 0);
if (startsWithCData)
{
// return the inner text so it gets properly extracted from the CDATA
return node.InnerText;
}
// otherwise, it looks like genuine XML; return the inner XML so that
// tags and comments are preserved and any XML escaping is preserved
return innerXml;
}
/// <summary>
/// Figure out whether there are any XML tags, other than comment tags,
/// in the string.
/// </summary>
/// <remarks>
/// We know the string coming in is a valid XML fragment. (The project loaded after all.)
/// So for example we can ignore an open comment tag without a matching closing comment tag.
/// </remarks>
private static bool ContainsNoTagsOtherThanComments(string innerXml, int firstLessThan)
{
bool insideComment = false;
for (int i = firstLessThan; i < innerXml.Length; i++)
{
if (!insideComment)
{
// XML comments start with exactly "<!--"
if (i < innerXml.Length - 3
&& innerXml[i] == '<'
&& innerXml[i + 1] == '!'
&& innerXml[i + 2] == '-'
&& innerXml[i + 3] == '-')
{
// Found the start of a comment
insideComment = true;
i = i + 3;
continue;
}
}
if (!insideComment)
{
if (innerXml[i] == '<')
{
// Found a tag!
return false;
}
}
if (insideComment)
{
// XML comments end with exactly "-->"
if (i < innerXml.Length - 2
&& innerXml[i] == '-'
&& innerXml[i + 1] == '-'
&& innerXml[i + 2] == '>')
{
// Found the end of a comment
insideComment = false;
i = i + 2;
continue;
}
}
}
// Didn't find any tags, except possibly comments
return true;
}
// used to find the xmlns attribute
private static readonly Regex xmlnsPattern = new Regex("xmlns=\"[^\"]*\"\\s*");
/// <summary>
/// Removes the xmlns attribute from an XML string.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="xml">XML string to process.</param>
/// <returns>The modified XML string.</returns>
internal static string RemoveXmlNamespace(string xml)
{
return xmlnsPattern.Replace(xml, String.Empty);
}
/// <summary>
/// Escapes given string, that is replaces special characters with escape sequences that allow MSBuild hosts
/// to treat MSBuild-interpreted characters literally (';' becomes "%3b" and so on).
/// </summary>
/// <param name="unescapedExpression">string to escape</param>
/// <returns>escaped string</returns>
public static string Escape(string unescapedExpression)
{
return EscapingUtilities.Escape(unescapedExpression);
}
/// <summary>
/// Instantiates a new BuildEventFileInfo object using an XML node (presumably from the project
/// file). The reason this isn't just another constructor on BuildEventFileInfo is because
/// BuildEventFileInfo.cs gets compiled into multiple assemblies (Engine and Conversion, at least),
/// and not all of those assemblies have the code for XmlUtilities.
/// </summary>
/// <param name="xmlNode"></param>
/// <param name="defaultFile"></param>
/// <returns></returns>
/// <owner>RGoel</owner>
internal static BuildEventFileInfo CreateBuildEventFileInfo(XmlNode xmlNode, string defaultFile)
{
ErrorUtilities.VerifyThrow(xmlNode != null, "Need Xml node.");
// Get the file path out of the Xml node.
int line = 0;
int column = 0;
string file = XmlUtilities.GetXmlNodeFile(xmlNode, String.Empty);
if (file.Length == 0)
{
file = defaultFile;
}
else
{
// Compute the line number and column number of the XML node.
XmlSearcher.GetLineColumnByNode(xmlNode, out line, out column);
}
return new BuildEventFileInfo(file, line, column);
}
/// <summary>
/// Helper useful for lazy table creation
/// </summary>
internal static Hashtable CreateTableIfNecessary(Hashtable table)
{
if (table == null)
{
return new Hashtable(StringComparer.OrdinalIgnoreCase);
}
return table;
}
/// <summary>
/// Helper useful for lazy table creation
/// </summary>
internal static Dictionary<string, V> CreateTableIfNecessary<V>(Dictionary<string, V> table)
{
if (table == null)
{
return new Dictionary<string, V>(StringComparer.OrdinalIgnoreCase);
}
return table;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using OrchardCore.Environment.Shell;
using OrchardCore.Modules;
using OrchardCore.OpenId.Abstractions.Managers;
using OrchardCore.OpenId.ViewModels;
using OrchardCore.Routing;
using OrchardCore.Security.Services;
using OrchardCore.Users.Services;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace OrchardCore.OpenId.Controllers
{
// Note: the error descriptions used in this controller are deliberately not localized as
// the OAuth 2.0 specification only allows select US-ASCII characters in error_description.
[Authorize, Feature(OpenIdConstants.Features.Server)]
public class AccessController : Controller
{
private readonly IOpenIdApplicationManager _applicationManager;
private readonly IOpenIdAuthorizationManager _authorizationManager;
private readonly IOpenIdScopeManager _scopeManager;
private readonly ShellSettings _shellSettings;
public AccessController(
IOpenIdApplicationManager applicationManager,
IOpenIdAuthorizationManager authorizationManager,
IOpenIdScopeManager scopeManager,
ShellSettings shellSettings)
{
_applicationManager = applicationManager;
_authorizationManager = authorizationManager;
_scopeManager = scopeManager;
_shellSettings = shellSettings;
}
[AllowAnonymous, HttpGet, HttpPost, IgnoreAntiforgeryToken]
public async Task<IActionResult> Authorize()
{
var response = HttpContext.GetOpenIddictServerResponse();
if (response != null)
{
return View("Error", new ErrorViewModel
{
Error = response.Error,
ErrorDescription = response.ErrorDescription
});
}
var request = HttpContext.GetOpenIddictServerRequest();
if (request == null)
{
return NotFound();
}
// Retrieve the claims stored in the authentication cookie.
// If they can't be extracted, redirect the user to the login page.
var result = await HttpContext.AuthenticateAsync();
if (result == null || !result.Succeeded || request.HasPrompt(Prompts.Login))
{
return RedirectToLoginPage(request);
}
// If a max_age parameter was provided, ensure that the cookie is not too old.
// If it's too old, automatically redirect the user agent to the login page.
if (request.MaxAge != null && result.Properties.IssuedUtc != null &&
DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))
{
return RedirectToLoginPage(request);
}
var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
throw new InvalidOperationException("The application details cannot be found.");
var authorizations = await _authorizationManager.FindAsync(
subject: result.Principal.GetUserIdentifier(),
client: await _applicationManager.GetIdAsync(application),
status: Statuses.Valid,
type: AuthorizationTypes.Permanent,
scopes: request.GetScopes()).ToListAsync();
switch (await _applicationManager.GetConsentTypeAsync(application))
{
case ConsentTypes.External when !authorizations.Any():
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
"The logged in user is not allowed to access this client application."
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
case ConsentTypes.Implicit:
case ConsentTypes.External when authorizations.Any():
case ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(Prompts.Consent):
var identity = new ClaimsIdentity(result.Principal.Claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
identity.AddClaim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.User,
Destinations.AccessToken, Destinations.IdentityToken);
// Note: while ASP.NET Core Identity uses the legacy WS-Federation claims (exposed by the ClaimTypes class),
// OpenIddict uses the newer JWT claims defined by the OpenID Connect specification. To ensure the mandatory
// subject claim is correctly populated (and avoid an InvalidOperationException), it's manually added here.
if (string.IsNullOrEmpty(result.Principal.FindFirst(Claims.Subject)?.Value))
{
identity.AddClaim(new Claim(Claims.Subject, result.Principal.GetUserIdentifier()));
}
if (string.IsNullOrEmpty(result.Principal.FindFirst(Claims.Name)?.Value))
{
identity.AddClaim(new Claim(Claims.Name, result.Principal.GetUserName()));
}
principal.SetScopes(request.GetScopes());
principal.SetResources(await GetResourcesAsync(request.GetScopes()));
// Automatically create a permanent authorization to avoid requiring explicit consent
// for future authorization or token requests containing the same scopes.
var authorization = authorizations.LastOrDefault();
if (authorization == null)
{
authorization = await _authorizationManager.CreateAsync(
principal: principal,
subject: principal.GetUserIdentifier(),
client: await _applicationManager.GetIdAsync(application),
type: AuthorizationTypes.Permanent,
scopes: principal.GetScopes());
}
principal.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));
foreach (var claim in principal.Claims)
{
claim.SetDestinations(GetDestinations(claim, principal));
}
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
case ConsentTypes.Explicit when request.HasPrompt(Prompts.None):
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
"Interactive user consent is required."
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
default:
return View(new AuthorizeViewModel
{
ApplicationName = await _applicationManager.GetLocalizedDisplayNameAsync(application),
RequestId = request.RequestId,
Scope = request.Scope
});
}
IActionResult RedirectToLoginPage(OpenIddictRequest request)
{
// If the client application requested promptless authentication,
// return an error indicating that the user is not logged in.
if (request.HasPrompt(Prompts.None))
{
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in."
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
string GetRedirectUrl()
{
// Override the prompt parameter to prevent infinite authentication/authorization loops.
var parameters = Request.Query.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
parameters[Parameters.Prompt] = "continue";
return Request.PathBase + Request.Path + QueryString.Create(parameters);
}
return Challenge(new AuthenticationProperties
{
RedirectUri = GetRedirectUrl()
});
}
}
[ActionName(nameof(Authorize))]
[FormValueRequired("submit.Accept"), HttpPost]
public async Task<IActionResult> AuthorizeAccept()
{
// Warning: unlike the main Authorize method, this method MUST NOT be decorated with
// [IgnoreAntiforgeryToken] as we must be able to reject authorization requests
// sent by a malicious client that could abuse this interactive endpoint to silently
// get codes/tokens without the user explicitly approving the authorization demand.
var response = HttpContext.GetOpenIddictServerResponse();
if (response != null)
{
return View("Error", new ErrorViewModel
{
Error = response.Error,
ErrorDescription = response.ErrorDescription
});
}
var request = HttpContext.GetOpenIddictServerRequest();
if (request == null)
{
return NotFound();
}
var application = await _applicationManager.FindByClientIdAsync(request.ClientId)
?? throw new InvalidOperationException("The application details cannot be found.");
var authorizations = await _authorizationManager.FindAsync(
subject: User.GetUserIdentifier(),
client: await _applicationManager.GetIdAsync(application),
status: Statuses.Valid,
type: AuthorizationTypes.Permanent,
scopes: request.GetScopes()).ToListAsync();
// Note: the same check is already made in the GET action but is repeated
// here to ensure a malicious user can't abuse this POST endpoint and
// force it to return a valid response without the external authorization.
switch (await _applicationManager.GetConsentTypeAsync(application))
{
case ConsentTypes.External when !authorizations.Any():
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
"The logged in user is not allowed to access this client application."
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
default:
var identity = new ClaimsIdentity(User.Claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
identity.AddClaim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.User,
Destinations.AccessToken, Destinations.IdentityToken);
// Note: while ASP.NET Core Identity uses the legacy WS-Federation claims (exposed by the ClaimTypes class),
// OpenIddict uses the newer JWT claims defined by the OpenID Connect specification. To ensure the mandatory
// subject claim is correctly populated (and avoid an InvalidOperationException), it's manually added here.
if (string.IsNullOrEmpty(User.FindFirst(Claims.Subject)?.Value))
{
identity.AddClaim(new Claim(Claims.Subject, User.GetUserIdentifier()));
}
if (string.IsNullOrEmpty(User.FindFirst(Claims.Name)?.Value))
{
identity.AddClaim(new Claim(Claims.Name, User.GetUserName()));
}
principal.SetScopes(request.GetScopes());
principal.SetResources(await GetResourcesAsync(request.GetScopes()));
// Automatically create a permanent authorization to avoid requiring explicit consent
// for future authorization or token requests containing the same scopes.
var authorization = authorizations.LastOrDefault();
if (authorization == null)
{
authorization = await _authorizationManager.CreateAsync(
principal: principal,
subject: principal.GetUserIdentifier(),
client: await _applicationManager.GetIdAsync(application),
type: AuthorizationTypes.Permanent,
scopes: principal.GetScopes());
}
principal.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));
foreach (var claim in principal.Claims)
{
claim.SetDestinations(GetDestinations(claim, principal));
}
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
}
[ActionName(nameof(Authorize))]
[FormValueRequired("submit.Deny"), HttpPost]
public IActionResult AuthorizeDeny()
{
var response = HttpContext.GetOpenIddictServerResponse();
if (response != null)
{
return View("Error", new ErrorViewModel
{
Error = response.Error,
ErrorDescription = response.ErrorDescription
});
}
var request = HttpContext.GetOpenIddictServerRequest();
if (request == null)
{
return NotFound();
}
return Forbid(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
[AllowAnonymous, HttpGet, HttpPost, IgnoreAntiforgeryToken]
public async Task<IActionResult> Logout()
{
var response = HttpContext.GetOpenIddictServerResponse();
if (response != null)
{
return View("Error", new ErrorViewModel
{
Error = response.Error,
ErrorDescription = response.ErrorDescription
});
}
var request = HttpContext.GetOpenIddictServerRequest();
if (request == null)
{
return NotFound();
}
if (!string.IsNullOrEmpty(request.PostLogoutRedirectUri))
{
// If the user is not logged in, allow redirecting the user agent back to the
// specified post_logout_redirect_uri without rendering a confirmation form.
var result = await HttpContext.AuthenticateAsync();
if (result == null || !result.Succeeded)
{
return SignOut(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
}
return View(new LogoutViewModel
{
RequestId = request.RequestId
});
}
[ActionName(nameof(Logout)), AllowAnonymous]
[FormValueRequired("submit.Accept"), HttpPost]
public async Task<IActionResult> LogoutAccept()
{
var response = HttpContext.GetOpenIddictServerResponse();
if (response != null)
{
return View("Error", new ErrorViewModel
{
Error = response.Error,
ErrorDescription = response.ErrorDescription
});
}
var request = HttpContext.GetOpenIddictServerRequest();
if (request == null)
{
return NotFound();
}
// Warning: unlike the main Logout method, this method MUST NOT be decorated with
// [IgnoreAntiforgeryToken] as we must be able to reject end session requests
// sent by a malicious client that could abuse this interactive endpoint to silently
// log the user out without the user explicitly approving the log out operation.
await HttpContext.SignOutAsync();
// If no post_logout_redirect_uri was specified, redirect the user agent
// to the root page, that should correspond to the home page in most cases.
if (string.IsNullOrEmpty(request.PostLogoutRedirectUri))
{
return Redirect("~/");
}
return SignOut(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
[ActionName(nameof(Logout)), AllowAnonymous]
[FormValueRequired("submit.Deny"), HttpPost]
public IActionResult LogoutDeny()
{
var response = HttpContext.GetOpenIddictServerResponse();
if (response != null)
{
return View("Error", new ErrorViewModel
{
Error = response.Error,
ErrorDescription = response.ErrorDescription
});
}
var request = HttpContext.GetOpenIddictServerRequest();
if (request == null)
{
return NotFound();
}
return Redirect("~/");
}
[AllowAnonymous, HttpPost]
[IgnoreAntiforgeryToken]
[Produces("application/json")]
public Task<IActionResult> Token()
{
// Warning: this action is decorated with IgnoreAntiforgeryTokenAttribute to override
// the global antiforgery token validation policy applied by the MVC modules stack,
// which is required for this stateless OAuth2/OIDC token endpoint to work correctly.
// To prevent effective CSRF/session fixation attacks, this action MUST NOT return
// an authentication cookie or try to establish an ASP.NET Core user session.
var request = HttpContext.GetOpenIddictServerRequest();
if (request == null)
{
return Task.FromResult((IActionResult)NotFound());
}
if (request.IsPasswordGrantType())
{
return ExchangePasswordGrantType(request);
}
if (request.IsClientCredentialsGrantType())
{
return ExchangeClientCredentialsGrantType(request);
}
if (request.IsAuthorizationCodeGrantType() || request.IsRefreshTokenGrantType())
{
return ExchangeAuthorizationCodeOrRefreshTokenGrantType(request);
}
throw new NotSupportedException("The specified grant type is not supported.");
}
private async Task<IActionResult> ExchangeClientCredentialsGrantType(OpenIddictRequest request)
{
// Note: client authentication is always enforced by OpenIddict before this action is invoked.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
throw new InvalidOperationException("The application details cannot be found.");
var identity = new ClaimsIdentity(
OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
Claims.Name, Claims.Role);
identity.AddClaim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.Application,
Destinations.AccessToken, Destinations.IdentityToken);
identity.AddClaim(Claims.Subject, request.ClientId,
Destinations.AccessToken, Destinations.IdentityToken);
identity.AddClaim(Claims.Name,
await _applicationManager.GetDisplayNameAsync(application),
Destinations.AccessToken, Destinations.IdentityToken);
// If the role service is available, add all the role claims
// associated with the application roles in the database.
var roleService = HttpContext.RequestServices.GetService<IRoleService>();
foreach (var role in await _applicationManager.GetRolesAsync(application))
{
identity.AddClaim(identity.RoleClaimType, role,
Destinations.AccessToken, Destinations.IdentityToken);
if (roleService != null)
{
foreach (var claim in await roleService.GetRoleClaimsAsync(role))
{
identity.AddClaim(claim.SetDestinations(Destinations.AccessToken, Destinations.IdentityToken));
}
}
}
var principal = new ClaimsPrincipal(identity);
principal.SetResources(await GetResourcesAsync(request.GetScopes()));
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
private async Task<IActionResult> ExchangePasswordGrantType(OpenIddictRequest request)
{
var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
throw new InvalidOperationException("The application details cannot be found.");
// By design, the password flow requires direct username/password validation, which is performed by
// the user service. If this service is not registered, prevent the password flow from being used.
var service = HttpContext.RequestServices.GetService<IUserService>();
if (service == null)
{
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.UnsupportedGrantType,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
"The resource owner password credentials grant is not supported."
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
string error = null;
var user = await service.AuthenticateAsync(request.Username, request.Password, (key, message) => error = message);
if (user == null)
{
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = error
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
var principal = await service.CreatePrincipalAsync(user);
var authorizations = await _authorizationManager.FindAsync(
subject: principal.GetUserIdentifier(),
client: await _applicationManager.GetIdAsync(application),
status: Statuses.Valid,
type: AuthorizationTypes.Permanent,
scopes: request.GetScopes()).ToListAsync();
// If the application is configured to use external consent,
// reject the request if no existing authorization can be found.
switch (await _applicationManager.GetConsentTypeAsync(application))
{
case ConsentTypes.External when !authorizations.Any():
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
"The logged in user is not allowed to access this client application."
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
var identity = (ClaimsIdentity)principal.Identity;
identity.AddClaim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.User,
Destinations.AccessToken, Destinations.IdentityToken);
// Note: while ASP.NET Core Identity uses the legacy WS-Federation claims (exposed by the ClaimTypes class),
// OpenIddict uses the newer JWT claims defined by the OpenID Connect specification. To ensure the mandatory
// subject claim is correctly populated (and avoid an InvalidOperationException), it's manually added here.
if (string.IsNullOrEmpty(principal.FindFirst(Claims.Subject)?.Value))
{
identity.AddClaim(new Claim(Claims.Subject, principal.GetUserIdentifier()));
}
if (string.IsNullOrEmpty(principal.FindFirst(Claims.Name)?.Value))
{
identity.AddClaim(new Claim(Claims.Name, principal.GetUserName()));
}
principal.SetScopes(request.GetScopes());
principal.SetResources(await GetResourcesAsync(request.GetScopes()));
// Automatically create a permanent authorization to avoid requiring explicit consent
// for future authorization or token requests containing the same scopes.
var authorization = authorizations.FirstOrDefault();
if (authorization == null)
{
authorization = await _authorizationManager.CreateAsync(
principal: principal,
subject: principal.GetUserIdentifier(),
client: await _applicationManager.GetIdAsync(application),
type: AuthorizationTypes.Permanent,
scopes: principal.GetScopes());
}
principal.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));
foreach (var claim in principal.Claims)
{
claim.SetDestinations(GetDestinations(claim, principal));
}
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
private async Task<IActionResult> ExchangeAuthorizationCodeOrRefreshTokenGrantType(OpenIddictRequest request)
{
// Retrieve the claims principal stored in the authorization code/refresh token.
var info = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme) ??
throw new InvalidOperationException("The user principal cannot be resolved.");
if (request.IsRefreshTokenGrantType())
{
var type = info.Principal.FindFirst(OpenIdConstants.Claims.EntityType)?.Value;
if (!string.Equals(type, OpenIdConstants.EntityTypes.User))
{
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.UnauthorizedClient,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
"The refresh token grant type is not allowed for refresh tokens retrieved using the client credentials flow."
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
}
// By default, re-use the principal stored in the authorization code/refresh token.
var principal = info.Principal;
// If the user service is available, try to refresh the principal by retrieving
// the user object from the database and creating a new claims-based principal.
var service = HttpContext.RequestServices.GetService<IUserService>();
if (service != null)
{
var user = await service.GetUserByUniqueIdAsync(principal.GetUserIdentifier());
if (user != null)
{
principal = await service.CreatePrincipalAsync(user);
}
}
var identity = (ClaimsIdentity)principal.Identity;
identity.AddClaim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.User,
Destinations.AccessToken, Destinations.IdentityToken);
// Note: while ASP.NET Core Identity uses the legacy WS-Federation claims (exposed by the ClaimTypes class),
// OpenIddict uses the newer JWT claims defined by the OpenID Connect specification. To ensure the mandatory
// subject claim is correctly populated (and avoid an InvalidOperationException), it's manually added here.
if (string.IsNullOrEmpty(principal.FindFirst(Claims.Subject)?.Value))
{
identity.AddClaim(new Claim(Claims.Subject, principal.GetUserIdentifier()));
}
if (string.IsNullOrEmpty(principal.FindFirst(Claims.Name)?.Value))
{
identity.AddClaim(new Claim(Claims.Name, principal.GetUserName()));
}
foreach (var claim in principal.Claims)
{
claim.SetDestinations(GetDestinations(claim, principal));
}
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
private IEnumerable<string> GetDestinations(Claim claim, ClaimsPrincipal principal)
{
// Note: by default, claims are NOT automatically included in the access and identity tokens.
// To allow OpenIddict to serialize them, you must attach them a destination, that specifies
// whether they should be included in access tokens, in identity tokens or in both.
switch (claim.Type)
{
// Never include the security stamp in the access and identity tokens, as it's a secret value.
case "AspNet.Identity.SecurityStamp":
break;
// Only add the claim to the id_token if the corresponding scope was granted.
// The other claims will only be added to the access_token.
case OpenIdConstants.Claims.EntityType:
case Claims.Name when principal.HasScope(Scopes.Profile):
case Claims.Email when principal.HasScope(Scopes.Email):
case Claims.Role when principal.HasScope(Scopes.Roles):
yield return Destinations.AccessToken;
yield return Destinations.IdentityToken;
break;
default:
yield return Destinations.AccessToken;
break;
}
}
private async Task<IEnumerable<string>> GetResourcesAsync(ImmutableArray<string> scopes)
{
// Note: the current tenant name is always added as a valid resource/audience,
// which allows the end user to use the corresponding tokens with the APIs
// located in the current tenant without having to explicitly register a scope.
var resources = new List<string>(1)
{
OpenIdConstants.Prefixes.Tenant + _shellSettings.Name
};
await foreach (var resource in _scopeManager.ListResourcesAsync(scopes))
{
resources.Add(resource);
}
return resources;
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Conditions
{
using System;
using System.Globalization;
using System.Collections.Generic;
using Common;
/// <summary>
/// Condition relational (<b>==</b>, <b>!=</b>, <b><</b>, <b><=</b>,
/// <b>></b> or <b>>=</b>) expression.
/// </summary>
internal sealed class ConditionRelationalExpression : ConditionExpression
{
/// <summary>
/// Initializes a new instance of the <see cref="ConditionRelationalExpression" /> class.
/// </summary>
/// <param name="leftExpression">The left expression.</param>
/// <param name="rightExpression">The right expression.</param>
/// <param name="relationalOperator">The relational operator.</param>
public ConditionRelationalExpression(ConditionExpression leftExpression, ConditionExpression rightExpression, ConditionRelationalOperator relationalOperator)
{
LeftExpression = leftExpression;
RightExpression = rightExpression;
RelationalOperator = relationalOperator;
}
/// <summary>
/// Gets the left expression.
/// </summary>
/// <value>The left expression.</value>
public ConditionExpression LeftExpression { get; private set; }
/// <summary>
/// Gets the right expression.
/// </summary>
/// <value>The right expression.</value>
public ConditionExpression RightExpression { get; private set; }
/// <summary>
/// Gets the relational operator.
/// </summary>
/// <value>The operator.</value>
public ConditionRelationalOperator RelationalOperator { get; private set; }
/// <summary>
/// Returns a string representation of the expression.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the condition expression.
/// </returns>
public override string ToString()
{
return "(" + LeftExpression + " " + GetOperatorString() + " " + RightExpression + ")";
}
/// <summary>
/// Evaluates the expression.
/// </summary>
/// <param name="context">Evaluation context.</param>
/// <returns>Expression result.</returns>
protected override object EvaluateNode(LogEventInfo context)
{
object v1 = LeftExpression.Evaluate(context);
object v2 = RightExpression.Evaluate(context);
return Compare(v1, v2, RelationalOperator);
}
/// <summary>
/// Compares the specified values using specified relational operator.
/// </summary>
/// <param name="leftValue">The first value.</param>
/// <param name="rightValue">The second value.</param>
/// <param name="relationalOperator">The relational operator.</param>
/// <returns>Result of the given relational operator.</returns>
private static object Compare(object leftValue, object rightValue, ConditionRelationalOperator relationalOperator)
{
StringComparer comparer = StringComparer.InvariantCulture;
PromoteTypes(ref leftValue, ref rightValue);
switch (relationalOperator)
{
case ConditionRelationalOperator.Equal:
return comparer.Compare(leftValue, rightValue) == 0;
case ConditionRelationalOperator.NotEqual:
return comparer.Compare(leftValue, rightValue) != 0;
case ConditionRelationalOperator.Greater:
return comparer.Compare(leftValue, rightValue) > 0;
case ConditionRelationalOperator.GreaterOrEqual:
return comparer.Compare(leftValue, rightValue) >= 0;
case ConditionRelationalOperator.LessOrEqual:
return comparer.Compare(leftValue, rightValue) <= 0;
case ConditionRelationalOperator.Less:
return comparer.Compare(leftValue, rightValue) < 0;
default:
throw new NotSupportedException("Relational operator " + relationalOperator + " is not supported.");
}
}
/// <summary>
/// Promote values to the type needed for the comparision, e.g. parse a string to int.
/// </summary>
/// <param name="leftValue"></param>
/// <param name="rightValue"></param>
private static void PromoteTypes(ref object leftValue, ref object rightValue)
{
if (leftValue == null || rightValue == null)
{
return;
}
var leftType = leftValue.GetType();
var rightType = rightValue.GetType();
if (leftType == rightType)
{
return;
}
//types are not equal
var leftTypeOrder = GetOrder(leftType);
var rightTypeOrder = GetOrder(rightType);
if (leftTypeOrder < rightTypeOrder)
{
// first try promote right value with left type
if (TryPromoteTypes(ref rightValue, leftType, ref leftValue, rightType)) return;
}
else
{
// otherwise try promote leftValue with right type
if (TryPromoteTypes(ref leftValue, rightType, ref rightValue, leftType)) return;
}
throw new ConditionEvaluationException("Cannot find common type for '" + leftType.Name + "' and '" + rightType.Name + "'.");
}
/// <summary>
/// Promoto <paramref name="val"/> to type
/// </summary>
/// <param name="val"></param>
/// <param name="type1"></param>
/// <returns>success?</returns>
private static bool TryPromoteType(ref object val, Type type1)
{
try
{
if (type1 == typeof(DateTime))
{
val = Convert.ToDateTime(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(double))
{
val = Convert.ToDouble(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(float))
{
val = Convert.ToSingle(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(decimal))
{
val = Convert.ToDecimal(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(long))
{
val = Convert.ToInt64(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(int))
{
val = Convert.ToInt32(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(bool))
{
val = Convert.ToBoolean(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(string))
{
val = Convert.ToString(val, CultureInfo.InvariantCulture);
InternalLogger.Debug("Using string comparision");
return true;
}
}
catch (Exception)
{
InternalLogger.Debug("conversion of {0} to {1} failed", val, type1.Name);
}
return false;
}
/// <summary>
/// Try to promote both values. First try to promote <paramref name="val1"/> to <paramref name="type1"/>,
/// when failed, try <paramref name="val2"/> to <paramref name="type2"/>.
/// </summary>
/// <returns></returns>
private static bool TryPromoteTypes(ref object val1, Type type1, ref object val2, Type type2)
{
if (TryPromoteType(ref val1, type1))
{
return true;
}
return TryPromoteType(ref val2, type2);
}
/// <summary>
/// Get the order for the type for comparision.
/// </summary>
/// <param name="type1"></param>
/// <returns>index, 0 to maxint. Lower is first</returns>
private static int GetOrder(Type type1)
{
int order;
var success = TypePromoteOrder.TryGetValue(type1, out order);
if (success)
{
return order;
}
//not found, try as last
return int.MaxValue;
}
/// <summary>
/// Dictionary from type to index. Lower index should be tested first.
/// </summary>
private static Dictionary<Type, int> TypePromoteOrder = BuildTypeOrderDictionary();
/// <summary>
/// Build the dictionary needed for the order of the types.
/// </summary>
/// <returns></returns>
private static Dictionary<Type, int> BuildTypeOrderDictionary()
{
var list = new List<Type>
{
typeof(DateTime),
typeof(double),
typeof(float),
typeof(decimal),
typeof(long),
typeof(int),
typeof(bool),
typeof(string),
};
var dict = new Dictionary<Type, int>(list.Count);
for (int i = 0; i < list.Count; i++)
{
dict.Add(list[i], i);
}
return dict;
}
/// <summary>
/// Get the string representing the current <see cref="ConditionRelationalOperator"/>
/// </summary>
/// <returns></returns>
private string GetOperatorString()
{
switch (RelationalOperator)
{
case ConditionRelationalOperator.Equal:
return "==";
case ConditionRelationalOperator.NotEqual:
return "!=";
case ConditionRelationalOperator.Greater:
return ">";
case ConditionRelationalOperator.Less:
return "<";
case ConditionRelationalOperator.GreaterOrEqual:
return ">=";
case ConditionRelationalOperator.LessOrEqual:
return "<=";
default:
throw new NotSupportedException("Relational operator " + RelationalOperator + " is not supported.");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.Serialization;
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>
/// OrderedDictionary offers IDictionary syntax with ordering. Objects
/// added or inserted in an IOrderedDictionary must have both a key and an index, and
/// can be retrieved by either.
/// OrderedDictionary is used by the ParameterCollection because MSAccess relies on ordering of
/// parameters, while almost all other DBs do not. DataKeyArray also uses it so
/// DataKeys can be retrieved by either their name or their index.
///
/// OrderedDictionary implements IDeserializationCallback because it needs to have the
/// contained ArrayList and Hashtable deserialized before it tries to get its count and objects.
/// </para>
/// </devdoc>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class OrderedDictionary : IOrderedDictionary, ISerializable, IDeserializationCallback
{
private ArrayList _objectsArray;
private Hashtable _objectsTable;
private int _initialCapacity;
private IEqualityComparer _comparer;
private bool _readOnly;
private object _syncRoot;
private SerializationInfo _siInfo; //A temporary variable which we need during deserialization.
private const string KeyComparerName = "KeyComparer"; // Do not rename (binary serialization)
private const string ArrayListName = "ArrayList"; // Do not rename (binary serialization)
private const string ReadOnlyName = "ReadOnly"; // Do not rename (binary serialization)
private const string InitCapacityName = "InitialCapacity"; // Do not rename (binary serialization)
public OrderedDictionary() : this(0)
{
}
public OrderedDictionary(int capacity) : this(capacity, null)
{
}
public OrderedDictionary(IEqualityComparer comparer) : this(0, comparer)
{
}
public OrderedDictionary(int capacity, IEqualityComparer comparer)
{
_initialCapacity = capacity;
_comparer = comparer;
}
private OrderedDictionary(OrderedDictionary dictionary)
{
Debug.Assert(dictionary != null);
_readOnly = true;
_objectsArray = dictionary._objectsArray;
_objectsTable = dictionary._objectsTable;
_comparer = dictionary._comparer;
_initialCapacity = dictionary._initialCapacity;
}
protected OrderedDictionary(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been deserialized
// and getting Counts and objects won't fail. For the time being, we'll just cache this.
// The graph is not valid until OnDeserialization has been called.
_siInfo = info;
}
/// <devdoc>
/// Gets the size of the table.
/// </devdoc>
public int Count
{
get
{
if (_objectsArray == null)
{
return 0;
}
return _objectsArray.Count;
}
}
/// <devdoc>
/// Indicates that the collection can grow.
/// </devdoc>
bool IDictionary.IsFixedSize
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that the collection is not read-only
/// </devdoc>
public bool IsReadOnly
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that this class is not synchronized
/// </devdoc>
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
/// <devdoc>
/// Gets the collection of keys in the table in order.
/// </devdoc>
public ICollection Keys
{
get
{
EnsureObjectsArray();
return new OrderedDictionaryKeyValueCollection(_objectsArray, true);
}
}
private void EnsureObjectsArray()
{
if (_objectsArray == null)
{
_objectsArray = new ArrayList(_initialCapacity);
}
}
private void EnsureObjectsTable()
{
if (_objectsTable == null)
{
_objectsTable = new Hashtable(_initialCapacity, _comparer);
}
}
/// <devdoc>
/// The SyncRoot object. Not used because IsSynchronized is false
/// </devdoc>
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
/// <devdoc>
/// Gets or sets the object at the specified index
/// </devdoc>
public object this[int index]
{
get
{
EnsureObjectsArray();
return ((DictionaryEntry)_objectsArray[index]).Value;
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (_objectsArray == null || index < 0 || index >= _objectsArray.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
EnsureObjectsArray();
EnsureObjectsTable();
object key = ((DictionaryEntry)_objectsArray[index]).Key;
_objectsArray[index] = new DictionaryEntry(key, value);
_objectsTable[key] = value;
}
}
/// <devdoc>
/// Gets or sets the object with the specified key
/// </devdoc>
public object this[object key]
{
get
{
if (_objectsTable == null)
{
return null;
}
return _objectsTable[key];
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
EnsureObjectsTable();
if (_objectsTable.Contains(key))
{
_objectsTable[key] = value;
EnsureObjectsArray();
_objectsArray[IndexOfKey(key)] = new DictionaryEntry(key, value);
}
else
{
Add(key, value);
}
}
}
/// <devdoc>
/// Returns an arrayList of the values in the table
/// </devdoc>
public ICollection Values
{
get
{
EnsureObjectsArray();
return new OrderedDictionaryKeyValueCollection(_objectsArray, false);
}
}
/// <devdoc>
/// Adds a new entry to the table with the lowest-available index.
/// </devdoc>
public void Add(object key, object value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
EnsureObjectsTable();
EnsureObjectsArray();
_objectsTable.Add(key, value);
_objectsArray.Add(new DictionaryEntry(key, value));
}
/// <devdoc>
/// Clears all elements in the table.
/// </devdoc>
public void Clear()
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (_objectsTable != null)
{
_objectsTable.Clear();
}
if (_objectsArray != null)
{
_objectsArray.Clear();
}
}
/// <devdoc>
/// Returns a readonly OrderedDictionary for the given OrderedDictionary.
/// </devdoc>
public OrderedDictionary AsReadOnly()
{
return new OrderedDictionary(this);
}
/// <devdoc>
/// Returns true if the key exists in the table, false otherwise.
/// </devdoc>
public bool Contains(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (_objectsTable == null)
{
return false;
}
return _objectsTable.Contains(key);
}
/// <devdoc>
/// Copies the table to an array. This will not preserve order.
/// </devdoc>
public void CopyTo(Array array, int index)
{
EnsureObjectsTable();
_objectsTable.CopyTo(array, index);
}
private int IndexOfKey(object key)
{
if (_objectsArray == null)
{
return -1;
}
for (int i = 0; i < _objectsArray.Count; i++)
{
object o = ((DictionaryEntry)_objectsArray[i]).Key;
if (_comparer != null)
{
if (_comparer.Equals(o, key))
{
return i;
}
}
else
{
if (o.Equals(key))
{
return i;
}
}
}
return -1;
}
/// <devdoc>
/// Inserts a new object at the given index with the given key.
/// </devdoc>
public void Insert(int index, object key, object value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index > Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
EnsureObjectsTable();
EnsureObjectsArray();
_objectsTable.Add(key, value);
_objectsArray.Insert(index, new DictionaryEntry(key, value));
}
/// <devdoc>
/// Removes the entry at the given index.
/// </devdoc>
public void RemoveAt(int index)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index >= Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
// The 'index >= Count' check above ensures
// that the '_objectsArray' and '_objectsTable' objects are initialized.
object key = ((DictionaryEntry)_objectsArray[index]).Key;
_objectsArray.RemoveAt(index);
_objectsTable.Remove(key);
}
/// <devdoc>
/// Removes the entry with the given key.
/// </devdoc>
public void Remove(object key)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
int index = IndexOfKey(key);
if (index < 0)
{
return;
}
EnsureObjectsTable();
EnsureObjectsArray();
_objectsTable.Remove(key);
_objectsArray.RemoveAt(index);
}
#region IDictionary implementation
public virtual IDictionaryEnumerator GetEnumerator()
{
EnsureObjectsArray();
return new OrderedDictionaryEnumerator(_objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
EnsureObjectsArray();
return new OrderedDictionaryEnumerator(_objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region ISerializable implementation
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer));
info.AddValue(ReadOnlyName, _readOnly);
info.AddValue(InitCapacityName, _initialCapacity);
object[] serArray = new object[Count];
EnsureObjectsArray();
_objectsArray.CopyTo(serArray);
info.AddValue(ArrayListName, serArray);
}
#endregion
#region IDeserializationCallback implementation
void IDeserializationCallback.OnDeserialization(object sender) {
OnDeserialization(sender);
}
protected virtual void OnDeserialization(object sender)
{
if (_siInfo == null)
{
throw new SerializationException(SR.Serialization_InvalidOnDeser);
}
_comparer = (IEqualityComparer)_siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer));
_readOnly = _siInfo.GetBoolean(ReadOnlyName);
_initialCapacity = _siInfo.GetInt32(InitCapacityName);
object[] serArray = (object[])_siInfo.GetValue(ArrayListName, typeof(object[]));
if (serArray != null)
{
EnsureObjectsTable();
EnsureObjectsArray();
foreach (object o in serArray)
{
DictionaryEntry entry;
try
{
// DictionaryEntry is a value type, so it can only be casted.
entry = (DictionaryEntry)o;
}
catch
{
throw new SerializationException(SR.OrderedDictionary_SerializationMismatch);
}
_objectsArray.Add(entry);
_objectsTable.Add(entry.Key, entry.Value);
}
}
}
#endregion
/// <devdoc>
/// OrderedDictionaryEnumerator works just like any other IDictionaryEnumerator, but it retrieves DictionaryEntries
/// in the order by index.
/// </devdoc>
private class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
private int _objectReturnType;
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictionaryEntry = 3;
private IEnumerator _arrayEnumerator;
internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType)
{
_arrayEnumerator = array.GetEnumerator();
_objectReturnType = objectReturnType;
}
/// <devdoc>
/// Retrieves the current DictionaryEntry. This is the same as Entry, but not strongly-typed.
/// </devdoc>
public object Current
{
get
{
if (_objectReturnType == Keys)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
if (_objectReturnType == Values)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
return Entry;
}
}
/// <devdoc>
/// Retrieves the current DictionaryEntry
/// </devdoc>
public DictionaryEntry Entry
{
get
{
return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value);
}
}
/// <devdoc>
/// Retrieves the key of the current DictionaryEntry
/// </devdoc>
public object Key
{
get
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
}
/// <devdoc>
/// Retrieves the value of the current DictionaryEntry
/// </devdoc>
public object Value
{
get
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
}
/// <devdoc>
/// Moves the enumerator pointer to the next member
/// </devdoc>
public bool MoveNext()
{
return _arrayEnumerator.MoveNext();
}
/// <devdoc>
/// Resets the enumerator pointer to the beginning.
/// </devdoc>
public void Reset()
{
_arrayEnumerator.Reset();
}
}
/// <devdoc>
/// OrderedDictionaryKeyValueCollection implements a collection for the Values and Keys properties
/// that is "live"- it will reflect changes to the OrderedDictionary on the collection made after the getter
/// was called.
/// </devdoc>
private class OrderedDictionaryKeyValueCollection : ICollection
{
private ArrayList _objects;
private bool _isKeys;
public OrderedDictionaryKeyValueCollection(ArrayList array, bool isKeys)
{
_objects = array;
_isKeys = isKeys;
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index);
foreach (object o in _objects)
{
array.SetValue(_isKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index);
index++;
}
}
int ICollection.Count
{
get
{
return _objects.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return _objects.SyncRoot;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new OrderedDictionaryEnumerator(_objects, _isKeys == true ? OrderedDictionaryEnumerator.Keys : OrderedDictionaryEnumerator.Values);
}
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Collections;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using SysTrace = System.Diagnostics.Trace;
using Alachisoft.NCache.Runtime.Serialization.IO;
using Runtime = Alachisoft.NCache.Runtime;
namespace Alachisoft.NCache.Common.Stats
{
/// <summary>
/// Class that is useful in capturing statistics.
/// </summary>
[Serializable]
public class TimeStats : Runtime.Serialization.ICompactSerializable
{
/// <summary> Total number of samples collected for the statistics. </summary>
private long _runCount;
/// <summary> Timestamp for the begining of a sample. </summary>
private long _lastStart;
/// <summary> Timestamp for the end of a sample. </summary>
private long _lastStop;
/// <summary> Total time spent in sampling, i.e., acrued sample time. </summary>
private long _totalTime;
/// <summary> Best time interval mesaured during sampling. </summary>
private long _bestTime;
/// <summary> Worst time interval mesaured during sampling. </summary>
private long _worstTime;
/// <summary> Avg. time interval mesaured during sampling. </summary>
private float _avgTime;
/// <summary> Total number of samples collected for the statistics. </summary>
private long _totalRunCount;
private long _worstThreshHole = long.MaxValue;
private long _worstOccurance;
/// <summary>
/// Constructor
/// </summary>
public TimeStats()
{
Reset();
}
/// <summary>
/// Constructor
/// </summary>
public TimeStats(long worstThreshHoleValue)
{
Reset();
_worstThreshHole = worstThreshHoleValue;
}
/// <summary>
/// Returns the total numbre of runs in the statistics capture.
/// </summary>
public long Runs
{
get { lock(this){ return _runCount; } }
}
/// <summary>
/// Gets or sets the threshhold value for worst case occurance count.
/// </summary>
public long WorstThreshHoldValue
{
get { return _worstThreshHole; }
set { _worstThreshHole = value; }
}
/// <summary>
/// Gets the number of total worst cases occured.
/// </summary>
public long TotalWorstCases
{
get { return _worstOccurance; }
}
/// <summary>
/// Returns the total time iterval spent in sampling
/// </summary>
public long Total
{
get { lock(this){ return _totalTime; } }
}
/// <summary>
/// Returns the time interval for the last sample
/// </summary>
public long Current
{
get { lock(this){ return _lastStop - _lastStart; } }
}
/// <summary>
/// Returns the best time interval mesaured during sampling
/// </summary>
public long Best
{
get { lock(this){ return _bestTime; } }
}
/// <summary>
/// Returns the avg. time interval mesaured during sampling
/// </summary>
public float Avg
{
get { lock(this){ return _avgTime ; } }
}
/// <summary>
/// Returns the worst time interval mesaured during sampling
/// </summary>
public long Worst
{
get { lock(this){ return _worstTime; } }
}
/// <summary>
/// Resets the statistics collected so far.
/// </summary>
public void Reset()
{
_runCount = 0;
_totalTime = _bestTime = _worstTime = _worstOccurance = 0;
_avgTime = 0;
}
/// <summary>
/// Timestamps the start of a sampling interval.
/// </summary>
public void BeginSample()
{
_lastStart = (DateTime.Now.Ticks - 621355968000000000) / 10000;
}
/// <summary>
/// Timestamps the end of interval and calculates the sample time
/// </summary>
public void EndSample()
{
lock(this)
{
_lastStop = (DateTime.Now.Ticks - 621355968000000000) / 10000;
AddSampleTime(Current);
}
}
/// <summary>
/// Timestamp the end of interval and calculates the sample time for bulk operations
/// </summary>
/// <param name="runcount">number of operations in bulk</param>
public void EndSample(int runcount)
{
lock (this)
{
_lastStop = (DateTime.Now.Ticks - 621355968000000000) / 10000;
AddSampleTime(Current, runcount);
}
}
/// <summary>
/// Adds a specified sample time to the statistics and updates the run count
/// </summary>
/// <param name="time">sample time in milliseconds.</param>
public void AddSampleTime(long time)
{
lock(this)
{
_runCount ++;
_totalRunCount ++;
if(_runCount == 1)
{
_avgTime = _totalTime = _bestTime = _worstTime = time;
}
else
{
_totalTime += time;
if(time < _bestTime) _bestTime = time;
if(time > _worstTime) _worstTime = time;
if (time > _worstThreshHole) _worstOccurance += 1;
_avgTime = (float)_totalTime / _runCount;
}
}
}
/// <summary>
/// Adds a specified sample time to the statistics and updates the run count
/// </summary>
/// <param name="time">sample time in milliseconds.</param>
/// <param name="runcount"> num of runs in case of bulk operations
public void AddSampleTime(long time, int runcount)
{
lock (this)
{
_runCount+= runcount;
_totalRunCount+= runcount;
if (_runCount == 1)
{
_avgTime = _totalTime = _bestTime = _worstTime = time;
}
else
{
_totalTime += time;
if (time < _bestTime) _bestTime = time;
if (time > _worstTime) _worstTime = time;
if (time > _worstThreshHole) _worstOccurance += 1;
_avgTime = (float)_totalTime / _runCount;
}
}
}
/// <summary>
/// Gets the total run count for the samples
/// </summary>
public long TotalRunCount
{
get { return _totalRunCount; }
}
/// <summary>
/// Override converts to string equivalent.
/// </summary>
/// <returns></returns>
public override string ToString()
{
lock(this)
{
string retval = "[Runs: " + _runCount + ", ";
retval += "Best(ms): " + _bestTime + ", ";
retval += "Avg.(ms): " + _avgTime + ", ";
retval += "Worst(ms): " + _worstTime + ", ";
retval += "WorstThreshHole(ms): " + _worstThreshHole + ", ";
retval += "Worst cases: " + _worstOccurance + "]";
return retval;
}
}
#region ICompact Serializable Members
public void Deserialize(CompactReader reader)
{
_runCount = reader.ReadInt64();
_lastStart = reader.ReadInt64();
_lastStop = reader.ReadInt64();
_totalTime = reader.ReadInt64();
_bestTime = reader.ReadInt64();
_worstTime = reader.ReadInt64();
_avgTime = (float)reader.ReadDouble();
_totalRunCount = reader.ReadInt64();
_worstThreshHole = reader.ReadInt64();
_worstOccurance = reader.ReadInt64();
}
public void Serialize(CompactWriter writer)
{
writer.Write(_runCount);
writer.Write(_lastStart);
writer.Write(_lastStop);
writer.Write(_totalTime);
writer.Write(_bestTime);
writer.Write(_worstTime);
writer.Write(_avgTime);
writer.Write(_totalRunCount);
writer.Write(_worstThreshHole);
writer.Write(_worstOccurance);
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Term = Lucene.Net.Index.Term;
using Directory = Lucene.Net.Store.Directory;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
/// <summary> Test Hits searches with interleaved deletions.
///
/// See {@link http://issues.apache.org/jira/browse/LUCENE-1096}.
/// </summary>
/// <deprecated> Hits will be removed in Lucene 3.0
/// </deprecated>
[TestFixture]
public class TestSearchHitsWithDeletions:LuceneTestCase
{
private static bool VERBOSE = false;
private const System.String TEXT_FIELD = "text";
private const int N = 16100;
private static Directory directory;
[Test]
public override void SetUp()
{
base.SetUp();
// Create an index writer.
directory = new RAMDirectory();
IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
for (int i = 0; i < N; i++)
{
writer.AddDocument(CreateDocument(i));
}
writer.Optimize();
writer.Close();
}
/// <summary> Deletions during search should not alter previously retrieved hits.</summary>
[Test]
public virtual void TestSearchHitsDeleteAll()
{
DoTestSearchHitsDeleteEvery(1, false);
}
/// <summary> Deletions during search should not alter previously retrieved hits.</summary>
[Test]
public virtual void TestSearchHitsDeleteEvery2ndHit()
{
DoTestSearchHitsDeleteEvery(2, false);
}
/// <summary> Deletions during search should not alter previously retrieved hits.</summary>
[Test]
public virtual void TestSearchHitsDeleteEvery4thHit()
{
DoTestSearchHitsDeleteEvery(4, false);
}
/// <summary> Deletions during search should not alter previously retrieved hits.</summary>
[Test]
public virtual void TestSearchHitsDeleteEvery8thHit()
{
DoTestSearchHitsDeleteEvery(8, false);
}
/// <summary> Deletions during search should not alter previously retrieved hits.</summary>
[Test]
public virtual void TestSearchHitsDeleteEvery90thHit()
{
DoTestSearchHitsDeleteEvery(90, false);
}
/// <summary> Deletions during search should not alter previously retrieved hits,
/// and deletions that affect total number of hits should throw the
/// correct exception when trying to fetch "too many".
/// </summary>
[Test]
public virtual void TestSearchHitsDeleteEvery8thHitAndInAdvance()
{
DoTestSearchHitsDeleteEvery(8, true);
}
/// <summary> Verify that ok also with no deletions at all.</summary>
[Test]
public virtual void TestSearchHitsNoDeletes()
{
DoTestSearchHitsDeleteEvery(N + 100, false);
}
/// <summary> Deletions that affect total number of hits should throw the
/// correct exception when trying to fetch "too many".
/// </summary>
[Test]
public virtual void TestSearchHitsDeleteInAdvance()
{
DoTestSearchHitsDeleteEvery(N + 100, true);
}
/// <summary> Intermittent deletions during search, should not alter previously retrieved hits.
/// (Using a debugger to verify that the check in Hits is performed only
/// </summary>
[Test]
public virtual void TestSearchHitsDeleteIntermittent()
{
DoTestSearchHitsDeleteEvery(- 1, false);
}
private void DoTestSearchHitsDeleteEvery(int k, bool deleteInFront)
{
bool intermittent = k < 0;
Log("Test search hits with " + (intermittent?"intermittent deletions.":"deletions of every " + k + " hit."));
IndexSearcher searcher = new IndexSearcher(directory);
IndexReader reader = searcher.GetIndexReader();
Query q = new TermQuery(new Term(TEXT_FIELD, "text")); // matching all docs
Hits hits = searcher.Search(q);
Log("Got " + hits.Length() + " results");
Assert.AreEqual(N, hits.Length(), "must match all " + N + " docs, not only " + hits.Length() + " docs!");
if (deleteInFront)
{
Log("deleting hits that was not yet retrieved!");
reader.DeleteDocument(reader.MaxDoc() - 1);
reader.DeleteDocument(reader.MaxDoc() - 2);
reader.DeleteDocument(reader.MaxDoc() - 3);
}
try
{
for (int i = 0; i < hits.Length(); i++)
{
int id = hits.Id(i);
Assert.AreEqual(i, hits.Id(i), "Hit " + i + " has doc id " + hits.Id(i) + " instead of " + i);
if ((intermittent && (i == 50 || i == 250 || i == 950)) || (!intermittent && (k < 2 || (i > 0 && i % k == 0))))
{
Document doc = hits.Doc(id);
Log("Deleting hit " + i + " - doc " + doc + " with id " + id);
reader.DeleteDocument(id);
}
if (intermittent)
{
// check internal behavior of Hits (go 50 ahead of getMoreDocs points because the deletions cause to use more of the available hits)
if (i == 150 || i == 450 || i == 1650)
{
Assert.IsTrue(hits.debugCheckedForDeletions, "Hit " + i + ": hits should have checked for deletions in last call to getMoreDocs()");
}
else if (i == 50 || i == 250 || i == 850)
{
Assert.IsFalse(hits.debugCheckedForDeletions, "Hit " + i + ": hits should have NOT checked for deletions in last call to getMoreDocs()");
}
}
}
}
catch (System.Exception e)
{
// this is the only valid exception, and only when deletng in front.
Assert.IsTrue(deleteInFront, e.Message + " not expected unless deleting hits that were not yet seen!");
}
searcher.Close();
}
private static Document CreateDocument(int id)
{
Document doc = new Document();
doc.Add(new Field(TEXT_FIELD, "text of document" + id, Field.Store.YES, Field.Index.ANALYZED));
return doc;
}
private static void Log(System.String s)
{
if (VERBOSE)
{
System.Console.Out.WriteLine(s);
}
}
}
}
| |
/*
Azure Media Services REST API v2 Function
This function submits a job to process a live stream with media analytics.
The first task is a subclipping task that createq a MP4 file, then media analytics are processed on this asset.
Input:
{
"channelName": "channel1", // Mandatory
"programName" : "program1", // Mandatory
"intervalSec" : 60 // Optional. Default is 60 seconds. The duration of subclip (and interval between two calls)
"mesSubclip" : // Optional as subclip will always be done but it is required to specify an output storage
{
"outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account)
},
"mesThumbnails" : // Optional but required to generate thumbnails with Media Encoder Standard (MES)
{
"start" : "{Best}", // Optional. Start time/mode. Default is "{Best}"
"outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account)
},
"indexV1" : // Optional but required to index audio with Media Indexer v1
{
"language" : "English", // Optional. Default is "English"
"outputStorage" : "amsstorage01" // Optional. Storage account name where to put the output asset (attached to AMS account)
}
// General job properties
"priority" : 10, // Optional, priority of the job
// For compatibility only with old workflows. Do not use anymore!
"indexV1Language" : "English", // Optional
"mesThumbnailsStart" : "{Best}", // Optional. Add a task to generate thumbnails
}
Output:
{
"triggerStart" : "" // date and time when the function was called
"jobId" : // job id
"subclip" :
{
assetId : "",
taskId : "",
start : "",
duration : ""
},
"indexV1" :
{
assetId : "",
taskId : "",
language : ""
},
"programId" = programid,
"channelName" : "",
"programName" : "",
"programUrl":"",
"programState" : "Running",
"programStateChanged" : "True", // if state changed since last call
"otherJobsQueue" = 3 // number of jobs in the queue
}
*/
using System;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.MediaServices.Client;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
namespace media_functions_for_logic_app
{
public static class live_subclip_analytics
{
// Field for service context.
private static CloudMediaContext _context = null;
[FunctionName("live-subclip-analytics")]
public static async Task<object> Run([HttpTrigger(WebHookType = "genericJson")]HttpRequestMessage req, TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext execContext)
{
// Variables
int taskindex = 0;
int OutputMES = -1;
int OutputPremium = -1;
int OutputIndex1 = -1;
int OutputMesThumbnails = -1;
int id = 0;
string programid = "";
string programName = "";
string channelName = "";
string programUrl = "";
string programState = "";
string lastProgramState = "";
IJob job = null;
ITask taskEncoding = null;
int NumberJobsQueue = 0;
int intervalsec = 60; // Interval for each subclip job (sec). Default is 60
TimeSpan starttime = TimeSpan.FromSeconds(0);
TimeSpan duration = TimeSpan.FromSeconds(intervalsec);
log.Info($"Webhook was triggered!");
string triggerStart = DateTime.UtcNow.ToString("o");
string jsonContent = await req.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(jsonContent);
log.Info(jsonContent);
if (data.channelName == null || data.programName == null)
{
return req.CreateResponse(HttpStatusCode.BadRequest, new
{
error = "Please pass channel name and program name in the input object (channelName, programName)"
});
}
if (data.intervalSec != null)
{
intervalsec = (int)data.intervalSec;
}
MediaServicesCredentials amsCredentials = new MediaServicesCredentials();
log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}");
try
{
AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
AzureEnvironments.AzureCloudEnvironment);
AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);
_context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);
// find the Channel, Program and Asset
channelName = (string)data.channelName;
var channel = _context.Channels.Where(c => c.Name == channelName).FirstOrDefault();
if (channel == null)
{
log.Info("Channel not found");
return req.CreateResponse(HttpStatusCode.BadRequest, new
{
error = "Channel not found"
});
}
programName = (string)data.programName;
var program = channel.Programs.Where(p => p.Name == programName).FirstOrDefault();
if (program == null)
{
log.Info("Program not found");
return req.CreateResponse(HttpStatusCode.BadRequest, new
{
error = "Program not found"
});
}
programState = program.State.ToString();
programid = program.Id;
var asset = ManifestHelpers.GetAssetFromProgram(_context, programid);
if (asset == null)
{
log.Info($"Asset not found for program {programid}");
return req.CreateResponse(HttpStatusCode.BadRequest, new
{
error = "Asset not found"
});
}
log.Info($"Using asset Id : {asset.Id}");
// Table storage to store and real the last timestamp processed
// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(amsCredentials.StorageAccountName, amsCredentials.StorageAccountKey), true);
// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
// Retrieve a reference to the table.
CloudTable table = tableClient.GetTableReference("liveanalytics");
// Create the table if it doesn't exist.
if (!table.CreateIfNotExists())
{
log.Info($"Table {table.Name} already exists");
}
else
{
log.Info($"Table {table.Name} created");
}
var lastendtimeInTable = ManifestHelpers.RetrieveLastEndTime(table, programid);
// Get the manifest data (timestamps)
var assetmanifestdata = ManifestHelpers.GetManifestTimingData(_context, asset, log);
if (assetmanifestdata.Error)
{
return req.CreateResponse(HttpStatusCode.InternalServerError, new { error = "Data cannot be read from program manifest." });
}
log.Info("Timestamps: " + string.Join(",", assetmanifestdata.TimestampList.Select(n => n.ToString()).ToArray()));
var livetime = TimeSpan.FromSeconds((double)assetmanifestdata.TimestampEndLastChunk / (double)assetmanifestdata.TimeScale);
log.Info($"Livetime: {livetime}");
starttime = ManifestHelpers.ReturnTimeSpanOnGOP(assetmanifestdata, livetime.Subtract(TimeSpan.FromSeconds(intervalsec)));
log.Info($"Value starttime : {starttime}");
if (lastendtimeInTable != null)
{
lastProgramState = lastendtimeInTable.ProgramState;
log.Info($"Value ProgramState retrieved : {lastProgramState}");
var lastendtimeInTableValue = TimeSpan.Parse(lastendtimeInTable.LastEndTime);
log.Info($"Value lastendtimeInTable retrieved : {lastendtimeInTableValue}");
id = int.Parse(lastendtimeInTable.Id);
log.Info($"Value id retrieved : {id}");
if (lastendtimeInTableValue != null)
{
var delta = (livetime - lastendtimeInTableValue - TimeSpan.FromSeconds(intervalsec)).Duration();
log.Info($"Delta: {delta}");
//if (delta < (new TimeSpan(0, 0, 3*intervalsec))) // less than 3 times the normal duration (3*60s)
if (delta < (TimeSpan.FromSeconds(3 * intervalsec))) // less than 3 times the normal duration (3*60s)
{
starttime = lastendtimeInTableValue;
log.Info($"Value new starttime : {starttime}");
}
}
}
duration = livetime - starttime;
log.Info($"Value duration: {duration}");
if (duration == new TimeSpan(0)) // Duration is zero, this may happen sometimes !
{
return req.CreateResponse(HttpStatusCode.InternalServerError, new { error = "Stopping. Duration of subclip is zero." });
}
// D:\home\site\wwwroot\Presets\LiveSubclip.json
string ConfigurationSubclip = File.ReadAllText(Path.Combine(System.IO.Directory.GetParent(execContext.FunctionDirectory).FullName, "presets", "LiveSubclip.json")).Replace("0:00:00.000000", starttime.Subtract(TimeSpan.FromMilliseconds(100)).ToString()).Replace("0:00:30.000000", duration.Add(TimeSpan.FromMilliseconds(200)).ToString());
int priority = 10;
if (data.priority != null)
{
priority = (int)data.priority;
}
// MES Subclipping TASK
// Declare a new encoding job with the Standard encoder
job = _context.Jobs.Create("Azure Function - Job for Live Analytics - " + programName, priority);
// Get a media processor reference, and pass to it the name of the
// processor to use for the specific task.
IMediaProcessor processor = MediaServicesHelper.GetLatestMediaProcessorByName(_context, "Media Encoder Standard");
// Change or modify the custom preset JSON used here.
// string preset = File.ReadAllText("D:\home\site\wwwroot\Presets\H264 Multiple Bitrate 720p.json");
// Create a task with the encoding details, using a string preset.
// In this case "H264 Multiple Bitrate 720p" system defined preset is used.
taskEncoding = job.Tasks.AddNew("Subclipping task",
processor,
ConfigurationSubclip,
TaskOptions.None);
// Specify the input asset to be encoded.
taskEncoding.InputAssets.Add(asset);
OutputMES = taskindex++;
// Add an output asset to contain the results of the job.
// This output is specified as AssetCreationOptions.None, which
// means the output asset is not encrypted.
var subclipasset = taskEncoding.OutputAssets.AddNew(asset.Name + " subclipped " + triggerStart, JobHelpers.OutputStorageFromParam(data.mesSubclip), AssetCreationOptions.None);
log.Info($"Adding media analytics tasks");
//new
OutputIndex1 = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.indexV1 == null) ? (string)data.indexV1Language : ((string)data.indexV1.language ?? "English"), "Azure Media Indexer", "IndexerV1.xml", "English", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.indexV1));
// MES Thumbnails
OutputMesThumbnails = JobHelpers.AddTask(execContext, _context, job, subclipasset, (data.mesThumbnails != null) ? ((string)data.mesThumbnails.Start ?? "{Best}") : null, "Media Encoder Standard", "MesThumbnails.json", "{Best}", ref taskindex, specifiedStorageAccountName: JobHelpers.OutputStorageFromParam(data.mesThumbnails));
job.Submit();
log.Info("Job Submitted");
id++;
ManifestHelpers.UpdateLastEndTime(table, starttime + duration, programid, id, program.State);
log.Info($"Output MES index {OutputMES}");
// Let store some data in altid of subclipped asset
var sid = JobHelpers.ReturnId(job, OutputMES);
log.Info($"SID {sid}");
var subclipassetrefreshed = _context.Assets.Where(a => a.Id == sid).FirstOrDefault();
log.Info($"subclipassetrefreshed ID {subclipassetrefreshed.Id}");
subclipassetrefreshed.AlternateId = JsonConvert.SerializeObject(new ManifestHelpers.SubclipInfo() { programId = programid, subclipStart = starttime, subclipDuration = duration });
subclipassetrefreshed.Update();
// Let store some data in altid of index assets
var index1sid = JobHelpers.ReturnId(job, OutputIndex1);
if (index1sid != null)
{
var index1assetrefreshed = _context.Assets.Where(a => a.Id == index1sid).FirstOrDefault();
log.Info($"index1assetrefreshed ID {index1assetrefreshed.Id}");
index1assetrefreshed.AlternateId = JsonConvert.SerializeObject(new ManifestHelpers.SubclipInfo() { programId = programid, subclipStart = starttime, subclipDuration = duration });
index1assetrefreshed.Update();
}
// Get program URL
var publishurlsmooth = MediaServicesHelper.GetValidOnDemandURI(_context, asset);
if (publishurlsmooth != null)
{
programUrl = publishurlsmooth.ToString();
}
NumberJobsQueue = _context.Jobs.Where(j => j.State == JobState.Queued).Count();
}
catch (Exception ex)
{
string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : "");
log.Info($"ERROR: Exception {message}");
return req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message });
}
log.Info("Job Id: " + job.Id);
log.Info("Output asset Id: " + ((OutputMES > -1) ? JobHelpers.ReturnId(job, OutputMES) : JobHelpers.ReturnId(job, OutputPremium)));
return req.CreateResponse(HttpStatusCode.OK, new
{
triggerStart = triggerStart,
jobId = job.Id,
subclip = new
{
assetId = JobHelpers.ReturnId(job, OutputMES),
taskId = JobHelpers.ReturnTaskId(job, OutputMES),
start = starttime,
duration = duration,
},
mesThumbnails = new
{
assetId = JobHelpers.ReturnId(job, OutputMesThumbnails),
taskId = JobHelpers.ReturnTaskId(job, OutputMesThumbnails)
},
indexV1 = new
{
assetId = JobHelpers.ReturnId(job, OutputIndex1),
taskId = JobHelpers.ReturnTaskId(job, OutputIndex1),
language = (string)data.indexV1Language
},
channelName = channelName,
programName = programName,
programId = programid,
programUrl = programUrl,
programState = programState,
programStateChanged = (lastProgramState != programState).ToString(),
otherJobsQueue = NumberJobsQueue
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Xml
{
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Diagnostics;
using Microsoft.Xml.Schema;
using Microsoft.Xml.XPath;
using MS.Internal.Xml.XPath;
using System.Globalization;
// Represents a single node in the document.
[DebuggerDisplay("{debuggerDisplayProxy}")]
public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable
{
internal XmlNode parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly.
internal XmlNode()
{
}
internal XmlNode(XmlDocument doc)
{
if (doc == null)
throw new ArgumentException(ResXml.Xdom_Node_Null_Doc);
this.parentNode = doc;
}
public virtual XPathNavigator CreateNavigator()
{
XmlDocument thisAsDoc = this as XmlDocument;
if (thisAsDoc != null)
{
return thisAsDoc.CreateNavigator(this);
}
XmlDocument doc = OwnerDocument;
Debug.Assert(doc != null);
return doc.CreateNavigator(this);
}
// Selects the first node that matches the xpath expression
public XmlNode SelectSingleNode(string xpath)
{
XmlNodeList list = SelectNodes(xpath);
// SelectNodes returns null for certain node types
return list != null ? list[0] : null;
}
// Selects the first node that matches the xpath expression and given namespace context.
public XmlNode SelectSingleNode(string xpath, XmlNamespaceManager nsmgr)
{
XPathNavigator xn = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if (xn == null)
return null;
XPathExpression exp = xn.Compile(xpath);
exp.SetContext(nsmgr);
return new XPathNodeList(xn.Select(exp))[0];
}
// Selects all nodes that match the xpath expression
public XmlNodeList SelectNodes(string xpath)
{
XPathNavigator n = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if (n == null)
return null;
return new XPathNodeList(n.Select(xpath));
}
// Selects all nodes that match the xpath expression and given namespace context.
public XmlNodeList SelectNodes(string xpath, XmlNamespaceManager nsmgr)
{
XPathNavigator xn = (this).CreateNavigator();
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
if (xn == null)
return null;
XPathExpression exp = xn.Compile(xpath);
exp.SetContext(nsmgr);
return new XPathNodeList(xn.Select(exp));
}
// Gets the name of the node.
public abstract string Name
{
get;
}
// Gets or sets the value of the node.
public virtual string Value
{
get { return null; }
set { throw new InvalidOperationException(string.Format(ResXml.Xdom_Node_SetVal, NodeType)); }
}
// Gets the type of the current node.
public abstract XmlNodeType NodeType
{
get;
}
// Gets the parent of this node (for nodes that can have parents).
public virtual XmlNode ParentNode
{
get
{
Debug.Assert(parentNode != null);
if (parentNode.NodeType != XmlNodeType.Document)
{
return parentNode;
}
// Linear lookup through the children of the document
XmlLinkedNode firstChild = parentNode.FirstChild as XmlLinkedNode;
if (firstChild != null)
{
XmlLinkedNode node = firstChild;
do
{
if (node == this)
{
return parentNode;
}
node = node.next;
}
while (node != null
&& node != firstChild);
}
return null;
}
}
// Gets all children of this node.
public virtual XmlNodeList ChildNodes
{
get { return new XmlChildNodes(this); }
}
// Gets the node immediately preceding this node.
public virtual XmlNode PreviousSibling
{
get { return null; }
}
// Gets the node immediately following this node.
public virtual XmlNode NextSibling
{
get { return null; }
}
// Gets a XmlAttributeCollection containing the attributes
// of this node.
public virtual XmlAttributeCollection Attributes
{
get { return null; }
}
// Gets the XmlDocument that contains this node.
public virtual XmlDocument OwnerDocument
{
get
{
Debug.Assert(parentNode != null);
if (parentNode.NodeType == XmlNodeType.Document)
return (XmlDocument)parentNode;
return parentNode.OwnerDocument;
}
}
// Gets the first child of this node.
public virtual XmlNode FirstChild
{
get
{
XmlLinkedNode linkedNode = LastNode;
if (linkedNode != null)
return linkedNode.next;
return null;
}
}
// Gets the last child of this node.
public virtual XmlNode LastChild
{
get { return LastNode; }
}
internal virtual bool IsContainer
{
get { return false; }
}
internal virtual XmlLinkedNode LastNode
{
get { return null; }
set { }
}
internal bool AncestorNode(XmlNode node)
{
XmlNode n = this.ParentNode;
while (n != null && n != this)
{
if (n == node)
return true;
n = n.ParentNode;
}
return false;
}
//trace to the top to find out its parent node.
internal bool IsConnected()
{
XmlNode parent = ParentNode;
while (parent != null && !(parent.NodeType == XmlNodeType.Document))
parent = parent.ParentNode;
return parent != null;
}
// Inserts the specified node immediately before the specified reference node.
public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild)
{
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(ResXml.Xdom_Node_Insert_Child);
if (refChild == null)
return AppendChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_Contain);
if (refChild.ParentNode != this)
throw new ArgumentException(ResXml.Xdom_Node_Insert_Path);
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(ResXml.Xdom_Node_Insert_Context);
if (!CanInsertBefore(newChild, refChild))
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_Location);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode first = newChild.FirstChild;
XmlNode node = first;
if (node != null)
{
newChild.RemoveChild(node);
InsertBefore(node, refChild);
// insert the rest of the children after this one.
InsertAfter(newChild, node);
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_TypeConflict);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
XmlLinkedNode refNode = (XmlLinkedNode)refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
if (refNode == FirstChild)
{
newNode.next = refNode;
LastNode.next = newNode;
newNode.SetParent(this);
if (newNode.IsText)
{
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
}
else
{
XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling;
newNode.next = refNode;
prevNode.next = newNode;
newNode.SetParent(this);
if (prevNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(prevNode, newNode);
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
else
{
if (refNode.IsText)
{
UnnestTextNodes(prevNode, refNode);
}
}
}
else
{
if (newNode.IsText)
{
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
// Inserts the specified node immediately after the specified reference node.
public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild)
{
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(ResXml.Xdom_Node_Insert_Child);
if (refChild == null)
return PrependChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_Contain);
if (refChild.ParentNode != this)
throw new ArgumentException(ResXml.Xdom_Node_Insert_Path);
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(ResXml.Xdom_Node_Insert_Context);
if (!CanInsertAfter(newChild, refChild))
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_Location);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode last = refChild;
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null)
{
XmlNode next = node.NextSibling;
newChild.RemoveChild(node);
InsertAfter(node, last);
last = node;
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_TypeConflict);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
XmlLinkedNode refNode = (XmlLinkedNode)refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
if (refNode == LastNode)
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
}
}
else
{
XmlLinkedNode nextNode = refNode.next;
newNode.next = nextNode;
refNode.next = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
if (nextNode.IsText)
{
NestTextNodes(newNode, nextNode);
}
}
else
{
if (nextNode.IsText)
{
UnnestTextNodes(refNode, nextNode);
}
}
}
else
{
if (newNode.IsText)
{
if (nextNode.IsText)
{
NestTextNodes(newNode, nextNode);
}
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
// Replaces the child node oldChild with newChild node.
public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild)
{
XmlNode nextNode = oldChild.NextSibling;
RemoveChild(oldChild);
XmlNode node = InsertBefore(newChild, nextNode);
return oldChild;
}
// Removes specified child node.
public virtual XmlNode RemoveChild(XmlNode oldChild)
{
if (!IsContainer)
throw new InvalidOperationException(ResXml.Xdom_Node_Remove_Contain);
if (oldChild.ParentNode != this)
throw new ArgumentException(ResXml.Xdom_Node_Remove_Child);
XmlLinkedNode oldNode = (XmlLinkedNode)oldChild;
string oldNodeValue = oldNode.Value;
XmlNodeChangedEventArgs args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove);
if (args != null)
BeforeEvent(args);
XmlLinkedNode lastNode = LastNode;
if (oldNode == FirstChild)
{
if (oldNode == lastNode)
{
LastNode = null;
oldNode.next = null;
oldNode.SetParent(null);
}
else
{
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText)
{
if (oldNode.IsText)
{
UnnestTextNodes(oldNode, nextNode);
}
}
lastNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
}
else
{
if (oldNode == lastNode)
{
XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
prevNode.next = oldNode.next;
LastNode = prevNode;
oldNode.next = null;
oldNode.SetParent(null);
}
else
{
XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText)
{
if (prevNode.IsText)
{
NestTextNodes(prevNode, nextNode);
}
else
{
if (oldNode.IsText)
{
UnnestTextNodes(oldNode, nextNode);
}
}
}
prevNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
}
if (args != null)
AfterEvent(args);
return oldChild;
}
// Adds the specified node to the beginning of the list of children of this node.
public virtual XmlNode PrependChild(XmlNode newChild)
{
return InsertBefore(newChild, FirstChild);
}
// Adds the specified node to the end of the list of children of this node.
public virtual XmlNode AppendChild(XmlNode newChild)
{
XmlDocument thisDoc = OwnerDocument;
if (thisDoc == null)
{
thisDoc = this as XmlDocument;
}
if (!IsContainer)
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_Contain);
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(ResXml.Xdom_Node_Insert_Child);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
XmlDocument childDoc = newChild.OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(ResXml.Xdom_Node_Insert_Context);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null)
{
XmlNode next = node.NextSibling;
newChild.RemoveChild(node);
AppendChild(node);
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_TypeConflict);
if (!CanInsertAfter(newChild, LastChild))
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_Location);
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (refNode == null)
{
newNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
}
else
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
//the function is provided only at Load time to speed up Load process
internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc)
{
XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this);
if (args != null)
doc.BeforeEvent(args);
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (refNode == null)
{
newNode.next = newNode;
LastNode = newNode;
newNode.SetParentForLoad(this);
}
else
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
if (refNode.IsText
&& newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
else
{
newNode.SetParentForLoad(this);
}
}
if (args != null)
doc.AfterEvent(args);
return newNode;
}
internal virtual bool IsValidChildType(XmlNodeType type)
{
return false;
}
internal virtual bool CanInsertBefore(XmlNode newChild, XmlNode refChild)
{
return true;
}
internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode refChild)
{
return true;
}
// Gets a value indicating whether this node has any child nodes.
public virtual bool HasChildNodes
{
get { return LastNode != null; }
}
// Creates a duplicate of this node.
public abstract XmlNode CloneNode(bool deep);
internal virtual void CopyChildren(XmlDocument doc, XmlNode container, bool deep)
{
for (XmlNode child = container.FirstChild; child != null; child = child.NextSibling)
{
AppendChildForLoad(child.CloneNode(deep), doc);
}
}
// DOM Level 2
// Puts all XmlText nodes in the full depth of the sub-tree
// underneath this XmlNode into a "normal" form where only
// markup (e.g., tags, comments, processing instructions, CDATA sections,
// and entity references) separates XmlText nodes, that is, there
// are no adjacent XmlText nodes.
public virtual void Normalize()
{
XmlNode firstChildTextLikeNode = null;
StringBuilder sb = new StringBuilder();
for (XmlNode crtChild = this.FirstChild; crtChild != null;)
{
XmlNode nextChild = crtChild.NextSibling;
switch (crtChild.NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
{
sb.Append(crtChild.Value);
XmlNode winner = NormalizeWinner(firstChildTextLikeNode, crtChild);
if (winner == firstChildTextLikeNode)
{
this.RemoveChild(crtChild);
}
else
{
if (firstChildTextLikeNode != null)
this.RemoveChild(firstChildTextLikeNode);
firstChildTextLikeNode = crtChild;
}
break;
}
case XmlNodeType.Element:
{
crtChild.Normalize();
goto default;
}
default:
{
if (firstChildTextLikeNode != null)
{
firstChildTextLikeNode.Value = sb.ToString();
firstChildTextLikeNode = null;
}
sb.Remove(0, sb.Length);
break;
}
}
crtChild = nextChild;
}
if (firstChildTextLikeNode != null && sb.Length > 0)
firstChildTextLikeNode.Value = sb.ToString();
}
private XmlNode NormalizeWinner(XmlNode firstNode, XmlNode secondNode)
{
//first node has the priority
if (firstNode == null)
return secondNode;
Debug.Assert(firstNode.NodeType == XmlNodeType.Text
|| firstNode.NodeType == XmlNodeType.SignificantWhitespace
|| firstNode.NodeType == XmlNodeType.Whitespace
|| secondNode.NodeType == XmlNodeType.Text
|| secondNode.NodeType == XmlNodeType.SignificantWhitespace
|| secondNode.NodeType == XmlNodeType.Whitespace);
if (firstNode.NodeType == XmlNodeType.Text)
return firstNode;
if (secondNode.NodeType == XmlNodeType.Text)
return secondNode;
if (firstNode.NodeType == XmlNodeType.SignificantWhitespace)
return firstNode;
if (secondNode.NodeType == XmlNodeType.SignificantWhitespace)
return secondNode;
if (firstNode.NodeType == XmlNodeType.Whitespace)
return firstNode;
if (secondNode.NodeType == XmlNodeType.Whitespace)
return secondNode;
Debug.Assert(true, "shouldn't have fall through here.");
return null;
}
// Test if the DOM implementation implements a specific feature.
public virtual bool Supports(string feature, string version)
{
if (String.Compare("XML", feature, StringComparison.OrdinalIgnoreCase) == 0)
{
if (version == null || version == "1.0" || version == "2.0")
return true;
}
return false;
}
// Gets the namespace URI of this node.
public virtual string NamespaceURI
{
get { return string.Empty; }
}
// Gets or sets the namespace prefix of this node.
public virtual string Prefix
{
get { return string.Empty; }
set { }
}
// Gets the name of the node without the namespace prefix.
public abstract string LocalName
{
get;
}
// Microsoft extensions
// Gets a value indicating whether the node is read-only.
public virtual bool IsReadOnly
{
get
{
XmlDocument doc = OwnerDocument;
return HasReadOnlyParent(this);
}
}
internal static bool HasReadOnlyParent(XmlNode n)
{
while (n != null)
{
switch (n.NodeType)
{
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
return true;
case XmlNodeType.Attribute:
n = ((XmlAttribute)n).OwnerElement;
break;
default:
n = n.ParentNode;
break;
}
}
return false;
}
// Creates a duplicate of this node.
public virtual XmlNode Clone()
{
return this.CloneNode(true);
}
object ICloneable.Clone()
{
return this.CloneNode(true);
}
// Provides a simple ForEach-style iteration over the
// collection of nodes in this XmlNamedNodeMap.
IEnumerator IEnumerable.GetEnumerator()
{
return new XmlChildEnumerator(this);
}
public IEnumerator GetEnumerator()
{
return new XmlChildEnumerator(this);
}
private void AppendChildText(StringBuilder builder)
{
for (XmlNode child = FirstChild; child != null; child = child.NextSibling)
{
if (child.FirstChild == null)
{
if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA
|| child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.SignificantWhitespace)
builder.Append(child.InnerText);
}
else
{
child.AppendChildText(builder);
}
}
}
// Gets or sets the concatenated values of the node and
// all its children.
public virtual string InnerText
{
get
{
XmlNode fc = FirstChild;
if (fc == null)
{
return string.Empty;
}
if (fc.NextSibling == null)
{
XmlNodeType nodeType = fc.NodeType;
switch (nodeType)
{
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return fc.Value;
}
}
StringBuilder builder = new StringBuilder();
AppendChildText(builder);
return builder.ToString();
}
set
{
XmlNode firstChild = FirstChild;
if (firstChild != null //there is one child
&& firstChild.NextSibling == null // and exactly one
&& firstChild.NodeType == XmlNodeType.Text)//which is a text node
{
//this branch is for perf reason and event fired when TextNode.Value is changed
firstChild.Value = value;
}
else
{
RemoveAll();
AppendChild(OwnerDocument.CreateTextNode(value));
}
}
}
// Gets the markup representing this node and all its children.
public virtual string OuterXml
{
get
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter(sw);
try
{
WriteTo(xw);
}
finally
{
xw.Close();
}
return sw.ToString();
}
}
// Gets or sets the markup representing just the children of this node.
public virtual string InnerXml
{
get
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter(sw);
try
{
WriteContentTo(xw);
}
finally
{
xw.Close();
}
return sw.ToString();
}
set
{
throw new InvalidOperationException(ResXml.Xdom_Set_InnerXml);
}
}
public virtual IXmlSchemaInfo SchemaInfo
{
get
{
return XmlDocument.NotKnownSchemaInfo;
}
}
public virtual String BaseURI
{
get
{
XmlNode curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref
while (curNode != null)
{
XmlNodeType nt = curNode.NodeType;
//EntityReference's children come from the dtd where they are defined.
//we need to investigate the same thing for entity's children if they are defined in an external dtd file.
if (nt == XmlNodeType.EntityReference)
return ((XmlEntityReference)curNode).ChildBaseURI;
if (nt == XmlNodeType.Document
|| nt == XmlNodeType.Entity
|| nt == XmlNodeType.Attribute)
return curNode.BaseURI;
curNode = curNode.ParentNode;
}
return String.Empty;
}
}
// Saves the current node to the specified XmlWriter.
public abstract void WriteTo(XmlWriter w);
// Saves all the children of the node to the specified XmlWriter.
public abstract void WriteContentTo(XmlWriter w);
// Removes all the children and/or attributes
// of the current node.
public virtual void RemoveAll()
{
XmlNode child = FirstChild;
XmlNode sibling = null;
while (child != null)
{
sibling = child.NextSibling;
RemoveChild(child);
child = sibling;
}
}
internal XmlDocument Document
{
get
{
if (NodeType == XmlNodeType.Document)
return (XmlDocument)this;
return OwnerDocument;
}
}
// Looks up the closest xmlns declaration for the given
// prefix that is in scope for the current node and returns
// the namespace URI in the declaration.
public virtual string GetNamespaceOfPrefix(string prefix)
{
string namespaceName = GetNamespaceOfPrefixStrict(prefix);
return namespaceName != null ? namespaceName : string.Empty;
}
internal string GetNamespaceOfPrefixStrict(string prefix)
{
XmlDocument doc = Document;
if (doc != null)
{
prefix = doc.NameTable.Get(prefix);
if (prefix == null)
return null;
XmlNode node = this;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
if (prefix.Length == 0)
{
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0)
{
if (Ref.Equal(attr.LocalName, doc.strXmlns))
{
return attr.Value; // found xmlns
}
}
}
}
else
{
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (Ref.Equal(attr.Prefix, doc.strXmlns))
{
if (Ref.Equal(attr.LocalName, prefix))
{
return attr.Value; // found xmlns:prefix
}
}
else if (Ref.Equal(attr.Prefix, prefix))
{
return attr.NamespaceURI; // found prefix:attr
}
}
}
}
if (Ref.Equal(node.Prefix, prefix))
{
return node.NamespaceURI;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
}
else
{
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strXml, prefix))
{ // xmlns:xml
return doc.strReservedXml;
}
else if (Ref.Equal(doc.strXmlns, prefix))
{ // xmlns:xmlns
return doc.strReservedXmlns;
}
}
return null;
}
// Looks up the closest xmlns declaration for the given namespace
// URI that is in scope for the current node and returns
// the prefix defined in that declaration.
public virtual string GetPrefixOfNamespace(string namespaceURI)
{
string prefix = GetPrefixOfNamespaceStrict(namespaceURI);
return prefix != null ? prefix : string.Empty;
}
internal string GetPrefixOfNamespaceStrict(string namespaceURI)
{
XmlDocument doc = Document;
if (doc != null)
{
namespaceURI = doc.NameTable.Add(namespaceURI);
XmlNode node = this;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0)
{
if (Ref.Equal(attr.LocalName, doc.strXmlns))
{
if (attr.Value == namespaceURI)
{
return string.Empty; // found xmlns="namespaceURI"
}
}
}
else if (Ref.Equal(attr.Prefix, doc.strXmlns))
{
if (attr.Value == namespaceURI)
{
return attr.LocalName; // found xmlns:prefix="namespaceURI"
}
}
else if (Ref.Equal(attr.NamespaceURI, namespaceURI))
{
return attr.Prefix; // found prefix:attr
// with prefix bound to namespaceURI
}
}
}
if (Ref.Equal(node.NamespaceURI, namespaceURI))
{
return node.Prefix;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
}
else
{
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strReservedXml, namespaceURI))
{ // xmlns:xml
return doc.strXml;
}
else if (Ref.Equal(doc.strReservedXmlns, namespaceURI))
{ // xmlns:xmlns
return doc.strXmlns;
}
}
return null;
}
// Retrieves the first child element with the specified name.
public virtual XmlElement this[string name]
{
get
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
{
if (n.NodeType == XmlNodeType.Element && n.Name == name)
return (XmlElement)n;
}
return null;
}
}
// Retrieves the first child element with the specified LocalName and
// NamespaceURI.
public virtual XmlElement this[string localname, string ns]
{
get
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
{
if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns)
return (XmlElement)n;
}
return null;
}
}
internal virtual void SetParent(XmlNode node)
{
if (node == null)
{
this.parentNode = OwnerDocument;
}
else
{
this.parentNode = node;
}
}
internal virtual void SetParentForLoad(XmlNode node)
{
this.parentNode = node;
}
internal static void SplitName(string name, out string prefix, out string localName)
{
int colonPos = name.IndexOf(':'); // ordinal compare
if (-1 == colonPos || 0 == colonPos || name.Length - 1 == colonPos)
{
prefix = string.Empty;
localName = name;
}
else
{
prefix = name.Substring(0, colonPos);
localName = name.Substring(colonPos + 1);
}
}
internal virtual XmlNode FindChild(XmlNodeType type)
{
for (XmlNode child = FirstChild; child != null; child = child.NextSibling)
{
if (child.NodeType == type)
{
return child;
}
}
return null;
}
internal virtual XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action)
{
XmlDocument doc = OwnerDocument;
if (doc != null)
{
if (!doc.IsLoading)
{
if (((newParent != null && newParent.IsReadOnly) || (oldParent != null && oldParent.IsReadOnly)))
throw new InvalidOperationException(ResXml.Xdom_Node_Modify_ReadOnly);
}
return doc.GetEventArgs(node, oldParent, newParent, oldValue, newValue, action);
}
return null;
}
internal virtual void BeforeEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
OwnerDocument.BeforeEvent(args);
}
internal virtual void AfterEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
OwnerDocument.AfterEvent(args);
}
internal virtual XmlSpace XmlSpace
{
get
{
XmlNode node = this;
XmlElement elem = null;
do
{
elem = node as XmlElement;
if (elem != null && elem.HasAttribute("xml:space"))
{
switch (XmlConvert.TrimString(elem.GetAttribute("xml:space")))
{
case "default":
return XmlSpace.Default;
case "preserve":
return XmlSpace.Preserve;
default:
//should we throw exception if value is otherwise?
break;
}
}
node = node.ParentNode;
}
while (node != null);
return XmlSpace.None;
}
}
internal virtual String XmlLang
{
get
{
XmlNode node = this;
XmlElement elem = null;
do
{
elem = node as XmlElement;
if (elem != null)
{
if (elem.HasAttribute("xml:lang"))
return elem.GetAttribute("xml:lang");
}
node = node.ParentNode;
} while (node != null);
return String.Empty;
}
}
internal virtual XPathNodeType XPNodeType
{
get
{
return (XPathNodeType)(-1);
}
}
internal virtual string XPLocalName
{
get
{
return string.Empty;
}
}
internal virtual string GetXPAttribute(string localName, string namespaceURI)
{
return String.Empty;
}
internal virtual bool IsText
{
get
{
return false;
}
}
public virtual XmlNode PreviousText
{
get
{
return null;
}
}
internal static void NestTextNodes(XmlNode prevNode, XmlNode nextNode)
{
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode;
}
internal static void UnnestTextNodes(XmlNode prevNode, XmlNode nextNode)
{
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode.ParentNode;
}
private object debuggerDisplayProxy { get { return new DebuggerDisplayXmlNodeProxy(this); } }
}
[DebuggerDisplay("{ToString()}")]
internal struct DebuggerDisplayXmlNodeProxy
{
private XmlNode _node;
public DebuggerDisplayXmlNodeProxy(XmlNode node)
{
_node = node;
}
public override string ToString()
{
XmlNodeType nodeType = _node.NodeType;
string result = nodeType.ToString();
switch (nodeType)
{
case XmlNodeType.Element:
case XmlNodeType.EntityReference:
result += ", Name=\"" + _node.Name + "\"";
break;
case XmlNodeType.Attribute:
case XmlNodeType.ProcessingInstruction:
result += ", Name=\"" + _node.Name + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value) + "\"";
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.XmlDeclaration:
result += ", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(_node.Value) + "\"";
break;
case XmlNodeType.DocumentType:
XmlDocumentType documentType = (XmlDocumentType)_node;
result += ", Name=\"" + documentType.Name + "\", SYSTEM=\"" + documentType.SystemId + "\", PUBLIC=\"" + documentType.PublicId + "\", Value=\"" + XmlConvert.EscapeValueForDebuggerDisplay(documentType.InternalSubset) + "\"";
break;
default:
break;
}
return result;
}
}
}
| |
// 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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.Schemas;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Progression;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal class AbstractGraphProvider : IGraphProvider
{
private readonly IGlyphService _glyphService;
private readonly IServiceProvider _serviceProvider;
private readonly GraphQueryManager _graphQueryManager;
private bool _initialized = false;
protected AbstractGraphProvider(
IGlyphService glyphService,
SVsServiceProvider serviceProvider,
Workspace workspace,
IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
_glyphService = glyphService;
_serviceProvider = serviceProvider;
var asyncListener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.GraphProvider);
_graphQueryManager = new GraphQueryManager(workspace, asyncListener);
}
private void EnsureInitialized()
{
if (_initialized)
{
return;
}
var iconService = (IIconService)_serviceProvider.GetService(typeof(IIconService));
IconHelper.Initialize(_glyphService, iconService);
_initialized = true;
}
internal static List<IGraphQuery> GetGraphQueries(IGraphContext context)
{
var graphQueries = new List<IGraphQuery>();
if (context.Direction == GraphContextDirection.Self && context.RequestedProperties.Contains(DgmlNodeProperties.ContainsChildren))
{
graphQueries.Add(new ContainsChildrenGraphQuery());
}
if (context.Direction == GraphContextDirection.Contains ||
(context.Direction == GraphContextDirection.Target && context.LinkCategories.Contains(CodeLinkCategories.Contains)))
{
graphQueries.Add(new ContainsGraphQuery());
}
if (context.LinkCategories.Contains(CodeLinkCategories.InheritsFrom))
{
if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new InheritsGraphQuery());
}
else if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new InheritedByGraphQuery());
}
}
if (context.LinkCategories.Contains(CodeLinkCategories.SourceReferences))
{
graphQueries.Add(new IsUsedByGraphQuery());
}
if (context.LinkCategories.Contains(CodeLinkCategories.Calls))
{
if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new CallsGraphQuery());
}
else if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new IsCalledByGraphQuery());
}
}
if (context.LinkCategories.Contains(CodeLinkCategories.Implements))
{
if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new ImplementsGraphQuery());
}
else if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new ImplementedByGraphQuery());
}
}
if (context.LinkCategories.Contains(RoslynGraphCategories.Overrides))
{
if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new OverridesGraphQuery());
}
else if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new OverriddenByGraphQuery());
}
}
if (context.Direction == GraphContextDirection.Custom)
{
var searchParameters = context.GetValue<ISolutionSearchParameters>(typeof(ISolutionSearchParameters).GUID.ToString());
if (searchParameters != null)
{
// WARNING: searchParameters.SearchQuery returns an IVsSearchQuery object, which
// is a COM type. Therefore, it's probably best to grab the values we want now
// rather than get surprised by COM marshalling later.
graphQueries.Add(new SearchGraphQuery(searchParameters.SearchQuery.SearchString));
}
}
return graphQueries;
}
public void BeginGetGraphData(IGraphContext context)
{
EnsureInitialized();
var graphQueries = GetGraphQueries(context);
if (graphQueries.Count > 0)
{
_graphQueryManager.AddQueries(context, graphQueries);
}
else
{
// It's an unknown query type, so we're done
context.OnCompleted();
}
}
public IEnumerable<GraphCommand> GetCommands(IEnumerable<GraphNode> nodes)
{
EnsureInitialized();
yield return new GraphCommand(
GraphCommandDefinition.Contains,
targetCategories: null,
linkCategories: new[] { GraphCommonSchema.Contains },
trackChanges: true);
// Only show 'Base Types' and 'Derived Types' on a class or interface.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Interface, TypeKind.Struct, TypeKind.Enum, TypeKind.Delegate)))
{
yield return new GraphCommand(
GraphCommandDefinition.BaseTypes,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.InheritsFrom },
trackChanges: true);
yield return new GraphCommand(
GraphCommandDefinition.DerivedTypes,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.InheritsFrom },
trackChanges: true);
}
// Only show 'Calls' on an applicable member in a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property, SymbolKind.Field)))
{
yield return new GraphCommand(
GraphCommandDefinition.Calls,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Calls },
trackChanges: true);
}
// Only show 'Is Called By' on an applicable member in a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct)))
{
yield return new GraphCommand(
GraphCommandDefinition.IsCalledBy,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Calls },
trackChanges: true);
}
// Show 'Is Used By'
yield return new GraphCommand(
GraphCommandDefinition.IsUsedBy,
targetCategories: new[] { CodeNodeCategories.SourceLocation },
linkCategories: new[] { CodeLinkCategories.SourceReferences },
trackChanges: true);
// Show 'Implements' on a class or struct, or an applicable member in a class or struct.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct)))
{
yield return new GraphCommand(
s_implementsCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
// Show 'Implements' on public, non-static members of a class or struct. Note: we should
// also show it on explicit interface impls in C#.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) &&
!GetModifiers(n).IsStatic))
{
if (nodes.Any(n => CheckAccessibility(n, Accessibility.Public) ||
HasExplicitInterfaces(n)))
{
yield return new GraphCommand(
s_implementsCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
}
// Show 'Implemented By' on an interface.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) &&
IsAnyTypeKind(n, TypeKind.Interface)))
{
yield return new GraphCommand(
s_implementedByCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
// Show 'Implemented By' on any member of an interface.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Interface)))
{
yield return new GraphCommand(
s_implementedByCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
// Show 'Overrides' on any applicable member of a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) &&
GetModifiers(n).IsOverride))
{
yield return new GraphCommand(
s_overridesCommandDefinition,
targetCategories: null,
linkCategories: new[] { RoslynGraphCategories.Overrides },
trackChanges: true);
}
// Show 'Overridden By' on any applicable member of a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) &&
IsOverridable(n)))
{
yield return new GraphCommand(
s_overriddenByCommandDefinition,
targetCategories: null,
linkCategories: new[] { RoslynGraphCategories.Overrides },
trackChanges: true);
}
}
private bool IsOverridable(GraphNode node)
{
var modifiers = GetModifiers(node);
return (modifiers.IsVirtual || modifiers.IsAbstract || modifiers.IsOverride) &&
!modifiers.IsSealed;
}
private DeclarationModifiers GetModifiers(GraphNode node)
{
return (DeclarationModifiers)node[RoslynGraphProperties.SymbolModifiers];
}
private bool CheckAccessibility(GraphNode node, Accessibility accessibility)
{
return node[RoslynGraphProperties.DeclaredAccessibility].Equals(accessibility);
}
private bool HasExplicitInterfaces(GraphNode node)
{
return ((IList<SymbolKey>)node[RoslynGraphProperties.ExplicitInterfaceImplementations]).Count > 0;
}
private bool IsAnySymbolKind(GraphNode node, params SymbolKind[] symbolKinds)
{
return symbolKinds.Any(k => k.Equals(node[RoslynGraphProperties.SymbolKind]));
}
private bool IsAnyTypeKind(GraphNode node, params TypeKind[] typeKinds)
{
return typeKinds.Any(k => node[RoslynGraphProperties.TypeKind].Equals(k));
}
private static readonly GraphCommandDefinition s_overridesCommandDefinition =
new GraphCommandDefinition("Overrides", ServicesVSResources.Overrides, GraphContextDirection.Target, 700);
private static readonly GraphCommandDefinition s_overriddenByCommandDefinition =
new GraphCommandDefinition("OverriddenBy", ServicesVSResources.OverriddenBy, GraphContextDirection.Source, 700);
private static readonly GraphCommandDefinition s_implementsCommandDefinition =
new GraphCommandDefinition("Implements", ServicesVSResources.Implements, GraphContextDirection.Target, 600);
private static readonly GraphCommandDefinition s_implementedByCommandDefinition =
new GraphCommandDefinition("ImplementedBy", ServicesVSResources.ImplementedBy, GraphContextDirection.Source, 600);
public T GetExtension<T>(GraphObject graphObject, T previous) where T : class
{
var graphNode = graphObject as GraphNode;
if (graphNode != null)
{
// If this is not a Roslyn node, bail out.
// TODO: The check here is to see if the SymbolId property exists on the node
// and if so, that's been created by us. However, eventually we'll want to extend
// this to other scenarios where C#\VB nodes that aren't created by us are passed in.
if (graphNode.GetValue<SymbolKey>(RoslynGraphProperties.SymbolId) == null)
{
return null;
}
if (typeof(T) == typeof(IGraphNavigateToItem))
{
return new GraphNavigatorExtension(PrimaryWorkspace.Workspace) as T;
}
if (typeof(T) == typeof(IGraphFormattedLabel))
{
return new GraphFormattedLabelExtension() as T;
}
}
return null;
}
public Graph Schema
{
get { return null; }
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using IronRuby.Builtins;
using IronRuby.Compiler;
using IronRuby.Runtime.Calls;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronRuby.Runtime.Conversions;
namespace IronRuby.Runtime {
[Flags]
public enum LoadFlags {
None = 0,
LoadOnce = 1,
LoadIsolated = 2,
AppendExtensions = 4,
/// <summary>
/// Returns a scope or assembly of already loaded targets.
/// </summary>
ResolveLoaded = 8,
AnyLanguage = 16,
Require = LoadOnce | AppendExtensions,
}
// TODO: thread safety
public sealed class Loader {
internal enum FileKind {
RubySourceFile,
NonRubySourceFile,
Assembly,
Type,
Unknown,
}
private RubyContext/*!*/ _context;
// $:
private readonly RubyArray/*!*/ _loadPaths;
// $"
private readonly RubyArray/*!*/ _loadedFiles;
// files that were required but their execution haven't completed yet:
private readonly Stack<string>/*!*/ _unfinishedFiles;
// lazy init
private SynchronizedDictionary<string, Scope> _loadedScripts;
// TODO: static
// maps full normalized path to compiled code:
private Dictionary<string, CompiledFile> _compiledFiles;
private readonly object/*!*/ _compiledFileMutex = new object();
private struct CompiledFile {
public readonly ScriptCode/*!*/ CompiledCode;
public CompiledFile(ScriptCode/*!*/ compiledCode) {
Assert.NotNull(compiledCode);
CompiledCode = compiledCode;
}
}
// counters:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
private int _cacheHitCount;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
private int _compiledFileCount;
/// <summary>
/// TODO: Thread safety: the user of this object is responsible for locking it.
/// </summary>
public RubyArray/*!*/ LoadPaths {
get { return _loadPaths; }
}
/// <summary>
/// TODO: Thread safety: the user of this object is responsible for locking it.
/// </summary>
public RubyArray/*!*/ LoadedFiles {
get { return _loadedFiles; }
}
/// <summary>
/// Contains all loaded foreign language scripts. Maps path to scope created for each loaded script.
/// A script is published here as soon as its scope is created just before it is executed.
/// </summary>
public IDictionary<string, Scope>/*!*/ LoadedScripts {
get {
if (_loadedScripts == null) {
Interlocked.CompareExchange(ref _loadedScripts,
new SynchronizedDictionary<string, Scope>(new Dictionary<string, Scope>(DomainManager.Platform.PathComparer)), null
);
}
return _loadedScripts;
}
}
private PlatformAdaptationLayer/*!*/ Platform {
get { return DomainManager.Platform; }
}
private ScriptDomainManager/*!*/ DomainManager {
get { return _context.DomainManager; }
}
internal Loader(RubyContext/*!*/ context) {
Assert.NotNull(context);
_context = context;
_toStrStorage = new ConversionStorage<MutableString>(context);
_loadPaths = MakeLoadPaths(context.RubyOptions);
_loadedFiles = new RubyArray();
_unfinishedFiles = new Stack<string>();
#if !SILVERLIGHT
if (!context.RubyOptions.NoAssemblyResolveHook) {
new AssemblyResolveHolder(this).HookAssemblyResolve();
}
#endif
}
private RubyArray/*!*/ MakeLoadPaths(RubyOptions/*!*/ options) {
var loadPaths = new RubyArray();
if (options.HasSearchPaths) {
foreach (string path in options.SearchPaths) {
loadPaths.Add(_context.EncodePath(path));
}
}
AddStandardLibraryPath(loadPaths, options.StandardLibraryPath, options.ApplicationBase);
// TODO: remove?
loadPaths.Add(MutableString.CreateAscii("."));
return loadPaths;
}
private void AddStandardLibraryPath(RubyArray/*!*/ loadPaths, string path, string applicationBaseDir) {
#if !SILVERLIGHT // no library paths on Silverlight
bool isFullPath;
if (path != null) {
try {
isFullPath = Platform.IsAbsolutePath(path);
} catch {
loadPaths.Add(_context.EncodePath(path));
return;
}
} else {
path = "../Lib";
isFullPath = false;
}
if (!isFullPath) {
try {
if (String.IsNullOrEmpty(applicationBaseDir)) {
applicationBaseDir = _context.Platform.GetEnvironmentVariable(RubyContext.BinDirEnvironmentVariable);
if (!Directory.Exists(applicationBaseDir)) {
applicationBaseDir = AppDomain.CurrentDomain.BaseDirectory;
}
}
} catch (SecurityException) {
applicationBaseDir = null;
}
try {
path = Platform.GetFullPath(RubyUtils.CombinePaths(applicationBaseDir, path));
} catch {
loadPaths.Add(_context.EncodePath(path));
return;
}
}
path = path.Replace('\\', '/');
loadPaths.Add(_context.EncodePath(RubyUtils.CombinePaths(path, "ironruby")));
loadPaths.Add(_context.EncodePath(RubyUtils.CombinePaths(path, "ruby/site_ruby/" + _context.StandardLibraryVersion)));
loadPaths.Add(_context.EncodePath(RubyUtils.CombinePaths(path, "ruby/" + _context.StandardLibraryVersion)));
#endif
}
private void AddAbsoluteLibraryPaths(RubyArray/*!*/ result, string applicationBaseDir, ICollection<string>/*!*/ paths) {
foreach (var path in paths) {
string fullPath;
if (applicationBaseDir != null) {
try {
fullPath = Platform.IsAbsolutePath(path) ? path : Platform.GetFullPath(Path.Combine(applicationBaseDir, path));
} catch (Exception) {
// error will be reported on first require:
fullPath = path;
}
} else {
fullPath = path;
}
result.Add(_context.EncodePath(fullPath.Replace('\\', '/')));
}
}
private Dictionary<string, CompiledFile>/*!*/ LoadCompiledCode() {
Debug.Assert(_context.RubyOptions.LoadFromDisk);
Dictionary<string, CompiledFile> result = new Dictionary<string, CompiledFile>();
Utils.Log("LOADING", "LOADER");
ScriptCode[] codes = SavableScriptCode.LoadFromAssembly(_context.DomainManager,
Assembly.Load(Path.GetFileName(_context.RubyOptions.MainFile))
);
for (int i = 0; i < codes.Length; i++) {
string path = codes[i].SourceUnit.Path;
string fullPath = Platform.GetFullPath(path);
result[fullPath] = new CompiledFile(codes[i]);
}
return result;
}
internal void SaveCompiledCode() {
string savePath = _context.RubyOptions.SavePath;
if (savePath != null) {
lock (_compiledFileMutex) {
var assemblyPath = Path.Combine(savePath, (Path.GetFileName(_context.RubyOptions.MainFile) ?? "snippets") + ".dll");
Utils.Log(String.Format("SAVING to {0}", Path.GetFullPath(assemblyPath)), "LOADER");
// TODO: allocate eagerly (as soon as config gets fixed)
if (_compiledFiles == null) {
_compiledFiles = new Dictionary<string, CompiledFile>();
}
SavableScriptCode[] codes = new SavableScriptCode[_compiledFiles.Count];
int i = 0;
foreach (CompiledFile file in _compiledFiles.Values) {
codes[i++] = (SavableScriptCode)file.CompiledCode;
}
SavableScriptCode.SaveToAssembly(assemblyPath, codes);
}
}
}
private bool TryGetCompiledFile(string/*!*/ fullPath, out CompiledFile compiledFile) {
if (!_context.RubyOptions.LoadFromDisk) {
compiledFile = default(CompiledFile);
return false;
}
lock (_compiledFileMutex) {
if (_compiledFiles == null) {
_compiledFiles = LoadCompiledCode();
}
return _compiledFiles.TryGetValue(fullPath, out compiledFile);
}
}
private void AddCompiledFile(string/*!*/ fullPath, ScriptCode/*!*/ compiledCode) {
if (_context.RubyOptions.SavePath != null) {
lock (_compiledFileMutex) {
// TODO: allocate eagerly (as soon as config gets fixed)
if (_compiledFiles == null) {
_compiledFiles = new Dictionary<string, CompiledFile>();
}
_compiledFiles[fullPath] = new CompiledFile(compiledCode);
}
}
}
public bool LoadFile(Scope globalScope, object self, MutableString/*!*/ path, LoadFlags flags) {
object loaded;
return LoadFile(globalScope, self, path, flags, out loaded);
}
/// <summary>
/// Returns <b>true</b> if a Ruby file is successfully loaded, <b>false</b> if it is already loaded.
/// </summary>
/// <param name="globalScope">
/// A scope against which the file should be executed or null to create a new scope.
/// </param>
/// <returns>True if the file was loaded/executed by this call.</returns>
public bool LoadFile(Scope globalScope, object self, MutableString/*!*/ path, LoadFlags flags, out object loaded) {
Assert.NotNull(path);
string assemblyName, typeName;
string strPath = path.ConvertToString();
if (TryParseAssemblyName(strPath, out typeName, out assemblyName)) {
if (AlreadyLoaded(strPath, (string)null, flags)) {
loaded = ((flags & LoadFlags.ResolveLoaded) != 0) ? GetAssembly(assemblyName, true, false) : null;
return false;
}
Assembly assembly = LoadAssembly(assemblyName, typeName, false, false);
if (assembly != null) {
FileLoaded(path.Clone(), flags);
loaded = assembly;
return true;
}
}
return LoadFromPath(globalScope, self, strPath, path.Encoding, flags, out loaded);
}
#region Assemblies
public Assembly LoadAssembly(string/*!*/ assemblyName, string typeName, bool throwOnError, bool tryPartialName) {
Assembly assembly = GetAssembly(assemblyName, throwOnError, tryPartialName);
return (assembly != null && LoadAssembly(assembly, typeName, throwOnError)) ? assembly : null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")]
private Assembly GetAssembly(string/*!*/ assemblyName, bool throwOnError, bool tryPartialName) {
#if SILVERLIGHT
tryPartialName = false;
#endif
try {
return Platform.LoadAssembly(assemblyName);
} catch (Exception e) {
if (!tryPartialName || !(e is FileNotFoundException)) {
if (throwOnError) {
throw RubyExceptions.CreateLoadError(e);
} else {
return null;
}
}
}
#if SILVERLIGHT
throw Assert.Unreachable;
#else
#pragma warning disable 618,612 // csc, gmcs
Assembly assembly;
try {
assembly = Assembly.LoadWithPartialName(assemblyName);
} catch (Exception e) {
if (throwOnError) {
throw RubyExceptions.CreateLoadError(e);
} else {
return null;
}
}
if (assembly == null && throwOnError) {
throw RubyExceptions.CreateLoadError(String.Format("Assembly '{0}' not found", assemblyName));
}
#pragma warning restore 618,612
return assembly;
#endif
}
private bool LoadAssembly(Assembly/*!*/ assembly, string typeName, bool throwOnError) {
Utils.Log(String.Format("Loading assembly '{0}' and type '{1}'", assembly, typeName), "LOADER");
Type initializerType;
if (typeName != null) {
// load Ruby library:
try {
initializerType = assembly.GetType(typeName, true);
} catch (Exception e) {
if (throwOnError) {
throw new LoadError(e.Message, e);
}
return false;
}
LoadLibrary(initializerType, false);
} else {
// load namespaces:
try {
DomainManager.LoadAssembly(assembly);
} catch (Exception e) {
if (throwOnError) {
throw RubyExceptions.CreateLoadError(e);
}
return false;
}
}
return true;
}
private static Regex _AssemblyNameRegex = new Regex(@"
\s*((?<type>[\w.+]+)\s*,)?\s* # type name
(?<assembly>
[^,=]+\s* # assembly name
(,\s*[\w]+\s*=\s*[^,]+\s*)+ # properties
)",
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline
);
internal static bool TryParseAssemblyName(string/*!*/ path, out string typeName, out string assemblyName) {
Match match = _AssemblyNameRegex.Match(path);
if (match.Success) {
Group typeGroup = match.Groups["type"];
Group assemblyGroup = match.Groups["assembly"];
Debug.Assert(assemblyGroup.Success);
typeName = typeGroup.Success ? typeGroup.Value : null;
assemblyName = assemblyGroup.Value;
return true;
}
if (path.Trim() == "mscorlib") {
typeName = null;
assemblyName = path;
return true;
}
typeName = null;
assemblyName = null;
return false;
}
#if !SILVERLIGHT
private sealed class AssemblyResolveHolder {
private readonly WeakReference _loader;
[ThreadStatic]
private static HashSet<string> _assembliesBeingResolved;
public AssemblyResolveHolder(Loader/*!*/ loader) {
_loader = new WeakReference(loader);
}
internal void HookAssemblyResolve() {
try {
HookAssemblyResolveInternal();
} catch (System.Security.SecurityException) {
// We may not have SecurityPermissionFlag.ControlAppDomain.
}
}
private void HookAssemblyResolveInternal() {
AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveEvent;
}
private Assembly AssemblyResolveEvent(object sender, ResolveEventArgs args) {
Loader loader = (Loader)_loader.Target;
if (loader != null) {
string assemblyName = args.Name;
Utils.Log(String.Format("assembly resolve event: {0}", assemblyName), "RESOLVE_ASSEMBLY");
if (_assembliesBeingResolved == null) {
_assembliesBeingResolved = new HashSet<string>();
} else if (_assembliesBeingResolved.Contains(assemblyName)) {
Utils.Log(String.Format("recursive assembly resolution: {0}", assemblyName), "RESOLVE_ASSEMBLY");
return null;
}
_assembliesBeingResolved.Add(assemblyName);
try {
return loader.ResolveAssembly(assemblyName);
} catch (Exception e) {
// the exception might not be reported by the type loader, so at least report a warning:
loader._context.ReportWarning(
String.Format("An exception was risen while resolving an assembly `{0}': {1}", assemblyName, e.Message)
);
throw;
} finally {
_assembliesBeingResolved.Remove(assemblyName);
}
} else {
AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolveEvent;
return null;
}
}
}
internal Assembly ResolveAssembly(string/*!*/ fullName) {
Utils.Log(String.Format("Resolving assembly: '{0}'", fullName), "RESOLVE_ASSEMBLY");
AssemblyName assemblyName = new AssemblyName(fullName);
ResolvedFile file = FindFile(assemblyName.Name, true, ArrayUtils.EmptyStrings).FirstOrDefault();
if (file == null || file.SourceUnit != null) {
return null;
}
Utils.Log(String.Format("Assembly '{0}' resolved: found in '{1}'", fullName, file.Path), "RESOLVE_ASSEMBLY");
try {
Assembly assembly = Platform.LoadAssemblyFromPath(file.Path);
if (AssemblyName.ReferenceMatchesDefinition(assemblyName, assembly.GetName())) {
Utils.Log(String.Format("Assembly '{0}' loaded for '{1}'", assembly.GetName(), fullName), "RESOLVE_ASSEMBLY");
DomainManager.LoadAssembly(assembly);
return assembly;
}
} catch (Exception e) {
throw RubyExceptions.CreateLoadError(e);
}
return null;
}
#endif
#endregion
private class ResolvedFile {
public readonly SourceUnit SourceUnit;
public readonly string/*!*/ Path;
public readonly string AppendedExtension;
public ResolvedFile(SourceUnit/*!*/ sourceUnit, string/*!*/ fullPath, string appendedExtension) {
Assert.NotNull(sourceUnit, fullPath);
SourceUnit = sourceUnit;
Path = fullPath;
AppendedExtension = appendedExtension;
}
public ResolvedFile(string/*!*/ fullLibraryPath, string appendedExtension) {
Assert.NotNull(fullLibraryPath);
Path = fullLibraryPath;
AppendedExtension = appendedExtension;
}
}
private bool LoadFromPath(Scope globalScope, object self, string/*!*/ path, RubyEncoding/*!*/ pathEncoding, LoadFlags flags, out object loaded) {
Assert.NotNull(pathEncoding, path);
string[] sourceFileExtensions;
if ((flags & LoadFlags.AnyLanguage) != 0) {
sourceFileExtensions = DomainManager.Configuration.GetFileExtensions();
} else {
sourceFileExtensions = DomainManager.Configuration.GetFileExtensions(_context);
}
IList<ResolvedFile> files = FindFile(path, (flags & LoadFlags.AppendExtensions) != 0, sourceFileExtensions);
if (files.Count == 0) {
// MRI: doesn't throw an exception if the path is in $" (performs resolution first though):
if (AlreadyLoaded(path, null, flags, sourceFileExtensions)) {
loaded = null;
return false;
}
throw RubyExceptions.CreateLoadError(String.Format("no such file to load -- {0}", path));
}
ResolvedFile file = files.First();
string pathWithExtension = path;
if (file.AppendedExtension != null) {
pathWithExtension += file.AppendedExtension;
}
if (AlreadyLoaded(path, files, flags) || _unfinishedFiles.Contains(file.Path)) {
if ((flags & LoadFlags.ResolveLoaded) != 0) {
if (file.SourceUnit != null) {
Scope loadedScope;
if (!LoadedScripts.TryGetValue(file.Path, out loadedScope)) {
throw RubyExceptions.CreateLoadError(String.Format("no such file to load -- {0}", file.Path));
}
loaded = loadedScope;
} else {
loaded = Platform.LoadAssemblyFromPath(file.Path);
}
} else {
loaded = null;
}
return false;
}
try {
// save path as is, no canonicalization nor combination with an extension or directory:
_unfinishedFiles.Push(file.Path);
if (file.SourceUnit != null) {
AddScriptLines(file.SourceUnit);
ScriptCode compiledCode;
if (file.SourceUnit.LanguageContext == _context) {
compiledCode = CompileRubySource(file.SourceUnit, flags);
} else {
compiledCode = file.SourceUnit.Compile();
}
loaded = Execute(globalScope, compiledCode);
} else {
Debug.Assert(file.Path != null);
try {
Assembly assembly = Platform.LoadAssemblyFromPath(file.Path);
DomainManager.LoadAssembly(assembly);
loaded = assembly;
} catch (Exception e) {
throw RubyExceptions.CreateLoadError(e);
}
}
FileLoaded(MutableString.Create(file.Path, pathEncoding), flags);
} finally {
_unfinishedFiles.Pop();
}
return true;
}
private ScriptCode/*!*/ CompileRubySource(SourceUnit/*!*/ sourceUnit, LoadFlags flags) {
Assert.NotNull(sourceUnit);
// TODO: check file timestamp
string fullPath = Platform.GetFullPath(sourceUnit.Path);
CompiledFile compiledFile;
if (TryGetCompiledFile(fullPath, out compiledFile)) {
Utils.Log(String.Format("{0}: {1}", ++_cacheHitCount, sourceUnit.Path), "LOAD_CACHED");
return compiledFile.CompiledCode;
} else {
Utils.Log(String.Format("{0}: {1}", ++_compiledFileCount, sourceUnit.Path), "LOAD_COMPILED");
RubyCompilerOptions options = new RubyCompilerOptions(_context.RubyOptions) {
FactoryKind = (flags & LoadFlags.LoadIsolated) != 0 ? TopScopeFactoryKind.WrappedFile : TopScopeFactoryKind.File
};
ScriptCode compiledCode = sourceUnit.Compile(options, _context.RuntimeErrorSink);
AddCompiledFile(fullPath, compiledCode);
return compiledCode;
}
}
internal Scope Execute(Scope globalScope, ScriptCode/*!*/ code) {
if (globalScope == null || code.LanguageContext != _context) {
if (globalScope == null) {
globalScope = code.CreateScope();
}
if (code.SourceUnit.Path != null) {
LoadedScripts[Platform.GetFullPath(code.SourceUnit.Path)] = globalScope;
}
code.Run(globalScope);
return globalScope;
} else {
code.Run(globalScope);
return null;
}
}
/// <summary>
/// Searches file in load directories and then appends extensions.
/// </summary>
private IList<ResolvedFile> FindFile(string/*!*/ path, bool appendExtensions, string[] sourceFileExtensions) {
Assert.NotNull(path);
bool isAbsolutePath;
#if SILVERLIGHT
{
#else
if (path.StartsWith("~/", StringComparison.Ordinal) || path.StartsWith("~\\", StringComparison.Ordinal)) {
path = RubyUtils.ExpandPath(_context.Platform, path);
isAbsolutePath = true;
} else {
#endif
try {
isAbsolutePath = Platform.IsAbsolutePath(path);
} catch (ArgumentException e) {
throw RubyExceptions.CreateLoadError(e);
}
}
string extension = RubyUtils.GetExtension(path);
// Absolute path -> load paths not consulted.
if (isAbsolutePath) {
var file = ResolveFile(path, extension, appendExtensions, sourceFileExtensions);
return file != null ? new[] { file } : new ResolvedFile[0];
}
string[] loadPaths = GetLoadPathStrings();
if (loadPaths.Length == 0) {
return new ResolvedFile[0];
}
// If load paths are non-empty and the path starts with .\ or ..\ then MRI also ignores the load paths.
if (path.StartsWith("./", StringComparison.Ordinal) ||
path.StartsWith("../", StringComparison.Ordinal) ||
path.StartsWith(".\\", StringComparison.Ordinal) ||
path.StartsWith("..\\", StringComparison.Ordinal)) {
var file = ResolveFile(path, extension, appendExtensions, sourceFileExtensions);
return file != null ? new[] { file } : new ResolvedFile[0];
}
var result = new List<ResolvedFile>();
foreach (var dir in loadPaths) {
ResolvedFile file = ResolveFile(RubyUtils.CombinePaths(dir, path), extension, appendExtensions, sourceFileExtensions);
if (file != null) {
result.Add(file);
//RHO
break;
//RHO
}
}
return result;
}
internal string[]/*!*/ GetLoadPathStrings() {
var loadPaths = GetLoadPaths();
var result = new string[loadPaths.Length];
var toPath = _toStrStorage.GetSite(CompositeConversionAction.Make(_context, CompositeConversion.ToPathToStr));
for (int i = 0; i < loadPaths.Length; i++) {
if (loadPaths[i] == null) {
throw RubyExceptions.CreateTypeConversionError("nil", "String");
}
result[i] = Protocols.CastToPath(toPath, loadPaths[i]).ConvertToString();
}
return result;
}
/// <summary>
/// Appends extensions if applicable.
/// </summary>
private ResolvedFile ResolveFile(string/*!*/ path, string/*!*/ extension, bool appendExtensions, string[]/*!*/ knownExtensions) {
Debug.Assert(RubyUtils.GetExtension(path) == extension);
string expandedPath = RubyUtils.ExpandPath(_context.Platform, path);
// MRI doesn't load file w/o .rb extension:
if (IsKnownExtension(extension, knownExtensions)) {
return GetSourceUnit(path, expandedPath, extension, false);
}
if (_LibraryExtensions.IndexOf(extension, DlrConfiguration.FileExtensionComparer) != -1) {
if (Platform.FileExists(expandedPath)) {
return new ResolvedFile(expandedPath, null);
}
} else if (!appendExtensions) {
return GetSourceUnit(path, expandedPath, extension, false);
}
if (appendExtensions) {
List<string> matchingExtensions = GetExtensionsOfExistingFiles(expandedPath, knownExtensions);
if (matchingExtensions.Count == 1) {
return GetSourceUnit(path + matchingExtensions[0], expandedPath + matchingExtensions[0], matchingExtensions[0], true);
} else if (matchingExtensions.Count > 1) {
Exception e = new AmbiguousFileNameException(expandedPath + matchingExtensions[0], expandedPath + matchingExtensions[1]);
throw RubyExceptions.CreateLoadError(e);
}
foreach (string libExtension in _LibraryExtensions) {
if (Platform.FileExists(expandedPath + libExtension)) {
return new ResolvedFile(expandedPath + libExtension, libExtension);
}
}
}
return null;
}
private static readonly string[] _LibraryExtensions = new string[] { ".dll", ".so", ".exe" };
private static bool IsKnownExtension(string/*!*/ extension, string[]/*!*/ knownExtensions) {
return extension.Length > 0 && knownExtensions.IndexOf(extension, DlrConfiguration.FileExtensionComparer) >= 0;
}
private ResolvedFile GetSourceUnit(string/*!*/ path, string/*!*/ fullPath, string/*!*/ extension, bool extensionAppended) {
Assert.NotNull(path, fullPath, extension);
LanguageContext language;
if (extension.Length == 0 || !DomainManager.TryGetLanguageByFileExtension(extension, out language)) {
// Ruby by default:
language = _context;
}
if (!DomainManager.Platform.FileExists(fullPath)) {
return null;
}
var sourceUnit = language.CreateFileUnit(path, RubyEncoding.Ascii.Encoding, SourceCodeKind.File);
return new ResolvedFile(sourceUnit, fullPath, extensionAppended ? extension : null);
}
private List<string>/*!*/ GetExtensionsOfExistingFiles(string/*!*/ path, IEnumerable<string>/*!*/ extensions) {
// all extensions that could be appended to the path to get an existing file:
List<string> result = new List<string>();
foreach (string extension in extensions) {
Debug.Assert(extension != null && extension.StartsWith("."));
string fullPath = path + extension;
if (Platform.FileExists(fullPath)) {
result.Add(extension);
//RHO
break;
//RHO
}
}
return result;
}
#region Global Variables
private readonly ConversionStorage<MutableString>/*!*/ _toStrStorage;
internal object[]/*!*/ GetLoadPaths() {
lock (_loadedFiles) {
return _loadPaths.ToArray();
}
}
public void SetLoadPaths(IEnumerable<string/*!*/>/*!*/ paths) {
ContractUtils.RequiresNotNullItems(paths, "paths");
lock (_loadPaths) {
_loadPaths.Clear();
foreach (string path in paths) {
_loadPaths.Add(_context.EncodePath(path));
}
}
}
internal void AddLoadPaths(IEnumerable<string/*!*/>/*!*/ paths) {
Assert.NotNullItems(paths);
lock (_loadPaths) {
foreach (string path in paths) {
_loadPaths.Add(_context.EncodePath(path));
}
}
}
internal void InsertLoadPaths(IEnumerable<string/*!*/>/*!*/ paths, int index) {
Assert.NotNullItems(paths);
lock (_loadPaths) {
foreach (string path in paths) {
_loadPaths.Insert(0, _context.EncodePath(path));
}
}
}
internal void InsertLoadPaths(IEnumerable<string/*!*/>/*!*/ paths) {
InsertLoadPaths(paths, 0);
}
private void AddLoadedFile(MutableString/*!*/ path) {
lock (_loadedFiles) {
_loadedFiles.Add(path);
}
}
private void FileLoaded(MutableString/*!*/ path, LoadFlags flags) {
if ((flags & LoadFlags.LoadOnce) != 0) {
AddLoadedFile(path);
}
}
/// <summary>
/// If the SCRIPT_LINES__ constant is set, we need to publish the file being loaded,
/// along with the contents of the file
/// </summary>
private void AddScriptLines(SourceUnit file) {
ConstantStorage storage;
if (!_context.ObjectClass.TryResolveConstant(null, "SCRIPT_LINES__", out storage)) {
return;
}
IDictionary scriptLines = storage.Value as IDictionary;
if (scriptLines == null) {
return;
}
lock (scriptLines) {
// Read in the contents of the file
RubyArray lines = new RubyArray();
SourceCodeReader reader = file.GetReader();
RubyEncoding encoding = RubyEncoding.GetRubyEncoding(reader.Encoding);
using (reader) {
reader.SeekLine(1);
while (true) {
string lineStr = reader.ReadLine();
if (lineStr == null) {
break;
}
MutableString line = MutableString.CreateMutable(lineStr.Length + 1, encoding);
line.Append(lineStr).Append('\n');
lines.Add(line);
}
}
// Publish the contents of the file, keyed by the file name
MutableString path = MutableString.Create(file.Document.FileName, _context.GetPathEncoding());
scriptLines[path] = lines;
}
}
internal object[]/*!*/ GetLoadedFiles() {
lock (_loadedFiles) {
return _loadedFiles.ToArray();
}
}
private bool AlreadyLoaded(string/*!*/ path, string fullPath, LoadFlags flags) {
return AlreadyLoaded(path, fullPath, flags, ArrayUtils.EmptyStrings);
}
private bool AlreadyLoaded(string/*!*/ path, string fullPath, LoadFlags flags, string[]/*!*/ sourceFileExtensions) {
Debug.Assert(fullPath == null || RubyUtils.GetExtension(path) == RubyUtils.GetExtension(fullPath));
return (flags & LoadFlags.LoadOnce) != 0 && AnyFileLoaded(GetPathsToTestLoaded(path, fullPath, flags, sourceFileExtensions));
}
private IEnumerable<MutableString>/*!*/ GetPathsToTestLoaded(string/*!*/ path, string fullPath, LoadFlags flags, string[]/*!*/ sourceFileExtensions) {
List<MutableString> paths = new List<MutableString>();
paths.Add(_context.EncodePath(path));
if (fullPath != null) {
paths.Add(_context.EncodePath(path));
}
if ((flags & LoadFlags.AppendExtensions) != 0 && RubyUtils.GetExtension(path).Length == 0) {
foreach (var extension in sourceFileExtensions) {
paths.Add(_context.EncodePath(path + extension));
}
foreach (var extension in _LibraryExtensions) {
paths.Add(_context.EncodePath(path + extension));
}
}
return paths;
}
/// <summary>
/// Return true if any of the files has alraedy been loaded.
/// </summary>
private bool AlreadyLoaded(string/*!*/ path, IEnumerable<ResolvedFile>/*!*/ files, LoadFlags flags) {
return (flags & LoadFlags.LoadOnce) != 0 && AnyFileLoaded(
new[] { _context.EncodePath(path) }.Concat(files.Select((file) => _context.EncodePath(file.Path)))
);
}
private bool AnyFileLoaded(IEnumerable<MutableString>/*!*/ paths) {
var toPath = _toStrStorage.GetSite(CompositeConversionAction.Make(_context, CompositeConversion.ToPathToStr));
foreach (object file in GetLoadedFiles()) {
if (file == null) {
throw RubyExceptions.CreateTypeConversionError("nil", "String");
}
// use case sensitive comparison
MutableString loadedPath = Protocols.CastToPath(toPath, file);
if (paths.Any((path) => loadedPath.Equals(path))) {
return true;
}
}
return false;
}
#endregion
#region IronRuby Libraries
/// <exception cref="LoadError"></exception>
internal void LoadBuiltins() {
Type initializerType;
try {
Assembly assembly = _context.DomainManager.Platform.LoadAssembly(GetIronRubyAssemblyLongName("IronRuby.Libraries"));
initializerType = assembly.GetType(LibraryInitializer.GetBuiltinsFullTypeName());
} catch (Exception e) {
throw RubyExceptions.CreateLoadError(e);
}
LoadLibrary(initializerType, true);
}
public static string/*!*/ GetIronRubyAssemblyLongName(string/*!*/ baseName) {
ContractUtils.RequiresNotNull(baseName, "baseName");
string fullName = typeof(RubyContext).Assembly.FullName;
int firstComma = fullName.IndexOf(',');
return firstComma > 0 ? baseName + fullName.Substring(firstComma) : baseName;
}
private readonly HashSet<Type> _loadedTypes = new HashSet<Type>();
/// <exception cref="LoadError"></exception>
private void LoadLibrary(Type/*!*/ initializerType, bool builtin) {
lock (_loadedTypes) {
if (_loadedTypes.Contains(initializerType)) {
return;
}
}
LibraryInitializer initializer;
try {
initializer = Activator.CreateInstance(initializerType) as LibraryInitializer;
} catch (TargetInvocationException e) {
throw RubyExceptions.CreateLoadError(e.InnerException);
} catch (Exception e) {
throw RubyExceptions.CreateLoadError(e);
}
if (initializer == null) {
throw RubyExceptions.CreateLoadError(String.Format("Specified type {0} is not a subclass of {1}",
initializerType.FullName,
typeof(LibraryInitializer).FullName)
);
}
// Propagate exceptions from initializers (do not wrap them to LoadError).
// E.g. TypeError (can't modify frozen module) can be thrown.
initializer.LoadModules(_context, builtin);
lock (_loadedTypes) {
_loadedTypes.Add(initializerType);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class AverageTests
{
// struct used to test selector function is called
public struct Data_int
{
public string name;
public int num;
}
// struct used to test selector function is called
public struct Data_Nint
{
public string name;
public int? num;
}
// struct used to test selector function is called
public struct Data_long
{
public string name;
public long num;
}
// struct used to test selector function is called
public struct Data_Nlong
{
public string name;
public long? num;
}
// struct used to test selector function is called
public struct Data_double
{
public string name;
public double num;
}
// struct used to test selector function is called
public struct Data_Ndouble
{
public string name;
public double? num;
}
// struct used to test selector function is called
public struct Data_decimal
{
public string name;
public decimal num;
}
// struct used to test selector function is called
public struct Data_Ndecimal
{
public string name;
public decimal? num;
}
// struct used to test selector function is called
public struct Data_float
{
public string name;
public float num;
}
// struct used to test selector function is called
public struct Data_Nfloat
{
public string name;
public float? num;
}
public class Average011
{
private static int Average001()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst1 = q.Average();
var rst2 = q.Average();
return ((rst1 == rst2) ? 0 : 1);
}
private static int Average002()
{
var q = from x in new long?[] { Int32.MaxValue, 0, 255, 127, 128, 1, 33, 99, null, Int32.MinValue }
select x;
var rst1 = q.Average();
var rst2 = q.Average();
return ((rst1 == rst2) ? 0 : 1);
}
public static int Main()
{
int ret = RunTest(Average001) + RunTest(Average002);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average10a
{
// Type: float?, source is empty
public static int Test10a()
{
float?[] source = { };
float? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test10a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average10b
{
// Type: float?, source has only one element
public static int Test10b()
{
float?[] source = { float.MinValue };
float? expected = float.MinValue;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test10b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average10c
{
// Type: float?, source has all equal values and average is zero
public static int Test10c()
{
float?[] source = { 0f, 0f, 0f, 0f, 0f };
float? expected = 0f;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test10c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average10d
{
// Type: float?, source has different values
public static int Test10d()
{
float?[] source = { 5.5f, 0, null, null, null, 15.5f, 40.5f, null, null, -23.5f };
float? expected = 7.6f;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test10d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average10e
{
// Type: float?, source has 1 non-null value
public static int Test10e()
{
float?[] source = { null, null, null, null, 45f };
float? expected = 45f;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test10e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average10f
{
// Type: float?, source has all null values
public static int Test10f()
{
float?[] source = { null, null, null, null, null };
float? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test10f();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average10g
{
// Type: float?, selector function is called
public static int Test10g()
{
Data_Nfloat[] source = new Data_Nfloat[]{ new Data_Nfloat{name="Tim", num=5.5f},
new Data_Nfloat{name="John", num=15.5f},
new Data_Nfloat{name="Bob", num=null}
};
float? expected = 10.5f;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test10g();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average1a
{
// Type: int, source is empty
public static int Test1a()
{
int[] source = { };
try
{
var actual = source.Average();
return 1;
}
catch (InvalidOperationException)
{
return 0;
}
}
public static int Main()
{
return Test1a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average1b
{
// Type: int, source has only one element
public static int Test1b()
{
int[] source = { 5 };
double expected = 5;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average1c
{
// Type: int, source has all equal values and average is zero
public static int Test1c()
{
int[] source = { 0, 0, 0, 0, 0 };
double expected = 0;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average1d
{
// Type: int, source has different values
public static int Test1d()
{
int[] source = { 5, -10, 15, 40, 28 };
double expected = 15.6;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average1e
{
// Type: int, selector function is called
public static int Test1e()
{
Data_int[] source = new Data_int[]{ new Data_int{name="Tim", num=10},
new Data_int{name="John", num=-10},
new Data_int{name="Bob", num=15}
};
double expected = 5;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average2a
{
// Type: int?, source is empty
public static int Test2a()
{
int?[] source = { };
double? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average2b
{
// Type: int?, source has only one element
public static int Test2b()
{
int?[] source = { -5 };
double? expected = -5;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average2c
{
// Type: int?, source has all equal values and average is zero
public static int Test2c()
{
int?[] source = { 0, 0, 0, 0, 0 };
double? expected = 0;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average2d
{
// Type: int?, source has different values
public static int Test2d()
{
int?[] source = { 5, -10, null, null, null, 15, 40, 28, null, null };
double? expected = 15.6;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average2e
{
// Type: int?, source has 1 non-null value
public static int Test2e()
{
int?[] source = { null, null, null, null, 50 };
double? expected = 50;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average2f
{
// Type: int?, source has all null values
public static int Test2f()
{
int?[] source = { null, null, null, null, null };
double? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2f();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average2g
{
// Type: int?, selector function is called
public static int Test2g()
{
Data_Nint[] source = new Data_Nint[]{ new Data_Nint{name="Tim", num=10},
new Data_Nint{name="John", num=null},
new Data_Nint{name="Bob", num=10}
};
double? expected = 10;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2g();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average3a
{
// Type: long, source is empty
public static int Test3a()
{
long[] source = { };
try
{
var actual = source.Average();
return 1;
}
catch (InvalidOperationException)
{
return 0;
}
}
public static int Main()
{
return Test3a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average3b
{
// Type: long, source has only one element
public static int Test3b()
{
long[] source = { Int64.MaxValue };
double expected = Int64.MaxValue;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test3b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average3c
{
// Type: long, source has all equal values and average is zero
public static int Test3c()
{
long[] source = { 0, 0, 0, 0, 0 };
double expected = 0;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test3c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average3d
{
// Type: long, source has different values
public static int Test3d()
{
long[] source = { 5, -10, 15, 40, 28 };
double expected = 15.6;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test3d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average3e
{
// Type: long, selector function is called
public static int Test3e()
{
Data_long[] source = new Data_long[]{ new Data_long{name="Tim", num=40L},
new Data_long{name="John", num=50L},
new Data_long{name="Bob", num=60L}
};
double expected = 50;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test3e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average3f
{
[Fact]
// Type: long, OverflowException is thrown by param sum
public void Test()
{
long[] source = { Int64.MaxValue, Int64.MaxValue };
Assert.Throws<OverflowException>(() => source.Average());
}
}
public class Average4a
{
// Type: long?, source is empty
public static int Test4a()
{
long?[] source = { };
double? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test4a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average4b
{
// Type: long?, source has only one element
public static int Test4b()
{
long?[] source = { Int64.MinValue };
double? expected = Int64.MinValue;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test4b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average4c
{
// Type: long?, source has all equal values and average is zero
public static int Test4c()
{
long?[] source = { 0, 0, 0, 0, 0 };
double? expected = 0;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test4c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average4d
{
// Type: long?, source has different values
public static int Test4d()
{
long?[] source = { 5, -10, null, null, null, 15, 40, 28, null, null };
double? expected = 15.6;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test4d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average4e
{
// Type: long?, source has 1 non-null value
public static int Test4e()
{
long?[] source = { null, null, null, null, 50 };
double? expected = 50;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test4e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average4f
{
// Type: long?, source has all null values
public static int Test4f()
{
long?[] source = { null, null, null, null, null };
double? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test4f();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average4g
{
// Type: long?, selector function is called
public static int Test4g()
{
Data_Nlong[] source = new Data_Nlong[]{ new Data_Nlong{name="Tim", num=40L},
new Data_Nlong{name="John", num=null},
new Data_Nlong{name="Bob", num=30L}
};
double? expected = 35;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test4g();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average5a
{
// Type: double, source is empty
public static int Test5a()
{
double[] source = { };
try
{
var actual = source.Average();
return 1;
}
catch (InvalidOperationException)
{
return 0;
}
}
public static int Main()
{
return Test5a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average5b
{
// Type: double, source has only one element
public static int Test5b()
{
double[] source = { Double.MaxValue };
double expected = Double.MaxValue;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test5b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average5c
{
// Type: double, source has all equal values and average is zero
public static int Test5c()
{
double[] source = { 0.0, 0.0, 0.0, 0.0, 0.0 };
double expected = 0;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test5c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average5d
{
// Type: double, source has different values
public static int Test5d()
{
double[] source = { 5.5, -10, 15.5, 40.5, 28.5 };
double expected = 16;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test5d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average5e
{
// Type: double, source has NaN
public static int Test5e()
{
double[] source = { 5.58, Double.NaN, 30, 4.55, 19.38 };
double expected = Double.NaN;
var actual = source.Average();
return ((expected.Equals(actual)) ? 0 : 1);
}
public static int Main()
{
return Test5e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average5f
{
// Type: double, selector function is called
public static int Test5f()
{
Data_double[] source = new Data_double[]{ new Data_double{name="Tim", num=5.5},
new Data_double{name="John", num=15.5},
new Data_double{name="Bob", num=3.0}
};
double expected = 8.0;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test5f();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average6a
{
// Type: double?, source is empty
public static int Test6a()
{
double?[] source = { };
double? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test6a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average6b
{
// Type: double?, source has only one element
public static int Test6b()
{
double?[] source = { Double.MinValue };
double? expected = Double.MinValue;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test6b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average6c
{
// Type: double?, source has all equal values and average is zero
public static int Test6c()
{
double?[] source = { 0, 0, 0, 0, 0 };
double? expected = 0;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test6c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average6d
{
// Type: double?, source has different values
public static int Test6d()
{
double?[] source = { 5.5, 0, null, null, null, 15.5, 40.5, null, null, -23.5 };
double? expected = 7.6;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test6d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average6e
{
// Type: double?, source has 1 non-null value
public static int Test6e()
{
double?[] source = { null, null, null, null, 45 };
double? expected = 45;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test6e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average6f
{
// Type: double?, source has all null values
public static int Test6f()
{
double?[] source = { null, null, null, null, null };
double? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test6f();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average6g
{
// Type: double?, source has all NaN value
public static int Test6g()
{
double?[] source = { -23.5, 0, Double.NaN, 54.3, 0.56 };
double? expected = Double.NaN;
var actual = source.Average();
return ((expected.Equals(actual)) ? 0 : 1);
}
public static int Main()
{
return Test6g();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average6h
{
// Type: double?, selector function is called
public static int Test6h()
{
Data_Ndouble[] source = new Data_Ndouble[]{ new Data_Ndouble{name="Tim", num=5.5},
new Data_Ndouble{name="John", num=15.5},
new Data_Ndouble{name="Bob", num=null}
};
double? expected = 10.5;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test6h();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average7a
{
// Type: decimal, source is empty
public static int Test7a()
{
decimal[] source = { };
try
{
var actual = source.Average();
return 1;
}
catch (InvalidOperationException)
{
return 0;
}
}
public static int Main()
{
return Test7a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average7b
{
// Type: decimal, source has only one element
public static int Test7b()
{
decimal[] source = { Decimal.MaxValue };
decimal expected = Decimal.MaxValue;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test7b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average7c
{
// Type: decimal, source has all equal values and average is zero
public static int Test7c()
{
decimal[] source = { 0.0m, 0.0m, 0.0m, 0.0m, 0.0m };
decimal expected = 0m;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test7c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average7d
{
// Type: decimal, source has different values
public static int Test7d()
{
decimal[] source = { 5.5m, -10m, 15.5m, 40.5m, 28.5m };
decimal expected = 16m;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test7d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average7e
{
// Type: decimal, selector function is called
public static int Test7e()
{
Data_decimal[] source = new Data_decimal[]{ new Data_decimal{name="Tim", num=5.5m},
new Data_decimal{name="John", num=15.5m},
new Data_decimal{name="Bob", num=3.0m}
};
decimal expected = 8.0m;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test7e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average8a
{
// Type: decimal?, source is empty
public static int Test8a()
{
decimal?[] source = { };
decimal? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test8a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average8b
{
// Type: decimal?, source has only one element
public static int Test8b()
{
decimal?[] source = { Decimal.MinValue };
decimal? expected = Decimal.MinValue;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test8b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average8c
{
// Type: decimal?, source has all equal values and average is zero
public static int Test8c()
{
decimal?[] source = { 0m, 0m, 0m, 0m, 0m };
decimal? expected = 0m;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test8c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average8d
{
// Type: decimal?, source has different values
public static int Test8d()
{
decimal?[] source = { 5.5m, 0, null, null, null, 15.5m, 40.5m, null, null, -23.5m };
decimal? expected = 7.6m;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test8d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average8e
{
// Type: decimal?, source has 1 non-null value
public static int Test8e()
{
decimal?[] source = { null, null, null, null, 45m };
decimal? expected = 45m;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test8e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average8f
{
// Type: decimal?, source has all null values
public static int Test8f()
{
decimal?[] source = { null, null, null, null, null };
decimal? expected = null;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test8f();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average8g
{
// Type: decimal, selector function is called
public static int Test8g()
{
Data_Ndecimal[] source = new Data_Ndecimal[]{ new Data_Ndecimal{name="Tim", num=5.5m},
new Data_Ndecimal{name="John", num=15.5m},
new Data_Ndecimal{name="Bob", num=null}
};
decimal? expected = 10.5m;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test8g();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average8h
{
// Type: decimal?, OverflowException is thrown by param sum
public static int Test8h()
{
decimal?[] source = { decimal.MaxValue, decimal.MaxValue };
try
{
var actual = source.Average();
return 1;
}
catch (OverflowException)
{
return 0;
}
}
public static int Main()
{
return Test8h();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average9a
{
// Type: float, source is empty
public static int Test9a()
{
float[] source = { };
try
{
var actual = source.Average();
return 1;
}
catch (InvalidOperationException)
{
return 0;
}
}
public static int Main()
{
return Test9a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average9b
{
// Type: float, source has only one element
public static int Test9b()
{
float[] source = { float.MaxValue };
float expected = float.MaxValue;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test9b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average9c
{
// Type: float, source has all equal values and average is zero
public static int Test9c()
{
float[] source = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float expected = 0f;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test9c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average9d
{
// Type: float, source has different values
public static int Test9d()
{
float[] source = { 5.5f, -10f, 15.5f, 40.5f, 28.5f };
float expected = 16f;
var actual = source.Average();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test9d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Average9e
{
// Type: float, selector function is called
public static int Test9e()
{
Data_float[] source = new Data_float[]{ new Data_float{name="Tim", num=5.5f},
new Data_float{name="John", num=15.5f},
new Data_float{name="Bob", num=3.0f}
};
float expected = 8.0f;
var actual = source.Average((e) => e.num);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test9e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Diagnostics;
public class BuildPlayer
{
[XmlRootAttribute("BuildSettings", Namespace = "http://www.cpandl.com", IsNullable = false)]
public class ProjectSettings
{
public string[] Scenes;
public string BuildOutputPath;
public string ProductName;
public string Icon; // sets it to the 1024 icon for Standalone build. Does not set the 'Default Icon'. Needs full path to icon 'Assets\Art\...'
public string DisplayResolutionDialog; // Enabled / Disabled / HiddenByDefault
public string VSyncCount; // DontSync / EveryVBlank / EverySecondVBlank
public string[] ExternalAssetsPaths;
public string[] ConfigFiles;
public string PostBuildScript;
}
// data for build specific settings
const string SettingsFileName = "BuildSettings.xml";
[MenuItem("VH/Build/Perform Windows Build")]
static void MenuPerformWindowsBuild()
{
PerformWindowsBuild();
}
[MenuItem("VH/Build/Perform Windows 64 Build")]
static void MenuPerformWindows64Build()
{
PerformWindows64Build();
}
[MenuItem("VH/Build/Perform OSX Build")]
static void MenuPerformOSXBuild()
{
PerformOSXBuild();
}
[MenuItem("VH/Build/Perform OSX 64 Build")]
static void MenuPerformOSX64Build()
{
PerformOSX64Build();
}
[MenuItem("VH/Build/Perform iOS Build")]
static void MenuPerformiOSBuild()
{
PerformiOSBuild();
}
[MenuItem("VH/Build/Perform Android Build")]
static void MenuPerformAndroidBuild()
{
PerformAndroidBuild();
}
public static void PerformWindowsBuild()
{
PerformBuild(BuildTarget.StandaloneWindows, BuildTargetGroup.Standalone);
}
public static void PerformWindows64Build()
{
PerformBuild(BuildTarget.StandaloneWindows64, BuildTargetGroup.Standalone);
}
public static void PerformOSXBuild()
{
PerformBuild(BuildTarget.StandaloneOSXIntel, BuildTargetGroup.Standalone);
}
public static void PerformOSX64Build()
{
PerformBuild(BuildTarget.StandaloneOSXIntel64, BuildTargetGroup.Standalone);
}
public static void PerformiOSBuild()
{
#if UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
PerformBuild(BuildTarget.iPhone, BuildTargetGroup.iOS);
#else
PerformBuild(BuildTarget.iOS, BuildTargetGroup.iOS);
#endif
}
public static void PerformAndroidBuild()
{
PerformBuild(BuildTarget.Android, BuildTargetGroup.Android);
}
public static void PerformBuild(BuildTarget buildTarget, BuildTargetGroup buildTargetGroup)
{
PerformBuild(buildTarget, buildTargetGroup, SettingsFileName);
}
public static void PerformBuild(BuildTarget buildTarget, BuildTargetGroup buildTargetGroup, string buildSettingsFile)
{
FileStream fs = null;
ProjectSettings configFile = null;
try
{
XmlSerializer serializer = new XmlSerializer(typeof(ProjectSettings));
fs = new FileStream(Application.dataPath + "/../" + buildSettingsFile, FileMode.Open);
configFile = (ProjectSettings)serializer.Deserialize(fs);
}
catch (Exception e)
{
UnityEngine.Debug.LogError("Failed to open: " + buildSettingsFile + " " + e.Message);
}
finally
{
if (fs != null)
{
fs.Close();
}
}
string dataPathNoAssets = Application.dataPath;
if (dataPathNoAssets.EndsWith("Assets"))
{
dataPathNoAssets = dataPathNoAssets.Remove(dataPathNoAssets.Length - "Assets".Length);
}
// the path where the build will reside
string locationPathName = string.Empty;
string executableName = string.Empty;
if (configFile != null && !string.IsNullOrEmpty(configFile.BuildOutputPath))
{
locationPathName = configFile.BuildOutputPath;
switch (buildTarget)
{
case BuildTarget.Android: locationPathName += ".apk"; break;
#if UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
case BuildTarget.iPhone: locationPathName += ".ios.app"; break;
#else
case BuildTarget.iOS: locationPathName += ".ios.app"; break;
#endif
case BuildTarget.StandaloneOSXIntel: locationPathName += ".app"; break;
default: locationPathName += ".exe"; break;
}
executableName = Path.GetFileName(locationPathName);
}
else
{
// it's not specified in the Settings file, default it
switch (buildTarget)
{
case BuildTarget.Android:
executableName = PlayerSettings.productName + ".apk";
break;
#if UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
case BuildTarget.iPhone:
#else
case BuildTarget.iOS:
#endif
case BuildTarget.StandaloneOSXIntel:
executableName = PlayerSettings.productName + ".app";
break;
default:
executableName = PlayerSettings.productName + ".exe";
break;
}
locationPathName = dataPathNoAssets + PlayerSettings.productName + "_Build/" + executableName;
}
// check which scenes are being used and build them
List<string> levels = new List<string>();
if (configFile.Scenes == null || configFile.Scenes.Length == 0)
{
// use the scenes that have been specified in the Unity Build Settings dialog
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
if (EditorBuildSettings.scenes[i].enabled)
{
levels.Add(EditorBuildSettings.scenes[i].path);
UnityEngine.Debug.Log(EditorBuildSettings.scenes[i].path);
}
}
}
else
{
// use the scenes specified in the settings xml file
levels.AddRange(configFile.Scenes);
}
// On XP, BuildPlayer() will fail if the dest folder doesn't exist VH-218
// Error is: Cancelling DisplayDialogComplex: Moving file failed Moving Temp/StagingArea/Data to ../../bin/GSUnity\GSUnity_Data
Directory.CreateDirectory(Path.GetDirectoryName(locationPathName));
string oldProductName = PlayerSettings.productName;
if (configFile != null && !string.IsNullOrEmpty(configFile.ProductName))
{
PlayerSettings.productName = configFile.ProductName;
}
Texture2D [] oldIcons = PlayerSettings.GetIconsForTargetGroup(buildTargetGroup);
Texture2D [] oldIconsCopy = new Texture2D [oldIcons.Length];
Texture2D [] newIcons = new Texture2D [oldIcons.Length];
Array.Copy(oldIcons, oldIconsCopy, oldIcons.Length);
Array.Copy(oldIcons, newIcons, oldIcons.Length);
if (configFile != null && !string.IsNullOrEmpty(configFile.Icon))
{
int [] oldIconSizes = PlayerSettings.GetIconSizesForTargetGroup(buildTargetGroup);
for (int i = 0; i < oldIconSizes.Length; i++)
{
if (oldIconSizes[i] == 1024)
{
newIcons[i] = (Texture2D)AssetDatabase.LoadMainAssetAtPath(configFile.Icon);
}
else
{
newIcons[i] = null;
}
}
PlayerSettings.SetIconsForTargetGroup(buildTargetGroup, newIcons);
}
ResolutionDialogSetting oldResolutionDialogSetting = PlayerSettings.displayResolutionDialog;
if (configFile != null && !string.IsNullOrEmpty(configFile.DisplayResolutionDialog))
{
ResolutionDialogSetting newResolutionDialogSetting = ResolutionDialogSetting.Enabled;
if (configFile.DisplayResolutionDialog == "Enabled") newResolutionDialogSetting = ResolutionDialogSetting.Enabled;
else if (configFile.DisplayResolutionDialog == "Disabled") newResolutionDialogSetting = ResolutionDialogSetting.Disabled;
else if (configFile.DisplayResolutionDialog == "HiddenByDefault") newResolutionDialogSetting = ResolutionDialogSetting.HiddenByDefault;
PlayerSettings.displayResolutionDialog = newResolutionDialogSetting;
}
int oldvSyncCount = QualitySettings.vSyncCount;
if (configFile != null && !string.IsNullOrEmpty(configFile.VSyncCount))
{
int newvSyncCount = 1;
if (configFile.VSyncCount == "DontSync") newvSyncCount = 0;
else if (configFile.DisplayResolutionDialog == "EveryVBlank") newvSyncCount = 1;
else if (configFile.DisplayResolutionDialog == "EverySecondVBlank") newvSyncCount = 2;
QualitySettings.vSyncCount = newvSyncCount;
}
BuildTarget currentBuildTarget = EditorUserBuildSettings.activeBuildTarget;
UnityEngine.Debug.Log("PerformBuild() - BuildPipeline.BuildPlayer() - " + locationPathName);
string errorMessage = BuildPipeline.BuildPlayer(levels.ToArray(), locationPathName, buildTarget, BuildOptions.None);
if (!string.IsNullOrEmpty(errorMessage))
{
UnityEngine.Debug.Log(errorMessage);
}
string destinationLocation = locationPathName.Replace(executableName, "");
// if Unity is in svn, then BuildPlayer copies over .svn hidden folders. things like:
// main\main_Data\Managed\.svn
// main\main_Data\Mono\etc\.svn
// so go through the data folder and remove these.
List<DirectoryInfo> dirlist = new List<DirectoryInfo>();
dirlist.Add(new DirectoryInfo(destinationLocation));
while (dirlist.Count > 0)
{
if (dirlist[0].Exists)
{
dirlist.AddRange(dirlist[0].GetDirectories());
if (dirlist[0].Name == ".svn")
{
VHFile.ClearAttributesRecursive(dirlist[0].FullName);
dirlist[0].Delete(true);
}
}
dirlist.RemoveAt(0);
}
// copy any folders that need to stay unbundled
if (configFile != null && configFile.ExternalAssetsPaths != null)
{
for (int i = 0; i < configFile.ExternalAssetsPaths.Length; i++)
{
if (!string.IsNullOrEmpty(configFile.ExternalAssetsPaths[i]))
{
string sourcePath = dataPathNoAssets + configFile.ExternalAssetsPaths[i];
UnityEngine.Debug.Log("PerformBuild() - Copying: '" + sourcePath + "' to '" + destinationLocation + configFile.ExternalAssetsPaths[i] + "'");
VHFile.CopyDirectory(sourcePath, destinationLocation + configFile.ExternalAssetsPaths[i], true, true, ".svn");
}
}
}
// copy over any config files that they have
if (configFile != null && configFile.ConfigFiles != null)
{
for (int i = 0; i < configFile.ConfigFiles.Length; i++)
{
if (!string.IsNullOrEmpty(configFile.ConfigFiles[i]))
{
string sourcePath = dataPathNoAssets + configFile.ConfigFiles[i];
string destinationDirectoryName = Path.GetDirectoryName(destinationLocation + configFile.ConfigFiles[i]);
UnityEngine.Debug.Log("PerformBuild() - destinationDirectoryName: " + destinationDirectoryName);
if (!Directory.Exists(destinationDirectoryName))
{
Directory.CreateDirectory((destinationDirectoryName));
}
UnityEngine.Debug.Log("PerformBuild() - Copying: '" + sourcePath + "' to '" + destinationLocation + configFile.ConfigFiles[i] + "'");
File.Copy(sourcePath, destinationLocation + configFile.ConfigFiles[i], true);
}
}
}
// trigger any post-build scripts
if (configFile != null && !string.IsNullOrEmpty(configFile.PostBuildScript))
{
string buildType = "Release";
//string buildType = Debug.isDebugBuild or EditorUserBuildSettings.development or EditorUserBuildSettings.allowDebugging?
string projectRoot = EditorApplication.applicationPath.Replace("Unity.exe", "") + @"..\..\..";
projectRoot = projectRoot.Replace(@"/", @"\");
string destinationLocationModified = destinationLocation.Replace(@"/", @"\") + @"Assets\Plugins";
UnityEngine.Debug.Log("PerformBuild() - calling " + configFile.PostBuildScript + " " + buildType + " " + projectRoot + " " + destinationLocationModified);
Process p = Process.Start(configFile.PostBuildScript, buildType + " " + projectRoot + " " + destinationLocationModified);
p.WaitForExit();
}
// revert settings that were changed before the build
PlayerSettings.productName = oldProductName;
if (configFile != null && !string.IsNullOrEmpty(configFile.Icon)) PlayerSettings.SetIconsForTargetGroup(BuildTargetGroup.Standalone, oldIconsCopy);
PlayerSettings.displayResolutionDialog = oldResolutionDialogSetting;
QualitySettings.vSyncCount = oldvSyncCount;
if (currentBuildTarget != EditorUserBuildSettings.activeBuildTarget)
EditorUserBuildSettings.SwitchActiveBuildTarget(buildTargetGroup, currentBuildTarget);
#if UNITY_5_5_OR_NEWER
AssetDatabase.SaveAssets();
#else
EditorApplication.SaveAssets();
#endif
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2016 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Win32;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Enumeration identifying a common language
/// runtime implementation.
/// </summary>
public enum RuntimeType
{
/// <summary>Any supported runtime framework</summary>
Any,
/// <summary>Microsoft .NET Framework</summary>
Net,
/// <summary>Microsoft Shared Source CLI</summary>
SSCLI,
/// <summary>Mono</summary>
Mono,
/// <summary>MonoTouch</summary>
MonoTouch
}
/// <summary>
/// RuntimeFramework represents a particular version
/// of a common language runtime implementation.
/// </summary>
[Serializable]
public sealed class RuntimeFramework
{
// NOTE: This version of RuntimeFramework is for use
// within the NUnit framework assembly. It is simpler
// than the version in the test engine because it does
// not need to know what frameworks are available,
// only what framework is currently running.
#region Static and Instance Fields
/// <summary>
/// DefaultVersion is an empty Version, used to indicate that
/// NUnit should select the CLR version to use for the test.
/// </summary>
public static readonly Version DefaultVersion = new Version(0,0);
private static readonly Lazy<RuntimeFramework> currentFramework = new Lazy<RuntimeFramework>(() =>
{
Type monoRuntimeType = Type.GetType("Mono.Runtime", false);
Type monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate,monotouch");
bool isMonoTouch = monoTouchType != null;
bool isMono = monoRuntimeType != null;
RuntimeType runtime = isMonoTouch
? RuntimeType.MonoTouch
: isMono
? RuntimeType.Mono
: RuntimeType.Net;
int major = Environment.Version.Major;
int minor = Environment.Version.Minor;
if (isMono)
{
switch (major)
{
case 1:
minor = 0;
break;
case 2:
major = 3;
minor = 5;
break;
}
}
else /* It's windows */
if (major == 2)
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework"))
{
if (key != null)
{
string installRoot = key.GetValue("InstallRoot") as string;
if (installRoot != null)
{
if (Directory.Exists(Path.Combine(installRoot, "v3.5")))
{
major = 3;
minor = 5;
}
else if (Directory.Exists(Path.Combine(installRoot, "v3.0")))
{
major = 3;
minor = 0;
}
}
}
}
}
else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null)
{
minor = 5;
}
var currentFramework = new RuntimeFramework( runtime, new Version (major, minor) )
{
ClrVersion = Environment.Version
};
if (isMono)
{
MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
"GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
if (getDisplayNameMethod != null)
currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
}
return currentFramework;
});
#endregion
#region Constructor
/// <summary>
/// Construct from a runtime type and version. If the version has
/// two parts, it is taken as a framework version. If it has three
/// or more, it is taken as a CLR version. In either case, the other
/// version is deduced based on the runtime type and provided version.
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework( RuntimeType runtime, Version version)
{
Runtime = runtime;
if (version.Build < 0)
InitFromFrameworkVersion(version);
else
InitFromClrVersion(version);
DisplayName = GetDefaultDisplayName(runtime, version);
}
private void InitFromFrameworkVersion(Version version)
{
FrameworkVersion = ClrVersion = version;
if (version.Major > 0) // 0 means any version
switch (Runtime)
{
case RuntimeType.Net:
case RuntimeType.Mono:
case RuntimeType.Any:
switch (version.Major)
{
case 1:
switch (version.Minor)
{
case 0:
ClrVersion = Runtime == RuntimeType.Mono
? new Version(1, 1, 4322)
: new Version(1, 0, 3705);
break;
case 1:
if (Runtime == RuntimeType.Mono)
FrameworkVersion = new Version(1, 0);
ClrVersion = new Version(1, 1, 4322);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
case 2:
case 3:
ClrVersion = new Version(2, 0, 50727);
break;
case 4:
ClrVersion = new Version(4, 0, 30319);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
}
}
private static void ThrowInvalidFrameworkVersion(Version version)
{
throw new ArgumentException("Unknown framework version " + version, "version");
}
private void InitFromClrVersion(Version version)
{
FrameworkVersion = new Version(version.Major, version.Minor);
ClrVersion = version;
if (Runtime == RuntimeType.Mono && version.Major == 1)
FrameworkVersion = new Version(1, 0);
}
#endregion
#region Properties
/// <summary>
/// Static method to return a RuntimeFramework object
/// for the framework that is currently in use.
/// </summary>
public static RuntimeFramework CurrentFramework
{
get
{
return currentFramework.Value;
}
}
/// <summary>
/// The type of this runtime framework
/// </summary>
public RuntimeType Runtime { get; private set; }
/// <summary>
/// The framework version for this runtime framework
/// </summary>
public Version FrameworkVersion { get; private set; }
/// <summary>
/// The CLR version for this runtime framework
/// </summary>
public Version ClrVersion { get; private set; }
/// <summary>
/// Return true if any CLR version may be used in
/// matching this RuntimeFramework object.
/// </summary>
public bool AllowAnyVersion
{
get { return ClrVersion == DefaultVersion; }
}
/// <summary>
/// Returns the Display name for this framework
/// </summary>
public string DisplayName { get; private set; }
#endregion
#region Public Methods
/// <summary>
/// Parses a string representing a RuntimeFramework.
/// The string may be just a RuntimeType name or just
/// a Version or a hyphenated RuntimeType-Version or
/// a Version prefixed by 'versionString'.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static RuntimeFramework Parse(string s)
{
RuntimeType runtime = RuntimeType.Any;
Version version = DefaultVersion;
string[] parts = s.Split('-');
if (parts.Length == 2)
{
runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), parts[0], true);
string vstring = parts[1];
if (vstring != "")
version = new Version(vstring);
}
else if (char.ToLower(s[0]) == 'v')
{
version = new Version(s.Substring(1));
}
else if (IsRuntimeTypeName(s))
{
runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), s, true);
}
else
{
version = new Version(s);
}
return new RuntimeFramework(runtime, version);
}
/// <summary>
/// Overridden to return the short name of the framework
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (AllowAnyVersion)
{
return Runtime.ToString().ToLower();
}
else
{
string vstring = FrameworkVersion.ToString();
if (Runtime == RuntimeType.Any)
return "v" + vstring;
else
return Runtime.ToString().ToLower() + "-" + vstring;
}
}
/// <summary>
/// Returns true if the current framework matches the
/// one supplied as an argument. Two frameworks match
/// if their runtime types are the same or either one
/// is RuntimeType.Any and all specified version components
/// are equal. Negative (i.e. unspecified) version
/// components are ignored.
/// </summary>
/// <param name="target">The RuntimeFramework to be matched.</param>
/// <returns>True on match, otherwise false</returns>
public bool Supports(RuntimeFramework target)
{
if (Runtime != RuntimeType.Any
&& target.Runtime != RuntimeType.Any
&& Runtime != target.Runtime)
return false;
if (AllowAnyVersion || target.AllowAnyVersion)
return true;
if (!VersionsMatch(ClrVersion, target.ClrVersion))
return false;
return FrameworkVersion.Major >= target.FrameworkVersion.Major && FrameworkVersion.Minor >= target.FrameworkVersion.Minor;
}
#endregion
#region Helper Methods
private static bool IsRuntimeTypeName(string name)
{
return Enum.GetNames( typeof(RuntimeType)).Any( item => item.ToLower() == name.ToLower() );
}
private static string GetDefaultDisplayName(RuntimeType runtime, Version version)
{
if (version == DefaultVersion)
return runtime.ToString();
else if (runtime == RuntimeType.Any)
return "v" + version;
else
return runtime + " " + version;
}
private static bool VersionsMatch(Version v1, Version v2)
{
return v1.Major == v2.Major &&
v1.Minor == v2.Minor &&
(v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) &&
(v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision);
}
#endregion
}
}
#endif
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using System.IO;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI81;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI81
{
/// <summary>
/// C_DigestEncryptUpdate and C_DecryptDigestUpdate tests.
/// </summary>
[TestClass]
public class _23_DigestEncryptAndDecryptDigestTest
{
/// <summary>
/// Basic C_DigestEncryptUpdate and C_DecryptDigestUpdate test.
/// </summary>
[TestMethod]
public void _01_BasicDigestEncryptAndDecryptDigestTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs81);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
ulong slotId = Helpers.GetUsableSlot(pkcs11);
ulong session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate symetric key
ulong keyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKey(pkcs11, session, ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate random initialization vector
byte[] iv = new byte[8];
rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt64(iv.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify encryption mechanism with initialization vector as parameter.
// Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
CK_MECHANISM encryptionMechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);
// Specify digesting mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM digestingMechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password");
byte[] encryptedData = null;
byte[] digest1 = null;
byte[] decryptedData = null;
byte[] digest2 = null;
// Multipart digesting and encryption function C_DigestEncryptUpdate can be used i.e. for digesting and encryption of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
{
// Initialize digesting operation
rv = pkcs11.C_DigestInit(session, ref digestingMechanism);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize encryption operation
rv = pkcs11.C_EncryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
ulong encryptedPartLen = Convert.ToUInt64(encryptedPart.Length);
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Process each individual source data part
encryptedPartLen = Convert.ToUInt64(encryptedPart.Length);
rv = pkcs11.C_DigestEncryptUpdate(session, part, Convert.ToUInt64(bytesRead), encryptedPart, ref encryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append encrypted data part to the output stream
outputStream.Write(encryptedPart, 0, Convert.ToInt32(encryptedPartLen));
}
// Get length of digest value in first call
ulong digestLen = 0;
rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(digestLen > 0);
// Allocate array for digest value
digest1 = new byte[digestLen];
// Get digest value in second call
rv = pkcs11.C_DigestFinal(session, digest1, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Get the length of last encrypted data part in first call
byte[] lastEncryptedPart = null;
ulong lastEncryptedPartLen = 0;
rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last encrypted data part
lastEncryptedPart = new byte[lastEncryptedPartLen];
// Get the last encrypted data part in second call
rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last encrypted data part to the output stream
outputStream.Write(lastEncryptedPart, 0, Convert.ToInt32(lastEncryptedPartLen));
// Read whole output stream to the byte array so we can compare results more easily
encryptedData = outputStream.ToArray();
}
// Do something interesting with encrypted data and digest
// Multipart decryption and digesting function C_DecryptDigestUpdate can be used i.e. for digesting and decryption of streamed data
using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
{
// Initialize decryption operation
rv = pkcs11.C_DecryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize digesting operation
rv = pkcs11.C_DigestInit(session, ref digestingMechanism);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
// Prepare buffer for decrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
ulong partLen = Convert.ToUInt64(part.Length);
// Read input stream with encrypted data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0)
{
// Process each individual encrypted data part
partLen = Convert.ToUInt64(part.Length);
rv = pkcs11.C_DecryptDigestUpdate(session, encryptedPart, Convert.ToUInt64(bytesRead), part, ref partLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append decrypted data part to the output stream
outputStream.Write(part, 0, Convert.ToInt32(partLen));
}
// Get the length of last decrypted data part in first call
byte[] lastPart = null;
ulong lastPartLen = 0;
rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last decrypted data part
lastPart = new byte[lastPartLen];
// Get the last decrypted data part in second call
rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last decrypted data part to the output stream
outputStream.Write(lastPart, 0, Convert.ToInt32(lastPartLen));
// Read whole output stream to the byte array so we can compare results more easily
decryptedData = outputStream.ToArray();
// Get length of digest value in first call
ulong digestLen = 0;
rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(digestLen > 0);
// Allocate array for digest value
digest2 = new byte[digestLen];
// Get digest value in second call
rv = pkcs11.C_DigestFinal(session, digest2, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with decrypted data and digest
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
Assert.IsTrue(Convert.ToBase64String(digest1) == Convert.ToBase64String(digest2));
// In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
UnmanagedMemory.Free(ref encryptionMechanism.Parameter);
encryptionMechanism.ParameterLen = 0;
rv = pkcs11.C_DestroyObject(session, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
/*
* [The "BSD licence"]
* Copyright (c) 2005-2008 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. 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.
*/
namespace TypeSql.Antlr.Runtime.Tree
{
using System.Collections.Generic;
using IList = System.Collections.IList;
/** <summary>
* A generic list of elements tracked in an alternative to be used in
* a -> rewrite rule. We need to subclass to fill in the next() method,
* which returns either an AST node wrapped around a token payload or
* an existing subtree.
* </summary>
*
* <remarks>
* Once you start next()ing, do not try to add more elements. It will
* break the cursor tracking I believe.
*
* TODO: add mechanism to detect/puke on modification after reading from stream
* </remarks>
*
* <see cref="RewriteRuleSubtreeStream"/>
* <see cref="RewriteRuleTokenStream"/>
*/
[System.Serializable]
public abstract class RewriteRuleElementStream
{
/** <summary>
* Cursor 0..n-1. If singleElement!=null, cursor is 0 until you next(),
* which bumps it to 1 meaning no more elements.
* </summary>
*/
protected int cursor = 0;
/** <summary>Track single elements w/o creating a list. Upon 2nd add, alloc list */
protected object singleElement;
/** <summary>The list of tokens or subtrees we are tracking */
protected IList elements;
/** <summary>Once a node / subtree has been used in a stream, it must be dup'd
* from then on. Streams are reset after subrules so that the streams
* can be reused in future subrules. So, reset must set a dirty bit.
* If dirty, then next() always returns a dup.
*
* I wanted to use "naughty bit" here, but couldn't think of a way
* to use "naughty".
*/
protected bool dirty = false;
/** <summary>The element or stream description; usually has name of the token or
* rule reference that this list tracks. Can include rulename too, but
* the exception would track that info.
*/
protected string elementDescription;
protected ITreeAdaptor adaptor;
public RewriteRuleElementStream( ITreeAdaptor adaptor, string elementDescription )
{
this.elementDescription = elementDescription;
this.adaptor = adaptor;
}
/** <summary>Create a stream with one element</summary> */
public RewriteRuleElementStream( ITreeAdaptor adaptor, string elementDescription, object oneElement )
: this( adaptor, elementDescription )
{
Add( oneElement );
}
/** <summary>Create a stream, but feed off an existing list</summary> */
public RewriteRuleElementStream( ITreeAdaptor adaptor, string elementDescription, IList elements )
: this( adaptor, elementDescription )
{
this.singleElement = null;
this.elements = elements;
}
/** <summary>
* Reset the condition of this stream so that it appears we have
* not consumed any of its elements. Elements themselves are untouched.
* Once we reset the stream, any future use will need duplicates. Set
* the dirty bit.
* </summary>
*/
public virtual void Reset()
{
cursor = 0;
dirty = true;
}
public virtual void Add( object el )
{
//System.out.println("add '"+elementDescription+"' is "+el);
if ( el == null )
{
return;
}
if ( elements != null )
{ // if in list, just add
elements.Add( el );
return;
}
if ( singleElement == null )
{ // no elements yet, track w/o list
singleElement = el;
return;
}
// adding 2nd element, move to list
elements = new List<object>( 5 );
elements.Add( singleElement );
singleElement = null;
elements.Add( el );
}
/** <summary>
* Return the next element in the stream. If out of elements, throw
* an exception unless size()==1. If size is 1, then return elements[0].
* Return a duplicate node/subtree if stream is out of elements and
* size==1. If we've already used the element, dup (dirty bit set).
* </summary>
*/
public virtual object NextTree()
{
int n = Count;
if ( dirty || ( cursor >= n && n == 1 ) )
{
// if out of elements and size is 1, dup
object el = NextCore();
return Dup( el );
}
// test size above then fetch
object el2 = NextCore();
return el2;
}
/** <summary>
* Do the work of getting the next element, making sure that it's
* a tree node or subtree. Deal with the optimization of single-
* element list versus list of size > 1. Throw an exception
* if the stream is empty or we're out of elements and size>1.
* protected so you can override in a subclass if necessary.
* </summary>
*/
protected virtual object NextCore()
{
int n = Count;
if ( n == 0 )
{
throw new RewriteEmptyStreamException( elementDescription );
}
if ( cursor >= n )
{ // out of elements?
if ( n == 1 )
{ // if size is 1, it's ok; return and we'll dup
return ToTree( singleElement );
}
// out of elements and size was not 1, so we can't dup
throw new RewriteCardinalityException( elementDescription );
}
// we have elements
if ( singleElement != null )
{
cursor++; // move cursor even for single element list
return ToTree( singleElement );
}
// must have more than one in list, pull from elements
object o = ToTree( elements[cursor] );
cursor++;
return o;
}
/** <summary>
* When constructing trees, sometimes we need to dup a token or AST
* subtree. Dup'ing a token means just creating another AST node
* around it. For trees, you must call the adaptor.dupTree() unless
* the element is for a tree root; then it must be a node dup.
* </summary>
*/
protected abstract object Dup( object el );
/** <summary>
* Ensure stream emits trees; tokens must be converted to AST nodes.
* AST nodes can be passed through unmolested.
* </summary>
*/
protected virtual object ToTree( object el )
{
return el;
}
public virtual bool HasNext
{
get
{
return ( singleElement != null && cursor < 1 ) ||
( elements != null && cursor < elements.Count );
}
}
public virtual int Count
{
get
{
int n = 0;
if ( singleElement != null )
{
n = 1;
}
if ( elements != null )
{
return elements.Count;
}
return n;
}
}
public virtual string Description
{
get
{
return elementDescription;
}
}
}
}
| |
/*
* 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.Datastream
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Data streamer internal interface to get rid of generics.
/// </summary>
internal interface IDataStreamer
{
/// <summary>
/// Callback invoked on topology size change.
/// </summary>
/// <param name="topVer">New topology version.</param>
/// <param name="topSize">New topology size.</param>
void TopologyChange(long topVer, int topSize);
}
/// <summary>
/// Data streamer implementation.
/// </summary>
internal class DataStreamerImpl<TK, TV> : PlatformDisposableTargetAdapter, IDataStreamer, IDataStreamer<TK, TV>
{
#pragma warning disable 0420
/** Policy: continue. */
internal const int PlcContinue = 0;
/** Policy: close. */
internal const int PlcClose = 1;
/** Policy: cancel and close. */
internal const int PlcCancelClose = 2;
/** Policy: flush. */
internal const int PlcFlush = 3;
/** Operation: update. */
private const int OpUpdate = 1;
/** Operation: set receiver. */
private const int OpReceiver = 2;
/** */
private const int OpAllowOverwrite = 3;
/** */
private const int OpSetAllowOverwrite = 4;
/** */
private const int OpSkipStore = 5;
/** */
private const int OpSetSkipStore = 6;
/** */
private const int OpPerNodeBufferSize = 7;
/** */
private const int OpSetPerNodeBufferSize = 8;
/** */
private const int OpPerNodeParallelOps = 9;
/** */
private const int OpSetPerNodeParallelOps = 10;
/** */
private const int OpListenTopology = 11;
/** */
private const int OpGetTimeout = 12;
/** */
private const int OpSetTimeout = 13;
/** Cache name. */
private readonly string _cacheName;
/** Lock. */
private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
/** Closed event. */
private readonly ManualResetEventSlim _closedEvt = new ManualResetEventSlim(false);
/** Close future. */
private readonly Future<object> _closeFut = new Future<object>();
/** GC handle to this streamer. */
private readonly long _hnd;
/** Topology version. */
private long _topVer;
/** Topology size. */
private int _topSize = 1;
/** Buffer send size. */
private volatile int _bufSndSize;
/** Current data streamer batch. */
private volatile DataStreamerBatch<TK, TV> _batch;
/** Flusher. */
private readonly Flusher<TK, TV> _flusher;
/** Receiver. */
private volatile IStreamReceiver<TK, TV> _rcv;
/** Receiver handle. */
private long _rcvHnd;
/** Receiver binary mode. */
private readonly bool _keepBinary;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="cacheName">Cache name.</param>
/// <param name="keepBinary">Binary flag.</param>
public DataStreamerImpl(IPlatformTargetInternal target, Marshaller marsh, string cacheName, bool keepBinary)
: base(target)
{
_cacheName = cacheName;
_keepBinary = keepBinary;
// Create empty batch.
_batch = new DataStreamerBatch<TK, TV>();
// Allocate GC handle so that this data streamer could be easily dereferenced from native code.
WeakReference thisRef = new WeakReference(this);
_hnd = marsh.Ignite.HandleRegistry.Allocate(thisRef);
// Start topology listening. This call will ensure that buffer size member is updated.
DoOutInOp(OpListenTopology, _hnd);
// Membar to ensure fields initialization before leaving constructor.
Thread.MemoryBarrier();
// Start flusher after everything else is initialized.
_flusher = new Flusher<TK, TV>(thisRef);
_flusher.RunThread();
}
/** <inheritDoc /> */
public string CacheName
{
get { return _cacheName; }
}
/** <inheritDoc /> */
public bool AllowOverwrite
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return DoOutInOp(OpAllowOverwrite) == True;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetAllowOverwrite, value ? True : False);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public bool SkipStore
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return DoOutInOp(OpSkipStore) == True;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetSkipStore, value ? True : False);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeBufferSize
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return (int) DoOutInOp(OpPerNodeBufferSize);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetPerNodeBufferSize, value);
_bufSndSize = _topSize * value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeParallelOperations
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return (int) DoOutInOp(OpPerNodeParallelOps);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetPerNodeParallelOps, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public long AutoFlushFrequency
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return _flusher.Frequency;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
_flusher.Frequency = value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task Task
{
get
{
return _closeFut.Task;
}
}
/** <inheritDoc /> */
public IStreamReceiver<TK, TV> Receiver
{
get
{
ThrowIfDisposed();
return _rcv;
}
set
{
IgniteArgumentCheck.NotNull(value, "value");
var handleRegistry = Marshaller.Ignite.HandleRegistry;
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_rcv == value)
return;
var rcvHolder = new StreamReceiverHolder(value,
(rec, grid, cache, stream, keepBinary) =>
StreamReceiverHolder.InvokeReceiver((IStreamReceiver<TK, TV>) rec, grid, cache, stream,
keepBinary));
var rcvHnd0 = handleRegistry.Allocate(rcvHolder);
try
{
DoOutOp(OpReceiver, w =>
{
w.WriteLong(rcvHnd0);
w.WriteObject(rcvHolder);
});
}
catch (Exception)
{
handleRegistry.Release(rcvHnd0);
throw;
}
if (_rcv != null)
handleRegistry.Release(_rcvHnd);
_rcv = value;
_rcvHnd = rcvHnd0;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task AddData(TK key, TV val)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerEntry<TK, TV>(key, val), 1);
}
/** <inheritDoc /> */
public Task AddData(KeyValuePair<TK, TV> pair)
{
ThrowIfDisposed();
return Add0(new DataStreamerEntry<TK, TV>(pair.Key, pair.Value), 1);
}
/** <inheritDoc /> */
public Task AddData(ICollection<KeyValuePair<TK, TV>> entries)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(entries, "entries");
return Add0(entries, entries.Count);
}
/** <inheritDoc /> */
public Task RemoveData(TK key)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerRemoveEntry<TK>(key), 1);
}
/** <inheritDoc /> */
public void TryFlush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, false, PlcFlush);
}
/** <inheritDoc /> */
public void Flush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, true, PlcFlush);
else
{
// Batch is null, i.e. data streamer is closing. Wait for close to complete.
_closedEvt.Wait();
}
}
/** <inheritDoc /> */
public void Close(bool cancel)
{
_flusher.Stop();
while (true)
{
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 == null)
{
// Wait for concurrent close to finish.
_closedEvt.Wait();
return;
}
if (Flush0(batch0, true, cancel ? PlcCancelClose : PlcClose))
{
_closeFut.OnDone(null, null);
_rwLock.EnterWriteLock();
try
{
base.Dispose(true);
if (_rcv != null)
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd);
_closedEvt.Set();
}
finally
{
_rwLock.ExitWriteLock();
}
Marshaller.Ignite.HandleRegistry.Release(_hnd);
break;
}
}
}
/** <inheritDoc /> */
public IDataStreamer<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_keepBinary)
{
var result = this as IDataStreamer<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of binary streamer. WithKeepBinary has been called on an instance of " +
"binary streamer with incompatible generic arguments.");
return result;
}
return Marshaller.Ignite.GetDataStreamer<TK1, TV1>(_cacheName, true);
}
/** <inheritDoc /> */
public TimeSpan Timeout
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return BinaryUtils.LongToTimeSpan(DoOutInOp(OpGetTimeout));
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetTimeout, (long) value.TotalMilliseconds);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void Dispose(bool disposing)
{
if (disposing)
Close(false); // Normal dispose: do not cancel
else
{
// Finalizer: just close Java streamer
try
{
if (_batch != null)
_batch.Send(this, PlcCancelClose);
}
// ReSharper disable once EmptyGeneralCatchClause
catch (Exception)
{
// Finalizers should never throw
}
Marshaller.Ignite.HandleRegistry.Release(_hnd, true);
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd, true);
}
base.Dispose(false);
}
/** <inheritDoc /> */
~DataStreamerImpl()
{
Dispose(false);
}
/** <inheritDoc /> */
public void TopologyChange(long topVer, int topSize)
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_topVer < topVer)
{
_topVer = topVer;
_topSize = topSize > 0 ? topSize : 1; // Do not set to 0 to avoid 0 buffer size.
_bufSndSize = (int) (_topSize * DoOutInOp(OpPerNodeBufferSize));
}
}
finally
{
_rwLock.ExitWriteLock();
}
}
/// <summary>
/// Internal add/remove routine.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="cnt">Items count.</param>
/// <returns>Future.</returns>
private Task Add0(object val, int cnt)
{
int bufSndSize0 = _bufSndSize;
Debug.Assert(bufSndSize0 > 0);
while (true)
{
var batch0 = _batch;
if (batch0 == null)
throw new InvalidOperationException("Data streamer is stopped.");
int size = batch0.Add(val, cnt);
if (size == -1)
{
// Batch is blocked, perform CAS.
Interlocked.CompareExchange(ref _batch,
new DataStreamerBatch<TK, TV>(batch0), batch0);
continue;
}
if (size >= bufSndSize0)
// Batch is too big, schedule flush.
Flush0(batch0, false, PlcContinue);
return batch0.Task;
}
}
/// <summary>
/// Internal flush routine.
/// </summary>
/// <param name="curBatch"></param>
/// <param name="wait">Whether to wait for flush to complete.</param>
/// <param name="plc">Whether this is the last batch.</param>
/// <returns>Whether this call was able to CAS previous batch</returns>
private bool Flush0(DataStreamerBatch<TK, TV> curBatch, bool wait, int plc)
{
// 1. Try setting new current batch to help further adders.
bool res = Interlocked.CompareExchange(ref _batch,
(plc == PlcContinue || plc == PlcFlush) ?
new DataStreamerBatch<TK, TV>(curBatch) : null, curBatch) == curBatch;
// 2. Perform actual send.
curBatch.Send(this, plc);
if (wait)
// 3. Wait for all futures to finish.
curBatch.AwaitCompletion();
return res;
}
/// <summary>
/// Start write.
/// </summary>
/// <returns>Writer.</returns>
internal void Update(Action<BinaryWriter> action)
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
DoOutOp(OpUpdate, action);
}
finally
{
_rwLock.ExitReadLock();
}
}
/// <summary>
/// Flusher.
/// </summary>
private class Flusher<TK1, TV1>
{
/** State: running. */
private const int StateRunning = 0;
/** State: stopping. */
private const int StateStopping = 1;
/** State: stopped. */
private const int StateStopped = 2;
/** Data streamer. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private readonly WeakReference _ldrRef;
/** Finish flag. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private int _state;
/** Flush frequency. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private long _freq;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ldrRef">Data streamer weak reference..</param>
public Flusher(WeakReference ldrRef)
{
_ldrRef = ldrRef;
lock (this)
{
_state = StateRunning;
}
}
/// <summary>
/// Main flusher routine.
/// </summary>
private void Run()
{
bool force = false;
long curFreq = 0;
try
{
while (true)
{
if (curFreq > 0 || force)
{
var ldr = _ldrRef.Target as DataStreamerImpl<TK1, TV1>;
if (ldr == null)
return;
ldr.TryFlush();
force = false;
}
lock (this)
{
// Stop immediately.
if (_state == StateStopping)
return;
if (curFreq == _freq)
{
// Frequency is unchanged
if (curFreq == 0)
// Just wait for a second and re-try.
Monitor.Wait(this, 1000);
else
{
// Calculate remaining time.
DateTime now = DateTime.Now;
long ticks;
try
{
ticks = now.AddMilliseconds(curFreq).Ticks - now.Ticks;
if (ticks > int.MaxValue)
ticks = int.MaxValue;
}
catch (ArgumentOutOfRangeException)
{
// Handle possible overflow.
ticks = int.MaxValue;
}
Monitor.Wait(this, TimeSpan.FromTicks(ticks));
}
}
else
{
if (curFreq != 0)
force = true;
curFreq = _freq;
}
}
}
}
finally
{
// Let streamer know about stop.
lock (this)
{
_state = StateStopped;
Monitor.PulseAll(this);
}
}
}
/// <summary>
/// Frequency.
/// </summary>
public long Frequency
{
get
{
return Interlocked.Read(ref _freq);
}
set
{
lock (this)
{
if (_freq != value)
{
_freq = value;
Monitor.PulseAll(this);
}
}
}
}
/// <summary>
/// Stop flusher.
/// </summary>
public void Stop()
{
lock (this)
{
if (_state == StateRunning)
{
_state = StateStopping;
Monitor.PulseAll(this);
}
while (_state != StateStopped)
Monitor.Wait(this);
}
}
/// <summary>
/// Runs the flusher thread.
/// </summary>
public void RunThread()
{
Task.Factory.StartNew(Run);
}
}
#pragma warning restore 0420
}
}
| |
// 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;
/// <summary>
/// System.Array.Sort(System.Array,System.Int32,System.Int32,System.Collections.IComparer)
/// </summary>
public class ArraySort5
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest8() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array using default comparer ");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Mike",
"Peter",
"Tom",
"Allin"};
string[] s2 = new string[6]{"Jack",
"Mary",
"Mike",
"Allin",
"Peter",
"Tom"};
Array.Sort(s1, 3, 3, null);
for (int i = 0; i < 6; i++)
{
if (s1[i] != s2[i])
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using comparer ");
try
{
int length = TestLibrary.Generator.GetByte(-55);
int[] i1 = new int[length];
int[] i2 = new int[length];
for (int i = 0; i < length; i++)
{
int value = TestLibrary.Generator.GetByte(-55);
i1[i] = value;
i2[i] = value;
}
IComparer a1 = new A();
int startIdx = GetInt(0, length - 2);
int endIdx = GetInt(startIdx, length - 1);
int count = length == 0 ? length : endIdx - startIdx + 1;
Array.Sort(i1, startIdx, count, a1);
for (int i = startIdx; i < endIdx; i++) //manually quich sort
{
for (int j = i + 1; j <= endIdx; j++)
{
if (i2[i] > i2[j])
{
int temp = i2[i];
i2[i] = i2[j];
i2[j] = temp;
}
}
}
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,the start index is:" + startIdx.ToString() + "the end index is:" + endIdx.ToString());
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using reverse comparer ");
try
{
char[] c1 = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] d1 = new char[10] { 'a', 'e', 'd', 'c', 'b', 'f', 'g', 'h', 'i', 'j' };
IComparer b = new B();
Array.Sort(c1, 1, 4, b);
for (int i = 0; i < 10; i++)
{
if (c1[i] != d1[i])
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Sort an int array from the minimal index to the maximal index of the array ");
try
{
int length = TestLibrary.Generator.GetInt16(-55);
int[] i1 = new int[length];
int[] i2 = new int[length];
for (int i = 0; i < length; i++)
{
int value = TestLibrary.Generator.GetByte(-55);
i1[i] = value;
i2[i] = value;
}
int startIdx = 0;
int count = length;
Array.Sort(i1, startIdx, count, new A());
Array.Sort(i2, new A());
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("007", string.Format("The result is not the value as expected, the length is:{0}", length));
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5:The implementation of comparer caused an error during the sort");
try
{
int[] i1 = new int[9] { 2, 34, 56, 87, 34, 23, 209, 34, 87 };
IComparer f = new F();
Array.Sort(i1, 0, 9, f);
for(int i=1; i<i1.Length; i++)
{
if (i1[i-1] > i1[i])
{
TestLibrary.TestFramework.LogError("107", "The " + i + " element in the array is out of order: [i-1]=" + i1[i-1] + " [i]="+i1[i]);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("114", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The array to be sorted is null reference ");
try
{
string[] s1 = null;
Array.Sort(s1, 0, 2, null);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected ");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The array is not one dimension ");
try
{
int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } };
Array.Sort(i1, 0, 3, null);
TestLibrary.TestFramework.LogError("103", "The RankException is not throw as expected ");
retVal = false;
}
catch (RankException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: The start index is less than the minimal bound of the array");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Peter",
"Mike",
"Tom",
"Allin"};
Array.Sort(s1, -1, 4, null);
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: Length is less than zero");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Peter",
"Mike",
"Tom",
"Allin"};
Array.Sort(s1, 3, -3, null);
TestLibrary.TestFramework.LogError("107", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: The start index is greater than the maximal range of the array");
try
{
int length = TestLibrary.Generator.GetByte(-55);
string[] s1 = new string[length];
for (int i = 0; i < length; i++)
{
string value = TestLibrary.Generator.GetString(-55, false, 0, 10);
s1[i] = value;
}
int startIdx = GetInt(1, Byte.MaxValue);
int increment = length;
Array.Sort(s1, startIdx + increment, 0, null);
TestLibrary.TestFramework.LogError("109", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: The start index and length do not specify a valid range in array. ");
try
{
int length = TestLibrary.Generator.GetByte(-55);
string[] s1 = new string[length];
for (int i = 0; i < length; i++)
{
string value = TestLibrary.Generator.GetString(-55, false, 0, 10);
s1[i] = value;
}
int startIdx = GetInt(1, length - 1);
int count = length;
Array.Sort(s1, startIdx, count, null);
TestLibrary.TestFramework.LogError("111", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest8: Elements in array do not implement the IComparable interface ");
try
{
E[] a1 = new E[4] { new E(), new E(), new E(), new E() };
IComparer d = null;
Array.Sort(a1, 0, 4, d);
TestLibrary.TestFramework.LogError("115", "The InvalidOperationException is not throw as expected ");
retVal = false;
}
catch (InvalidOperationException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("116", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ArraySort5 test = new ArraySort5();
TestLibrary.TestFramework.BeginTestCase("ArraySort5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
class A : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return ((int)x).CompareTo((int)y);
}
#endregion
}
class B : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
if (((char)x).CompareTo((char)y) > 0)
return -1;
else
{
if (x == y)
{
return 0;
}
else
{
return 1;
}
}
}
#endregion
}
class C : IComparer
{
protected int c_value;
public C(int a)
{
this.c_value = a;
}
#region IComparer Members
public int Compare(object x, object y)
{
return (x as C).c_value.CompareTo((y as C).c_value);
}
#endregion
}
class D : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
return 0;
}
#endregion
}
class E
{
public E() { }
}
class F : IComparer
{
public int Compare(object x, object y)
{
int a = (int)x;
int b = (int)y;
return a > b ? 1 : (-1);
}
}
#region Help method for geting test data
private Int32 GetInt(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
//
// OracleBoolean.cs
//
// Part of the Mono class libraries at
// mcs/class/System.Data.OracleClient/System.Data.OracleClient
//
// Assembly: System.Data.OracleClient.dll
// Namespace: System.Data.OracleClient
//
// Author: Tim Coleman <tim@timcoleman.com>
//
// Copyright (C) Tim Coleman, 2003
//
// Licensed under the MIT/X11 License.
//
using System;
using System.Data.SqlTypes;
namespace System.Data.OracleClient {
public struct OracleBoolean : IComparable
{
#region Fields
public static readonly OracleBoolean False = new OracleBoolean (false);
public static readonly OracleBoolean Null = new OracleBoolean ();
public static readonly OracleBoolean One = new OracleBoolean (1);
public static readonly OracleBoolean True = new OracleBoolean (true);
public static readonly OracleBoolean Zero = new OracleBoolean (0);
bool value;
bool notNull;
#endregion // Fields
#region Constructors
public OracleBoolean (bool value)
{
this.value = value;
notNull = true;
}
public OracleBoolean (int value)
: this (value != 0)
{
}
#endregion // Constructors
#region Properties
public bool IsFalse {
get { return (!IsNull && !value); }
}
public bool IsNull {
get { return !notNull; }
}
public bool IsTrue {
get { return (!IsNull && value); }
}
public bool Value {
get { return IsTrue; }
}
#endregion // Properties
#region Methods
public static OracleBoolean And (OracleBoolean x, OracleBoolean y)
{
if (x.IsNull || y.IsNull)
return OracleBoolean.Null;
return new OracleBoolean (x.Value && y.Value);
}
[MonoTODO]
public int CompareTo (object obj)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override bool Equals (object value)
{
throw new NotImplementedException ();
}
public static OracleBoolean Equals (OracleBoolean x, OracleBoolean y)
{
if (x.IsNull || y.IsNull)
return OracleBoolean.Null;
return new OracleBoolean (x.Value == y.Value);
}
[MonoTODO]
public override int GetHashCode ()
{
throw new NotImplementedException ();
}
public static OracleBoolean NotEquals (OracleBoolean x, OracleBoolean y)
{
if (x.IsNull || y.IsNull)
return OracleBoolean.Null;
return new OracleBoolean (x.Value != y.Value);
}
public static OracleBoolean OnesComplement (OracleBoolean x)
{
if (x.IsNull)
return OracleBoolean.Null;
return new OracleBoolean (!x.Value);
}
public static OracleBoolean Or (OracleBoolean x, OracleBoolean y)
{
if (x.IsNull || y.IsNull)
return OracleBoolean.Null;
return new OracleBoolean (x.Value || y.Value);
}
[MonoTODO]
public static OracleBoolean Parse (string s)
{
throw new NotImplementedException ();
}
public override string ToString ()
{
if (IsNull)
return "Null";
if (IsTrue)
return "True";
return "False";
}
public static OracleBoolean Xor (OracleBoolean x, OracleBoolean y)
{
if (x.IsNull || y.IsNull)
return OracleBoolean.Null;
return new OracleBoolean (x.Value ^ y.Value);
}
#endregion // Methods
#region Operators and Type Conversions
public static OracleBoolean operator & (OracleBoolean x, OracleBoolean y)
{
return And (x, y);
}
public static OracleBoolean operator | (OracleBoolean x, OracleBoolean y)
{
return Or (x, y);
}
public static OracleBoolean operator == (OracleBoolean x, OracleBoolean y)
{
return Equals (x, y);
}
public static OracleBoolean operator ^ (OracleBoolean x, OracleBoolean y)
{
return Xor (x, y);
}
public static bool operator false (OracleBoolean x)
{
return x.IsFalse;
}
public static OracleBoolean operator != (OracleBoolean x, OracleBoolean y)
{
return NotEquals (x, y);
}
public static OracleBoolean operator ! (OracleBoolean x)
{
return OnesComplement (x);
}
public static OracleBoolean operator ~ (OracleBoolean x)
{
return OnesComplement (x);
}
public static bool operator true (OracleBoolean x)
{
return x.IsTrue;
}
public static explicit operator bool (OracleBoolean x)
{
if (x.IsNull)
throw new NullReferenceException ();
return x.Value;
}
public static explicit operator OracleBoolean (OracleNumber x)
{
return new OracleBoolean ((int) x);
}
public static explicit operator OracleBoolean (string x)
{
return OracleBoolean.Parse (x);
}
public static implicit operator OracleBoolean (bool x)
{
return new OracleBoolean (x);
}
#endregion // Operators and Type Conversions
}
}
| |
//
// DocumentTest.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System.Collections.Generic;
using Couchbase.Lite;
using NUnit.Framework;
using Sharpen;
using Couchbase.Lite.Internal;
namespace Couchbase.Lite
{
public class DocumentTest : LiteTestCase
{
[Test] // #447
public void TestDocumentArraysMaintainOrder()
{
List<int> dateArray = new List<int> { 2015, 6, 14, 1, 10, 0 };
var props = new Dictionary<string, object> {
{ "starttime", dateArray }
};
var doc = database.CreateDocument();
var docId = doc.Id;
doc.PutProperties(props);
var doc2 = database.GetExistingDocument(docId);
Assert.AreEqual(dateArray, doc2.UserProperties["starttime"].AsList<int>());
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[Test]
public void TestNewDocumentHasCurrentRevision() {
var document = database.CreateDocument();
var properties = new Dictionary<string, object>()
{
{"foo", "foo"},
{"bar", false}
};
document.PutProperties(properties);
Assert.IsNotNull(document.CurrentRevisionId);
Assert.IsNotNull(document.CurrentRevision);
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[Test]
public void TestGetNonExistentDocument() {
Assert.IsNull(database.GetExistingDocument("missing"));
var doc = database.GetDocument("missing");
Assert.IsNotNull(doc);
Assert.IsNull(database.GetExistingDocument("missing"));
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[Test]
public void TestUnsavedDocumentReturnsNullValues()
{
var document = database.CreateDocument();
try
{
Assert.IsNull(document.Properties);
Assert.IsNull(document.CurrentRevisionId);
Assert.IsNull(document.CurrentRevision);
Assert.IsNull(document.RevisionHistory);
Assert.IsNull(document.GetRevision("doc2"));
}
catch
{
Assert.Fail("Document getter threw an exception");
}
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[Test]
public void TestSavedDocumentHasCurrentRevision()
{
var document = database.CreateDocument();
var properties = new Dictionary<string, object>();
properties["foo"] = "foo";
properties["bar"] = false;
document.PutProperties(properties);
Assert.IsNotNull(document.CurrentRevisionId);
Assert.IsNotNull(document.CurrentRevision);
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[Test]
public void TestPutDeletedDocument()
{
Document document = database.CreateDocument();
var properties = new Dictionary<string, object>();
properties["foo"] = "foo";
properties["bar"] = false;
document.PutProperties(properties);
Assert.IsNotNull(document.CurrentRevision);
var docId = document.Id;
properties["_rev"] = document.CurrentRevisionId;
properties["_deleted"] = true;
properties["mykey"] = "myval";
var newRev = document.PutProperties(properties);
newRev.LoadProperties();
Assert.IsTrue(newRev.Properties.ContainsKey("mykey"));
Assert.IsTrue(document.Deleted);
var featchedDoc = database.GetExistingDocument(docId);
Assert.IsNull(featchedDoc);
var queryAllDocs = database.CreateAllDocumentsQuery();
var queryEnumerator = queryAllDocs.Run();
foreach(QueryRow row in queryEnumerator)
{
Assert.AreNotEqual(row.Document.Id, docId);
}
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[Test]
public void TestDeleteDocument()
{
var document = database.CreateDocument();
var properties = new Dictionary<string, object>();
properties["foo"] = "foo";
properties["bar"] = false;
document.PutProperties(properties);
Assert.IsNotNull(document.CurrentRevision);
var docId = document.Id;
document.Delete();
Assert.IsTrue(document.Deleted);
Document fetchedDoc = database.GetExistingDocument(docId);
Assert.IsNull(fetchedDoc);
// query all docs and make sure we don't see that document
database.GetAllDocs(new QueryOptions());
Query queryAllDocs = database.CreateAllDocumentsQuery();
QueryEnumerator queryEnumerator = queryAllDocs.Run();
for (IEnumerator<QueryRow> it = queryEnumerator; it.MoveNext();)
{
QueryRow row = it.Current;
Assert.IsFalse(row.Document.Id.Equals(docId));
}
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[Test]
public void TestDocumentWithRemovedProperty() {
var props = new Dictionary<string, object>()
{
{"_id", "fakeid"},
{"_removed", true},
{"foo", "bar"}
};
var doc = CreateDocumentWithProperties(database, props);
Assert.IsNotNull(doc);
var docFetched = database.GetDocument(doc.Id);
var fetchedProps = docFetched.CurrentRevision.Properties;
Assert.IsNotNull(fetchedProps["_removed"]);
Assert.IsTrue(docFetched.CurrentRevision.IsGone);
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[Test]
public void TestLoadRevisionBody()
{
var document = database.CreateDocument();
var properties = new Dictionary<string, object>();
properties["foo"] = "foo";
properties["bar"] = false;
properties["_id"] = document.Id;
document.PutProperties(properties);
properties["_rev"] = document.CurrentRevisionId;
Assert.IsNotNull(document.CurrentRevision);
var revisionInternal = new RevisionInternal(
document.Id, document.CurrentRevisionId, false);
database.LoadRevisionBody(revisionInternal);
Assert.AreEqual(properties, revisionInternal.GetProperties());
revisionInternal.SetBody(null);
// now lets purge the document, and then try to load the revision body again
document.Purge();
var gotExpectedException = false;
try {
database.LoadRevisionBody(revisionInternal);
} catch (CouchbaseLiteException e) {
gotExpectedException |=
e.CBLStatus.Code == StatusCode.NotFound;
}
Assert.IsTrue(gotExpectedException);
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Globalization;
#if NET_3_0 || REMOTING
using System.Runtime.Serialization;
using System.ComponentModel;
#endif
namespace ProtoBuf
{
/// <summary>
/// Provides protocol-buffer serialization capability for concrete, attributed types.
/// </summary>
/// <remarks>
/// Protocol-buffer serialization is a compact binary format, designed to take
/// advantage of sparse data and knowledge of specific data types; it is also
/// extensible, allowing a type to be deserialized / merged even if some data is
/// not recognised.
/// </remarks>
public static partial class Serializer
{
const string OBSOLETE_MESSAGE_PREFIX_STYLE = "Please specify a PrefixStyle; existing code should use Base128 to retain wire-compatibility.";
internal static void VerifyBytesWritten(int expected, int actual)
{
if (actual != expected)
{
throw new ProtoException(string.Format(
"Wrote {0} bytes, but expected to write {1}.", actual, expected));
}
}
internal static readonly Type[] EmptyTypes = new Type[0];
internal static bool IsEntityType(Type type)
{
return Entity.IsEntity(type);
}
/// <summary>
/// Supports various different property metadata patterns:
/// [ProtoMember] is the most specific, allowing the data-format to be set.
/// [DataMember], [XmlElement] are supported for compatibility.
/// In any event, there must be a unique positive Tag/Order.
/// </summary>
internal static bool TryGetTag(MemberInfo member, out int tag, out string name, out DataFormat format, out MemberSerializationOptions options)
{
return TryGetTag(member, out tag, out name, false, out format, out options);
}
internal static IEnumerable<MemberInfo> GetProtoMembers(Type type)
{
foreach(MemberInfo member in type.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
switch(member.MemberType) {
case MemberTypes.Property:
case MemberTypes.Field:
yield return member;
break;
}
}
}
static void AddImplicitByDeclaringType<T>(Type declaringType, List<MemberInfo> list, T[] members)
where T : MemberInfo
{
int tag;
string name;
DataFormat fmt;
MemberSerializationOptions options;
foreach(T member in members)
{
if(member.DeclaringType == declaringType
&& member.GetCustomAttributes(typeof(XmlIgnoreAttribute), false).Length == 0
&& TryGetTag(member, out tag, out name, true, out fmt, out options) && tag < 1) list.Add(member);
}
}
internal const string DataMemberAttributeFullName = "System.Runtime.Serialization.DataMemberAttribute";
internal const string DataContractAttributeFullName = "System.Runtime.Serialization.DataContractAttribute";
internal static bool TryGetTag(MemberInfo member, out int tag, out string name, bool callerIsTagInference, out DataFormat format, out MemberSerializationOptions options)
{
name = member.Name;
format = DataFormat.Default;
tag = -1;
options = MemberSerializationOptions.None;
// check for delegates (don't even try!)
Type valueType;
switch(member.MemberType)
{
case MemberTypes.Property:
valueType = ((PropertyInfo)member).PropertyType;
break;
case MemberTypes.Field:
valueType = ((FieldInfo) member).FieldType;
break;
default: // not sure what this is!
return false;
}
if (valueType.IsSubclassOf(typeof(Delegate))) return false;
// check for exclusion
if(AttributeUtils.GetAttribute<ProtoIgnoreAttribute>(member) != null
|| AttributeUtils.GetAttribute<ProtoPartialIgnoreAttribute>(member.ReflectedType,
delegate( ProtoPartialIgnoreAttribute ppia)
{ return ppia.MemberName == member.Name; }) != null) return false;
// check against the property
ProtoMemberAttribute pm = AttributeUtils.GetAttribute<ProtoMemberAttribute>(member);
if (pm == null)
{ // check also against the type
pm = AttributeUtils.GetAttribute<ProtoPartialMemberAttribute>(member.ReflectedType,
delegate(ProtoPartialMemberAttribute ppma) { return ppma.MemberName == member.Name; });
}
if (pm != null)
{
format = pm.DataFormat;
if (!string.IsNullOrEmpty(pm.Name)) name = pm.Name;
tag = pm.Tag;
options = pm.Options;
return tag > 0;
}
ProtoContractAttribute pca = AttributeUtils.GetAttribute<ProtoContractAttribute>(member.DeclaringType);
if(pca != null && pca.ImplicitFields != ImplicitFields.None)
{
#if !SILVERLIGHT
// skip [NonSerialized]
if(AttributeUtils.GetAttribute<NonSerializedAttribute>(member) != null) return false;
#endif
if(callerIsTagInference) return true; // short-circuit
List<MemberInfo> members = new List<MemberInfo>();
switch(pca.ImplicitFields)
{
case ImplicitFields.AllFields:
AddImplicitByDeclaringType(member.DeclaringType, members,
member.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic));
break;
case ImplicitFields.AllPublic:
AddImplicitByDeclaringType(member.DeclaringType, members,
member.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.Public));
AddImplicitByDeclaringType(member.DeclaringType, members,
member.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Public));
break;
default:
throw new NotSupportedException("Unknown ImplicitFields option: " + pca.ImplicitFields);
}
members.Sort(delegate (MemberInfo x, MemberInfo y)
{
return string.CompareOrdinal(x.Name, y.Name);
});
int index = members.IndexOf(member);
if(index >= 0)
{
tag = index + pca.ImplicitFirstTag;
return true;
}
return false;
}
#if NET_3_0
DataMemberAttribute dm = AttributeUtils.GetAttribute<DataMemberAttribute>(member);
#else
Attribute dm = AttributeUtils.GetAttribute(member, DataMemberAttributeFullName);
#endif
if (dm != null)
{
string dmName;
int dmOrder;
bool dmIsRequired;
ParseDataMemberAttribute(dm, out dmName, out dmOrder, out dmIsRequired);
if (!string.IsNullOrEmpty(dmName)) name = dmName;
tag = dmOrder;
if (pca != null) tag += pca.DataMemberOffset;
if(!callerIsTagInference) // avoid infinite recursion
{
if (pca != null && pca.InferTagFromName)
{
// since the type has inference enabled, identify the members for the
// type and give each an order based on the Order and Name, then find
// where the current property comes in the list. This will be repeated
// once (or more) per property during initialization, but not during
// core runtime - so it is not a perfomance bottleneck (so not worth
// complicating the implementation by caching it anywhere).
// find all properties under consideration
List<KeyValuePair<string, int>> members = new List<KeyValuePair<string,int>>();
string tmpName; // use this also to cache the "out" name (not usable from lambda)
foreach(MemberInfo prop in GetProtoMembers(member.DeclaringType))
{
int tmpTag;
DataFormat tmpFormat;
MemberSerializationOptions tmpOptions;
if (TryGetTag(prop, out tmpTag, out tmpName, true, out tmpFormat, out tmpOptions))
{
members.Add(new KeyValuePair<string,int>(tmpName, tmpTag));
}
}
// sort by "Order, Name", where "Name" includes any renaming (i.e. not MemberInfo.Name)
members.Sort(delegate(KeyValuePair<string, int> x, KeyValuePair<string, int> y)
{
int result = x.Value.CompareTo(y.Value);
if (result == 0) result = string.CompareOrdinal(x.Key, y.Key);
return result;
});
// find the current item
// (can't use FindIndex because of Silverlight)
tmpName = name;
int index = 1;
tag = 0;
foreach (KeyValuePair<string, int> x in members)
{
if (x.Key == tmpName)
{
tag = index;
break;
}
index++;
}
}
}
if(dmIsRequired) options |= MemberSerializationOptions.Required;
return callerIsTagInference || tag > 0;
}
XmlElementAttribute xe = AttributeUtils.GetAttribute<XmlElementAttribute>(member);
if (xe != null)
{
if (!string.IsNullOrEmpty(xe.ElementName)) name = xe.ElementName;
tag = xe.Order;
return tag > 0;
}
XmlArrayAttribute xa = AttributeUtils.GetAttribute<XmlArrayAttribute>(member);
if (xa != null)
{
if (!string.IsNullOrEmpty(xa.ElementName)) name = xa.ElementName;
tag = xa.Order;
return tag > 0;
}
return false;
}
internal static void ParseDataContractAttribute(
Attribute attribute, out string name)
{
if (attribute == null) throw new ArgumentNullException("attribute");
#if NET_3_0
name = ((DataContractAttribute)attribute).Name;
#else
name = AttributeUtils.GetValue<string>(attribute, "Name");
#endif
}
internal static void ParseDataMemberAttribute (
#if NET_3_0
DataMemberAttribute attribute,
#else
Attribute attribute,
#endif
out string name, out int order, out bool isRequired)
{
if(attribute == null) throw new ArgumentNullException("attribute");
#if NET_3_0
name = attribute.Name;
order = attribute.Order;
isRequired = attribute.IsRequired;
#else
name = AttributeUtils.GetValue<string>(attribute, "Name");
order = AttributeUtils.GetValue<int>(attribute, "Order");
isRequired = AttributeUtils.GetValue<bool>(attribute,"IsRequired");
#endif
}
/// <summary>
/// Creates a new instance from a protocol-buffer stream
/// </summary>
/// <typeparam name="T">The type to be created.</typeparam>
/// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
/// <returns>A new, initialized instance.</returns>
public static T Deserialize<T>(Stream source)
{
return Deserialize<T>(new SerializationContext(source, null));
}
private static T Deserialize<T>(SerializationContext source)
{
T instance = default(T);
try
{
SerializerProxy<T>.Default.Deserialize(ref instance, source);
}
catch (Exception ex)
{
ThrowInner(ex);
throw; // if no inner (preserves stacktrace)
}
return instance;
}
/// <summary>
/// Creates a new instance from a protocol-buffer stream that has a length-prefix
/// on data (to assist with network IO).
/// </summary>
/// <typeparam name="T">The type to be created.</typeparam>
/// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
/// <returns>A new, initialized instance.</returns>
[Obsolete(OBSOLETE_MESSAGE_PREFIX_STYLE, false)]
#if !SILVERLIGHT && !CF
[EditorBrowsable(EditorBrowsableState.Never)]
#endif
public static T DeserializeWithLengthPrefix<T>(Stream source)
{
return DeserializeWithLengthPrefix<T>(source, PrefixStyle.Base128);
}
/// <summary>
/// The implicit tag used when serializing lists and other enumerable data.
/// </summary>
public const int ListItemTag = 1;
/// <summary>
/// Reads a sequence of consecutive length-prefixed items from a stream, using
/// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
/// are directly comparable to serializing multiple items in succession
/// (use the <see cref="ListItemTag"/> tag to emulate the implicit behavior
/// when serializing a list/array). When a tag is
/// specified, any records with different tags are silently omitted. The
/// tag is ignored. The tag is ignores for fixed-length prefixes.
/// </summary>
/// <typeparam name="T">The type of object to deserialize.</typeparam>
/// <param name="source">The binary stream containing the serialized records.</param>
/// <param name="style">The prefix style used in the data.</param>
/// <param name="tag">The tag of records to return (if non-positive, then no tag is
/// expected and all records are returned).</param>
/// <returns>The sequence of deserialized objects.</returns>
public static IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int tag)
{
if (source == null) throw new ArgumentNullException("source");
switch (style)
{
case PrefixStyle.Fixed32:
if (tag > 0) throw new ArgumentException("A tag cannot be used with fixed-length prefixes.", "tag");
break;
case PrefixStyle.Base128:
break;
default:
throw new ArgumentException("Prefix style is not valid: " + style, "style");
}
return DeserializeItemsWithLengthPrefixChecked<T>(source, style, tag);
}
private static IEnumerable<T> DeserializeItemsWithLengthPrefixChecked<T>(Stream source, PrefixStyle style, int tag)
{
SerializationContext ctx = new SerializationContext(source, null);
T item;
while(TryDeserializeWithLengthPrefix(ctx, style, tag, out item))
{
yield return item;
}
}
private static uint ReadPrefixLength(Stream source, PrefixStyle style)
{
uint value;
if(!TryReadPrefixLength(source, style, 0, out value, null))
{
throw new EndOfStreamException();
}
return value;
}
private static bool TryReadPrefixLength(SerializationContext context, PrefixStyle style, int tag, out uint length)
{
MethodStart:
switch (style)
{
case PrefixStyle.None:
length = uint.MaxValue;
return true;
case PrefixStyle.Base128:
if (tag <= 0) return context.TryDecodeUInt32(out length);
uint expected = GetFieldToken(tag, WireType.String), actual;
if (!context.TryDecodeUInt32(out actual))
{
length = 0;
return false;
}
if (expected == actual)
{
length = context.DecodeUInt32();
return true;
}
WireType wireType;
int actualTag;
ParseFieldToken(actual, out wireType, out actualTag);
SkipData(context, actualTag, wireType);
goto MethodStart;
case PrefixStyle.Fixed32:
return context.TryDecodeUInt32Fixed(out length);
default:
throw new NotSupportedException("Invalid prefix style: " + style);
}
}
private static bool TryReadPrefixLength(Stream source, PrefixStyle style, int tag, out uint length, Getter<int,bool> processField)
{
MethodStart:
switch (style)
{
case PrefixStyle.None:
length = uint.MaxValue;
return true;
case PrefixStyle.Base128:
if(tag <= 0) return SerializationContext.TryDecodeUInt32(source, out length);
uint expected = GetFieldToken(tag, WireType.String), actual;
if(!SerializationContext.TryDecodeUInt32(source, out actual))
{
length = 0;
return false;
}
WireType wireType;
int actualTag;
ParseFieldToken(actual, out wireType, out actualTag);
if (processField != null)
{
if (processField(actualTag))
{
length = SerializationContext.DecodeUInt32(source);
return true;
}
}
else if(expected == actual)
{
length = SerializationContext.DecodeUInt32(source);
return true;
}
switch(wireType)
{
case WireType.String:
SerializationContext.SkipStringData(source);
goto MethodStart;
default:
throw new ProtoException("A record with a different tag could not be jumped because of the wire-type: " + wireType);
}
case PrefixStyle.Fixed32:
return SerializationContext.TryDecodeUInt32Fixed(source, out length);
default:
throw new NotSupportedException("Invalid prefix style: " + style);
}
}
/// <summary>
/// Creates a new instance from a protocol-buffer stream that has a length-prefix
/// on data (to assist with network IO).
/// </summary>
/// <typeparam name="T">The type to be created.</typeparam>
/// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <returns>A new, initialized instance.</returns>
public static T DeserializeWithLengthPrefix<T>(Stream source, PrefixStyle style)
{
return DeserializeWithLengthPrefix<T>(source, style, 0);
}
/// <summary>
/// Creates a new instance from a protocol-buffer stream that has a length-prefix
/// on data (to assist with network IO).
/// </summary>
/// <typeparam name="T">The type to be created.</typeparam>
/// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="tag">The expected tag of the item (only used with base-128 prefix style).</param>
/// <returns>A new, initialized instance.</returns>
public static T DeserializeWithLengthPrefix<T>(Stream source, PrefixStyle style, int tag)
{
T item;
if(!TryDeserializeWithLengthPrefix(source, style, tag, out item))
{
throw new EndOfStreamException();
}
return item;
}
private static bool TryDeserializeWithLengthPrefix<T>(SerializationContext context, PrefixStyle style, int tag, out T item)
{
uint len;
if (!TryReadPrefixLength(context, style, tag, out len))
{
item = default(T);
return false;
}
item = default(T);
switch(len)
{
case 0: // nothing to do
break;
case uint.MaxValue: // read to end
SerializerProxy<T>.Default.Deserialize(ref item, context);
break;
default: // limit and read sub-stream
long restore = context.Limit(len);
SerializerProxy<T>.Default.Deserialize(ref item, context);
context.MaxReadPosition = restore;
break;
}
return true;
}
/// <summary>Indicates the number of bytes expected for the next message.</summary>
/// <param name="source">The stream containing the data to investigate for a length.</param>
/// <param name="style">The algorithm used to encode the length.</param>
/// <param name="length">The length of the message, if it could be identified.</param>
/// <returns>True if a length could be obtained, false otherwise.</returns>
public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length)
{
uint len;
bool result;
switch (style)
{
case PrefixStyle.Fixed32:
result = SerializationContext.TryDecodeUInt32Fixed(source, out len);
break;
case PrefixStyle.Base128:
result = SerializationContext.TryDecodeUInt32(source, out len);
break;
default:
throw new ArgumentOutOfRangeException("style", "Invalid prefix style: " + style);
}
length = (int)len;
return result;
}
/// <summary>Indicates the number of bytes expected for the next message.</summary>
/// <param name="buffer">The buffer containing the data to investigate for a length.</param>
/// <param name="index">The offset of the first byte to read from the buffer.</param>
/// <param name="count">The number of bytes to read from the buffer.</param>
/// <param name="style">The algorithm used to encode the length.</param>
/// <param name="length">The length of the message, if it could be identified.</param>
/// <returns>True if a length could be obtained, false otherwise.</returns>
public static bool TryReadLengthPrefix(byte[] buffer, int index, int count, PrefixStyle style, out int length)
{
using (Stream source = new MemoryStream(buffer, index, count))
{
return TryReadLengthPrefix(source, style, out length);
}
}
private static bool TryDeserializeWithLengthPrefix<T>(Stream source, PrefixStyle style, int tag, out T item)
{
uint len;
if(!TryReadPrefixLength(source, style, tag, out len, null))
{
item = default(T);
return false;
}
if (len == uint.MaxValue)
{
item = Deserialize<T>(source);
}
else
{
using (SubStream subStream = new SubStream(source, len, false))
{
item = Deserialize<T>(subStream);
}
}
return true;
}
internal static Exception ThrowNoEncoder(DataFormat format, Type valueType)
{
throw new InvalidOperationException(string.Format(
"No suitable {0} {1} encoding found.",
format, valueType.Name));
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public static T Merge<T>(Stream source, T instance)
{
try
{
SerializerProxy<T>.Default.Deserialize(ref instance, source);
return instance;
}
catch (Exception ex)
{
ThrowInner(ex);
throw; // if no inner (preserves stacktrace)
}
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance, using length-prefixed
/// data - useful with network IO.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
[Obsolete(OBSOLETE_MESSAGE_PREFIX_STYLE, false)]
#if !SILVERLIGHT && !CF
[EditorBrowsable(EditorBrowsableState.Never)]
#endif
public static T MergeWithLengthPrefix<T>(Stream source, T instance)
{
return MergeWithLengthPrefix<T>(source, instance, PrefixStyle.Base128);
}
/// <summary>
/// Applies a protocol-buffer stream to an existing instance, using length-prefixed
/// data - useful with network IO.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (can be null).</param>
/// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <returns>The updated instance; this may be different to the instance argument if
/// either the original instance was null, or the stream defines a known sub-type of the
/// original instance.</returns>
public static T MergeWithLengthPrefix<T>(Stream source, T instance, PrefixStyle style)
{
uint len = ReadPrefixLength(source, style);
if (len == uint.MaxValue) return Merge<T>(source, instance);
using (SubStream subStream = new SubStream(source, len, false))
{
return Merge<T>(subStream, instance);
}
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="destination">The destination stream to write to.</param>
public static void Serialize<T>(Stream destination, T instance)
{
try
{
SerializerProxy<T>.Default.Serialize(instance, destination);
}
catch (Exception ex)
{
ThrowInner(ex);
throw; // if no inner (preserves stacktrace)
}
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream,
/// with a length-prefix. This is useful for socket programming,
/// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
/// from an ongoing stream.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="destination">The destination stream to write to.</param>
[Obsolete(OBSOLETE_MESSAGE_PREFIX_STYLE, false)]
#if !SILVERLIGHT && !CF
[EditorBrowsable(EditorBrowsableState.Never)]
#endif
public static void SerializeWithLengthPrefix<T>(Stream destination, T instance)
{
SerializeWithLengthPrefix<T>(destination, instance, PrefixStyle.Base128, 0);
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream,
/// with a length-prefix. This is useful for socket programming,
/// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
/// from an ongoing stream.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="destination">The destination stream to write to.</param>
public static void SerializeWithLengthPrefix<T>(Stream destination, T instance, PrefixStyle style)
{
SerializeWithLengthPrefix<T>(destination, instance, style, 0);
}
internal static uint GetFieldToken(int tag, WireType wireType)
{
return (uint)((tag << 3) | ((int)wireType));
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied stream,
/// with a length-prefix. This is useful for socket programming,
/// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
/// from an ongoing stream.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="style">How to encode the length prefix.</param>
/// <param name="destination">The destination stream to write to.</param>
/// <param name="tag">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
public static void SerializeWithLengthPrefix<T>(Stream destination, T instance, PrefixStyle style, int tag)
{
if(style == PrefixStyle.None)
{
Serialize<T>(destination, instance);
return;
}
using (MemoryStream ms = new MemoryStream())
{
Serialize<T>(ms, instance);
byte[] tmp = new byte[20];
int len;
switch(style)
{
case PrefixStyle.Base128:
len = 0;
if(tag > 0)
{
uint prefix = GetFieldToken(tag, WireType.String);
len += SerializationContext.EncodeUInt32(prefix, tmp, 0);
}
len += SerializationContext.EncodeUInt32((uint)ms.Length, tmp, len);
break;
case PrefixStyle.Fixed32:
SerializationContext.EncodeUInt32Fixed((uint)ms.Length, tmp, 0);
len = 4;
break;
default:
throw new NotSupportedException("Invalid prefix style: " + style);
}
destination.Write(tmp, 0, len);
destination.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
destination.Flush();
}
private const string ProtoBinaryField = "proto";
#if REMOTING
/// <summary>
/// Creates a new IFormatter that uses protocol-buffer [de]serialization.
/// </summary>
/// <typeparam name="T">The type of object to be [de]deserialized by the formatter.</typeparam>
/// <returns>A new IFormatter to be used during [de]serialization.</returns>
public static IFormatter CreateFormatter<T>()
{
return new Formatter<T>();
}
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="info">The destination SerializationInfo to write to.</param>
public static void Serialize<T>(SerializationInfo info, T instance) where T : class, ISerializable
{
// note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization)
if (info == null) throw new ArgumentNullException("info");
if (instance == null) throw new ArgumentNullException("instance");
if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance");
using (MemoryStream ms = new MemoryStream())
{
Serialize<T>(ms, instance);
info.AddValue(ProtoBinaryField, ms.ToArray());
//string s = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
//info.AddValue(ProtoBinaryField, s);
}
}
/// <summary>
/// Applies a protocol-buffer from a SerializationInfo to an existing instance.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (cannot be null).</param>
/// <param name="info">The SerializationInfo containing the data to apply to the instance (cannot be null).</param>
public static void Merge<T>(SerializationInfo info, T instance) where T : class, ISerializable
{
// note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization)
if (info == null) throw new ArgumentNullException("info");
if (instance == null) throw new ArgumentNullException("instance");
if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance");
//string s = info.GetString(ProtoBinaryField);
//using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(s)))
byte[] buffer = (byte[])info.GetValue(ProtoBinaryField, typeof(byte[]));
using (MemoryStream ms = new MemoryStream(buffer))
{
T result = Merge<T>(ms, instance);
if(!ReferenceEquals(result,instance))
{
throw new ProtoException("Deserialization changed the instance; cannot succeed.");
}
}
}
#endif
/// <summary>
/// Writes a protocol-buffer representation of the given instance to the supplied XmlWriter.
/// </summary>
/// <typeparam name="T">The type being serialized.</typeparam>
/// <param name="instance">The existing instance to be serialized (cannot be null).</param>
/// <param name="writer">The destination XmlWriter to write to.</param>
public static void Serialize<T>(System.Xml.XmlWriter writer, T instance) where T : IXmlSerializable
{
if (writer == null) throw new ArgumentNullException("writer");
if (instance == null) throw new ArgumentNullException("instance");
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, instance);
writer.WriteBase64(ms.GetBuffer(), 0, (int)ms.Length);
}
}
/// <summary>
/// Applies a protocol-buffer from an XmlReader to an existing instance.
/// </summary>
/// <typeparam name="T">The type being merged.</typeparam>
/// <param name="instance">The existing instance to be modified (cannot be null).</param>
/// <param name="reader">The XmlReader containing the data to apply to the instance (cannot be null).</param>
public static void Merge<T>(System.Xml.XmlReader reader, T instance) where T : IXmlSerializable
{
if (reader == null) throw new ArgumentNullException("reader");
if (instance == null) throw new ArgumentNullException("instance");
const int LEN = 4096;
byte[] buffer = new byte[LEN];
int read;
using (MemoryStream ms = new MemoryStream())
{
while ((read = reader.ReadElementContentAsBase64(buffer, 0, LEN)) > 0)
{
ms.Write(buffer, 0, read);
}
ms.Position = 0;
Serializer.Merge(ms, instance);
}
}
/// <summary>
/// Create a deep clone of the supplied instance; any sub-items are also cloned.
/// </summary>
/// <typeparam name="T">The type being cloned.</typeparam>
/// <param name="instance">The existing instance to be cloned.</param>
/// <returns>A new copy, cloned from the supplied instance.</returns>
public static T DeepClone<T>(T instance)
{
return ChangeType<T, T>(instance);
}
/// <summary>
/// Serializes a given instance and deserializes it as a different type;
/// this can be used to translate between wire-compatible objects (where
/// two .NET types represent the same data), or to promote/demote a type
/// through an inheritance hierarchy.
/// </summary>
/// <remarks>No assumption of compatibility is made between the types.</remarks>
/// <typeparam name="TOldType">The type of the object being copied.</typeparam>
/// <typeparam name="TNewType">The type of the new object to be created.</typeparam>
/// <param name="instance">The existing instance to use as a template.</param>
/// <returns>A new instane of type TNewType, with the data from TOldType.</returns>
public static TNewType ChangeType<TOldType, TNewType>(TOldType instance)
{
return ChangeType<TOldType, TNewType>(instance, null);
}
/// <summary>
/// As per the public ChangeType, but allows for workspace-sharing to reduce buffer overhead.
/// </summary>
internal static TNewType ChangeType<TOldType, TNewType>(TOldType instance, SerializationContext context)
{
if (instance == null)
{
return default(TNewType); // GIGO
}
using (MemoryStream ms = new MemoryStream())
{
SerializationContext tmpCtx = new SerializationContext(ms, context);
Serialize<TOldType>(ms, instance);
tmpCtx.Flush();
ms.Position = 0;
TNewType result = Deserialize<TNewType>(ms);
if (context != null)
{
context.ReadFrom(tmpCtx);
}
return result;
}
}
#if !CF
/// <summary>
/// Suggest a .proto definition for the given type
/// </summary>
/// <typeparam name="T">The type to generate a .proto definition for</typeparam>
/// <returns>The .proto definition as a string</returns>
public static string GetProto<T>() where T : class
{
try
{
return Serializer<T>.GetProto();
}
catch (Exception ex)
{
ThrowInner(ex);
throw; // if no inner (preserves stacktrace)
}
}
#endif
static void ThrowInner(Exception exception)
{
if (exception != null && exception.InnerException != null)
{
if (exception is TargetInvocationException
#if !CF
|| exception is TypeInitializationException
#endif
)
{
ThrowInner(exception.InnerException);
throw exception.InnerException;
}
}
}
internal static string GetDefinedTypeName<T>()
{
Entity e = Entity.Get(typeof(T));
return e == null ? typeof(T).Name : e.Name;
}
internal static int GetPrefixLength(int tag)
{
if ((tag & ~0x0000000F) == 0) return 1; // 4 bits
if ((tag & ~0x000007FF) == 0) return 2; // 11 bits
if ((tag & ~0x0003FFFF) == 0) return 3; // 18 bits
if ((tag & ~0x01FFFFFF) == 0) return 4; // 25 bits
return 5;
}
internal static void ParseFieldToken(uint token, out WireType wireType, out int tag)
{
wireType = (WireType)(token & 7);
tag = (int)(token >> 3);
if (tag <= 0)
{
throw new ProtoException("Invalid tag: " + tag.ToString());
}
}
internal static void SkipData(SerializationContext context, int fieldTag, WireType wireType)
{
switch (wireType)
{
case WireType.Variant:
context.ReadRawVariant();
break;
case WireType.Fixed32:
context.ReadBlock(4);
break;
case WireType.Fixed64:
context.ReadBlock(8);
break;
case WireType.String:
int len = context.DecodeInt32();
context.WriteTo(Stream.Null, len);
break;
case WireType.EndGroup:
throw new ProtoException("End-group not expected at this location");
case WireType.StartGroup:
context.StartGroup(fieldTag); // will be ended internally
Serializer<UnknownType>.Build();
UnknownType ut = UnknownType.Default;
Serializer<UnknownType>.Deserialize<UnknownType>(ref ut, context);
break;
default:
throw new ProtoException("Unknown wire-type " + wireType.ToString());
}
}
internal static int WriteFieldToken(int tag, WireType wireType, SerializationContext context)
{
uint prefix = GetFieldToken(tag, wireType);
return context.EncodeUInt32(prefix);
}
internal struct ProtoEnumValue<TEnum>
{
private readonly TEnum enumValue;
private readonly int wireValue;
private readonly string name;
public TEnum EnumValue { get { return enumValue; } }
public int WireValue { get { return wireValue; } }
public string Name { get { return name; } }
public ProtoEnumValue(TEnum enumValue, int wireValue, string name)
{
this.enumValue = enumValue;
this.wireValue = wireValue;
this.name = name;
}
}
internal static IEnumerable<ProtoEnumValue<TEnum>> GetEnumValues<TEnum>()
{
List<ProtoEnumValue<TEnum>> list = new List<ProtoEnumValue<TEnum>>();
foreach (FieldInfo enumField in typeof(TEnum).GetFields(BindingFlags.Static | BindingFlags.Public))
{
if (!enumField.IsLiteral)
{
continue;
}
TEnum key = (TEnum)enumField.GetValue(null);
ProtoEnumAttribute ea = AttributeUtils.GetAttribute<ProtoEnumAttribute>(enumField);
int value;
string name = (ea == null || string.IsNullOrEmpty(ea.Name)) ? enumField.Name : ea.Name;
if (ea == null || !ea.HasValue())
{
value = (int)Convert.ChangeType(key, typeof(int), CultureInfo.InvariantCulture);
}
else
{
value = (int)ea.Value;
}
list.Add(new ProtoEnumValue<TEnum>(key, value, name));
}
list.Sort(delegate(ProtoEnumValue<TEnum> x, ProtoEnumValue<TEnum> y)
{
return x.WireValue.CompareTo(y.WireValue);
});
return list;
}
/// <summary>
/// Ensures that the serialization algorithm has been prepared for
/// the given type; this can be useful in highly threaded code to
/// ensure that all types are ready ahead of time, avoiding deadlock
/// scenarios.
/// </summary>
/// <typeparam name="T">The object type to prepare.</typeparam>
public static void PrepareSerializer<T>() where T : class
{
Serializer<T>.Build();
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
using PCSComUtils.Framework.ReportFrame.DS;
using PCSComUtils.Framework.TableFrame.DS;
namespace PCSComUtils.Framework.ReportFrame.BO
{
public class ReportParameterBO
{
private const string THIS = "PCSComUtils.Framework.ReportFrame.BO.ReportParameterBO";
public ReportParameterBO()
{
}
//**************************************************************************
/// <Description>
/// This method checks business rule and call Add() method of DS class
/// </Description>
/// <Inputs>
/// Value object
/// </Inputs>
/// <Outputs>
/// N/A
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
sys_ReportParaDS templateDS = new sys_ReportParaDS();
templateDS.Add(pobjObjectVO);
}
//**************************************************************************
/// <Description>
/// This method not implements yet
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID,string VOclass)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME,new Exception());
}
//**************************************************************************
/// <Description>
/// This method not implements yet
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(object pObjectVO)
{
sys_ReportParaDS templateDS = new sys_ReportParaDS();
templateDS.Delete(((sys_ReportParaVO)pObjectVO).ReportID, ((sys_ReportParaVO)pObjectVO).ParaName);
}
//**************************************************************************
/// <Description>
/// This method checks business rule and call Delete() method of DS class
/// </Description>
/// <Inputs>
/// pintID
/// </Inputs>
/// <Outputs>
/// Delete a record from Database
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
sys_ReportParaDS templateDS = new sys_ReportParaDS();
templateDS.Delete(pintID);
}
//**************************************************************************
/// <Description>
/// This method uses to get data
/// </Description>
/// <Inputs>
/// pintID
/// </Inputs>
/// <Outputs>
/// Value object
/// </Outputs>
/// <Returns>
/// object
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(string pstrReportID, string pstrParaName)
{
sys_ReportParaDS dsReportPara = new sys_ReportParaDS();
return dsReportPara.GetObjectVO(pstrReportID, pstrParaName);
}
//**************************************************************************
/// <Description>
/// This method uses to update data
/// </Description>
/// <Inputs>
/// pobjObjecVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
sys_ReportParaDS templateDS = new sys_ReportParaDS();
templateDS.Update(pobjObjecVO);
}
//**************************************************************************
/// <Description>
/// This method uses to update data
/// </Description>
/// <Inputs>
/// pobjObjecVO, Old para name
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 09-Jan-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO, string pstrParaName)
{
sys_ReportParaDS templateDS = new sys_ReportParaDS();
templateDS.Update(pobjObjecVO, pstrParaName);
}
//**************************************************************************
/// <Description>
/// This method uses to get all data
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
///
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
sys_ReportParaDS templateDS = new sys_ReportParaDS();
return templateDS.List();
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
/// N/A
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
sys_ReportParaDS templateDS = new sys_ReportParaDS();
templateDS.UpdateDataSet(pData);
}
//**************************************************************************
/// <Description>
/// This method uses to get all para of specified report
/// </Description>
/// <Inputs>
/// ReportID
/// </Inputs>
/// <Outputs>
/// List of parameter
/// </Outputs>
/// <Returns>
/// ArrayList
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 05-Jan-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public ArrayList ListByReport(string pstrReportID)
{
sys_ReportParaDS dsReportPara = new sys_ReportParaDS();
return dsReportPara.GetObjectVOs(pstrReportID);
}
//**************************************************************************
/// <Description>
/// This method uses to change up order of a row in sys_ReportPara
/// </Description>
/// <Inputs>
/// ReportID, ParaName
/// </Inputs>
/// <Outputs>
/// changes
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// Created: 05-Jan-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public bool MoveUp(string pstrReportID, string pstrParaName)
{
bool blnResult = false;
sys_ReportParaDS dsReportPara = new sys_ReportParaDS();
sys_ReportParaVO voPreviousPara = new sys_ReportParaVO();
// get current para order
sys_ReportParaVO voCurrentPara = (sys_ReportParaVO)dsReportPara.GetObjectVO(pstrReportID, pstrParaName);
// if current parameter reached the top of order - 1, then cannot move
if (voCurrentPara.ParaOrder <= 1)
{
blnResult = false;
}
else
{
// get next para order
int intNextOrder = dsReportPara.GetNextOrder(pstrReportID, voCurrentPara.ParaOrder, MoveDirection.Up);
// change order
voPreviousPara.ParaOrder = voCurrentPara.ParaOrder;
voCurrentPara.ParaOrder = intNextOrder;
// update two rows in database
dsReportPara.Update(voPreviousPara);
dsReportPara.Update(voCurrentPara);
// return value
blnResult = true;
}
return blnResult;
}
//**************************************************************************
/// <Description>
/// This method uses to change down order of a row in sys_ReportPara
/// </Description>
/// <Inputs>
/// ReportID, ParaName
/// </Inputs>
/// <Outputs>
/// changes
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// Created: 05-Jan-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public bool MoveDown(string pstrReportID, string pstrParaName)
{
bool blnResult = false;
sys_ReportParaDS dsReportPara = new sys_ReportParaDS();
sys_ReportParaVO voNextPara = new sys_ReportParaVO();
// get current para order
sys_ReportParaVO voCurrentPara = (sys_ReportParaVO)dsReportPara.GetObjectVO(pstrReportID, pstrParaName);
// get max order
int intMaxOrder = dsReportPara.GetMaxOrder(pstrReportID);
// if current parameter reached the bottom, then cannot move down
if (voCurrentPara.ParaOrder == intMaxOrder)
{
blnResult = false;
}
else
{
// get next para order
int intNextOrder = dsReportPara.GetNextOrder(pstrReportID, voCurrentPara.ParaOrder, MoveDirection.Down);
// change order
voNextPara.ParaOrder = voCurrentPara.ParaOrder;
voCurrentPara.ParaOrder = intNextOrder;
// update two rows in database
dsReportPara.Update(voNextPara);
dsReportPara.Update(voCurrentPara);
// return value
blnResult = true;
}
return blnResult;
}
//**************************************************************************
/// <Description>
/// This method uses to get max para order of specified report
/// </Description>
/// <Inputs>
/// ReportID
/// </Inputs>
/// <Outputs>
/// Max order
/// </Outputs>
/// <Returns>
/// int
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// Created: 09-Jan-2005
/// </History>
/// <Notes>
/// Change output from ArrayList to DataSet
/// </Notes>
//**************************************************************************
public int GetMaxParaOrder(string pstrReportID)
{
sys_ReportParaDS dsReportPara = new sys_ReportParaDS();
return dsReportPara.GetMaxOrder(pstrReportID);
}
//**************************************************************************
/// <Description>
/// This method uses to get all table
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// Created: 05-Jan-2005
/// Modified: 08-Jan-2005
/// </History>
/// <Notes>
/// Change output from ArrayList to DataSet
/// </Notes>
//**************************************************************************
public DataSet GetAllTables()
{
sys_TableDS dsTable = new sys_TableDS();
return dsTable.GetAllTables();
}
//**************************************************************************
/// <Description>
/// Return the list of Fields from database
/// </Description>
/// <Inputs>
/// Null
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 07-Jan-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet getFieldList(int pintTableID)
{
sys_TableFieldDS objTableFieldDS = new sys_TableFieldDS();
return objTableFieldDS.List(pintTableID);
}
/// <summary>
/// Switch two params order
/// </summary>
/// <param name="pobjSourceParameter">Source Parameter</param>
/// <param name="pobjDestParameter">Destination Parameter</param>
public void SwitchParameters(object pobjSourceParameter, object pobjDestParameter)
{
sys_ReportParaDS dsReportParameter = new sys_ReportParaDS();
dsReportParameter.Update(pobjSourceParameter);
dsReportParameter.Update(pobjDestParameter);
}
}
}
| |
// Copyright (c) 2006, ComponentAce
// http://www.componentace.com
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ComponentAce 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.
/*
Copyright (c) 2001 Lapo Luchini.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS
OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
using ComponentAce.Compression.Libs.zlib;
using System;
namespace zlib
{
public class ZOutputStream:System.IO.Stream
{
private void InitBlock()
{
flush_Renamed_Field = zlibConst.Z_NO_FLUSH;
buf = new byte[bufsize];
}
virtual public int FlushMode
{
get
{
return (flush_Renamed_Field);
}
set
{
this.flush_Renamed_Field = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get
{
return z.total_in;
}
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get
{
return z.total_out;
}
}
protected internal ZStream z = new ZStream();
protected internal int bufsize = 512;
protected internal int flush_Renamed_Field;
protected internal byte[] buf, buf1 = new byte[1];
protected internal bool compress;
private System.IO.Stream out_Renamed;
public ZOutputStream(System.IO.Stream out_Renamed):base()
{
InitBlock();
this.out_Renamed = out_Renamed;
z.inflateInit();
compress = false;
}
public ZOutputStream(System.IO.Stream out_Renamed, int level):base()
{
InitBlock();
this.out_Renamed = out_Renamed;
z.deflateInit(level);
compress = true;
}
public void WriteByte(int b)
{
buf1[0] = (byte) b;
Write(buf1, 0, 1);
}
//UPGRADE_TODO: The differences in the Expected value of parameters for method 'WriteByte' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092_3"'
public override void WriteByte(byte b)
{
WriteByte((int) b);
}
public override void Write(System.Byte[] b1, int off, int len)
{
if (len == 0)
return ;
int err;
byte[] b = new byte[b1.Length];
System.Array.Copy(b1,b,b1.Length);
z.next_in = b;
z.next_in_index = off;
z.avail_in = len;
do
{
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress)
err = z.deflate(flush_Renamed_Field);
else
err = z.inflate(flush_Renamed_Field);
//if (err != zlibConst.Z_OK)
// throw new ZStreamException((compress?"de":"in") + "flating: " + z.msg);
out_Renamed.Write(buf, 0, bufsize - z.avail_out);
}
while (z.avail_in > 0 || z.avail_out == 0);
}
public virtual void finish()
{
int err;
do
{
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress)
{
err = z.deflate(zlibConst.Z_FINISH);
}
else
{
err = z.inflate(zlibConst.Z_FINISH);
}
if (err != zlibConst.Z_STREAM_END && err != zlibConst.Z_OK)
throw new ZStreamException((compress?"de":"in") + "flating: " + z.msg);
if (bufsize - z.avail_out > 0)
{
out_Renamed.Write(buf, 0, bufsize - z.avail_out);
}
}
while (z.avail_in > 0 || z.avail_out == 0);
try
{
Flush();
}
catch
{
}
}
public virtual void end()
{
if (compress)
{
z.deflateEnd();
}
else
{
z.inflateEnd();
}
z.free();
z = null;
}
public override void Close()
{
try
{
try
{
finish();
}
catch
{
}
}
finally
{
end();
out_Renamed.Close();
out_Renamed = null;
}
}
public override void Flush()
{
out_Renamed.Flush();
}
//UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
{
return 0;
}
//UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override void SetLength(System.Int64 value)
{
}
//UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin)
{
return 0;
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override System.Boolean CanRead
{
get
{
return false;
}
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override System.Boolean CanSeek
{
get
{
return false;
}
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override System.Boolean CanWrite
{
get
{
return false;
}
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override System.Int64 Length
{
get
{
return 0;
}
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override System.Int64 Position
{
get
{
return 0;
}
set
{
}
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// IntegratedUserInfoList
/// </summary>
[DataContract]
public partial class IntegratedUserInfoList : IEquatable<IntegratedUserInfoList>, IValidatableObject
{
public IntegratedUserInfoList()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="IntegratedUserInfoList" /> class.
/// </summary>
/// <param name="AllUsersSelected">AllUsersSelected.</param>
/// <param name="EndPosition">The last position in the result set. .</param>
/// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param>
/// <param name="PreviousUri">The postal code for the billing address..</param>
/// <param name="ResultSetSize">The number of results returned in this response. .</param>
/// <param name="StartPosition">Starting position of the current result set..</param>
/// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
/// <param name="Users">Users.</param>
public IntegratedUserInfoList(string AllUsersSelected = default(string), string EndPosition = default(string), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string), List<UserInfo> Users = default(List<UserInfo>))
{
this.AllUsersSelected = AllUsersSelected;
this.EndPosition = EndPosition;
this.NextUri = NextUri;
this.PreviousUri = PreviousUri;
this.ResultSetSize = ResultSetSize;
this.StartPosition = StartPosition;
this.TotalSetSize = TotalSetSize;
this.Users = Users;
}
/// <summary>
/// Gets or Sets AllUsersSelected
/// </summary>
[DataMember(Name="allUsersSelected", EmitDefaultValue=false)]
public string AllUsersSelected { get; set; }
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set. </value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response. </value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { get; set; }
/// <summary>
/// Gets or Sets Users
/// </summary>
[DataMember(Name="users", EmitDefaultValue=false)]
public List<UserInfo> Users { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class IntegratedUserInfoList {\n");
sb.Append(" AllUsersSelected: ").Append(AllUsersSelected).Append("\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n");
sb.Append(" Users: ").Append(Users).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as IntegratedUserInfoList);
}
/// <summary>
/// Returns true if IntegratedUserInfoList instances are equal
/// </summary>
/// <param name="other">Instance of IntegratedUserInfoList to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(IntegratedUserInfoList other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AllUsersSelected == other.AllUsersSelected ||
this.AllUsersSelected != null &&
this.AllUsersSelected.Equals(other.AllUsersSelected)
) &&
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
) &&
(
this.Users == other.Users ||
this.Users != null &&
this.Users.SequenceEqual(other.Users)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.AllUsersSelected != null)
hash = hash * 59 + this.AllUsersSelected.GetHashCode();
if (this.EndPosition != null)
hash = hash * 59 + this.EndPosition.GetHashCode();
if (this.NextUri != null)
hash = hash * 59 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 59 + this.PreviousUri.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 59 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 59 + this.TotalSetSize.GetHashCode();
if (this.Users != null)
hash = hash * 59 + this.Users.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.ADF.CATIDs;
using System.Runtime.InteropServices;
namespace GETransformCSharp
{
[Guid("4E927ADF-0368-4d6e-8473-86022A719E13")]
public class GETransform_Scale: IGraphicAttributes, IGeometricEffect, IPersistVariant, IEditInteraction
{
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
ArcGISCategoryRegistration(registerType);
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
ArcGISCategoryUnregistration(registerType);
}
#endregion
#region Component Category Registration
static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = String.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
GeometricEffect.Register(regKey);
}
static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = String.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
GeometricEffect.Unregister(regKey);
}
#endregion
double m_dFactorX;
double m_dFactorY;
bool m_bDone;
IGeometry m_pGeom;
ITransform2D m_pTransform;
IClone m_pCloneGeom;
IGeometry m_pGeomCopy;
IPoint m_pCenterPoint;
public GETransform_Scale()
{
m_dFactorX = 1;
m_dFactorY = 1;
m_pCenterPoint = new Point();
}
#region IGraphicAttributes Members
string IGraphicAttributes.ClassName
{
get {return "Transform Scale";}
}
int IGraphicAttributes.GraphicAttributeCount
{
get { return 2; }
}
int IGraphicAttributes.get_ID(int attrIndex)
{
if (attrIndex < 2)
{
return attrIndex;
}
return -1;
}
int IGraphicAttributes.get_IDByName(string Name)
{
if (Name == "X Transform Scale") {
return 0;
}
if (Name == "Y Transform Scale") {
return 1;
}
return -1;
}
string IGraphicAttributes.get_Name(int attrId)
{
if (attrId == 0) {return "X Transform Scale";}
if (attrId == 1) {return "Y Transform Scale";}
return "";
}
IGraphicAttributeType IGraphicAttributes.get_Type(int attrId)
{
if (attrId == 0)
{
return new GraphicAttributeSizeType();
}
if (attrId == 1)
{
return new GraphicAttributeSizeType();
}
return null;
}
object IGraphicAttributes.get_Value(int attrId)
{
if (attrId == 0)
{
return m_dFactorX;
}
if (attrId == 1)
{
return m_dFactorY;
}
return null;
}
void IGraphicAttributes.set_Value(int attrId, object val)
{
if (attrId == 0)
{
m_dFactorX = (double)val;
}
if (attrId == 1)
{
m_dFactorY = (double)val;
}
}
#endregion
#region IGeometricEffect Members
IGeometry IGeometricEffect.NextGeometry()
{
if (m_bDone)
{
return null;
}
else
{
m_pCloneGeom = (IClone)m_pGeom;
m_pGeomCopy = (IGeometry)m_pCloneGeom.Clone();
m_pTransform = (ITransform2D)m_pGeomCopy;
m_pTransform.Scale(m_pCenterPoint, m_dFactorX, m_dFactorY);
m_bDone = true;
return m_pGeomCopy;
}
}
void IGeometricEffect.Reset(IGeometry Geometry)
{
m_pGeom = Geometry;
m_pGeomCopy = null;
double dXCenter;
double dYCenter;
dXCenter = (m_pGeom.Envelope.XMin + m_pGeom.Envelope.XMax) / 2;
dYCenter = (m_pGeom.Envelope.YMin + m_pGeom.Envelope.YMax) / 2;
m_pCenterPoint.PutCoords(dXCenter, dYCenter);
m_pCenterPoint.SpatialReference = m_pGeom.SpatialReference;
m_bDone = false;
}
esriGeometryType IGeometricEffect.get_OutputType(esriGeometryType inputType)
{
if (inputType == esriGeometryType.esriGeometryPolygon)
{
return inputType;
}
if (inputType == esriGeometryType.esriGeometryPolyline)
{
return inputType;
}
return esriGeometryType.esriGeometryNull;
}
#endregion
#region IPersistVariant Members
UID IPersistVariant.ID
{
get
{
UID pUID;
pUID = new UID();
pUID.Value = "{4E927ADF-0368-4d6e-8473-86022A719E13}";
return pUID;
}
}
void IPersistVariant.Load(IVariantStream Stream)
{
int version;
version = (int)Stream.Read();
m_dFactorX = (double)Stream.Read();
m_dFactorY = (double)Stream.Read();
}
void IPersistVariant.Save(IVariantStream Stream)
{
int version;
version = 1;
Stream.Write(version);
Stream.Write(m_dFactorX);
Stream.Write(m_dFactorY);
}
#endregion
#region IEditInteraction Members
void IEditInteraction.ModifyAttributes(object editParams, object attrArray)
{
IResizeInteraction pResize;
pResize = editParams as IResizeInteraction;
short[] a = (short[])attrArray;
if (!(pResize == null))
{
if (Convert.ToBoolean(a[0]))
{
m_dFactorX = m_dFactorX * pResize.RatioX;
}
if (Convert.ToBoolean(a[1]))
{
m_dFactorY = m_dFactorY * pResize.RatioY;
}
}
}
bool IEditInteraction.get_IsEditableAttribute(object editParams, int attrIndex)
{
IResizeInteraction pResize;
pResize = editParams as IResizeInteraction;
if (!(pResize == null))
{
if (attrIndex == 0 | attrIndex == 1)
{
return true;
}
}
return false;
}
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
/// <summary>
/// This editor helper class makes it easy to create and show a context menu.
/// It ensures that it's possible to add multiple items with the same name.
/// </summary>
public static class NGUIContextMenu
{
[MenuItem("Help/NGUI Documentation (v.3.6.6)")]
static void ShowHelp0 (MenuCommand command) { NGUIHelp.Show(); }
[MenuItem("Help/NGUI Support Forum")]
static void ShowHelp01 (MenuCommand command) { Application.OpenURL("http://www.tasharen.com/forum/index.php?board=1.0"); }
[MenuItem("CONTEXT/UIWidget/Copy Widget")]
static void CopyStyle (MenuCommand command) { NGUISettings.CopyWidget(command.context as UIWidget); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Values")]
static void PasteStyle (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, true); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Style")]
static void PasteStyle2 (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, false); }
[MenuItem("CONTEXT/UIWidget/Help")]
static void ShowHelp1 (MenuCommand command) { NGUIHelp.Show(command.context); }
[MenuItem("CONTEXT/UIButton/Help")]
static void ShowHelp2 (MenuCommand command) { NGUIHelp.Show(typeof(UIButton)); }
[MenuItem("CONTEXT/UIToggle/Help")]
static void ShowHelp3 (MenuCommand command) { NGUIHelp.Show(typeof(UIToggle)); }
[MenuItem("CONTEXT/UIRoot/Help")]
static void ShowHelp4 (MenuCommand command) { NGUIHelp.Show(typeof(UIRoot)); }
[MenuItem("CONTEXT/UICamera/Help")]
static void ShowHelp5 (MenuCommand command) { NGUIHelp.Show(typeof(UICamera)); }
[MenuItem("CONTEXT/UIAnchor/Help")]
static void ShowHelp6 (MenuCommand command) { NGUIHelp.Show(typeof(UIAnchor)); }
[MenuItem("CONTEXT/UIStretch/Help")]
static void ShowHelp7 (MenuCommand command) { NGUIHelp.Show(typeof(UIStretch)); }
[MenuItem("CONTEXT/UISlider/Help")]
static void ShowHelp8 (MenuCommand command) { NGUIHelp.Show(typeof(UISlider)); }
[MenuItem("CONTEXT/UI2DSprite/Help")]
static void ShowHelp9 (MenuCommand command) { NGUIHelp.Show(typeof(UI2DSprite)); }
[MenuItem("CONTEXT/UIScrollBar/Help")]
static void ShowHelp10 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollBar)); }
[MenuItem("CONTEXT/UIProgressBar/Help")]
static void ShowHelp11 (MenuCommand command) { NGUIHelp.Show(typeof(UIProgressBar)); }
[MenuItem("CONTEXT/UIPopupList/Help")]
static void ShowHelp12 (MenuCommand command) { NGUIHelp.Show(typeof(UIPopupList)); }
[MenuItem("CONTEXT/UIInput/Help")]
static void ShowHelp13 (MenuCommand command) { NGUIHelp.Show(typeof(UIInput)); }
[MenuItem("CONTEXT/UIKeyBinding/Help")]
static void ShowHelp14 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyBinding)); }
[MenuItem("CONTEXT/UIGrid/Help")]
static void ShowHelp15 (MenuCommand command) { NGUIHelp.Show(typeof(UIGrid)); }
[MenuItem("CONTEXT/UITable/Help")]
static void ShowHelp16 (MenuCommand command) { NGUIHelp.Show(typeof(UITable)); }
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp17 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayTween)); }
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp18 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIPlaySound/Help")]
static void ShowHelp19 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlaySound)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
static void ShowHelp20 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp21 (MenuCommand command) { NGUIHelp.Show(typeof(UIDragScrollView)); }
[MenuItem("CONTEXT/UICenterOnChild/Help")]
static void ShowHelp22 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnChild)); }
[MenuItem("CONTEXT/UICenterOnClick/Help")]
static void ShowHelp23 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnClick)); }
[MenuItem("CONTEXT/UITweener/Help")]
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp24 (MenuCommand command) { NGUIHelp.Show(typeof(UITweener)); }
[MenuItem("CONTEXT/ActiveAnimation/Help")]
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp25 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp26 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIPanel/Help")]
static void ShowHelp27 (MenuCommand command) { NGUIHelp.Show(typeof(UIPanel)); }
[MenuItem("CONTEXT/UILocalize/Help")]
static void ShowHelp28 (MenuCommand command) { NGUIHelp.Show(typeof(UILocalize)); }
[MenuItem("CONTEXT/Localization/Help")]
static void ShowHelp29 (MenuCommand command) { NGUIHelp.Show(typeof(Localization)); }
[MenuItem("CONTEXT/UIKeyNavigation/Help")]
static void ShowHelp30 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyNavigation)); }
[MenuItem("CONTEXT/PropertyBinding/Help")]
static void ShowHelp31 (MenuCommand command) { NGUIHelp.Show(typeof(PropertyBinding)); }
public delegate UIWidget AddFunc (GameObject go);
static BetterList<string> mEntries = new BetterList<string>();
static GenericMenu mMenu;
/// <summary>
/// Clear the context menu list.
/// </summary>
static public void Clear ()
{
mEntries.Clear();
mMenu = null;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddItem (string item, bool isChecked, GenericMenu.MenuFunction2 callback, object param)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.size; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, callback, param);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddChild (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeGameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddChildWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.size; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddChild, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddSibling (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeTransform.parent.gameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddSiblingWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.size; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddSibling, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Add commonly NGUI context menu options.
/// </summary>
static public void AddCommonItems (GameObject target)
{
if (target != null)
{
UIWidget widget = target.GetComponent<UIWidget>();
string myName = string.Format("Selected {0}", (widget != null) ? NGUITools.GetTypeName(widget) : "Object");
AddItem(myName + "/Bring to Front", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.BringForward(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Push to Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.PushBack(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Nudge Forward", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], 1);
},
null);
AddItem(myName + "/Nudge Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], -1);
},
null);
if (widget != null)
{
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Make Pixel-Perfect", false, OnMakePixelPerfect, Selection.activeTransform);
if (target.GetComponent<BoxCollider>() != null)
{
AddItem(myName + "/Reset Collider Size", false, OnBoxCollider, target);
}
}
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Delete", false, OnDelete, target);
NGUIContextMenu.AddSeparator("");
if (Selection.activeTransform.parent != null && widget != null)
{
AddChildWidget("Create/Sprite/Child", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label/Child", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget/Child", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture/Child", false, NGUISettings.AddTexture);
AddChildWidget("Create/Unity 2D Sprite/Child", false, NGUISettings.Add2DSprite);
AddSiblingWidget("Create/Sprite/Sibling", false, NGUISettings.AddSprite);
AddSiblingWidget("Create/Label/Sibling", false, NGUISettings.AddLabel);
AddSiblingWidget("Create/Invisible Widget/Sibling", false, NGUISettings.AddWidget);
AddSiblingWidget("Create/Simple Texture/Sibling", false, NGUISettings.AddTexture);
AddSiblingWidget("Create/Unity 2D Sprite/Sibling", false, NGUISettings.Add2DSprite);
}
else
{
AddChildWidget("Create/Sprite", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture", false, NGUISettings.AddTexture);
AddChildWidget("Create/Unity 2D Sprite", false, NGUISettings.Add2DSprite);
}
NGUIContextMenu.AddSeparator("Create/");
AddItem("Create/Panel", false, AddPanel, target);
AddItem("Create/Scroll View", false, AddScrollView, target);
AddItem("Create/Grid", false, AddChild<UIGrid>, target);
AddItem("Create/Table", false, AddChild<UITable>, target);
AddItem("Create/Anchor (Legacy)", false, AddChild<UIAnchor>, target);
if (target.GetComponent<UIPanel>() != null)
{
if (target.GetComponent<UIScrollView>() == null)
{
AddItem("Attach/Scroll View", false, Attach, typeof(UIScrollView));
NGUIContextMenu.AddSeparator("Attach/");
}
}
else if (target.collider == null && target.GetComponent<Collider2D>() == null)
{
AddItem("Attach/Box Collider", false, AttachCollider, null);
NGUIContextMenu.AddSeparator("Attach/");
}
bool header = false;
UIScrollView scrollView = NGUITools.FindInParents<UIScrollView>(target);
if (scrollView != null)
{
if (scrollView.GetComponentInChildren<UICenterOnChild>() == null)
{
AddItem("Attach/Center Scroll View on Child", false, Attach, typeof(UICenterOnChild));
header = true;
}
}
if (target.collider != null || target.GetComponent<Collider2D>() != null)
{
if (scrollView != null)
{
if (target.GetComponent<UIDragScrollView>() == null)
{
AddItem("Attach/Drag Scroll View", false, Attach, typeof(UIDragScrollView));
header = true;
}
if (target.GetComponent<UICenterOnClick>() == null && NGUITools.FindInParents<UICenterOnChild>(target) != null)
{
AddItem("Attach/Center Scroll View on Click", false, Attach, typeof(UICenterOnClick));
header = true;
}
}
if (header) NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Button Script", false, Attach, typeof(UIButton));
AddItem("Attach/Toggle Script", false, Attach, typeof(UIToggle));
AddItem("Attach/Slider Script", false, Attach, typeof(UISlider));
AddItem("Attach/Scroll Bar Script", false, Attach, typeof(UIScrollBar));
AddItem("Attach/Progress Bar Script", false, Attach, typeof(UISlider));
AddItem("Attach/Popup List Script", false, Attach, typeof(UIPopupList));
AddItem("Attach/Input Field Script", false, Attach, typeof(UIInput));
NGUIContextMenu.AddSeparator("Attach/");
if (target.GetComponent<UIDragResize>() == null)
AddItem("Attach/Drag Resize Script", false, Attach, typeof(UIDragResize));
if (target.GetComponent<UIDragScrollView>() == null)
{
for (int i = 0; i < UIPanel.list.size; ++i)
{
UIPanel pan = UIPanel.list[i];
if (pan.clipping == UIDrawCall.Clipping.None) continue;
UIScrollView dr = pan.GetComponent<UIScrollView>();
if (dr == null) continue;
AddItem("Attach/Drag Scroll View", false, delegate(object obj)
{ target.AddComponent<UIDragScrollView>().scrollView = dr; }, null);
header = true;
break;
}
}
AddItem("Attach/Key Binding Script", false, Attach, typeof(UIKeyBinding));
if (target.GetComponent<UIKeyNavigation>() == null)
AddItem("Attach/Key Navigation Script", false, Attach, typeof(UIKeyNavigation));
NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Play Tween Script", false, Attach, typeof(UIPlayTween));
AddItem("Attach/Play Animation Script", false, Attach, typeof(UIPlayAnimation));
AddItem("Attach/Play Sound Script", false, Attach, typeof(UIPlaySound));
}
AddItem("Attach/Property Binding", false, Attach, typeof(PropertyBinding));
if (target.GetComponent<UILocalize>() == null)
AddItem("Attach/Localization Script", false, Attach, typeof(UILocalize));
if (widget != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
AddMissingItem<TweenColor>(target, "Tween/Color");
AddMissingItem<TweenWidth>(target, "Tween/Width");
AddMissingItem<TweenHeight>(target, "Tween/Height");
}
else if (target.GetComponent<UIPanel>() != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
}
NGUIContextMenu.AddSeparator("Tween/");
AddMissingItem<TweenPosition>(target, "Tween/Position");
AddMissingItem<TweenRotation>(target, "Tween/Rotation");
AddMissingItem<TweenScale>(target, "Tween/Scale");
AddMissingItem<TweenTransform>(target, "Tween/Transform");
if (target.GetComponent<AudioSource>() != null)
AddMissingItem<TweenVolume>(target, "Tween/Volume");
if (target.GetComponent<Camera>() != null)
{
AddMissingItem<TweenFOV>(target, "Tween/Field of View");
AddMissingItem<TweenOrthoSize>(target, "Tween/Orthographic Size");
}
}
}
/// <summary>
/// Helper function that adds a widget collider to the specified object.
/// </summary>
static void AttachCollider (object obj)
{
if (Selection.activeGameObject != null)
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AddWidgetCollider(Selection.gameObjects[i]);
}
/// <summary>
/// Helper function that adds the specified type to all selected game objects. Used with the menu options above.
/// </summary>
static void Attach (object obj)
{
if (Selection.activeGameObject == null) return;
System.Type type = (System.Type)obj;
for (int i = 0; i < Selection.gameObjects.Length; ++i)
{
GameObject go = Selection.gameObjects[i];
if (go.GetComponent(type) != null) continue;
#if !UNITY_3_5
Component cmp = go.AddComponent(type);
Undo.RegisterCreatedObjectUndo(cmp, "Attach " + type);
#endif
}
}
/// <summary>
/// Helper function.
/// </summary>
static void AddMissingItem<T> (GameObject target, string name) where T : MonoBehaviour
{
if (target.GetComponent<T>() == null)
AddItem(name, false, Attach, typeof(T));
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddChild<T> (object obj) where T : MonoBehaviour
{
GameObject go = obj as GameObject;
T t = NGUITools.AddChild<T>(go);
Selection.activeGameObject = t.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddPanel (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddScrollView (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
panel.clipping = UIDrawCall.Clipping.SoftClip;
panel.gameObject.AddComponent<UIScrollView>();
panel.name = "Scroll View";
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Add help options based on the components present on the specified game object.
/// </summary>
static public void AddHelp (GameObject go, bool addSeparator)
{
MonoBehaviour[] comps = Selection.activeGameObject.GetComponents<MonoBehaviour>();
bool addedSomething = false;
for (int i = 0; i < comps.Length; ++i)
{
System.Type type = comps[i].GetType();
string url = NGUIHelp.GetHelpURL(type);
if (url != null)
{
if (addSeparator)
{
addSeparator = false;
AddSeparator("");
}
AddItem("Help/" + type, false, delegate(object obj) { Application.OpenURL(url); }, null);
addedSomething = true;
}
}
if (addedSomething) AddSeparator("Help/");
AddItem("Help/All Topics", false, delegate(object obj) { NGUIHelp.Show(); }, null);
}
static void OnHelp (object obj) { NGUIHelp.Show(obj); }
static void OnMakePixelPerfect (object obj) { NGUITools.MakePixelPerfect(obj as Transform); }
static void OnBoxCollider (object obj) { NGUITools.AddWidgetCollider(obj as GameObject); }
static void OnDelete (object obj)
{
GameObject go = obj as GameObject;
Selection.activeGameObject = go.transform.parent.gameObject;
Undo.DestroyObjectImmediate(go);
}
/// <summary>
/// Add a new disabled context menu entry.
/// </summary>
static public void AddDisabledItem (string item)
{
if (mMenu == null) mMenu = new GenericMenu();
mMenu.AddDisabledItem(new GUIContent(item));
}
/// <summary>
/// Add a separator to the menu.
/// </summary>
static public void AddSeparator (string path)
{
if (mMenu == null) mMenu = new GenericMenu();
// For some weird reason adding separators on OSX causes the entire menu to be disabled. Wtf?
if (Application.platform != RuntimePlatform.OSXEditor)
mMenu.AddSeparator(path);
}
/// <summary>
/// Show the context menu with all the added items.
/// </summary>
static public void Show ()
{
if (mMenu != null)
{
mMenu.ShowAsContext();
mMenu = null;
mEntries.Clear();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Lucene.Net.Index;
using Lucene.Net.Support;
using IndexReader = Lucene.Net.Index.IndexReader;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
using Query = Lucene.Net.Search.Query;
namespace Lucene.Net.Search.Spans
{
/// <summary>Removes matches which overlap with another SpanQuery. </summary>
//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
public class SpanNotQuery:SpanQuery, System.ICloneable
{
private class AnonymousClassSpans : Spans
{
public AnonymousClassSpans(Lucene.Net.Index.IndexReader reader, SpanNotQuery enclosingInstance)
{
InitBlock(reader, enclosingInstance);
}
private void InitBlock(Lucene.Net.Index.IndexReader reader, SpanNotQuery enclosingInstance)
{
this.reader = reader;
this.enclosingInstance = enclosingInstance;
includeSpans = Enclosing_Instance.include.GetSpans(reader);
excludeSpans = Enclosing_Instance.exclude.GetSpans(reader);
moreExclude = excludeSpans.Next();
}
private Lucene.Net.Index.IndexReader reader;
private SpanNotQuery enclosingInstance;
public SpanNotQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private Spans includeSpans;
private bool moreInclude = true;
private Spans excludeSpans;
private bool moreExclude;
public override bool Next()
{
if (moreInclude)
// move to next include
moreInclude = includeSpans.Next();
while (moreInclude && moreExclude)
{
if (includeSpans.Doc() > excludeSpans.Doc())
// skip exclude
moreExclude = excludeSpans.SkipTo(includeSpans.Doc());
while (moreExclude && includeSpans.Doc() == excludeSpans.Doc() && excludeSpans.End() <= includeSpans.Start())
{
moreExclude = excludeSpans.Next(); // increment exclude
}
if (!moreExclude || includeSpans.Doc() != excludeSpans.Doc() || includeSpans.End() <= excludeSpans.Start())
break; // we found a match
moreInclude = includeSpans.Next(); // intersected: keep scanning
}
return moreInclude;
}
public override bool SkipTo(int target)
{
if (moreInclude)
// skip include
moreInclude = includeSpans.SkipTo(target);
if (!moreInclude)
return false;
if (moreExclude && includeSpans.Doc() > excludeSpans.Doc())
moreExclude = excludeSpans.SkipTo(includeSpans.Doc());
while (moreExclude && includeSpans.Doc() == excludeSpans.Doc() && excludeSpans.End() <= includeSpans.Start())
{
moreExclude = excludeSpans.Next(); // increment exclude
}
if (!moreExclude || includeSpans.Doc() != excludeSpans.Doc() || includeSpans.End() <= excludeSpans.Start())
return true; // we found a match
return Next(); // scan to next match
}
public override int Doc()
{
return includeSpans.Doc();
}
public override int Start()
{
return includeSpans.Start();
}
public override int End()
{
return includeSpans.End();
}
// TODO: Remove warning after API has been finalizedb
public override ICollection<byte[]> GetPayload()
{
System.Collections.Generic.ICollection<byte[]> result = null;
if (includeSpans.IsPayloadAvailable())
{
result = includeSpans.GetPayload();
}
return result;
}
// TODO: Remove warning after API has been finalized
public override bool IsPayloadAvailable()
{
return includeSpans.IsPayloadAvailable();
}
public override System.String ToString()
{
return "spans(" + Enclosing_Instance.ToString() + ")";
}
}
private SpanQuery include;
private SpanQuery exclude;
/// <summary>Construct a SpanNotQuery matching spans from <c>include</c> which
/// have no overlap with spans from <c>exclude</c>.
/// </summary>
public SpanNotQuery(SpanQuery include, SpanQuery exclude)
{
this.include = include;
this.exclude = exclude;
if (!include.Field.Equals(exclude.Field))
throw new System.ArgumentException("Clauses must have same field.");
}
/// <summary>Return the SpanQuery whose matches are filtered. </summary>
public virtual SpanQuery Include
{
get { return include; }
}
/// <summary>Return the SpanQuery whose matches must not overlap those returned. </summary>
public virtual SpanQuery Exclude
{
get { return exclude; }
}
public override string Field
{
get { return include.Field; }
}
public override void ExtractTerms(System.Collections.Generic.ISet<Term> terms)
{
include.ExtractTerms(terms);
}
public override System.String ToString(System.String field)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
buffer.Append("spanNot(");
buffer.Append(include.ToString(field));
buffer.Append(", ");
buffer.Append(exclude.ToString(field));
buffer.Append(")");
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override System.Object Clone()
{
SpanNotQuery spanNotQuery = new SpanNotQuery((SpanQuery) include.Clone(), (SpanQuery) exclude.Clone());
spanNotQuery.Boost = Boost;
return spanNotQuery;
}
public override Spans GetSpans(IndexReader reader)
{
return new AnonymousClassSpans(reader, this);
}
public override Query Rewrite(IndexReader reader)
{
SpanNotQuery clone = null;
SpanQuery rewrittenInclude = (SpanQuery) include.Rewrite(reader);
if (rewrittenInclude != include)
{
clone = (SpanNotQuery) this.Clone();
clone.include = rewrittenInclude;
}
SpanQuery rewrittenExclude = (SpanQuery) exclude.Rewrite(reader);
if (rewrittenExclude != exclude)
{
if (clone == null)
clone = (SpanNotQuery) this.Clone();
clone.exclude = rewrittenExclude;
}
if (clone != null)
{
return clone; // some clauses rewrote
}
else
{
return this; // no clauses rewrote
}
}
/// <summary>Returns true iff <c>o</c> is equal to this. </summary>
public override bool Equals(System.Object o)
{
if (this == o)
return true;
if (!(o is SpanNotQuery))
return false;
SpanNotQuery other = (SpanNotQuery) o;
return this.include.Equals(other.include) && this.exclude.Equals(other.exclude) && this.Boost == other.Boost;
}
public override int GetHashCode()
{
int h = include.GetHashCode();
h = (h << 1) | (Number.URShift(h, 31)); // rotate left
h ^= exclude.GetHashCode();
h = (h << 1) | (Number.URShift(h, 31)); // rotate left
h ^= System.Convert.ToInt32(Boost);
return h;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace angeldnd.dap {
public sealed class WeakData : Data {
public readonly string Kind = null;
private RealData _Real = null;
public WeakData(string kind, RealData real) {
Kind = kind;
_Real = real;
}
public override Data Clone() {
WeakData clone = null;
if (Kind != null) {
clone = DataCache.Take(Kind);
_Real._CopyTo(clone._Real);
} else {
clone = new WeakData(Kind, _Real.Clone() as RealData);
}
return clone;
}
protected override void OnRecycle() {
_Real._Recycle();
}
public override void Clear() {
_Real.Clear();
}
public override int Count {
get {
return _Real.Count;
}
}
public override IEnumerable<string> Keys {
get {
return _Real.Keys;
}
}
public override bool HasKey(string key) {
return _Real.HasKey(key);
}
public override DataType GetValueType(string key) {
return _Real.GetValueType(key);
}
public override object GetValue(string key) {
return _Real.GetValue(key);
}
public override bool TryGetValue(string key, out object val) {
return _Real.TryGetValue(key, out val);
}
//SILP: WEAK_DATA_TYPE(Bool, bool)
public override bool IsBool(string key) { //__SILP__
return _Real.IsBool(key); //__SILP__
} //__SILP__
//__SILP__
public override bool TryGetBool(string key, out bool val, bool isDebug = false) { //__SILP__
return _Real.TryGetBool(key, out val, isDebug); //__SILP__
} //__SILP__
//__SILP__
public override bool GetBool(string key) { //__SILP__
return _Real.GetBool(key); //__SILP__
} //__SILP__
//__SILP__
public override bool GetBool(string key, bool defaultValue) { //__SILP__
return _Real.GetBool(key, defaultValue); //__SILP__
} //__SILP__
//__SILP__
public override bool SetBool(string key, bool val) { //__SILP__
return _Real.SetBool(key, val); //__SILP__
} //__SILP__
//__SILP__
public override void ForEachBool(Action<int, bool> callback) { //__SILP__
_Real.ForEachBool(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilTrueBool(Func<int, bool, bool> callback) { //__SILP__
return _Real.UntilTrueBool(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilFalseBool(Func<int, bool, bool> callback) { //__SILP__
return _Real.UntilFalseBool(callback); //__SILP__
} //__SILP__
//__SILP__
//SILP: WEAK_DATA_TYPE(Int, int)
public override bool IsInt(string key) { //__SILP__
return _Real.IsInt(key); //__SILP__
} //__SILP__
//__SILP__
public override bool TryGetInt(string key, out int val, bool isDebug = false) { //__SILP__
return _Real.TryGetInt(key, out val, isDebug); //__SILP__
} //__SILP__
//__SILP__
public override int GetInt(string key) { //__SILP__
return _Real.GetInt(key); //__SILP__
} //__SILP__
//__SILP__
public override int GetInt(string key, int defaultValue) { //__SILP__
return _Real.GetInt(key, defaultValue); //__SILP__
} //__SILP__
//__SILP__
public override bool SetInt(string key, int val) { //__SILP__
return _Real.SetInt(key, val); //__SILP__
} //__SILP__
//__SILP__
public override void ForEachInt(Action<int, int> callback) { //__SILP__
_Real.ForEachInt(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilTrueInt(Func<int, int, bool> callback) { //__SILP__
return _Real.UntilTrueInt(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilFalseInt(Func<int, int, bool> callback) { //__SILP__
return _Real.UntilFalseInt(callback); //__SILP__
} //__SILP__
//__SILP__
//SILP: WEAK_DATA_TYPE(Long, long)
public override bool IsLong(string key) { //__SILP__
return _Real.IsLong(key); //__SILP__
} //__SILP__
//__SILP__
public override bool TryGetLong(string key, out long val, bool isDebug = false) { //__SILP__
return _Real.TryGetLong(key, out val, isDebug); //__SILP__
} //__SILP__
//__SILP__
public override long GetLong(string key) { //__SILP__
return _Real.GetLong(key); //__SILP__
} //__SILP__
//__SILP__
public override long GetLong(string key, long defaultValue) { //__SILP__
return _Real.GetLong(key, defaultValue); //__SILP__
} //__SILP__
//__SILP__
public override bool SetLong(string key, long val) { //__SILP__
return _Real.SetLong(key, val); //__SILP__
} //__SILP__
//__SILP__
public override void ForEachLong(Action<int, long> callback) { //__SILP__
_Real.ForEachLong(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilTrueLong(Func<int, long, bool> callback) { //__SILP__
return _Real.UntilTrueLong(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilFalseLong(Func<int, long, bool> callback) { //__SILP__
return _Real.UntilFalseLong(callback); //__SILP__
} //__SILP__
//__SILP__
//SILP: WEAK_DATA_TYPE(Float, float)
public override bool IsFloat(string key) { //__SILP__
return _Real.IsFloat(key); //__SILP__
} //__SILP__
//__SILP__
public override bool TryGetFloat(string key, out float val, bool isDebug = false) { //__SILP__
return _Real.TryGetFloat(key, out val, isDebug); //__SILP__
} //__SILP__
//__SILP__
public override float GetFloat(string key) { //__SILP__
return _Real.GetFloat(key); //__SILP__
} //__SILP__
//__SILP__
public override float GetFloat(string key, float defaultValue) { //__SILP__
return _Real.GetFloat(key, defaultValue); //__SILP__
} //__SILP__
//__SILP__
public override bool SetFloat(string key, float val) { //__SILP__
return _Real.SetFloat(key, val); //__SILP__
} //__SILP__
//__SILP__
public override void ForEachFloat(Action<int, float> callback) { //__SILP__
_Real.ForEachFloat(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilTrueFloat(Func<int, float, bool> callback) { //__SILP__
return _Real.UntilTrueFloat(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilFalseFloat(Func<int, float, bool> callback) { //__SILP__
return _Real.UntilFalseFloat(callback); //__SILP__
} //__SILP__
//__SILP__
//SILP: WEAK_DATA_TYPE(Double, double)
public override bool IsDouble(string key) { //__SILP__
return _Real.IsDouble(key); //__SILP__
} //__SILP__
//__SILP__
public override bool TryGetDouble(string key, out double val, bool isDebug = false) { //__SILP__
return _Real.TryGetDouble(key, out val, isDebug); //__SILP__
} //__SILP__
//__SILP__
public override double GetDouble(string key) { //__SILP__
return _Real.GetDouble(key); //__SILP__
} //__SILP__
//__SILP__
public override double GetDouble(string key, double defaultValue) { //__SILP__
return _Real.GetDouble(key, defaultValue); //__SILP__
} //__SILP__
//__SILP__
public override bool SetDouble(string key, double val) { //__SILP__
return _Real.SetDouble(key, val); //__SILP__
} //__SILP__
//__SILP__
public override void ForEachDouble(Action<int, double> callback) { //__SILP__
_Real.ForEachDouble(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilTrueDouble(Func<int, double, bool> callback) { //__SILP__
return _Real.UntilTrueDouble(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilFalseDouble(Func<int, double, bool> callback) { //__SILP__
return _Real.UntilFalseDouble(callback); //__SILP__
} //__SILP__
//__SILP__
//SILP: WEAK_DATA_TYPE(String, string)
public override bool IsString(string key) { //__SILP__
return _Real.IsString(key); //__SILP__
} //__SILP__
//__SILP__
public override bool TryGetString(string key, out string val, bool isDebug = false) { //__SILP__
return _Real.TryGetString(key, out val, isDebug); //__SILP__
} //__SILP__
//__SILP__
public override string GetString(string key) { //__SILP__
return _Real.GetString(key); //__SILP__
} //__SILP__
//__SILP__
public override string GetString(string key, string defaultValue) { //__SILP__
return _Real.GetString(key, defaultValue); //__SILP__
} //__SILP__
//__SILP__
public override bool SetString(string key, string val) { //__SILP__
return _Real.SetString(key, val); //__SILP__
} //__SILP__
//__SILP__
public override void ForEachString(Action<int, string> callback) { //__SILP__
_Real.ForEachString(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilTrueString(Func<int, string, bool> callback) { //__SILP__
return _Real.UntilTrueString(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool UntilFalseString(Func<int, string, bool> callback) { //__SILP__
return _Real.UntilFalseString(callback); //__SILP__
} //__SILP__
//__SILP__
public override bool IsData(string key) {
return _Real.IsData(key);
}
public override bool TryGetData(string key, out Data val, bool isDebug = false) {
return _Real.TryGetData(key, out val, isDebug);
}
public override Data GetData(string key) {
return _Real.GetData(key);
}
public override Data GetData(string key, Data defaultValue) {
return _Real.GetData(key, defaultValue);
}
public override bool SetData(string key, Data val) {
bool isTempKey = IsTempKey(key);
if (Sealed && !isTempKey) {
Log.Error("Already Sealed: {0} -> {1}", key, val);
return false;
}
if (isTempKey || !HasKey(key)) {
Data subData = val;
if (Kind != null) {
RealData real = val as RealData;
if (real != null) {
WeakData weak = DataCache.Take(Kind, key);
real._CopyTo(weak._Real);
subData = weak;
}
}
return _Real.SetData(key, subData);
}
Log.Error("Key Exist: {0} {1} -> {2}", key, GetValue(key), val);
return false;
}
public override void ForEachData(Action<int, Data> callback) {
_Real.ForEachData(callback);
}
public override bool UntilTrueData(Func<int, Data, bool> callback) {
return _Real.UntilTrueData(callback);
}
public override bool UntilFalseData(Func<int, Data, bool> callback) {
return _Real.UntilFalseData(callback);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
using NetOffice.ExcelApi.Enums;
using Excel = NetOffice.ExcelApi;
namespace UsefulDataTools
{
public static class ExcelOutputExtensions
{
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable{T}" /> into Excel and opens Excel to display the exported
/// data. If <see cref="T" /> is a complex type, all properties and fields are exported into columns. If
/// <see cref="T" /> is a simple type, the data is exported into a single column.
/// </summary>
/// <typeparam name="T">A generic type which is contained within the IEnumerable.</typeparam>
/// <param name="input">An <see cref="IEnumerable{T}" /> which will be evaluated, expanded and exported into Excel.</param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable<T> ToExcel<T>(this IEnumerable<T> input)
{
ExcelOutputItem.CreateInstance(input).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable" /> of type <see cref="type" /> into Excel. If
/// <see cref="type" /> is a complex type, all properties and fields are exported into columns. If <see cref="type" />
/// is a simple type, the data is exported into a single column.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="type">The type of the objects contained within the IEnumerable in <see cref="input" />.</param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable ToExcel(IEnumerable input, Type type)
{
ExcelOutputItem.CreateInstance(input, type).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable{T}" /> into Excel and opens Excel to display the exported
/// data. If <see cref="T" /> is a complex type, all properties and fields are exported into columns. If
/// <see cref="T" /> is a simple type, the data is exported into a single column.
/// </summary>
/// <typeparam name="T">A generic type which is contained within the IEnumerable.</typeparam>
/// <param name="input">An <see cref="IEnumerable{T}" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable<T> ToExcel<T>(this IEnumerable<T> input, bool trim)
{
ExcelOutputItem.CreateInstance(input, trim).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable" /> of type <see cref="type" /> into Excel. If
/// <see cref="type" /> is a complex type, all properties and fields are exported into columns. If <see cref="type" />
/// is a simple type, the data is exported into a single column.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="type">The type of the objects contained within the IEnumerable in <see cref="input" />.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable ToExcel(IEnumerable input, Type type, bool trim)
{
ExcelOutputItem.CreateInstance(input, type, trim).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable{T}" /> into Excel and opens Excel to display the exported
/// data. If <see cref="T" /> is a complex type, all properties and fields are exported into columns. If
/// <see cref="T" /> is a simple type, the data is exported into a single column.
/// </summary>
/// <typeparam name="T">A generic type which is contained within the IEnumerable.</typeparam>
/// <param name="input">An <see cref="IEnumerable{T}" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="worksheetName">The name given to the newly generated worksheet.</param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable<T> ToExcel<T>(this IEnumerable<T> input, string worksheetName)
{
ExcelOutputItem.CreateInstance(input, worksheetName).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable" /> of type <see cref="type" /> into Excel. If
/// <see cref="type" /> is a complex type, all properties and fields are exported into columns. If <see cref="type" />
/// is a simple type, the data is exported into a single column.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="type">The type of the objects contained within the IEnumerable in <see cref="input" />.</param>
/// <param name="worksheetName">The name given to the newly generated worksheet.</param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable ToExcel(this IEnumerable input, Type type, string worksheetName)
{
ExcelOutputItem.CreateInstance(input, type, worksheetName).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable{T}" /> into Excel. If <see cref="T" /> is a complex type,
/// all properties and fields are exported into columns. If <see cref="T" /> is a simple type, the data is exported into
/// a single column.
/// </summary>
/// <typeparam name="T">A generic type which is contained within the IEnumerable.</typeparam>
/// <param name="input">An <see cref="IEnumerable{T}" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable<T> ToExcel<T>(this IEnumerable<T> input, PostCreationActions postCreationAction, string path)
{
ExcelOutputItem.CreateInstance(input, postCreationAction, path).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable" /> of type <see cref="type" /> into Excel. If
/// <see cref="type" /> is a complex type, all properties and fields are exported into columns. If <see cref="type" />
/// is a simple type, the data is exported into a single column.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="type">The type of the objects contained within the IEnumerable in <see cref="input" />.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable ToExcel(this IEnumerable input, Type type, PostCreationActions postCreationAction, string path)
{
ExcelOutputItem.CreateInstance(input, type, postCreationAction, path).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable{T}" /> into Excel. If <see cref="T" /> is a complex type,
/// all properties and fields are exported into columns. If <see cref="T" /> is a simple type, the data is exported into
/// a single column.
/// </summary>
/// <typeparam name="T">A generic type which is contained within the IEnumerable.</typeparam>
/// <param name="input">An <see cref="IEnumerable{T}" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <param name="worksheetName">The name given to the newly generated worksheet.</param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable<T> ToExcel<T>(this IEnumerable<T> input, string worksheetName, bool trim, PostCreationActions postCreationAction, string path)
{
ExcelOutputItem.CreateInstance(input, worksheetName, trim, postCreationAction, path).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports an <see cref="IEnumerable" /> of type <see cref="type" /> into Excel. If
/// <see cref="type" /> is a complex type, all properties and fields are exported into columns. If <see cref="type" />
/// is a simple type, the data is exported into a single column.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="type">The type of the objects contained within the IEnumerable in <see cref="input" />.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <param name="worksheetName">The name given to the newly generated worksheet.</param>
/// <returns>Returns the <see cref="IEnumerable{T}" /> for further processing if required.</returns>
public static IEnumerable ToExcel(IEnumerable input, Type type, string worksheetName, bool trim, PostCreationActions postCreationAction, string path)
{
ExcelOutputItem.CreateInstance(input, type, worksheetName, trim, postCreationAction, path).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataTable" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <returns>Returns the <see cref="DataTable" /> for further processing if required.</returns>
public static DataTable ToExcel(this DataTable input)
{
ExcelOutputItem.CreateInstance(input).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataTable" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="worksheetName">The name given to the newly generated worksheet.</param>
/// <returns>Returns the <see cref="DataTable" /> for further processing if required.</returns>
public static DataTable ToExcel(this DataTable input, string worksheetName)
{
ExcelOutputItem.CreateInstance(input, worksheetName).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataTable" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="worksheetName">The name given to the newly generated worksheet.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <returns>Returns the <see cref="DataTable" /> for further processing if required.</returns>
public static DataTable ToExcel(this DataTable input, string worksheetName, bool trim)
{
ExcelOutputItem.CreateInstance(input, worksheetName, trim).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataTable" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="worksheetName">The name given to the newly generated worksheet.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <returns>Returns the <see cref="DataTable" /> for further processing if required.</returns>
public static DataTable ToExcel(this DataTable input, string worksheetName, PostCreationActions postCreationAction, string path)
{
ExcelOutputItem.CreateInstance(input, worksheetName, postCreationAction, path).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataTable" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <returns>Returns the <see cref="DataTable" /> for further processing if required.</returns>
public static DataTable ToExcel(this DataTable input, bool trim)
{
ExcelOutputItem.CreateInstance(input, trim).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataTable" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <returns>Returns the <see cref="DataTable" /> for further processing if required.</returns>
public static DataTable ToExcel(this DataTable input, PostCreationActions postCreationAction, string path)
{
ExcelOutputItem.CreateInstance(input, postCreationAction, path).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataTable" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <returns>Returns the <see cref="DataTable" /> for further processing if required.</returns>
public static DataTable ToExcel(this DataTable input, bool trim, PostCreationActions postCreationAction, string path)
{
ExcelOutputItem.CreateInstance(input, trim, postCreationAction, path);
return input;
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataTable" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="IEnumerable" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="worksheetName">The name given to the newly generated worksheet.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <returns>Returns the <see cref="DataTable" /> for further processing if required.</returns>
public static DataTable ToExcel(this DataTable input, string worksheetName, bool trim, PostCreationActions postCreationAction, string path)
{
ExcelOutputItem.CreateInstance(input, worksheetName, trim, postCreationAction, path).ToExcel();
return input;
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataSet" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="DataSet" /> which will be evaluated, expanded and exported into Excel.</param>
/// <returns>Returns the <see cref="DataSet" /> for further processing if required.</returns>
public static DataSet ToExcel(this DataSet input)
{
return input.ToExcel(true, PostCreationActions.Open, string.Empty);
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataSet" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="DataSet" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <returns>Returns the <see cref="DataSet" /> for further processing if required.</returns>
public static DataSet ToExcel(this DataSet input, bool trim)
{
return input.ToExcel(trim, PostCreationActions.Open, string.Empty);
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataSet" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="DataSet" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <returns>Returns the <see cref="DataSet" /> for further processing if required.</returns>
public static DataSet ToExcel(this DataSet input, PostCreationActions postCreationAction, string path)
{
return input.ToExcel(true, PostCreationActions.Open, path);
}
/// <summary>
/// Evaluates, expands and exports a <see cref="DataSet" /> into Excel.
/// </summary>
/// <param name="input">An <see cref="DataSet" /> which will be evaluated, expanded and exported into Excel.</param>
/// <param name="trim">A parameter which determines whether strings should be trimmed before being written to Excel.</param>
/// <param name="postCreationAction">
/// Determines whether the Excel file will be opened with the data, opened and saved or just saved.
/// </param>
/// <param name="path">
/// If the path parameter determines where the Excel file will be saved to if a save action is selected from the
/// <see cref="PostCreationActions" />.
/// </param>
/// <returns>Returns the <see cref="DataSet" /> for further processing if required.</returns>
public static DataSet ToExcel(this DataSet input, bool trim, PostCreationActions postCreationAction, string path)
{
var excelOutputCollection = new ExcelOutputCollection();
var unnamedWorksheetCounter = 1;
foreach (DataTable dataTable in input.Tables)
if (string.IsNullOrWhiteSpace(dataTable.TableName))
{
var excelOutputItem = ExcelOutputItem.CreateInstance(dataTable, string.Concat(ExcelOutputConfiguration.DefaultWorksheetName, unnamedWorksheetCounter), trim, postCreationAction, path);
excelOutputCollection.Add(excelOutputItem);
unnamedWorksheetCounter++;
}
else
{
var excelOutputItem = ExcelOutputItem.CreateInstance(dataTable, trim, postCreationAction, path);
excelOutputCollection.Add(excelOutputItem);
}
excelOutputCollection.ToExcel();
return input;
}
/// <summary>
/// Exports an <see cref="ExcelOutputItem" /> into Excel.
/// </summary>
/// <param name="excelOutputItem">
/// An object containing all the necessary parameters to create an Excel export into a single worksheet.
/// </param>
public static void ToExcel(this ExcelOutputItem excelOutputItem)
{
var excelOutputCollection = new ExcelOutputCollection(excelOutputItem.PostCreationActions, excelOutputItem.Path) {excelOutputItem};
excelOutputCollection.ToExcel();
}
/// <summary>
/// Exports an <see cref="ExcelOutputCollection" /> into Excel. A new sheet is created for each
/// <see cref="ExcelOutputItem" /> within the <see cref="ExcelOutputCollection" />.
/// </summary>
/// <param name="excelOutputCollection">
/// An object containing all the necessary parameters to create an Excel export into a multiple worksheets.
/// </param>
public static void ToExcel(this ExcelOutputCollection excelOutputCollection)
{
//HACK: Workaround for Excel on machines which are set up in the English language, but not an English region.
var enusCultureInfo = CultureInfo.GetCultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = enusCultureInfo;
AbortIfPathIsEmptyAndSaveIsRequired(excelOutputCollection.Path, excelOutputCollection.PostCreationAction);
using (var app = new Excel.Application())
{
var sheetsInNewWorkbook = app.SheetsInNewWorkbook;
app.SheetsInNewWorkbook = excelOutputCollection.Count;
try
{
CreateWorkbook(app, excelOutputCollection);
ExecutePostCreationActions(app, excelOutputCollection.PostCreationAction, excelOutputCollection.Path);
}
catch (Exception)
{
if (app.Workbooks.Any())
foreach (var workbook in app.Workbooks.Where(x => !x.IsDisposed))
{
workbook.Close(false, Missing.Value, Missing.Value);
workbook.Dispose();
}
if (app.IsDisposed)
throw;
app.SheetsInNewWorkbook = sheetsInNewWorkbook;
app.Quit();
app.Dispose();
throw;
}
finally
{
Thread.CurrentThread.CurrentCulture = ExcelOutputConfiguration.DefaultCulture;
}
}
}
private static void ExecutePostCreationActions(Excel.Application app, PostCreationActions postCreationAction, string path)
{
switch (postCreationAction)
{
case PostCreationActions.Open:
app.Visible = true;
break;
case PostCreationActions.SaveAndView:
app.ActiveWorkbook.SaveAs(path);
app.Visible = true;
break;
case PostCreationActions.SaveAndClose:
app.ActiveWorkbook.SaveAs(path);
app.Quit();
app.Dispose();
break;
default:
throw new ArgumentOutOfRangeException(nameof(postCreationAction), postCreationAction, null);
}
}
private static void CreateWorkbook(Excel.Application app, ExcelOutputCollection excelOutputCollection)
{
using (var wb = app.Workbooks.Add())
{
var count = 1;
foreach (var item in excelOutputCollection)
{
if (item.Enumerable != null)
CreateWorksheetFromEnumerableItem(ref count, wb, item);
if (item.DataTable != null)
CreateWorksheetFromDataTableItem(ref count, wb, item);
}
}
}
private static void CreateWorksheetFromEnumerableItem(ref int count, Excel.Workbook wb, ExcelOutputItem item)
{
using (var ws = (Excel.Worksheet) wb.Worksheets[count])
{
var enumerator = item.Enumerable.GetEnumerator();
var arrayList = new ArrayList();
while (enumerator.MoveNext())
arrayList.Add(enumerator.Current);
var inputArray = arrayList.ToArray();
var rowCount = inputArray.Length;
ws.Name = item.WorksheetName;
if (item.Type.IsSimpleType())
SimpleTypeProcessing(item.Type, inputArray, rowCount, ws);
else
ComplexTypeProcessing(item.Trim, item.Type, inputArray, rowCount, ws);
ws.Columns.AutoFit();
}
count++;
}
private static void CreateWorksheetFromDataTableItem(ref int count, Excel.Workbook wb, ExcelOutputItem item)
{
using (var ws = (Excel.Worksheet) wb.Worksheets[count])
{
var enumerator = item.DataTable.Rows.GetEnumerator();
var arrayList = new ArrayList();
while (enumerator.MoveNext())
arrayList.Add(enumerator.Current);
var inputArray = arrayList.ToArray();
var rowCount = inputArray.Length;
ws.Name = item.WorksheetName;
DataTableProcessing(item.Trim, item.WorksheetName, item.DataTable.Columns, inputArray, rowCount, ws);
ws.Columns.AutoFit();
}
count++;
}
private static void ComplexTypeProcessing(bool stringsTrimmed, Type type, object[] inputArray, int rowCount, Excel.Worksheet ws)
{
var properties = type.GetProperties();
var fields = type.GetFields();
var simpleProperties = properties.Where(p => p.PropertyType.IsSimpleType()).ToArray();
var simpleFields = fields.Where(f => f.FieldType.IsSimpleType()).ToArray();
var simplePropertyCount = simpleProperties.Length;
var simpleFieldCount = simpleFields.Length;
var headerStartCell = ws.Cells[1, 1];
var headerEndCell = ws.Cells[1, simplePropertyCount + simpleFieldCount];
var headerRange = ws.Range(headerStartCell, headerEndCell);
var propertyHeaderArray = simpleProperties.Select(x => x.GetCustomAttribute<ColumnHeaderAttribute>() != null ? x.GetCustomAttribute<ColumnHeaderAttribute>().Header : x.Name).ToArray();
var fieldHeaderArray = simpleFields.Select(x => x.GetCustomAttribute<ColumnHeaderAttribute>() != null ? x.GetCustomAttribute<ColumnHeaderAttribute>().Header : x.Name).ToArray();
var headerList = new List<string>(simplePropertyCount + simpleFieldCount);
headerList.AddRange(propertyHeaderArray);
headerList.AddRange(fieldHeaderArray);
var headerArray = headerList.ToArray();
headerRange.Value2 = headerArray;
SetPropertyColumnDataTypes(ws, simpleProperties);
SetFieldColumnDataTypes(ws, simpleProperties.Length, simpleFields);
var dataStartCell = ws.Cells[2, 1];
var dataEndCell = ws.Cells[rowCount + 1, simplePropertyCount + simpleFieldCount];
var dataRange = ws.Range(dataStartCell, dataEndCell);
var dataArray = new object[rowCount, simplePropertyCount + simpleFieldCount];
for (var row = 0; row < rowCount; row++)
{
SetPropertyDataPerColumn(stringsTrimmed, inputArray, simpleProperties, simplePropertyCount, dataArray, row);
SetFieldDataPerColumn(stringsTrimmed, inputArray, simpleFields, simplePropertyCount, simpleFieldCount, dataArray, row);
}
dataRange.Value2 = dataArray;
var fullRange = ws.Range(headerStartCell, dataEndCell);
fullRange.Worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange, fullRange, Type.Missing, XlYesNoGuess.xlYes, Type.Missing).Name = $"Table_{type.Name}";
}
private static void DataTableProcessing(bool stringsTrimmed, string name, DataColumnCollection columns, object[] inputArray, int rowCount, Excel.Worksheet ws)
{
var columnsCount = columns.Count;
var headerStartCell = ws.Cells[1, 1];
var headerEndCell = ws.Cells[1, columnsCount];
var headerRange = ws.Range(headerStartCell, headerEndCell);
var headerList = new List<string>(columnsCount);
foreach (DataColumn column in columns)
headerList.Add(column.ColumnName);
var headerArray = headerList.ToArray();
headerRange.Value2 = headerArray;
SetDataTableColumnDataTypes(ws, columns);
var dataStartCell = ws.Cells[2, 1];
var dataEndCell = ws.Cells[rowCount + 1, columnsCount];
var dataRange = ws.Range(dataStartCell, dataEndCell);
var dataArray = new object[rowCount, columnsCount];
for (var row = 0; row < rowCount; row++) SetDataTableDataPerColumn(stringsTrimmed, inputArray, row, columnsCount, dataArray);
dataRange.Value2 = dataArray;
var fullRange = ws.Range(headerStartCell, dataEndCell);
fullRange.Worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange, fullRange, Type.Missing, XlYesNoGuess.xlYes, Type.Missing).Name = $"Table_{name}";
}
private static void SetPropertyColumnDataTypes(Excel.Worksheet ws, PropertyInfo[] simpleProperties)
{
for (var column = 0; column < simpleProperties.Length; column++)
{
var rangeColumn = GetExcelColumnName(column + 1);
var range = ws.Range($"{rangeColumn}:{rangeColumn}");
var columnDataTypeAttribute = simpleProperties[column].GetCustomAttribute<ColumnNumberFormatAttribute>();
if (columnDataTypeAttribute == null)
SetRangeNumberFormatBasedOnDataType(simpleProperties[column].PropertyType, range);
else
SetRangeNumberFormatBasedOnAttribute(range, columnDataTypeAttribute.NumberFormat);
}
}
private static void SetFieldColumnDataTypes(Excel.Worksheet ws, int simplePropertiesCount, FieldInfo[] simpleFields)
{
for (var column = simplePropertiesCount; column < simplePropertiesCount + simpleFields.Length; column++)
{
var rangeColumn = GetExcelColumnName(column + 1);
var range = ws.Range($"{rangeColumn}:{rangeColumn}");
var columnDataTypeAttribute = simpleFields[column - simplePropertiesCount].GetCustomAttribute<ColumnNumberFormatAttribute>();
if (columnDataTypeAttribute == null)
SetRangeNumberFormatBasedOnDataType(simpleFields[column - simplePropertiesCount].FieldType, range);
else
SetRangeNumberFormatBasedOnAttribute(range, columnDataTypeAttribute.NumberFormat);
}
}
private static void SetDataTableColumnDataTypes(Excel.Worksheet ws, DataColumnCollection columns)
{
for (var column = 0; column < columns.Count; column++)
{
var rangeColumn = GetExcelColumnName(column + 1);
var range = ws.Range($"{rangeColumn}:{rangeColumn}");
SetRangeNumberFormatBasedOnDataType(columns[column].DataType, range);
}
}
private static void SetRangeNumberFormatBasedOnDataType(Type type, Excel.Range range)
{
if (type == typeof(string) || type == typeof(char) || Nullable.GetUnderlyingType(type) == typeof(char))
range.NumberFormat = "@";
else if (type == typeof(DateTime) || Nullable.GetUnderlyingType(type) == typeof(DateTime))
range.NumberFormat = ExcelOutputConfiguration.DefaultDateTimeFormat;
}
private static void SetRangeNumberFormatBasedOnAttribute(Excel.Range range, string numberFormat)
{
range.NumberFormat = numberFormat;
}
private static void SetPropertyDataPerColumn(bool stringsTrimmed, object[] inputArray, PropertyInfo[] simpleProperties, int simplePropertyCount, object[,] dataArray, int row)
{
for (var column = 0; column < simplePropertyCount; column++) inputArray[row].SetDataPerColumn(stringsTrimmed, column, row, dataArray, simpleProperties[column].GetValue);
}
private static void SetFieldDataPerColumn(bool stringsTrimmed, object[] inputArray, FieldInfo[] simpleFields, int simplePropertyCount, int simpleFieldCount, object[,] dataArray, int row)
{
for (var column = simplePropertyCount; column < simplePropertyCount + simpleFieldCount; column++) inputArray[row].SetDataPerColumn(stringsTrimmed, column, row, dataArray, simpleFields[column - simplePropertyCount].GetValue);
}
private static void SetDataTableDataPerColumn(bool stringsTrimmed, object[] inputArray, int row, int columnCount, object[,] dataArray)
{
var dataRow = (DataRow) inputArray[row];
for (var i = 0; i < columnCount; i++)
{
var column = i;
inputArray[row].SetDataPerColumn(stringsTrimmed, i, row, dataArray, o => dataRow.ItemArray[column]);
}
}
private static void SetDataPerColumn(this object item, bool stringsTrimmed, int column, int row, object[,] dataArray, Func<object, object> getValueFunction)
{
var value = getValueFunction(item);
if (value != null && (value is string || value is char) && stringsTrimmed)
dataArray[row, column] = value.ToTrimmedString();
else
dataArray[row, column] = value;
}
private static void SimpleTypeProcessing(Type type, object[] inputArray, int rowCount, Excel.Worksheet ws)
{
var dataArray = new object[rowCount, 1];
for (var i = 0; i < inputArray.Length; i++)
dataArray[i, 0] = inputArray[i];
var dataStartCell = ws.Cells[1, 1];
var dataEndCell = ws.Cells[rowCount, 1];
var dataRange = ws.Range(dataStartCell, dataEndCell);
const string rangeColumn = "A";
var range = ws.Range($"{rangeColumn}:{rangeColumn}");
SetRangeNumberFormatBasedOnDataType(type, range);
dataRange.Value2 = dataArray;
var fullRange = ws.Range(dataStartCell, dataEndCell);
fullRange.Worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange, fullRange, Type.Missing, XlYesNoGuess.xlNo, Type.Missing).Name = $"Table_{type.Name}";
}
private static void AbortIfPathIsEmptyAndSaveIsRequired(string path, PostCreationActions postCreationAction)
{
switch (postCreationAction)
{
case PostCreationActions.SaveAndView:
case PostCreationActions.SaveAndClose:
if (string.IsNullOrEmpty(path))
throw new ArgumentException($"The {nameof(path)} cannot be null or empty if the file is to be saved.", nameof(path));
break;
case PostCreationActions.Open:
break;
default:
throw new ArgumentOutOfRangeException(nameof(postCreationAction), postCreationAction, null);
}
}
/// <summary>
/// Returns the alphabetical column name when given the number of an excel column.
/// </summary>
/// <param name="columnNumber">The number to be converted to text</param>
/// <returns>
/// <see cref="string" />
/// </returns>
public static string GetExcelColumnName(int columnNumber)
{
var dividend = columnNumber;
var columnName = string.Empty;
while (dividend > 0)
{
var modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo) + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=InputScopeAttribute.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: InputScopeAttribute is an image object that links IOleDataObject.
//
// History:
// 10/02/2003 : yutakas
//
//---------------------------------------------------------------------------
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Diagnostics;
using System.Windows.Media;
using System.Windows.Input;
using System.Windows.Documents;
using System.Windows.Controls;
using MS.Win32;
namespace System.Windows.Documents
{
//
// InputScopeAttribute is Image object that links IOleDataObject, which
// is insterted by ITextStoreACP::InsertEmbedded().
//
internal class InputScopeAttribute : UnsafeNativeMethods.ITfInputScope
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// Creates a new InputScopeAttribute instance.
internal InputScopeAttribute(InputScope inputscope)
{
_inputScope= inputscope;
}
#endregion Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// A method of ITfInputScope.
// This returns InputScopes in the array that is allocated by CoTaskMemAlloc.
/// <SecurityNote>
/// Critical - it satisfies Marshal.* LinkDemands for unmanaged code permissions. handles out a valid pointer to unmanaged memory.
/// </SecurityNote>
[SecurityCritical]
public void GetInputScopes(out IntPtr ppinputscopes, out int count)
{
if (_inputScope != null)
{
int offset = 0;
count = _inputScope.Names.Count;
try
{
ppinputscopes = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Int32)) * count);
}
catch (OutOfMemoryException)
{
throw new COMException(SR.Get(SRID.InputScopeAttribute_E_OUTOFMEMORY), NativeMethods.E_OUTOFMEMORY);
}
for (int i = 0; i < count; i++)
{
Marshal.WriteInt32(ppinputscopes, offset, (Int32)((InputScopeName)_inputScope.Names[i]).NameValue);
offset += Marshal.SizeOf(typeof(Int32));
}
}
else
{
ppinputscopes = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Int32)) * 1);
Marshal.WriteInt32(ppinputscopes, (Int32)InputScopeNameValue.Default);
count = 1;
}
}
// A method of ITfInputScope.
// This returns BSTRs in the array that is allocated by CoTaskMemAlloc.
/// <SecurityNote>
/// Critical - it satisfies Marshal.AllocCoTaskMem() LinkDemand for unmanaged code permissions. handles out a valid pointer to unmanaged memory.
/// </SecurityNote>
[SecurityCritical]
public int GetPhrase(out IntPtr ppbstrPhrases, out int count)
{
count = _inputScope == null ? 0 : _inputScope.PhraseList.Count;
try
{
ppbstrPhrases = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr))*count);
}
catch (OutOfMemoryException)
{
throw new COMException(SR.Get(SRID.InputScopeAttribute_E_OUTOFMEMORY), NativeMethods.E_OUTOFMEMORY);
}
int offset = 0;
for(int i=0; i <count; i++)
{
IntPtr pbstr;
try
{
pbstr = Marshal.StringToBSTR(((InputScopePhrase)_inputScope.PhraseList[i]).Name);
}
catch (OutOfMemoryException)
{
offset = 0;
for (int j=0; j < i; j++)
{
Marshal.FreeBSTR(Marshal.ReadIntPtr(ppbstrPhrases, offset));
offset += Marshal.SizeOf(typeof(IntPtr));
}
throw new COMException(SR.Get(SRID.InputScopeAttribute_E_OUTOFMEMORY), NativeMethods.E_OUTOFMEMORY);
}
Marshal.WriteIntPtr(ppbstrPhrases , offset, pbstr);
offset += Marshal.SizeOf(typeof(IntPtr));
}
return count > 0 ? NativeMethods.S_OK : NativeMethods.S_FALSE;
}
// A method of ITfInputScope.
public int GetRegularExpression(out string desc)
{
desc = null;
if (_inputScope != null)
{
desc = _inputScope.RegularExpression;
}
return desc != null ? NativeMethods.S_OK : NativeMethods.S_FALSE;
}
// A method of ITfInputScope.
public int GetSRGC(out string desc)
{
desc = null;
if (_inputScope != null)
{
desc = _inputScope.SrgsMarkup;
}
return desc != null ? NativeMethods.S_OK : NativeMethods.S_FALSE;
}
// A method of ITfInputScope.
public int GetXML(out string desc)
{
desc = null;
return NativeMethods.S_FALSE;
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// InputScope value for this instance for ITfInputScope.
private InputScope _inputScope;
#endregion Private Fields
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCPRPT
{
using Microsoft.Protocols.TestTools;
/// <summary>
/// The interface of MS-OXCPRPTAdapter class.
/// </summary>
public interface IMS_OXCPRPTAdapter : IAdapter
{
/// <summary>
/// This method is used to initialize the test environment for private mailbox.
/// </summary>
void InitializeMailBox();
/// <summary>
/// This method is used to initialize the test environment for public folders.
/// </summary>
void InitializePublicFolder();
/// <summary>
/// This method is used to get object for different object types.
/// </summary>
/// <param name="objType">Specifies the object type.</param>
/// <param name="objToOperate">Specifies which objects to operate.</param>
void GetObject(ServerObjectType objType, ObjectToOperate objToOperate);
/// <summary>
/// The method is used to query an object for all the named properties.
/// </summary>
/// <param name="queryFlags">Specifies QueryFlags parameter in request.</param>
/// <param name="hasGuid">Indicates whether HasGuid is zero,
/// If the HasGUID field is non-zero then the PropertyGUID field MUST be included in the request.
/// If no PropertyGUID is specified, then properties from any GUID MUST be returned in the results.</param>
/// <param name="isKind0x01Returned">True if the named properties of the response with the Kind field
/// ([MS-OXCDATA] section 2.6.1) set to 0x1 was returned.</param>
/// <param name="isKind0x00Returned">True if the named properties of the response with the Kind field
/// ([MS-OXCDATA] section 2.6.1) set to 0x0 was returned.</param>
/// <param name="isNamedPropertyGuidReturned">True if the named properties with a GUID field ([MS-OXCDATA]
/// section 2.6.1) value that does not match the value of the PropertyGUID field was returned.</param>
void RopQueryNamedPropertiesMethod(
QueryFlags queryFlags,
bool hasGuid,
out bool isKind0x01Returned,
out bool isKind0x00Returned,
out bool isNamedPropertyGuidReturned);
/// <summary>
/// This method is used to query for and return all of the property tags and values of properties that have been set.
/// </summary>
/// <param name="isPropertySizeLimitZero">Indicates whether PropertySizeLimit parameter is zero.</param>
/// <param name="isPropertyLargerThanLimit">Indicates whether request properties larger than limit:
/// When PropertySizeLimit is non-zero, it indicates whether request properties larger than PropertySizeLimit,
/// When PropertySizeLimit is zero, it indicates whether request properties larger than size of response.</param>
/// <param name="isUnicode">Indicates whether the requested property is encoded in Unicode format in response buffer.</param>
/// <param name="isValueContainsNotEnoughMemory">Indicates whether returned value contains NotEnoughMemory error when the request properties are too large.</param>
void RopGetPropertiesAllMethod(bool isPropertySizeLimitZero, bool isPropertyLargerThanLimit, bool isUnicode, out bool isValueContainsNotEnoughMemory);
/// <summary>
/// This method is used to query for and return all of the property tags for properties that have been set on an object.
/// </summary>
void RopGetPropertiesListMethod();
/// <summary>
/// This method is used to query for and return the values of properties specified in the PropertyTags field.
/// </summary>
/// <param name="isTestOrder">Indicates whether to test returned PropertyNames order.</param>
/// <param name="isPropertySizeLimitZero">Indicates whether PropertySizeLimit parameter is zero.</param>
/// <param name="isPropertyLargerThanLimit">Indicates whether request properties larger than limit
/// When PropertySizeLimit is non-zero, it indicates whether request properties larger than PropertySizeLimit
/// When PropertySizeLimit is zero, it indicates whether request properties larger than size of response.</param>
/// <param name="isValueContainsNotEnoughMemory">Indicates whether returned value contains NotEnoughMemory error when the request properties are too large.</param>
void RopGetPropertiesSpecificMethod(bool isTestOrder, bool isPropertySizeLimitZero, bool isPropertyLargerThanLimit, out bool isValueContainsNotEnoughMemory);
/// <summary>
/// This method is used to query for and return the values of properties specified in the PropertyTags field, which is related with unicode format.
/// </summary>
/// <param name="isUnicode">Indicates whether the requested property is encoded in Unicode format in response buffer</param>
void RopGetPropertiesSpecificForWantUnicode(bool isUnicode);
/// <summary>
/// This method is used to query for and return the values of properties specified in the PropertyTags field, which is related with tagged properties.
/// </summary>
void RopGetPropertiesSpecificForTaggedProperties();
/// <summary>
/// This method is used to map abstract, client-defined named properties to concrete 16-bit property IDs.
/// </summary>
/// <param name="isTestOrder">Indicates whether to test returned PropertyNames order.</param>
/// <param name="isCreateFlagSet">Indicates whether the "Create" Flags in request parameter is set.</param>
/// <param name="isPropertyNameExisting">Indicates whether PropertyName is existing in object mapping.</param>
/// <param name="specialPropertyName">Specifies PropertyName of request parameter.</param>
/// <param name="isCreatedEntryReturned">If Create Flags is set: If set, indicates that the server MUST create new
/// entries for any name parameters that are not found in the existing mapping set, and return existing entries for any
/// name parameters that are found in the existing mapping set.</param>
/// <param name="error">Specifies the ErrorCode when server reached limit.</param>
void RopGetPropertyIdsFromNamesMethod(
bool isTestOrder,
bool isCreateFlagSet,
bool isPropertyNameExisting,
SpecificPropertyName specialPropertyName,
out bool isCreatedEntryReturned,
out CPRPTErrorCode error);
/// <summary>
/// This method is used to map concrete property IDs to abstract, client-defined named properties.
/// </summary>
/// <param name="propertyIdType">Specifies different PropertyId type</param>
void RopGetNamesFromPropertyIdsMethod(PropertyIdType propertyIdType);
/// <summary>
/// This method is used to set property values for an object without invoking replication.
/// </summary>
/// <param name="isSameWithSetProperties">
/// Indicates whether result is same as RopSetProperties.
/// </param>
void RopSetPropertiesNoReplicateMethod(out bool isSameWithSetProperties);
/// <summary>
/// This method is used to delete property values from an object without invoking replication.
/// </summary>
/// <param name="isSameWithDeleteProperties">Indicates whether result is same as RopDeleteProperties.</param>
/// <param name="isChangedInDB">Indicates the database is changed or not</param>
void RopDeletePropertiesNoReplicateMethod(out bool isSameWithDeleteProperties, out bool isChangedInDB);
/// <summary>
/// This method is used to update the specified properties on an object.
/// </summary>
/// <param name="isModifiedValueReturned">Indicates whether the modified value of a property can be returned use a same handle.</param>
/// <param name="isChangedInDB">Indicates whether the modified value is submit to DB.
/// For Message and Attachment object, it require another ROP for submit DB.
/// For Logon and Folder object, it DO NOT need any other ROPs for submit.</param>
void RopSetPropertiesMethod(out bool isModifiedValueReturned, out bool isChangedInDB);
/// <summary>
/// This method is used to remove the specified properties from an object.
/// </summary>
/// <param name="isNoValidValueReturnedForDeletedProperties">
/// If the server returns success, it MUST NOT have a valid value to return to a client that asks for the value of this property.
/// </param>
/// <param name="isChangedInDB">
/// Indicates whether the modified value is submit to DB For Message and Attachment object, it require another
/// ROP for submit DB. For Logon and Folder object, it DO NOT need any other ROPs for submit.</param>
void RopDeletePropertiesMethod(out bool isNoValidValueReturnedForDeletedProperties, out bool isChangedInDB);
/// <summary>
/// This method is used to commit the changes made to a message.
/// </summary>
/// <param name="isChangedInDB">Indicates whether changes of Message object submit to database
/// when [RopSetProperties] or [RopDeleteProperties].</param>
void RopSaveChangesMessageMethod(out bool isChangedInDB);
/// <summary>
/// This method is used to commit the changes made to an attachment.
/// </summary>
/// <param name="isChangedInDB">Indicates whether changes of Message object submit to database
/// when [RopSetProperties] or [RopDeleteProperties].</param>
void RopSaveChangesAttachmentMethod(out bool isChangedInDB);
/// <summary>
/// This method is used to open a property as a Stream object, enabling the client to perform various streaming operations on the property.
/// </summary>
/// <param name="obj">Specifies which object will be operated.</param>
/// <param name="openFlag">Specifies OpenModeFlags for [RopOpenStream].</param>
/// <param name="isPropertyTagExist">Indicates whether request property exist.</param>
/// <param name="isStreamSizeEqualToStream">Indicates whether StreamSize in response is
/// the same with the current number of BYTES in the stream.</param>
/// <param name="error">If the property tag does not exist for the object and "Create"
/// is not specified in OpenModeFlags, NotFound error should be returned.</param>
void RopOpenStreamMethod(ObjectToOperate obj, OpenModeFlags openFlag, bool isPropertyTagExist, out bool isStreamSizeEqualToStream, out CPRPTErrorCode error);
/// <summary>
/// This method is used to open a different type of properties as a Stream object, enabling the client to perform various streaming operations on the property.
/// </summary>
/// <param name="obj">Specifies which object will be operated.</param>
/// <param name="propertyType">Specifies which type of property will be operated.</param>
/// <param name="error">Returned error code.</param>
void RopOpenStreamWithDifferentPropertyType(ObjectToOperate obj, PropertyTypeName propertyType, out CPRPTErrorCode error);
/// <summary>
/// This method is used to release all resources associated with a Server object.
/// The client uses RopRelease ([MS-OXCROPS] section 2.2.14.3) after it is done with the Stream object.
/// </summary>
/// <param name="obj">Specifies which object will be operated.</param>
void RopReleaseMethodNoVerify(ObjectToOperate obj);
/// <summary>
/// This method is used to read the stream of bytes from a Stream object.
/// </summary>
/// <param name="isReadingFailed">Indicates whether reading stream get failure. E.g. object handle is not stream.</param>
void RopReadStreamMethod(bool isReadingFailed);
/// <summary>
/// This method is used to read the stream of limited size bytes from a Stream object.
/// </summary>
/// <param name="byteCount">Indicates the size to be read.</param>
/// <param name="maxByteCount">If byteCount is 0xBABE, use MaximumByteCount to determine the size to be read.</param>
void RopReadStreamWithLimitedSize(ushort byteCount, uint maxByteCount);
/// <summary>
/// This method is used to set the seek pointer to a new location, which is relative to the beginning of the stream, the end of the stream, or the location of the current seek pointer.
/// </summary>
/// <param name="condition">Specifies particular scenario of RopSeekStream.</param>
/// <param name="isStreamExtended">Indicates whether a stream object is extended and zero filled to the new seek location.</param>
/// <param name="error">Returned error code.</param>
void RopSeekStreamMethod(SeekStreamCondition condition, out bool isStreamExtended, out CPRPTErrorCode error);
/// <summary>
/// This method is used to lock a specified range of bytes in a Stream object.
/// </summary>
/// <param name="preState">Specifies the pre-state before call [RopLockRegionStream]</param>
/// <param name="error">Return error
/// 1. If there are previous locks that are not expired, the server MUST return an AccessDenied error.
/// 2. If a session with an expired lock calls any ROP for this Stream object that would encounter the locked region,
/// the server MUST return a NetworkError.</param>
void RopLockRegionStreamMethod(PreStateBeforeLock preState, out CPRPTErrorCode error);
/// <summary>
/// This method is used to unlock a specified range of bytes in a Stream object.
/// </summary>
/// <param name="isPreviousLockExists">Indicates whether a previous lock exists and not owned by this session.
/// If there are previous locks that are not owned by the session calling the ROP, the server MUST leave them unmodified.</param>
void RopUnlockRegionStreamMethod(bool isPreviousLockExists);
/// <summary>
/// This method is used to write the stream of bytes into a Stream object.
/// </summary>
/// <param name="openFlag">Specifies the OpenModeFlags of the stream.</param>
/// <param name="isExceedMax">Indicates whether the write will exceed the maximum stream size.</param>
/// <param name="error"> Specifies the ErrorCode when WriteStream failed:
/// STG_E_ACCESSDENIED 0x80030005 Write access is denied.
/// When stream is opened with ReadOnly flag.</param>
void RopWriteStreamMethod(OpenModeFlags openFlag, bool isExceedMax, out CPRPTErrorCode error);
/// <summary>
/// This method is used to write the stream of bytes into a Stream object.
/// </summary>
/// <param name="openFlag">Specifies the OpenModeFlags of the stream.</param>
/// <param name="isExceedMax">Indicates whether the write will exceed the maximum stream size.</param>
/// <param name="error"> Specifies the ErrorCode when WriteStreamExtended failed:STG_E_ACCESSDENIED
/// 0x80030005 Write access is denied.When stream is opened with ReadOnly flag.</param>
void RopWriteStreamExtendedMethod(OpenModeFlags openFlag, bool isExceedMax, out CPRPTErrorCode error);
/// <summary>
/// This method is used to ensure that any changes made to a Stream object are persisted in storage for a Folder object.
/// </summary>
/// <param name="openFlag">Indicates the OpenModeFlags when stream is opened.</param>
/// <param name="isPropertyValueChanged">Indicates whether property value is changed.</param>
void RopCommitStreamMethod(OpenModeFlags openFlag, out bool isPropertyValueChanged);
/// <summary>
/// Method for ROP lease operation.
/// The client uses RopRelease ([MS-OXCROPS] section 2.2.14.3) after it is done with the Stream object.
/// </summary>
/// <param name="obj">Specifies which object will be operated.</param>
/// <param name="isPropertyValueChanged">
/// For Folder Object, this ROP should not change the value in stream after RopWriteStream.
/// For non-Folder Object, this ROP should change the value.
/// </param>
void RopReleaseMethod(ObjectToOperate obj, out bool isPropertyValueChanged);
/// <summary>
/// This method is used to copy a specified number of bytes from the current seek pointer in the source stream to the current seek pointer in the destination stream.
/// </summary>
/// <param name="isDestinationExist">Specified the whether the destination existed.</param>
/// <param name="isReadWriteSuccess">When call success:The server MUST read the number of BYTES
/// requested from the source Stream object, and write those bytes into the destination Stream object.</param>
/// <param name="error">If Destination object does not exist, expect DestinationNullObject error.</param>
void RopCopyToStreamMethod(bool isDestinationExist, out bool isReadWriteSuccess, out CPRPTErrorCode error);
/// <summary>
/// This method is used to write bytes to a stream and commits the stream.
/// </summary>
/// <param name="error">This ROP MUST NOT be used on Stream objects opened on
/// properties on Folder objects which means it should be failed against Folder object.</param>
void RopWriteAndCommitStreamMethod(out CPRPTErrorCode error);
/// <summary>
/// This method is used to create a new Stream object that is a clone of another Stream object.
/// </summary>
void RopCloneStreamMethod();
/// <summary>
/// This method is used to retrieve the size of the stream.
/// </summary>
void RopGetStreamSizeMethod();
/// <summary>
/// This method is used to set the size of a stream.
/// </summary>
/// <param name="isSizeIncreased"> Indicates the new size is increased or decreased.</param>
/// <param name="isExtendedValueZero">
/// If the size of the stream is increased, then value of the extended stream MUST be zero.
/// </param>
/// <param name="isLost">
/// If the size of the stream is decreased, the information that extends past the end of the new size is lost.
/// </param>
/// <param name="isIncrease">If the size of the stream is increased, set this value to true</param>
void RopSetStreamSizeMethod(bool isSizeIncreased, out bool isExtendedValueZero, out bool isLost, out bool isIncrease);
/// <summary>
/// This method is used to copy or move one or more properties from one object to another.
/// </summary>
/// <param name="copyFlag">Specifies the CopyFlags in the call request.</param>
/// <param name="isWantAsynchronousZero">Indicates whether WantAsynchronous parameter in call request is zero.</param>
/// <param name="isDestinationExist">Indicates whether destination object is exist for [RopCopyProperties].</param>
/// <param name="isPropertiesDeleted">If CopyFlags is set to Move,Source object will be deleted after copy to.</param>
/// <param name="isChangedInDB">Indicates whether the change is submit to DB.</param>
/// <param name="isOverwriteDestination">If CopyFlags is set to NoOverWrite,Destination should not be overwritten.</param>
/// <param name="isReturnedRopProgress">If this ROP is performed Asynchronously,RopProgress response returned.</param>
/// <param name="error">If destination object is not exist,NullDestinationObject error will be returned.</param>
void RopCopyPropertiesMethod(
CopyFlags copyFlag,
bool isWantAsynchronousZero,
bool isDestinationExist,
out bool isPropertiesDeleted,
out bool isChangedInDB,
out bool isOverwriteDestination,
out bool isReturnedRopProgress,
out CPRPTErrorCode error);
/// <summary>
/// This method is used to copy or move all but a specified few properties from a source object to a destination object.
/// </summary>
/// <param name="copyFlag">Specifies the CopyFlags in the call request.</param>
/// <param name="isWantAsynchronousZero">Indicates whether WantAsynchronous parameter in call request is zero.</param>
/// <param name="isWantSubObjectsZero">Indicates whether WantSubObjects parameter in call request is zero.</param>
/// <param name="isDestinationExist">Indicates whether destination object is exist for [RopCopyTo]</param>
/// <param name="isPropertiesDeleted">If CopyFlags is set to Move,Source object will be deleted after copy to.</param>
/// <param name="isSubObjectCopied">Indicates whether sub-object properties is also be copied.</param>
/// <param name="isOverwriteDestination">If CopyFlags is set to NoOverWrite, destination should not be overwritten.</param>
/// <param name="isReturnedRopProgress">If this ROP is performed Asynchronously, RopProgress response will be returned.</param>
/// <param name="isChangedInDB">Indicates whether destination is changed in database.</param>
/// <param name="error">If destination object does not exist, NullDestinationObject error will be returned.</param>
void RopCopyToMethod(
CopyFlags copyFlag,
bool isWantAsynchronousZero,
bool isWantSubObjectsZero,
bool isDestinationExist,
out bool isPropertiesDeleted,
out bool isSubObjectCopied,
out bool isOverwriteDestination,
out bool isReturnedRopProgress,
out bool isChangedInDB,
out CPRPTErrorCode error);
/// <summary>
/// This method is used to copy or move properties from a source object to a destination object with error code returned.
/// </summary>
/// <param name="condition">Specifies a special scenario of RopCopyTo.</param>
void RopCopyToMethodForErrorCodeTable(CopyToCondition condition);
/// <summary>
/// This method is used to copy or move properties from a source object to a destination object on public folder.
/// </summary>
void RopCopyToForPublicFolder();
/// <summary>
/// This method is used to report the progress status of an asynchronous operation.
/// </summary>
/// <param name="isOtherRopSent">Indicates whether other ROP is sent.</param>
/// <param name="isWantCancel">Indicates whether WantCancel parameter is set to non-zero,any
/// non-zero value means client want cancel the original operation.</param>
/// <param name="isOriginalOpsResponse">If original asynchronous ROPs are done or canceled,
/// response should be original ROPs response. Otherwise, it should be RopProgress response.</param>
/// <param name="isOtherRopResponse">Indicates the other ROP's response is returned. If the client sends a
/// ROP other than RopProgress to the server with the same logon before the asynchronous operation is
/// complete the server MUST abort the asynchronous operation and respond to the new ROP.</param>
void RopProgressMethod(bool isOtherRopSent, bool isWantCancel, out bool isOriginalOpsResponse, out bool isOtherRopResponse);
/// <summary>
/// Get common object properties in order to test their type.
/// </summary>
/// <param name="commonProperty">The nine Common Object Properties defined in section 2.2.1.</param>
void GetCommonObjectProperties(CommonObjectProperty commonProperty);
/// <summary>
/// Set common object properties in order to test whether each of them is read-only.
/// </summary>
/// <param name="commonProperty">The nine Common Object Properties defined in section 2.2.1.</param>
/// <param name="error">When a property is specified as "read-only for the client", the server MUST
/// return an error and ignore any request to change the value of that property.</param>
void SetCommonObjectProperties(CommonObjectProperty commonProperty, out CPRPTErrorCode error);
/// <summary>
/// Checks if the requirement is enabled in the SHOULDMAY ptfconfig files.
/// </summary>
/// <param name="rsid">Requirement ID</param>
/// <param name="enabled">True represents the requirement is enabled; false represents the requirement is disabled.</param>
void CheckRequirementEnabled(int rsid, out bool enabled);
/// <summary>
/// This method is used to check whether MAPIHTTP transport is supported by SUT.
/// </summary>
/// <param name="isSupported">The transport is supported or not.</param>
void CheckMAPIHTTPTransportSupported(out bool isSupported);
}
}
| |
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 Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmStockGroup : 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;
int gID;
List<TextBox> txtFields = new List<TextBox>();
List<CheckBox> chkFields = new List<CheckBox>();
private void loadLanguage()
{
//frmStockGroup = No Code [Edit Stock Group Details]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmStockGroup.Caption = rsLang("LanguageLayoutLnk_Description"): frmStockGroup.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
//Undo|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.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.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010;
//General|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1078;
//Stock Group Name|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_38.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_38.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//_chkFields_1 = No Code [Disable this Stock Group]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _chkFields_1.Caption = rsLang("LanguageLayoutLnk_Description"): _chkFields_1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmStockGroup.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 buildDataControls()
{
// doDataControl Me.cmbChannel, "SELECT ChannelID, Channel_Name FROM Channel ORDER BY ChannelID", "Customer_ChannelID", "ChannelID", "Channel_Name"
}
private void doDataControl(ref myDataGridView dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField)
{
//Dim rs As ADODB.Recordset
//rs = getRS(sql)
//dataControl.DataSource = rs
//dataControl.DataSource = adoPrimaryRS
//dataControl.DataField = DataField
//dataControl.boundColumn = boundColumn
//dataControl.listField = listField
}
public void loadItem(ref int id)
{
System.Windows.Forms.TextBox oText = null;
System.Windows.Forms.CheckBox oCheck = null;
// ERROR: Not supported in C#: OnErrorStatement
if (id) {
adoPrimaryRS = modRecordSet.getRS(ref "select * from StockGroup WHERE StockGRoupID = " + id);
} else {
adoPrimaryRS = modRecordSet.getRS(ref "select * from StockGroup");
adoPrimaryRS.AddNew();
this.Text = this.Text + " [New record]";
mbAddNewFlag = true;
}
setup();
BindingSource bind = new BindingSource();
foreach (TextBox oText_loopVariable in this.txtFields) {
oText = oText_loopVariable;
bind.DataSource = adoPrimaryRS;
oText.DataBindings.Add(bind.DataSource);
oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize;
}
foreach (CheckBox oCheck_loopVariable in this.chkFields) {
oCheck = oCheck_loopVariable;
oCheck.DataBindings.Add(bind.DataSource);
}
buildDataControls();
mbDataChanged = false;
loadLanguage();
ShowDialog();
}
private void setup()
{
}
private void frmStockGroup_Load(object sender, System.EventArgs e)
{
txtFields.AddRange(new TextBox[] { _txtFields_0 });
chkFields.AddRange(new CheckBox[] { _chkFields_1 });
}
private void frmStockGroup_Resize(System.Object eventSender, System.EventArgs eventArgs)
{
Button cmdLast = new Button();
Button cmdnext = new Button();
Label lblStatus = new Label();
// ERROR: Not supported in C#: OnErrorStatement
lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500;
cmdnext.Left = lblStatus.Width + 700;
cmdLast.Left = cmdnext.Left + 340;
}
private void frmStockGroup_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (mbEditFlag | mbAddNewFlag)
goto EventExitSub;
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
adoPrimaryRS.Move(0);
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
EventExitSub:
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmStockGroup_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(System.Object eventSender, System.EventArgs eventArgs)
{
// ERROR: Not supported in C#: OnErrorStatement
if (mbAddNewFlag) {
this.Close();
} else {
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
if (mvBookMark > 0) {
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
mbDataChanged = false;
}
}
private bool update_Renamed()
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
functionReturnValue = true;
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
if (mbAddNewFlag) {
adoPrimaryRS.MoveLast();
//move to the new record
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
functionReturnValue = false;
return functionReturnValue;
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
if (update_Renamed()) {
this.Close();
}
}
private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocus(ref _txtFields_0);
}
private void txtInteger_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtInteger(Index)
}
private void txtInteger_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPress KeyAscii
}
private void txtInteger_MyLostFocus(ref short Index)
{
// LostFocus txtInteger(Index), 0
}
private void txtFloat_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtFloat(Index)
}
private void txtFloat_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPress KeyAscii
}
private void txtFloat_MyLostFocus(ref short Index)
{
// MyGotFocusNumeric txtFloat(Index), 2
}
private void txtFloatNegative_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtFloatNegative(Index)
}
private void txtFloatNegative_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPressNegative txtFloatNegative(Index), KeyAscii
}
private void txtFloatNegative_MyLostFocus(ref short Index)
{
// LostFocus txtFloatNegative(Index), 2
}
}
}
| |
/* Code created by vzrus: http://sourceforge.net/users/vzrus
* for Yet Another Forum.NET http://www.yetanotherforum.net/
* and can be used and modified without any limitations as part
* of Yet Another Forum.NET under every open source licence.
* Creation date:10/3/09
*/
namespace YAF.Pages.Admin
{
#region Using
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web.UI.WebControls;
using YAF.Classes;
using YAF.Classes.Data;
using YAF.Controls;
using YAF.Core;
using YAF.Core.Extensions;
using YAF.Core.Helpers;
using YAF.Core.Model;
using YAF.Core.Services;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.Extensions;
using YAF.Types.Flags;
using YAF.Types.Interfaces;
using YAF.Types.Models;
using YAF.Types.Objects;
using YAF.Utilities;
using YAF.Utils;
using YAF.Utils.Helpers;
#endregion
/// <summary>
/// The control generates test data for different data layers.
/// </summary>
public partial class test_data : AdminPage
{
// private string regBase = @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$";
#region Constants and Fields
/// <summary>
/// The board create limit.
/// </summary>
private const int BoardCreateLimit = 100;
/// <summary>
/// The category create limit.
/// </summary>
private const int categoryCreateLimit = 100;
/// <summary>
/// The create common limit.
/// </summary>
private const int createCommonLimit = 9999;
/// <summary>
/// The pmessage prefix.
/// </summary>
private const string pmessagePrefix = "pmsg-";
/// <summary>
/// The random guid.
/// </summary>
private string randomGuid = Guid.NewGuid().ToString();
#endregion
#region Methods
/// <summary>
/// The cancel_ click.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Cancel_Click([NotNull] object sender, [NotNull] EventArgs e)
{
YafBuildLink.Redirect(ForumPages.admin_test_data);
}
/// <summary>
/// The categories boards options_ on selected index changed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void CategoriesBoardsOptions_OnSelectedIndexChanged([NotNull] object sender, [NotNull] EventArgs e)
{
this.CategoriesBoardsList.Visible = this.CategoriesBoardsOptions.SelectedIndex == 3;
}
/// <summary>
/// The create test data_ click.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void CreateTestData_Click([NotNull] object sender, [NotNull] EventArgs e)
{
if (!this.Page.IsValid)
{
return;
}
if (!this.ValidateControlsValues())
{
return;
}
var sb = new StringBuilder();
sb.AppendLine("Test Data Generator reports: ");
sb.AppendLine("Created:");
sb.Append(this.CreateUsers());
sb.Append(this.CreateBoards());
sb.Append(this.CreateCategories());
sb.Append("; ");
sb.AppendFormat("{0} Forums, ", this.CreateForums());
sb.AppendFormat("{0} Topics, ", this.CreateTopics(0, 0, 0));
sb.AppendFormat("{0} Messages, ", this.CreatePosts(0, 0, 0));
sb.AppendFormat("{0} Private Messages, ", this.CreatePMessages());
string mesRetStr = sb.ToString();
this.Logger.Log(this.PageContext.PageUserID, this, mesRetStr, EventLogTypes.Information);
this.PageContext.AddLoadMessage(mesRetStr);
YafBuildLink.Redirect(ForumPages.admin_test_data);
}
/// <summary>
/// The forums category_ on selected index changed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void ForumsCategory_OnSelectedIndexChanged([NotNull] object sender, [NotNull] EventArgs e)
{
DataTable forums_category = LegacyDb.forum_listall_fromCat(
this.PageContext.PageBoardID, this.ForumsCategory.SelectedValue.ToType<int>());
this.ForumsParent.DataSource = forums_category;
this.ForumsParent.DataBind();
}
/// <summary>
/// The On PreRender event.
/// </summary>
/// <param name="e">
/// the Event Arguments
/// </param>
protected override void OnPreRender([NotNull] EventArgs e)
{
// setup jQuery and Jquery Ui Tabs.
YafContext.Current.PageElements.RegisterJsBlock(
"TestDataTabsJs",
JavaScriptBlocks.JqueryUITabsLoadJs(
this.TestDataTabs.ClientID,
this.hidLastTab.ClientID,
this.hidLastTabId.ClientID,
false));
base.OnPreRender(e);
}
/// <summary>
/// The p messages boards options_ on selected index changed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void PMessagesBoardsOptions_OnSelectedIndexChanged([NotNull] object sender, [NotNull] EventArgs e)
{
this.PMessagesBoardsList.Visible = this.PMessagesBoardsOptions.SelectedIndex == 3;
}
/// <summary>
/// The page_ load.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
if (this.IsPostBack)
{
return;
}
this.PageLinks.AddRoot();
this.PageLinks.AddLink(
this.GetText("ADMIN_ADMIN", "Administration"), YafBuildLink.GetLink(ForumPages.admin_admin));
this.PageLinks.AddLink(this.GetText("ADMIN_TEST_DATA", "TITLE"), string.Empty);
this.Page.Header.Title = "{0} - {1}".FormatWith(
this.GetText("ADMIN_ADMIN", "Administration"), this.GetText("ADMIN_TEST_DATA", "TITLE"));
this.Populate_Controls();
const string _BoardOptionsCurrentBoardIn = "In Current Board";
const string _BoardOptionsAllBoardsIn = "In All Boards";
const string _BoardOptionsAllBoardsButCurrentIn = "In All But Current";
const string _BoardOptionsAllBoardsSpecificIn = "In A Specific Board";
this.TimeZones.DataSource = StaticDataHelper.TimeZones();
DataTable categories = this.GetRepository<Category>().List();
this.ForumsCategory.DataSource = categories;
this.TopicsCategory.DataSource = categories;
this.PostsCategory.DataSource = categories;
// Access Mask Lists
this.ForumsStartMask.DataSource = this.GetRepository<AccessMask>().List();
this.ForumsAdminMask.DataSource = this.ForumsStartMask.DataSource;
this.ForumsGroups.DataSource = this.GetRepository<Group>().List(boardId: this.PageContext.PageBoardID);
// Board lists
this.UsersBoardsList.DataSource = this.GetRepository<Board>().List();
this.CategoriesBoardsList.DataSource = this.UsersBoardsList.DataSource;
this.PMessagesBoardsList.DataSource = this.UsersBoardsList.DataSource;
this.DataBind();
if (this.ForumsAdminMask.Items.Count > 0)
{
this.ForumsAdminMask.SelectedIndex = this.ForumsAdminMask.Items.Count - 1;
}
if (this.ForumsStartMask.Items.Count > 1)
{
this.ForumsStartMask.SelectedIndex = 1;
}
this.TopicsCategory.ClearSelection();
this.PostsCategory.ClearSelection();
this.ForumsCategory.SelectedIndex = -1;
this.TimeZones.Items.FindByValue("0").Selected = true;
this.From.Text = this.PageContext.User.UserName;
this.To.Text = this.PageContext.User.UserName;
this.TopicsPriorityList.Items.Add(new ListItem("Normal", "0"));
this.TopicsPriorityList.Items.Add(new ListItem("Sticky", "1"));
this.TopicsPriorityList.Items.Add(new ListItem("Announcement", "2"));
this.TopicsPriorityList.SelectedIndex = 0;
this.UsersBoardsOptions.Items.Add(new ListItem(_BoardOptionsCurrentBoardIn, "0"));
this.UsersBoardsOptions.Items.Add(new ListItem(_BoardOptionsAllBoardsIn, "1"));
this.UsersBoardsOptions.Items.Add(new ListItem(_BoardOptionsAllBoardsButCurrentIn, "2"));
this.UsersBoardsOptions.Items.Add(new ListItem(_BoardOptionsAllBoardsSpecificIn, "3"));
this.UsersBoardsOptions.SelectedIndex = 0;
this.CategoriesBoardsOptions.Items.Add(new ListItem(_BoardOptionsCurrentBoardIn, "0"));
this.CategoriesBoardsOptions.Items.Add(new ListItem(_BoardOptionsAllBoardsIn, "1"));
this.CategoriesBoardsOptions.Items.Add(new ListItem(_BoardOptionsAllBoardsButCurrentIn, "2"));
this.CategoriesBoardsOptions.Items.Add(new ListItem(_BoardOptionsAllBoardsSpecificIn, "3"));
this.CategoriesBoardsOptions.SelectedIndex = 0;
this.PMessagesBoardsOptions.Items.Add(new ListItem(_BoardOptionsCurrentBoardIn, "0"));
this.PMessagesBoardsOptions.Items.Add(new ListItem(_BoardOptionsAllBoardsIn, "1"));
this.PMessagesBoardsOptions.Items.Add(new ListItem(_BoardOptionsAllBoardsButCurrentIn, "2"));
this.PMessagesBoardsOptions.Items.Add(new ListItem(_BoardOptionsAllBoardsSpecificIn, "3"));
this.PMessagesBoardsOptions.SelectedIndex = 0;
}
/// <summary>
/// The posts category_ on selected index changed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void PostsCategory_OnSelectedIndexChanged([NotNull] object sender, [NotNull] EventArgs e)
{
DataTable posts_category = LegacyDb.forum_listall_fromCat(
this.PageContext.PageBoardID, this.PostsCategory.SelectedValue.ToType<int>());
this.PostsForum.DataSource = posts_category;
this.PostsForum.DataBind();
}
/// <summary>
/// The posts forum_ on selected index changed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void PostsForum_OnSelectedIndexChanged([NotNull] object sender, [NotNull] EventArgs e)
{
int _forumID;
if (!int.TryParse(this.PostsForum.SelectedValue, out _forumID))
{
return;
}
DataTable topics = LegacyDb.topic_list(
this.PostsForum.SelectedValue.ToType<int>(),
this.PageContext.PageUserID,
DateTimeHelper.SqlDbMinTime(),
DateTime.UtcNow,
0,
100,
false,
false,
false);
this.PostsTopic.DataSource = topics;
this.PostsTopic.DataBind();
}
/// <summary>
/// The topics category_ on selected index changed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void TopicsCategory_OnSelectedIndexChanged([NotNull] object sender, [NotNull] EventArgs e)
{
DataTable topic_forums = LegacyDb.forum_listall_fromCat(
this.PageContext.PageBoardID, this.TopicsCategory.SelectedValue.ToType<int>());
this.TopicsForum.DataSource = topic_forums;
this.TopicsForum.DataBind();
}
/// <summary>
/// The users boards options_ on selected index changed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void UsersBoardsOptions_OnSelectedIndexChanged([NotNull] object sender, [NotNull] EventArgs e)
{
this.UsersBoardsList.Visible = this.UsersBoardsOptions.SelectedIndex == 3;
}
/// <summary>
/// The create boards.
/// </summary>
/// <returns>
/// The number of created boards.
/// </returns>
private string CreateBoards()
{
int _boardNumber;
int _usersNumber;
if (!int.TryParse(this.BoardNumber.Text.Trim(), out _boardNumber))
{
return null;
}
if (_boardNumber <= 0)
{
return null;
}
if (!int.TryParse(this.BoardsUsersNumber.Text.Trim(), out _usersNumber))
{
return null;
}
if (_usersNumber < 0)
{
return null;
}
if (_boardNumber > BoardCreateLimit)
{
_boardNumber = BoardCreateLimit;
}
this.BoardMembershipName.Text = null;
this.BoardRolesName.Text = null;
int i;
for (i = 0; i < _boardNumber; i++)
{
string boardName = this.BoardPrefixTB.Text.Trim() + Guid.NewGuid();
int curboard = this.GetRepository<Board>().Create(
boardName,
"en-US",
"english.xml",
this.BoardMembershipName.Text.Trim(),
this.BoardRolesName.Text.Trim(),
this.PageContext.User.UserName,
this.PageContext.User.Email,
this.PageContext.User.ProviderUserKey.ToString(),
this.PageContext.IsHostAdmin,
Config.CreateDistinctRoles && Config.IsAnyPortal ? "YAF " : string.Empty);
this.CreateUsers(curboard, _usersNumber);
}
return string.Format("{0} Boards, {1} Users in each Board; ", i, _usersNumber);
}
/// <summary>
/// Create categories from boards
/// </summary>
/// <param name="boardID">
/// The boardID
/// </param>
/// <returns>
/// The create categories.
/// </returns>
private string CreateCategories(int boardID)
{
string noCategories = "0 categories";
bool excludeCurrentBoardB = false;
bool useListB = false;
int numCategoriesInt = 0;
if (!int.TryParse(this.BoardsCategoriesNumber.Text.Trim(), out numCategoriesInt))
{
return noCategories;
}
if (numCategoriesInt < 0)
{
return noCategories;
}
if (numCategoriesInt > categoryCreateLimit)
{
numCategoriesInt = categoryCreateLimit;
}
int _numForums;
if (!int.TryParse(this.BoardsForumsNumber.Text.Trim(), out _numForums))
{
return noCategories;
}
if (_numForums < 0)
{
return noCategories;
}
int _numTopics;
if (!int.TryParse(this.BoardsTopicsNumber.Text.Trim(), out _numTopics))
{
return noCategories;
}
if (_numTopics < 0)
{
return noCategories;
}
int _numMessages;
if (!int.TryParse(this.BoardsMessagesNumber.Text.Trim(), out _numMessages))
{
return noCategories;
}
if (_numMessages < 0)
{
return noCategories;
}
return this.CreateCategoriesBase(
boardID, 1, _numForums, _numTopics, _numMessages, numCategoriesInt, excludeCurrentBoardB, useListB);
}
/// <summary>
/// Create categories from Categories
/// </summary>
/// <returns>
/// The create categories.
/// </returns>
private string CreateCategories()
{
const string noCategories = "0 categories";
int boardID = 0;
// int categoriesLimit = 1;
bool _excludeCurrentBoard = false;
int _numForums;
if (!int.TryParse(this.CategoriesForumsNumber.Text.Trim(), out _numForums))
{
return noCategories;
}
if (_numForums < 0)
{
return noCategories;
}
int _numTopics;
if (!int.TryParse(this.CategoriesTopicsNumber.Text.Trim(), out _numTopics))
{
return "0 Categories";
}
if (_numTopics < 0)
{
return noCategories;
}
int _numMessages;
if (!int.TryParse(this.CategoriesMessagesNumber.Text.Trim(), out _numMessages))
{
return noCategories;
}
if (_numMessages < 0)
{
return noCategories;
}
int _numCategories;
int _boardCount = 1;
bool _useList = false;
switch (this.CategoriesBoardsOptions.SelectedIndex)
{
case 0:
boardID = YafContext.Current.PageBoardID;
break;
case 1:
_boardCount = this.CategoriesBoardsList.Items.Count;
_useList = true;
break;
case 2:
_boardCount = this.CategoriesBoardsList.Items.Count - 1;
_excludeCurrentBoard = true;
_useList = true;
break;
case 3:
boardID = this.CategoriesBoardsList.SelectedValue.ToType<int>();
break;
}
if (!int.TryParse(this.CategoriesNumber.Text.Trim(), out _numCategories))
{
return noCategories;
}
if (_numCategories <= 0)
{
return noCategories;
}
if (_numCategories > categoryCreateLimit)
{
_numCategories = categoryCreateLimit;
}
return this.CreateCategoriesBase(
boardID,
_boardCount,
_numForums,
_numTopics,
_numMessages,
_numCategories,
_excludeCurrentBoard,
_useList);
}
/// <summary>
/// The create categories base.
/// </summary>
/// <param name="boardID">
/// The board id.
/// </param>
/// <param name="boardCount">
/// The board count.
/// </param>
/// <param name="numForums">
/// The num forums.
/// </param>
/// <param name="numTopics">
/// The num topics.
/// </param>
/// <param name="numMessages">
/// The num messages.
/// </param>
/// <param name="numCategories">
/// The num categories.
/// </param>
/// <param name="excludeCurrentBoard">
/// The exclude current board.
/// </param>
/// <param name="useList">
/// The use list.
/// </param>
/// <returns>
/// The create categories base.
/// </returns>
private string CreateCategoriesBase(
int boardID,
int boardCount,
int numForums,
int numTopics,
int numMessages,
int numCategories,
bool excludeCurrentBoard,
bool useList)
{
int ib;
for (ib = 0; ib < boardCount; ib++)
{
if (useList)
{
boardID = this.CategoriesBoardsList.Items[ib].Value.ToType<int>();
}
int i;
if (!(excludeCurrentBoard && boardID == YafContext.Current.PageBoardID))
{
for (i = 0; i < numCategories; i++)
{
string catName = this.CategoryPrefixTB.Text.Trim() + Guid.NewGuid();
// TODO: should return number of categories created
this.GetRepository<Category>().Save(null, catName, null, 100, boardID);
DataTable dt = this.GetRepository<Category>().Simplelist(0, 10000);
foreach (DataRow dr in dt.Rows.Cast<DataRow>().Where(dr => dr["Name"].ToString() == catName))
{
this.CreateForums(dr["CategoryID"].ToType<int>(), null, numForums, numTopics, numMessages);
}
// We don't have last category index, so not implemented.... CreateForums( categoryID,numForums,numTopics,numMessages )
}
}
i = 0;
}
return "{0} Categories, ".FormatWith(ib);
}
/// <summary>
/// Create forums from Forums page
/// </summary>
/// <returns>
/// The create forums.
/// </returns>
private int CreateForums()
{
object parentID = null;
int parentIDInt;
if (int.TryParse(this.ForumsParent.Text.Trim(), out parentIDInt))
{
parentID = parentIDInt;
}
int numTopics;
if (!int.TryParse(this.ForumsTopicsNumber.Text.Trim(), out numTopics))
{
return 0;
}
if (numTopics < 0)
{
return 0;
}
int numPosts;
if (!int.TryParse(this.ForumsMessagesNumber.Text.Trim(), out numPosts))
{
return 0;
}
if (numPosts < 0)
{
return 0;
}
int numForums;
if (!int.TryParse(this.ForumsNumber.Text.Trim(), out numForums))
{
return 0;
}
if (numForums <= 0)
{
return 0;
}
int categoryID;
if (!int.TryParse(this.ForumsCategory.SelectedValue, out categoryID))
{
return 0;
}
if (numForums > createCommonLimit)
{
numForums = createCommonLimit;
}
return this.CreateForums(categoryID, parentID, numForums, numTopics, numPosts);
}
/// <summary>
/// Create forums from Categories
/// </summary>
/// <param name="categoryID">
/// </param>
/// <param name="parentID">
/// The parent ID.
/// </param>
/// <param name="numForums">
/// The num Forums.
/// </param>
/// <param name="_topicsToCreate">
/// Number of topics to create.
/// </param>
/// <param name="_messagesToCreate">
/// Number of messages to create.
/// </param>
/// <returns>
/// The create forums.
/// </returns>
private int CreateForums(
int categoryID, [NotNull] object parentID, int numForums, int _topicsToCreate, int _messagesToCreate)
{
bool countMessagesInStatistics = this.ForumsCountMessages.Text.Trim().IsNotSet();
bool isHiddenIfNoAccess = this.ForumsHideNoAccess.Text.Trim().IsNotSet();
isHiddenIfNoAccess = true;
// ForumsCategory.Items.FindByValue("0").Selected = true;
long uniqueForum = 0;
int iforums;
for (iforums = 0; iforums < numForums; iforums++)
{
long _forumID = 0;
this.randomGuid = Guid.NewGuid().ToString();
DataTable _accessForumList = LegacyDb.forumaccess_list(_forumID);
_forumID = LegacyDb.forum_save(
_forumID,
categoryID,
parentID,
this.ForumPrefixTB.Text.Trim() + this.randomGuid,
"Description of " + this.ForumPrefixTB.Text.Trim() + this.randomGuid,
100,
false,
isHiddenIfNoAccess,
countMessagesInStatistics,
false,
null,
false,
this.ForumsStartMask.SelectedValue,
null,
null,
null,
null,
false);
if (_forumID <= 0)
{
continue;
}
for (int i1 = 0; i1 < _accessForumList.Rows.Count; i1++)
{
LegacyDb.forumaccess_save(
_forumID,
_accessForumList.Rows[i1]["GroupID"],
_accessForumList.Rows[i1]["AccessMaskID"].ToType<int>());
}
LegacyDb.forumaccess_save(_forumID, this.ForumsGroups.SelectedValue, this.ForumsAdminMask.SelectedValue);
if (_topicsToCreate <= 0)
{
continue;
}
if (uniqueForum == _forumID)
{
continue;
}
this.CreateTopics(_forumID.ToType<int>(), _topicsToCreate, _messagesToCreate);
uniqueForum = _forumID;
}
return iforums;
}
/// <summary>
/// The create p messages.
/// </summary>
/// <returns>
/// The number of created p messages.
/// </returns>
private int CreatePMessages()
{
int userID = this.PageContext.PageUserID;
int numPMessages;
if (!int.TryParse(this.PMessagesNumber.Text.Trim(), out numPMessages))
{
return 0;
}
if (numPMessages <= 0)
{
return 0;
}
string _fromUser = this.From.Text.Trim();
string _toUser = this.To.Text.Trim();
if (numPMessages > createCommonLimit)
{
numPMessages = createCommonLimit;
}
int i;
for (i = 0; i < numPMessages; i++)
{
this.randomGuid = Guid.NewGuid().ToString();
LegacyDb.pmessage_save(
LegacyDb.user_get(YafContext.Current.PageBoardID, Membership.GetUser(_fromUser).ProviderUserKey),
LegacyDb.user_get(YafContext.Current.PageBoardID, Membership.GetUser(_toUser).ProviderUserKey),
this.TopicPrefixTB.Text.Trim() + this.randomGuid,
"{0}{1} {2}".FormatWith(pmessagePrefix, this.randomGuid, this.PMessageText.Text.Trim()),
6,
-1);
}
if (this.MarkRead.Checked)
{
int userAID = LegacyDb.user_get(
YafContext.Current.PageBoardID, Membership.GetUser(_toUser).ProviderUserKey);
foreach (DataRow dr in LegacyDb.pmessage_list(null, userAID, null).Rows)
{
LegacyDb.pmessage_markread(dr["PMessageID"]);
// Clearing cache with old permissions data...
this.Get<IDataCache>().Remove(Constants.Cache.ActiveUserLazyData.FormatWith(userAID));
}
}
return i;
}
/// <summary>
/// The create posts.
/// </summary>
/// <param name="forumID">
/// The forum id.
/// </param>
/// <param name="topicID">
/// The topic id.
/// </param>
/// <param name="numMessages">
/// The num messages.
/// </param>
/// <returns>
/// The number of created posts.
/// </returns>
private int CreatePosts(int forumID, int topicID, int numMessages)
{
if (numMessages <= 0)
{
if (!int.TryParse(this.PostsNumber.Text.Trim(), out numMessages))
{
return 0;
}
}
if (numMessages <= 0)
{
return 0;
}
int categoryID;
if (!int.TryParse(this.PostsCategory.SelectedValue, out categoryID))
{
return 0;
}
if (forumID <= 0)
{
if (!int.TryParse(this.PostsForum.SelectedValue, out forumID))
{
return 0;
}
}
if (topicID <= 0)
{
if (!int.TryParse(this.PostsTopic.SelectedValue, out topicID))
{
return 0;
}
}
// if ( numMessages > createCommonLimit ) numMessages = createCommonLimit;
long messageid = 0;
int iposts;
const int _replyTo = -1;
for (iposts = 0; iposts < numMessages; iposts++)
{
this.randomGuid = Guid.NewGuid().ToString();
LegacyDb.message_save(
topicID,
this.PageContext.PageUserID,
"msgd-" + this.randomGuid + " " + this.MyMessage.Text.Trim(),
this.PageContext.User.UserName,
this.Request.GetUserRealIPAddress(),
null,
_replyTo,
this.GetMessageFlags(),
ref messageid);
// User != null ? null : From.Text
}
return iposts;
}
/// <summary>
/// The create topics.
/// </summary>
/// <param name="forumID">
/// The forum id.
/// </param>
/// <param name="numTopics">
/// The num topics.
/// </param>
/// <param name="_messagesToCreate">
/// The _messages to create.
/// </param>
/// <returns>
/// Number of created topics.
/// </returns>
private int CreateTopics(int forumID, int numTopics, int _messagesToCreate)
{
object _priority = 0;
if (forumID <= 0)
{
_priority = this.TopicsPriorityList.SelectedValue;
}
if (numTopics <= 0)
{
if (!int.TryParse(this.TopicsNumber.Text.Trim(), out numTopics))
{
return 0;
}
}
if (numTopics <= 0)
{
return 0;
}
int categoryID;
if (!int.TryParse(this.TopicsCategory.SelectedValue, out categoryID))
{
return 0;
}
if (forumID <= 0)
{
if (!int.TryParse(this.TopicsForum.SelectedValue, out forumID))
{
return 0;
}
}
if (_messagesToCreate <= 0)
{
if (!int.TryParse(this.TopicsMessagesNumber.Text.Trim(), out _messagesToCreate))
{
return 0;
}
}
if (_messagesToCreate < 0)
{
return 0;
}
// if ( numTopics > createCommonLimit ) numTopics = createCommonLimit;
int itopics;
for (itopics = 0; itopics < numTopics; itopics++)
{
long messageid = 0;
this.randomGuid = Guid.NewGuid().ToString();
object pollID = null;
long topicID = LegacyDb.topic_save(
forumID,
this.TopicPrefixTB.Text.Trim() + this.randomGuid,
string.Empty,
string.Empty,
"{0}{1}descr".FormatWith(this.TopicPrefixTB.Text.Trim(), this.randomGuid),
this.MessageContentPrefixTB.Text.Trim() + this.randomGuid,
this.PageContext.PageUserID,
_priority,
this.PageContext.User.UserName,
this.Request.GetUserRealIPAddress(),
DateTime.UtcNow,
string.Empty,
this.GetMessageFlags(),
ref messageid);
if (this.PollCreate.Checked)
{
// vzrus: always one in current code - a number of questions
const int questionsTotal = 1;
var pollList = new List<PollSaveList>(questionsTotal);
var rawChoices = new string[3,2];
rawChoices[0, 0] = "ans1-" + this.randomGuid;
rawChoices[0, 1] = "ans2-" + this.randomGuid;
rawChoices[1, 0] = null;
rawChoices[1, 1] = null;
rawChoices[2, 0] = null;
rawChoices[2, 1] = null;
object datePollExpire = null;
pollList.Add(
new PollSaveList(
"quest-" + this.randomGuid,
rawChoices,
(DateTime?)datePollExpire,
this.PageContext.PageUserID,
(int?)topicID,
null,
null,
null,
null,
null,
false,
false,
false,
false,
false));
pollID = LegacyDb.poll_save(pollList);
}
if (_messagesToCreate > 0)
{
this.CreatePosts(forumID, topicID.ToType<int>(), _messagesToCreate);
}
// User != null ? null : From.Text
}
return itopics;
}
/// <summary>
/// From Users Tab
/// </summary>
/// <returns>
/// The create users.
/// </returns>
private string CreateUsers()
{
int boardID = 0;
int _users_Number;
const int _outCounter = 0;
int _countLimit = 1;
bool _excludeCurrentBoard = false;
if (!int.TryParse(this.UsersNumber.Text.Trim(), out _users_Number))
{
return null;
}
if (_users_Number <= 0)
{
return null;
}
switch (this.UsersBoardsOptions.SelectedIndex)
{
case 0:
boardID = YafContext.Current.PageBoardID;
break;
case 1:
_countLimit = this.UsersBoardsList.Items.Count;
break;
case 2:
_countLimit = this.UsersBoardsList.Items.Count - 1;
_excludeCurrentBoard = true;
break;
case 3:
boardID = this.UsersBoardsList.SelectedValue.ToType<int>();
break;
}
return this.CreateUsers(0, _users_Number, _outCounter, _countLimit, _excludeCurrentBoard);
}
/// <summary>
/// Create Users From Board
/// </summary>
/// <param name="boardID">
/// </param>
/// <param name="_users_Number">
/// </param>
private void CreateUsers(int boardID, int _users_Number)
{
int _outCounter = 0;
int _countLimit = 1;
bool _excludeCurrentBoard = false;
this.CreateUsers(boardID, _users_Number, _outCounter, _countLimit, _excludeCurrentBoard);
return;
}
/// <summary>
/// The create users.
/// </summary>
/// <param name="boardID">
/// The board id.
/// </param>
/// <param name="_users_Number">
/// The _users_ number.
/// </param>
/// <param name="_outCounter">
/// The _out counter.
/// </param>
/// <param name="_countLimit">
/// The _count limit.
/// </param>
/// <param name="_excludeCurrentBoard">
/// The _exclude current board.
/// </param>
/// <returns>
/// The string with number of created users.
/// </returns>
private string CreateUsers(
int boardID, int _users_Number, int _outCounter, int _countLimit, bool _excludeCurrentBoard)
{
int iboards;
// if ( _users_Number > createCommonLimit ) _users_Number = createCommonLimit;
for (iboards = 0; iboards < _countLimit; iboards++)
{
boardID = this.UsersBoardsList.Items[iboards].Value.ToType<int>();
int i;
for (i = 0; i < this.UsersNumber.Text.Trim().ToType<int>(); i++)
{
this.randomGuid = Guid.NewGuid().ToString();
string newEmail = this.UserPrefixTB.Text.Trim() + this.randomGuid + "@test.info";
string newUsername = this.UserPrefixTB.Text.Trim() + this.randomGuid;
if (UserMembershipHelper.UserExists(newUsername, newEmail))
{
continue;
}
string hashinput = DateTime.UtcNow + newEmail + Security.CreatePassword(20);
string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5");
MembershipCreateStatus status;
MembershipUser user = this.Get<MembershipProvider>().CreateUser(
newUsername,
this.Password.Text.Trim(),
newEmail,
this.Question.Text.Trim(),
this.Answer.Text.Trim(),
!this.Get<YafBoardSettings>().EmailVerification,
null,
out status);
if (status != MembershipCreateStatus.Success)
{
continue;
}
// setup inital roles (if any) for this user
RoleMembershipHelper.SetupUserRoles(boardID, newUsername);
// create the user in the YAF DB as well as sync roles...
int? userID = RoleMembershipHelper.CreateForumUser(user, boardID);
// create profile
YafUserProfile userProfile = YafUserProfile.GetProfile(newUsername);
// setup their inital profile information
userProfile.Location = this.Location.Text.Trim();
userProfile.Homepage = this.HomePage.Text.Trim();
userProfile.Save();
// save the time zone...
if (
!(this.UsersBoardsList.Items[iboards].Value.ToType<int>() == YafContext.Current.PageBoardID &&
_excludeCurrentBoard))
{
LegacyDb.user_save(
LegacyDb.user_get(boardID, user.ProviderUserKey),
boardID,
null,
null,
null,
this.TimeZones.SelectedValue.ToType<int>(),
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null);
_outCounter++;
}
}
}
return _outCounter + " Users in " + iboards + " Board(s); ";
}
/// <summary>
/// The get message flags.
/// </summary>
/// <returns>
/// The method returns message flags.
/// </returns>
private int GetMessageFlags()
{
var editorModule = this.PageContext.Get<IModuleManager<ForumEditor>>().GetBy(this.Get<YafBoardSettings>().ForumEditor);
var topicFlags = new MessageFlags
{
IsHtml = editorModule.UsesHTML,
IsBBCode = editorModule.UsesBBCode,
IsPersistent = false,
IsApproved = this.PageContext.IsAdmin
};
// Bypass Approval if Admin or Moderator.
return topicFlags.BitValue;
}
/// <summary>
/// The populate_ controls.
/// </summary>
private void Populate_Controls()
{
}
/// <summary>
/// The validate controls values.
/// </summary>
/// <returns>
/// The method returns true if all controls values are valid.
/// </returns>
private bool ValidateControlsValues()
{
if (Membership.GetUser(this.From.Text.Trim()) == null)
{
this.PageContext.AddLoadMessage("You should enter valid 'from' user name.");
return false;
}
if (Membership.GetUser(this.To.Text.Trim()) == null)
{
this.PageContext.AddLoadMessage("You should enter valid 'to' user name.");
return false;
}
if (!ValidationHelper.IsValidInt(this.PMessagesNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for pmessage number.");
return false;
}
if (!ValidationHelper.IsValidInt(this.UsersNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for users.");
return false;
}
if (!ValidationHelper.IsValidInt(this.CategoriesNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for categories.");
return false;
}
if (!ValidationHelper.IsValidInt(this.BoardNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for boards.");
return false;
}
if (!ValidationHelper.IsValidInt(this.ForumsNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for forums.");
return false;
}
if (!ValidationHelper.IsValidInt(this.TopicsNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for topics.");
return false;
}
if (!ValidationHelper.IsValidInt(this.PostsNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for generated posts .");
return false;
}
// **************************
if (!ValidationHelper.IsValidInt(this.BoardsTopicsNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for topics generated messages .");
return false;
}
if (!ValidationHelper.IsValidInt(this.BoardsForumsNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for forums generated messages .");
return false;
}
if (!ValidationHelper.IsValidInt(this.BoardsCategoriesNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for categories generated messages .");
return false;
}
if (!ValidationHelper.IsValidInt(this.BoardsMessagesNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for boards generated messages .");
return false;
}
// ****************************
if (!ValidationHelper.IsValidInt(this.CategoriesTopicsNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for forums generated messages .");
return false;
}
if (!ValidationHelper.IsValidInt(this.CategoriesForumsNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for categories generated messages .");
return false;
}
if (!ValidationHelper.IsValidInt(this.CategoriesMessagesNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for boards generated messages .");
return false;
}
// *************************
if (!ValidationHelper.IsValidInt(this.ForumsTopicsNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for categories generated messages .");
return false;
}
if (!ValidationHelper.IsValidInt(this.ForumsMessagesNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for boards generated messages .");
return false;
}
// **********************************
if (!ValidationHelper.IsValidInt(this.TopicsMessagesNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for boards generated messages .");
return false;
}
if (!ValidationHelper.IsValidInt(this.BoardsUsersNumber.Text.Trim()))
{
this.PageContext.AddLoadMessage("You should enter integer value for users generated with boards.");
return false;
}
return true;
}
#endregion
}
}
| |
using System;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class PlanarReflectionProbeCache
{
internal static readonly int s_InputTexID = Shader.PropertyToID("_InputTex");
internal static readonly int s_LoDID = Shader.PropertyToID("_LoD");
internal static readonly int s_FaceIndexID = Shader.PropertyToID("_FaceIndex");
enum ProbeFilteringState
{
Convolving,
Ready
}
int m_ProbeSize;
int m_CacheSize;
IBLFilterGGX m_IBLFilterGGX;
TextureCache2D m_TextureCache;
RenderTexture m_TempRenderTexture;
RenderTexture m_ConvolutionTargetTexture;
ProbeFilteringState[] m_ProbeBakingState;
Material m_ConvertTextureMaterial;
MaterialPropertyBlock m_ConvertTextureMPB;
bool m_PerformBC6HCompression;
public PlanarReflectionProbeCache(HDRenderPipelineAsset hdAsset, IBLFilterGGX iblFilter, int cacheSize, int probeSize, TextureFormat probeFormat, bool isMipmaped)
{
m_ConvertTextureMaterial = CoreUtils.CreateEngineMaterial(hdAsset.renderPipelineResources.shaders.blitCubeTextureFacePS);
m_ConvertTextureMPB = new MaterialPropertyBlock();
// BC6H requires CPP feature not yet available
probeFormat = TextureFormat.RGBAHalf;
Debug.Assert(probeFormat == TextureFormat.BC6H || probeFormat == TextureFormat.RGBAHalf, "Reflection Probe Cache format for HDRP can only be BC6H or FP16.");
m_ProbeSize = probeSize;
m_CacheSize = cacheSize;
m_TextureCache = new TextureCache2D("PlanarReflectionProbe");
m_TextureCache.AllocTextureArray(cacheSize, probeSize, probeSize, probeFormat, isMipmaped);
m_IBLFilterGGX = iblFilter;
m_PerformBC6HCompression = probeFormat == TextureFormat.BC6H;
InitializeProbeBakingStates();
}
void Initialize()
{
if (m_TempRenderTexture == null)
{
// Temporary RT used for convolution and compression
m_TempRenderTexture = new RenderTexture(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf);
m_TempRenderTexture.hideFlags = HideFlags.HideAndDontSave;
m_TempRenderTexture.dimension = TextureDimension.Tex2D;
m_TempRenderTexture.useMipMap = true;
m_TempRenderTexture.autoGenerateMips = false;
m_TempRenderTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf, "PlanarReflectionTemp", mips: true);
m_TempRenderTexture.Create();
m_ConvolutionTargetTexture = new RenderTexture(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf);
m_ConvolutionTargetTexture.hideFlags = HideFlags.HideAndDontSave;
m_ConvolutionTargetTexture.dimension = TextureDimension.Tex2D;
m_ConvolutionTargetTexture.useMipMap = true;
m_ConvolutionTargetTexture.autoGenerateMips = false;
m_ConvolutionTargetTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf, "PlanarReflectionConvolution", mips: true);
m_ConvolutionTargetTexture.enableRandomWrite = true;
m_ConvolutionTargetTexture.Create();
InitializeProbeBakingStates();
}
}
void InitializeProbeBakingStates()
{
if (m_ProbeBakingState == null || m_ProbeBakingState.Length != m_CacheSize)
{
Array.Resize(ref m_ProbeBakingState, m_CacheSize);
for (var i = 0; i < m_CacheSize; ++i)
m_ProbeBakingState[i] = ProbeFilteringState.Convolving;
}
}
public void Release()
{
m_TextureCache.Release();
CoreUtils.Destroy(m_TempRenderTexture);
CoreUtils.Destroy(m_ConvolutionTargetTexture);
m_ProbeBakingState = null;
CoreUtils.Destroy(m_ConvertTextureMaterial);
}
public void NewFrame()
{
Initialize();
m_TextureCache.NewFrame();
}
// This method is used to convert inputs that are either compressed or not of the right size.
// We can't use Graphics.ConvertTexture here because it does not work with a RenderTexture as destination.
void ConvertTexture(CommandBuffer cmd, Texture input, RenderTexture target)
{
m_ConvertTextureMPB.SetTexture(s_InputTexID, input);
m_ConvertTextureMPB.SetFloat(s_LoDID, 0.0f); // We want to convert mip 0 to whatever the size of the destination cache is.
CoreUtils.SetRenderTarget(cmd, target, ClearFlag.None, Color.black, 0, 0);
CoreUtils.DrawFullScreen(cmd, m_ConvertTextureMaterial, m_ConvertTextureMPB);
}
Texture ConvolveProbeTexture(CommandBuffer cmd, Texture texture)
{
// Probes can be either Cubemaps (for baked probes) or RenderTextures (for realtime probes)
Texture2D texture2D = texture as Texture2D;
RenderTexture renderTexture = texture as RenderTexture;
RenderTexture convolutionSourceTexture = null;
if (texture2D != null)
{
// if the size if different from the cache probe size or if the input texture format is compressed, we need to convert it
// 1) to a format for which we can generate mip maps
// 2) to the proper reflection probe cache size
var sizeMismatch = texture2D.width != m_ProbeSize || texture2D.height != m_ProbeSize;
var formatMismatch = texture2D.format != TextureFormat.RGBAHalf; // Temporary RT for convolution is always FP16
if (formatMismatch || sizeMismatch)
{
if (sizeMismatch)
{
Debug.LogWarningFormat("Baked Planar Reflection Probe {0} does not match HDRP Planar Reflection Probe Cache size of {1}. Consider baking it at the same size for better loading performance.", texture.name, m_ProbeSize);
}
else if (texture2D.format == TextureFormat.BC6H)
{
Debug.LogWarningFormat("Baked Planar Reflection Probe {0} is compressed but the HDRP Planar Reflection Probe Cache is not. Consider removing compression from the input texture for better quality.", texture.name);
}
ConvertTexture(cmd, texture2D, m_TempRenderTexture);
}
else
cmd.CopyTexture(texture2D, 0, 0, m_TempRenderTexture, 0, 0);
// Ideally if input is not compressed and has mipmaps, don't do anything here. Problem is, we can't know if mips have been already convolved offline...
cmd.GenerateMips(m_TempRenderTexture);
convolutionSourceTexture = m_TempRenderTexture;
}
else
{
Debug.Assert(renderTexture != null);
if (renderTexture.dimension != TextureDimension.Tex2D)
{
Debug.LogError("Planar Realtime reflection probe should always be a 2D RenderTexture.");
return null;
}
// TODO: Do a different case for downsizing, in this case, instead of doing ConvertTexture just use the relevant mipmaps.
var sizeMismatch = renderTexture.width != m_ProbeSize || renderTexture.height != m_ProbeSize;
if (sizeMismatch)
{
ConvertTexture(cmd, renderTexture, m_TempRenderTexture);
convolutionSourceTexture = m_TempRenderTexture;
}
else
convolutionSourceTexture = renderTexture;
// Generate unfiltered mipmaps as a base for convolution
// TODO: Make sure that we don't first convolve everything on the GPU with the legacy code path executed after rendering the probe.
cmd.GenerateMips(convolutionSourceTexture);
}
m_IBLFilterGGX.FilterPlanarTexture(cmd, convolutionSourceTexture, m_ConvolutionTargetTexture);
return m_ConvolutionTargetTexture;
}
public int FetchSlice(CommandBuffer cmd, Texture texture)
{
bool needUpdate;
var sliceIndex = m_TextureCache.ReserveSlice(texture, out needUpdate);
if (sliceIndex != -1)
{
if (needUpdate || m_ProbeBakingState[sliceIndex] != ProbeFilteringState.Ready)
{
using (new ProfilingSample(cmd, "Convolve Planar Reflection Probe"))
{
// For now baking is done directly but will be time sliced in the future. Just preparing the code here.
m_ProbeBakingState[sliceIndex] = ProbeFilteringState.Convolving;
Texture result = ConvolveProbeTexture(cmd, texture);
if (result == null)
return -1;
if (m_PerformBC6HCompression)
{
throw new NotImplementedException("BC6H Support not implemented for PlanarReflectionProbeCache");
}
else
{
m_TextureCache.UpdateSlice(cmd, sliceIndex, result, m_TextureCache.GetTextureHash(texture)); // Be careful to provide the update count from the input texture, not the temporary one used for convolving.
}
m_ProbeBakingState[sliceIndex] = ProbeFilteringState.Ready;
}
}
}
return sliceIndex;
}
public Texture GetTexCache()
{
return m_TextureCache.GetTexCache();
}
internal static long GetApproxCacheSizeInByte(int nbElement, int resolution, int sliceSize)
{
return TextureCache2D.GetApproxCacheSizeInByte(nbElement, resolution, sliceSize);
}
internal static int GetMaxCacheSizeForWeightInByte(int weight, int resolution, int sliceSize)
{
return TextureCache2D.GetMaxCacheSizeForWeightInByte(weight, resolution, sliceSize);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using OLEDB.Test.ModuleCore;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
////////////////////////////////////////////////////////////////
// Module
//
////////////////////////////////////////////////////////////////
[TestModule(Name = "Name Table", Desc = "Test for Get and Add methods")]
public partial class CNameTableTestModule : CTestModule
{
//Accessors
private string _TestData = null;
public string TestData
{
get
{
return _TestData;
}
}
public override int Init(object objParam)
{
int ret = base.Init(objParam);
_TestData = Path.Combine(FilePathUtil.GetTestDataPath(), @"XmlReader\");
// Create global usage test files
string strFile = String.Empty;
NameTable_TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC);
return ret;
}
public override int Terminate(object objParam)
{
return base.Terminate(objParam);
}
}
////////////////////////////////////////////////////////////////
// TestCase TCBase
//
////////////////////////////////////////////////////////////////
public partial class TCBase : CTestCase
{
public enum ENAMETABLE_VER
{
VERIFY_WITH_GETSTR,
VERIFY_WITH_GETCHAR,
VERIFY_WITH_ADDSTR,
VERIFY_WITH_ADDCHAR,
};
private ENAMETABLE_VER _eNTVer;
public ENAMETABLE_VER NameTableVer
{
get { return _eNTVer; }
set { _eNTVer = value; }
}
public static string WRONG_EXCEPTION = "Catching Wrong Exception";
protected static string BigStr = new String('Z', (1 << 20) - 1);
protected XmlReader DataReader;
public override int Init(object objParam)
{
if (GetDescription() == "VerifyWGetString")
{
NameTableVer = ENAMETABLE_VER.VERIFY_WITH_GETSTR;
}
else if (GetDescription() == "VerifyWGetChar")
{
NameTableVer = ENAMETABLE_VER.VERIFY_WITH_GETCHAR;
}
else if (GetDescription() == "VerifyWAddString")
{
NameTableVer = ENAMETABLE_VER.VERIFY_WITH_ADDSTR;
}
else if (GetDescription() == "VerifyWAddChar")
{
NameTableVer = ENAMETABLE_VER.VERIFY_WITH_ADDCHAR;
}
else
throw (new Exception());
int ival = base.Init(objParam);
ReloadSource();
if (TEST_PASS == ival)
{
while (DataReader.Read() == true) ;
}
return ival;
}
protected void ReloadSource()
{
if (DataReader != null)
{
DataReader.Dispose();
}
string strFile = NameTable_TestFiles.GetTestFileName(EREADER_TYPE.GENERIC);
DataReader = XmlReader.Create(FilePathUtil.getStream(strFile), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore });//new XmlTextReader(strFile);
}
public void VerifyNameTable(object objActual, string str, char[] ach, int offset, int length)
{
VerifyNameTableGet(objActual, str, ach, offset, length);
VerifyNameTableAdd(objActual, str, ach, offset, length);
}
public void VerifyNameTableGet(object objActual, string str, char[] ach, int offset, int length)
{
object objExpected = null;
if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_GETSTR)
{
objExpected = DataReader.NameTable.Get(str);
CError.WriteLine("VerifyNameTableWGetStr");
CError.Compare(objActual, objExpected, "VerifyNameTableWGetStr");
}
else if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_GETCHAR)
{
objExpected = DataReader.NameTable.Get(ach, offset, length);
CError.WriteLine("VerifyNameTableWGetChar");
CError.Compare(objActual, objExpected, "VerifyNameTableWGetChar");
}
}
public void VerifyNameTableAdd(object objActual, string str, char[] ach, int offset, int length)
{
object objExpected = null;
if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_ADDSTR)
{
objExpected = DataReader.NameTable.Add(ach, offset, length);
CError.WriteLine("VerifyNameTableWAddStr");
CError.Compare(objActual, objExpected, "VerifyNameTableWAddStr");
}
else if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_ADDCHAR)
{
objExpected = DataReader.NameTable.Add(str);
CError.WriteLine("VerifyNameTableWAddChar");
CError.Compare(objActual, objExpected, "VerifyNameTableWAddChar");
}
}
}
////////////////////////////////////////////////////////////////
// TestCase TCRecord NameTable.Get
//
////////////////////////////////////////////////////////////////
//[TestCase(Name="NameTable(Get) VerifyWGetChar", Desc="VerifyWGetChar")]
//[TestCase(Name="NameTable(Get) VerifyWGetString", Desc="VerifyWGetString")]
//[TestCase(Name="NameTable(Get) VerifyWAddString", Desc="VerifyWAddString")]
//[TestCase(Name="NameTable(Get) VerifyWAddChar", Desc="VerifyWAddChar")]
public partial class TCRecordNameTableGet : TCBase
{
public static char[] chInv = { 'U', 'n', 'a', 't', 'o', 'm', 'i', 'z', 'e', 'd' };
public static char[] chVal = { 'P', 'L', 'A', 'Y' };
public static char[] chValW1EndExtra = { 'P', 'L', 'A', 'Y', 'Y' };
public static char[] chValW1FrExtra = { 'P', 'P', 'L', 'A', 'Y' };
public static char[] chValW1Fr1EndExtra = { 'P', 'P', 'L', 'A', 'Y', 'Y' };
public static char[] chValWEndExtras = { 'P', 'L', 'A', 'Y', 'Y', 'Y' };
public static char[] chValWFrExtras = { 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'L', 'A', 'Y' };
public static char[] chValWFrEndExtras = { 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'L', 'A', 'Y', 'Y', 'Y' };
public static string[] strPerVal =
{
"PLYA", "PALY", "PAYL", "PYLA", "PYAL",
"LPAY", "LPYA", "LAPY", "LAYP", "LYPA", "LYAP",
"ALPY", "ALYP", "APLY", "APYL", "AYLP", "AYPL",
"YLPA", "YLAP", "YPLA", "YPAL", "YALP", "YAPL",
};
public static string[] strPerValCase =
{
"pLAY", "plAY", "plaY", "play",
"plAY", "plaY",
"pLaY", "pLay",
"pLAy",
"PlAY", "PlaY", "Play",
"PLaY",
"PLAy"
};
public static string strInv = "Unatomized";
public static string strVal = "PLAY";
[Variation("GetUnAutomized", Pri = 0)]
public int Variation_1()
{
object objActual = DataReader.NameTable.Get(strInv);
object objActual1 = DataReader.NameTable.Get(strInv);
CError.Compare(objActual, null, CurVariation.Desc);
CError.Compare(objActual1, null, CurVariation.Desc);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTableGet(objActual, strInv, chInv, 0, chInv.Length);
return TEST_PASS;
}
[Variation("Get Atomized String", Pri = 0)]
public int Variation_2()
{
object objActual = DataReader.NameTable.Get(chVal, 0, chVal.Length);
object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chVal, 0, chVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with end padded", Pri = 0)]
public int Variation_3()
{
object objActual = DataReader.NameTable.Get(chValW1EndExtra, 0, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValW1EndExtra, 0, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1EndExtra, 0, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with front and end padded", Pri = 0)]
public int Variation_4()
{
object objActual = DataReader.NameTable.Get(chValW1Fr1EndExtra, 1, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValW1Fr1EndExtra, 1, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1Fr1EndExtra, 1, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with front padded", Pri = 0)]
public int Variation_5()
{
object objActual = DataReader.NameTable.Get(chValW1FrExtra, 1, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValW1FrExtra, 1, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1FrExtra, 1, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with end multi-padded", Pri = 0)]
public int Variation_6()
{
object objActual = DataReader.NameTable.Get(chValWEndExtras, 0, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValWEndExtras, 0, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWEndExtras, 0, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with front and end multi-padded", Pri = 0)]
public int Variation_7()
{
object objActual = DataReader.NameTable.Get(chValWFrEndExtras, 6, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValWFrEndExtras, 6, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWFrEndExtras, 6, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with front multi-padded", Pri = 0)]
public int Variation_8()
{
object objActual = DataReader.NameTable.Get(chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length);
return TEST_PASS;
}
[Variation("Get Invalid permutation of valid string", Pri = 0)]
public int Variation_9()
{
for (int i = 0; i < strPerVal.Length; i++)
{
char[] ach = strPerVal[i].ToCharArray();
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length);
CError.Compare(objActual, null, CurVariation.Desc);
CError.Compare(objActual1, null, CurVariation.Desc);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTableGet(objActual, strPerVal[i], ach, 0, ach.Length);
}
return TEST_PASS;
}
[Variation("Get Valid Super String")]
public int Variation_10()
{
string filename = null;
NameTable_TestFiles.CreateTestFile(ref filename, EREADER_TYPE.BIG_ELEMENT_SIZE);
XmlReader rDataReader = XmlReader.Create(FilePathUtil.getStream(filename));
while (rDataReader.Read() == true) ;
XmlNameTable nt = rDataReader.NameTable;
object objTest1 = nt.Get(BigStr + "Z");
object objTest2 = nt.Get(BigStr + "X");
object objTest3 = nt.Get(BigStr + "Y");
if (objTest1 != null)
{
throw new CTestException(CTestBase.TEST_FAIL, "objTest1 is not null");
}
if (objTest2 == null)
{
throw new CTestException(CTestBase.TEST_FAIL, "objTest2 is null");
}
if (objTest3 == null)
{
throw new CTestException(CTestBase.TEST_FAIL, "objTest3 is null");
}
if ((objTest1 == objTest2) || (objTest1 == objTest3) || (objTest2 == objTest3))
throw new CTestException(CTestBase.TEST_FAIL, "objTest1 is equal to objTest2, or objTest3");
return TEST_PASS;
}
[Variation("Get invalid Super String")]
public int Variation_11()
{
int size = (1 << 24);
string str = "";
char[] ach = str.ToCharArray();
bool fRetry = false;
for (; ;)
{
try
{
str = new String('Z', size);
ach = str.ToCharArray();
}
catch (OutOfMemoryException exc)
{
size >>= 1;
CError.WriteLine(exc + " : " + exc.Message + " Retry with " + size);
fRetry = true;
}
if (size < (1 << 30))
{
fRetry = true;
}
if (fRetry)
{
CError.WriteLine("Tested size == " + size);
if (str == null)
CError.WriteLine("string is null");
break;
}
}
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTableGet(objActual, str, ach, 0, ach.Length);
return TEST_PASS;
}
[Variation("Get empty string, valid offset and length = 0", Pri = 0)]
public int Variation_12()
{
string str = String.Empty;
char[] ach = str.ToCharArray();
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, 0);
object objActual2 = DataReader.NameTable.Get(str);
CError.Compare(objActual, objActual1, "Char with StringEmpty");
CError.Compare(String.Empty, objActual1, "Char with StringEmpty");
CError.Compare(String.Empty, objActual2, "StringEmpty");
VerifyNameTable(objActual, str, ach, 0, 0);
return TEST_PASS;
}
[Variation("Get empty string, valid offset and length = 1", Pri = 0)]
public int Variation_13()
{
char[] ach = new char[] { };
try
{
object objActual = DataReader.NameTable.Get(ach, 0, 1);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get null char[], valid offset and length = 0", Pri = 0)]
public int Variation_14()
{
char[] ach = null;
object objActual = DataReader.NameTable.Add(ach, 0, 0);
CError.Compare(String.Empty, objActual, "Char with null");
return TEST_PASS;
}
[Variation("Get null string", Pri = 0)]
public int Variation_15()
{
string str = null;
try
{
object objActual = DataReader.NameTable.Get(str);
}
catch (ArgumentNullException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get null char[], valid offset and length = 1", Pri = 0)]
public int Variation_16()
{
char[] ach = null;
try
{
object objActual = DataReader.NameTable.Add(ach, 0, 1);
}
catch (NullReferenceException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid length, length = 0", Pri = 0)]
public int Variation_17()
{
object objActual = DataReader.NameTable.Get(chVal, 0, 0);
object objActual1 = DataReader.NameTable.Get(chVal, 0, 0);
CError.WriteLine("Here " + chVal.ToString());
CError.WriteLine("Here2 " + DataReader.NameTable.Get(chVal, 0, 0));
if (DataReader.NameTable.Get(chVal, 0, 0) == String.Empty)
CError.WriteLine("here");
if (DataReader.NameTable.Get(chVal, 0, 0) == null)
CError.WriteLine("null");
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, String.Empty, chVal, 0, 0);
return TEST_PASS;
}
[Variation("Get valid string, invalid length, length = Length+1", Pri = 0)]
public int Variation_18()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, 0, chVal.Length + 1);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid length, length = max_int", Pri = 0)]
public int Variation_19()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, 0, Int32.MaxValue);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid length, length = -1", Pri = 0)]
public int Variation_20()
{
object objActual = DataReader.NameTable.Get(chVal, 0, -1);
CError.WriteLine("HERE " + objActual);
return TEST_PASS;
}
[Variation("Get valid string, invalid offset > Length", Pri = 0)]
public int Variation_21()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, chVal.Length + 1, chVal.Length);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid offset = max_int", Pri = 0)]
public int Variation_22()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, Int32.MaxValue, chVal.Length);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid offset = Length", Pri = 0)]
public int Variation_23()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, chVal.Length, chVal.Length);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid offset -1", Pri = 0)]
public int Variation_24()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, -1, chVal.Length);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid offset and length", Pri = 0)]
public int Variation_25()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, -1, -1);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
}
////////////////////////////////////////////////////////////////
// TestCase TCRecord NameTable.Add
//
////////////////////////////////////////////////////////////////
//[TestCase(Name="NameTable(Add) VerifyWGetString", Desc="VerifyWGetString")]
//[TestCase(Name="NameTable(Add) VerifyWGetChar", Desc="VerifyWGetChar")]
//[TestCase(Name="NameTable(Add) VerifyWAddString", Desc="VerifyWAddString")]
//[TestCase(Name="NameTable(Add) VerifyWAddChar", Desc="VerifyWAddChar")]
public partial class TCRecordNameTableAdd : TCBase
{
public static char[] chVal = { 'F', 'O', 'O' };
public static char[] chValW1EndExtra = { 'F', 'O', 'O', 'O' };
public static char[] chValW1FrExtra = { 'F', 'F', 'O', 'O', 'O' };
public static char[] chValW1Fr1EndExtra = { 'F', 'F', 'O', 'O', 'O' };
public static char[] chValWEndExtras = { 'F', 'O', 'O', 'O', 'O', 'O' };
public static char[] chValWFrExtras = { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'O', 'O', 'O' };
public static char[] chValWFrEndExtras = { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'O', 'O', 'O', 'O', 'O' };
public static string[] strPerVal =
{
"OFO", "OOF"
};
public static string[] strPerValCase =
{
"fOO", "foO", "foo",
"FoO", "Foo",
"FOo"
};
public static string strVal = "FOO";
public static string strWhitespaceVal = "WITH WHITESPACE";
public static string strAlphaNumVal = "WITH1Number";
public static string strSignVal = "+SIGN-";
[Variation("Add a new atomized string (padded with chars at the end), valid offset and length = str_length", Pri = 0)]
public int Variation_1()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValWEndExtras, 0, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValWEndExtras, 0, strVal.Length);
if (objActual == objActual1)
CError.WriteLine(objActual + " and ", objActual1);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWEndExtras, 0, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded with chars at both front and end), valid offset and length = str_length", Pri = 0)]
public int Variation_2()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWFrExtras, 6, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded with chars at the front), valid offset and length = str_length", Pri = 0)]
public int Variation_3()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWFrEndExtras, 6, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded a char at the end), valid offset and length = str_length", Pri = 0)]
public int Variation_4()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValW1EndExtra, 0, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValW1EndExtra, 0, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1EndExtra, 0, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded with a char at both front and end), valid offset and length = str_length", Pri = 0)]
public int Variation_5()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValW1Fr1EndExtra, 1, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValW1Fr1EndExtra, 1, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1Fr1EndExtra, 1, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded with a char at the front), valid offset and length = str_length", Pri = 0)]
public int Variation_6()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValW1FrExtra, 1, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValW1FrExtra, 1, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1FrExtra, 1, strVal.Length);
return TEST_PASS;
}
[Variation("Add new string between 1M - 2M in size, valid offset and length")]
public int Variation_7()
{
char[] chTest = BigStr.ToCharArray();
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual2 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objActual2, CurVariation.Desc);
VerifyNameTable(objActual1, BigStr, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add an existing atomized string (with Max string for test: 1-2M), valid offset and valid length")]
public int Variation_8()
{
////////////////////////////
// Add strings again and verify
string filename = null;
NameTable_TestFiles.CreateTestFile(ref filename, EREADER_TYPE.BIG_ELEMENT_SIZE);
XmlReader rDataReader = XmlReader.Create(FilePathUtil.getStream(filename));
while (rDataReader.Read() == true) ;
XmlNameTable nt = rDataReader.NameTable;
string strTest = BigStr + "X";
char[] chTest = strTest.ToCharArray();
Object objActual1 = nt.Add(chTest, 0, chTest.Length);
Object objActual2 = nt.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objActual2, "Comparing objActual1 and objActual2");
CError.Compare(objActual1, nt.Get(chTest, 0, chTest.Length), "Comparing objActual1 and GetCharArray");
CError.Compare(objActual1, nt.Get(strTest), "Comparing objActual1 and GetString");
CError.Compare(objActual1, nt.Add(strTest), "Comparing objActual1 and AddString");
NameTable_TestFiles.RemoveDataReader(EREADER_TYPE.BIG_ELEMENT_SIZE);
return TEST_PASS;
}
[Variation("Add new string, and do Get with a combination of the same string in different order", Pri = 0)]
public int Variation_9()
{
ReloadSource();
// Add string
Object objAdded = DataReader.NameTable.Add(strVal);
// Look for permutations of strings, should be null.
for (int i = 0; i < strPerVal.Length; i++)
{
char[] ach = strPerVal[i].ToCharArray();
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length);
CError.Compare(objActual, null, CurVariation.Desc);
CError.Compare(objActual, objActual1, CurVariation.Desc);
}
return TEST_PASS;
}
[Variation("Add new string, and Add a combination of the same string in different case, all are different objects", Pri = 0)]
public int Variation_10()
{
ReloadSource();
// Add string
Object objAdded = DataReader.NameTable.Add(strVal);
// Look for permutations of strings, should be null.
for (int i = 0; i < strPerValCase.Length; i++)
{
char[] ach = strPerValCase[i].ToCharArray();
object objActual = DataReader.NameTable.Add(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Add(ach, 0, ach.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual1, strPerValCase[i], ach, 0, ach.Length);
if (objAdded == objActual)
{
throw new Exception("\n Object are the same for " + strVal + " and " + strPerValCase[i]);
}
}
return TEST_PASS;
}
[Variation("Add 1M new string, and do Get with the last char different than the original string", Pri = 0)]
public int Variation_11()
{
object objAdded = DataReader.NameTable.Add(BigStr + "M");
object objActual = DataReader.NameTable.Get(BigStr + "D");
CError.Compare(objActual, null, CurVariation.Desc);
return TEST_PASS;
}
[Variation("Add new alpha numeric, valid offset, valid length", Pri = 0)]
public int Variation_12()
{
ReloadSource();
char[] chTest = strAlphaNumVal.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objAdded, CurVariation.Desc);
VerifyNameTable(objAdded, strAlphaNumVal, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add new alpha numeric, valid offset, length= 0", Pri = 0)]
public int Variation_13()
{
ReloadSource();
char[] chTest = strAlphaNumVal.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, 0);
object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length);
object objActual2 = DataReader.NameTable.Get(strVal);
CError.Compare(objActual1, null, "Get should fail since Add with length=0 should fail");
CError.Compare(objActual1, objActual2, "Both Get should fail");
return TEST_PASS;
}
[Variation("Add new with whitespace, valid offset, valid length", Pri = 0)]
public int Variation_14()
{
ReloadSource();
char[] chTest = strWhitespaceVal.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objAdded, CurVariation.Desc);
VerifyNameTable(objAdded, strWhitespaceVal, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add new with sign characters, valid offset, valid length", Pri = 0)]
public int Variation_15()
{
ReloadSource();
char[] chTest = strSignVal.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objAdded, CurVariation.Desc);
VerifyNameTable(objAdded, strSignVal, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add new string between 1M - 2M in size, valid offset and length", Pri = 0)]
public int Variation_16()
{
ReloadSource();
char[] chTest = BigStr.ToCharArray();
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual2 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objActual2, CurVariation.Desc);
VerifyNameTable(objActual1, BigStr, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add new string, get object using permutations of upper & lowecase, should be null", Pri = 0)]
public int Variation_17()
{
ReloadSource();
// Add string
Object objAdded = DataReader.NameTable.Add(strVal);
// Look for permutations of strings, should be null.
for (int i = 0; i < strPerValCase.Length; i++)
{
char[] ach = strPerValCase[i].ToCharArray();
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length);
CError.Compare(objActual, null, CurVariation.Desc);
CError.Compare(objActual, objActual1, CurVariation.Desc);
}
return TEST_PASS;
}
[Variation("Add an empty atomized string, valid offset and length = 0", Pri = 0)]
public int Variation_18()
{
ReloadSource();
string strEmpty = String.Empty;
object objAdded = DataReader.NameTable.Add(strEmpty);
object objAdded1 = DataReader.NameTable.Add(strEmpty.ToCharArray(), 0, strEmpty.Length);
object objActual1 = DataReader.NameTable.Get(strEmpty.ToCharArray(), 0, strEmpty.Length);
object objActual2 = DataReader.NameTable.Get(strEmpty);
CError.WriteLine("String " + DataReader.NameTable.Get(strEmpty));
CError.WriteLine("String " + objAdded1 + " String2 " + objAdded1);
if (objAdded != objAdded1)
CError.WriteLine("HERE");
CError.Compare(objActual1, objActual2, CurVariation.Desc);
VerifyNameTable(objActual1, strEmpty, strEmpty.ToCharArray(), 0, 0);
return TEST_PASS;
}
[Variation("Add an empty atomized string (array char only), valid offset and length = 1", Pri = 0)]
public int Variation_19()
{
try
{
char[] chTest = String.Empty.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, 1);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a NULL atomized string, valid offset and length = 0", Pri = 0)]
public int Variation_20()
{
object objAdded = DataReader.NameTable.Add(null, 0, 0);
VerifyNameTable(objAdded, String.Empty, (String.Empty).ToCharArray(), 0, 0);
return TEST_PASS;
}
[Variation("Add a NULL atomized string, valid offset and length = 1", Pri = 0)]
public int Variation_21()
{
try
{
object objAdded = DataReader.NameTable.Add(null, 0, 1);
}
catch (NullReferenceException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid offset and length = 0", Pri = 0)]
public int Variation_22()
{
ReloadSource();
object objAdded = DataReader.NameTable.Add(chVal, 0, 0);
object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length);
object objActual2 = DataReader.NameTable.Get(strVal);
CError.Compare(objActual1, null, "Get should fail since Add with length=0 should fail");
CError.Compare(objActual1, objActual2, "Both Get should fail");
return TEST_PASS;
}
[Variation("Add a valid atomized string, valid offset and length > valid_length", Pri = 0)]
public int Variation_23()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, 0, chVal.Length * 2);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid offset and length = max_int", Pri = 0)]
public int Variation_24()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, 0, Int32.MaxValue);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid offset and length = - 1", Pri = 0)]
public int Variation_25()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, 0, -1);
}
catch (ArgumentOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid length and offset > str_length", Pri = 0)]
public int Variation_26()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, chVal.Length * 2, chVal.Length);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid length and offset = max_int", Pri = 0)]
public int Variation_27()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, Int32.MaxValue, chVal.Length);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid length and offset = str_length", Pri = 0)]
public int Variation_28()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, chVal.Length, chVal.Length);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid length and offset = - 1", Pri = 0)]
public int Variation_29()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, -1, chVal.Length);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, with both invalid offset and length", Pri = 0)]
public int Variation_30()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, -1, -1);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmAddProcedure.
/// </summary>
public partial class frmUpdStaffAction : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected System.Web.UI.WebControls.RadioButtonList rblStatusSS;
private int GetIndexOfLocs (string s)
{
return (lstLocations.Items.IndexOf (lstLocations.Items.FindByValue(s)));
}
private int GetIndexOfVisibility (string s)
{
return (lstVisibility.Items.IndexOf (lstVisibility.Items.FindByValue(s)));
}
private int GetIndexOfPayMethods (string s)
{
return (lstPayMethods.Items.IndexOf (lstPayMethods.Items.FindByValue(s)));
}
private int GetIndexOfRoles (string s)
{
return (lstRoles.Items.IndexOf (lstRoles.Items.FindByValue(s)));
}
private int GetIndexOfPayGrades (string s)
{
return (lstPayGrades.Items.IndexOf (lstPayGrades.Items.FindByValue(s)));
}
private int GetIndexOfBudgets(string s)
{
return (lstFunds.Items.IndexOf(lstFunds.Items.FindByValue(s)));
}
/*private int GetIndexOfStatus (string s)
{
if (s == "0")
{
return 0;
}
else if (s == "1")
{
return 1;
}
else if (s == "2")
{
return 2;
}
else if (s == "3")
{
return 3;
}
else if (s == "4")
{
return 4;
}
else
{
return 0;
}
}*/
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
lblPay.Visible = false;
lstPayMethods.Visible = false;
lblRoles.Visible = false;
lstRoles.Visible = false;
lblLocation.Visible = false;
lstLocations.Visible = false;
lblOrg.Text=(Session["OrgName"]).ToString();
lblAptType.Text = "Appointment Type: " + Session["STName"].ToString();
loadVisibility();
loadLocs();
loadPayMethods();
loadRoles();
loadSOF();
loadPayGrades();
lstPayMethods.BorderColor=System.Drawing.Color.Navy;
lstPayMethods.ForeColor=System.Drawing.Color.Navy;
lstVisibility.SelectedIndex=GetIndexOfVisibility(Request.Params["Vis"]);
if (Session["btnAction"].ToString() == "Update")
{
loadStaffAction();
loadStaffSalary();
loadPGSalDetails();
if (lstAptStatus.SelectedItem.Value != "0")
{
btnPeople.Visible = false;
}
txtStartDateS.Focus();
lblStartDate.Visible = true;
}
else
{
//1/6/10 btnPeople.Visible=true;
loadPGSalDetails();
/*1/6/10 if (Session["PeopleId"] == null)
{
lblStartDate.Visible = false;
txtStartDate.Visible = false;
lblEndDate.Visible = false;
txtEndDate.Visible = false;
lblAptType.Visible = false;
lblAptStatus.Visible = false;
lstAptStatus.Visible = false;
lblVisibility.Visible = false;
lstVisibility.Visible = false;
lblSARevision.Visible = false;
lblSalary.Visible = false;
txtSalary.Visible = false;
lblSalaryPeriod.Visible = false;
lblSalMax.Visible = false;
lblSalMin.Visible = false;
lblPayGrades.Visible = false;
lstPayGrades.Visible = false;
}*/
lblCurrStartDate.Visible = false;
lblCurr.Visible = false;
lblCurrGrade.Visible = false;
lblCurrSal.Visible = false;
lblRev.Visible = false;
lblSalaryPeriod1.Visible = false;
lblStartDateS.Visible = false;
txtStartDateS.Visible = false;
}
if (Session["PeopleId"] != null)
{
lblName.Text = "Name: " + Session["PeopleName"].ToString();
}
lblContent1.Text=Session["btnAction"].ToString() + " Appointment Action";
if (Session["btnAction"].ToString() == "Add")
{
btnAction.Text="OK";
}
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
private void loadPGSalDetails()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="hrs_RetrievePayGrade";
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=lstPayGrades.SelectedItem.Value;
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"PGID");
lblSalaryPeriod.Text=ds.Tables["PGID"].Rows[0][0].ToString()
+ " per " + ds.Tables["PGID"].Rows[0][4].ToString();
lblSalaryPeriod1.Text = ds.Tables["PGID"].Rows[0][0].ToString()
+ " per " + ds.Tables["PGID"].Rows[0][4].ToString();
lblSalMin.Text="Minimum Salary for this Grade Level: "
+ ds.Tables["PGID"].Rows[0][1].ToString()
+ " "
+ ds.Tables["PGID"].Rows[0][0].ToString()
+ " per " + ds.Tables["PGID"].Rows[0][4].ToString();
lblSalMax.Text="Maximum Salary for this Grade Level: "
+ ds.Tables["PGID"].Rows[0][2].ToString()
+ " "
+ ds.Tables["PGID"].Rows[0][0].ToString()
+ " per " + ds.Tables["PGID"].Rows[0][4].ToString();
}
private void loadStaffAction()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="hrs_RetrieveStaffAction";
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Session["Id"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"StaffAction");
if (Session["PeopleId"] != null)
{
lblName.Text = "Name: " + Session["PeopleName"].ToString();
}
else if (ds.Tables["StaffAction"].Rows[0][0].ToString() == null)
{
lblName.Text= "Name: " + "Unidentified";
Session["PeopleId"]=null;
}
else
{
Session["PeopleId"]=ds.Tables["StaffAction"].Rows[0][0].ToString();
lblName.Text="Name: " + ds.Tables["StaffAction"].Rows[0][1].ToString();
}
lstLocations.SelectedIndex=
GetIndexOfLocs(ds.Tables["StaffAction"].Rows[0][3].ToString());
lstVisibility.SelectedIndex=
GetIndexOfVisibility(ds.Tables["StaffAction"].Rows[0][4].ToString());
lstPayMethods.SelectedIndex = GetIndexOfPayMethods (ds.Tables["StaffAction"].Rows[0][5].ToString());
Session["Status"]=ds.Tables["StaffAction"].Rows[0][7].ToString();
//txtSalary.Text=ds.Tables["StaffAction"].Rows[0][8].ToString();
//lstPayGrades.SelectedIndex = GetIndexOfPayGrades(ds.Tables["StaffAction"].Rows[0][9].ToString());
lstRoles.SelectedIndex = GetIndexOfRoles (ds.Tables["StaffAction"].Rows[0][10].ToString());
lstAptStatus.SelectedIndex=Int32.Parse(Session["Status"].ToString());
txtStartDate.Text = ds.Tables["StaffAction"].Rows[0][11].ToString();
txtEndDate.Text = ds.Tables["StaffAction"].Rows[0][12].ToString();
lstFunds.SelectedIndex = GetIndexOfBudgets(ds.Tables["StaffAction"].Rows[0][13].ToString());
//refreshTextBox();
}
private void loadStaffSalary()
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "hrs_RetrieveStaffSalary";
cmd.Parameters.Add("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value = Session["Id"].ToString();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "StaffSalary");
lblCurrStartDate.Text = "Start Date: " + ds.Tables["StaffSalary"].Rows[0][1].ToString();
Session["DT"] = ds.Tables["StaffSalary"].Rows[0][1].ToString();
lblCurrSal.Text = "Salary: " + ds.Tables["StaffSalary"].Rows[0][2].ToString();
lstPayGrades.SelectedIndex = GetIndexOfPayGrades(ds.Tables["StaffSalary"].Rows[0][3].ToString());
Session["CurrPayGrade"] = lstPayGrades.SelectedItem.Value;
lblCurrGrade.Text = "Grade: " + ds.Tables["StaffSalary"].Rows[0][4].ToString();
txtSalary.Text = "";
txtStartDateS.Text = "";
}
catch (Exception Ex)
{
if (Ex.Message.StartsWith("String was not recognized as a valid DateTime."))
{
lblContent2.Text = "Please enter dates in form mm/dd/yyyy.";
}
else lblContent2.Text = Ex.Message;
}
}
/*private void refreshTextBox()
{
if (txtStartDate.Text.StartsWith("&") == true)
{
txtStartDate.Text = "";
}
if (txtEndDate.Text.StartsWith("&") == true)
{
txtEndDate.Text = "";
}
}*/
protected void btnAction_Click(object sender, System.EventArgs e)
{
try
{
if (Session["btnAction"].ToString() == "Add")
{
int t = 0;
if (Convert.ToDateTime(txtStartDate.Text) ==
Convert.ToDateTime(txtEndDate.Text))
{
t = 1;
}
else
{
t = 2;
}
if (txtSalary.Text == "")
{
lblContent1.Text = "You must enter the Salary, actual or estimated, even if it is not determined yet.";
}
else if (txtStartDateS.Text == "")
{
lblContent1.Text = "You must enter the start date even if it is not determined yet.";
}
else if (lblName.Text == "")
{
if (lstAptStatus.SelectedItem.Value == "1")
{
lblContent1.Text = "You must identify the person being appointed.";
}
}
if (txtStartDate.Text == "")
{
lblContent2.Text = "You must enter an appointment start date";
}
else if (txtEndDate.Text.StartsWith(" ") == true)
{
txtEndDate.Text = "";
lblContent2.Text = "You must enter an appointment end date";
}
else if (Convert.ToDateTime(txtEndDate.Text) < Convert.ToDateTime(txtStartDate.Text))
{
lblContent2.Text = "Appointment End Date cannot be before the Appointment Start Date.";
}
else if (Session["PeopleId"] == null)
{
lblContent2.Text = "You must identify the person being appointed.";
}
else
{
addAData();
getStaffActionsId();
addSData();
Done();
}
}
else
{
if ((txtStartDateS.Text == "") && (txtSalary.Text == "") &&
(lstPayGrades.SelectedItem.Value == (Session["CurrPayGrade"].ToString())))
{
updateAData();
Done();
}
else
{
if (txtStartDateS.Text == "")
{
lblContent1.Text = "You must enter the start date for this update.";
txtStartDateS.Focus();
}
else if (txtSalary.Text == "")
{
lblContent1.Text = "You must enter the Salary amount after this update.";
}
else if (Convert.ToDateTime(txtEndDate.Text) < Convert.ToDateTime(txtStartDate.Text))
{
lblContent2.Text = "Appointment End Date cannot be before the Appointment Start Date.";
}
else if (Convert.ToDateTime(txtStartDateS.Text) < Convert.ToDateTime(txtStartDate.Text))
{
lblContent2.Text = "Salary Start Date cannot be before the Appointment Start Date.";
}
else if (Convert.ToDateTime(txtStartDateS.Text) > Convert.ToDateTime(txtEndDate.Text))
{
lblContent2.Text = "Salary Start Date cannot be after the Appointment End Date.";
}
else
{
if (Session["Ctr"] == null)
{
DateTime dtCurr = new DateTime();
dtCurr = Convert.ToDateTime(Session["DT"].ToString());
DateTime dtRev = new DateTime();
dtRev = Convert.ToDateTime(txtStartDateS.Text);
if (DateTime.Compare(dtCurr, dtRev) >= 0)
{
lblContent2.Text = "Start date of this revision is PRIOR to the start date of current revision (see above). "
+ " By continuing with this update, you will replace the current revision with this update, not simply update it. "
+ " To continue"
+ " click on 'OK' again. Else click on 'Cancel'";
Session["Ctr"] = "OK";
}
else
{
updateAData();
addSData();
updateSData();
Done();
}
}
else
{
if (Session["Ctr"].ToString() == "OK")//delete staff action(s) with dates prior to this one.
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "hrs_DeleteSARevisions";
cmd.Parameters.Add("@StartDate", SqlDbType.SmallDateTime);
cmd.Parameters["@StartDate"].Value = Convert.ToDateTime(txtStartDateS.Text);
cmd.Parameters.Add("@StaffActionsId", SqlDbType.Int);
cmd.Parameters["@StaffActionsId"].Value = Session["Id"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
Session["Ctr"] = null;
updateAData();
addSData();
Done();
}
}
}
}
}
catch (Exception Ex)
{
if (Ex.Message.StartsWith("String was not recognized as a valid DateTime."))
{
lblContent2.Text = "Please enter dates in form mm/dd/yyyy.";
}
else lblContent2.Text = Ex.Message;
}
}
private void updateSData()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "hrs_updateSARevisions";
cmd.Parameters.Add("@EndDate", SqlDbType.SmallDateTime);
cmd.Parameters["@EndDate"].Value = Convert.ToDateTime(txtStartDateS.Text);
cmd.Parameters.Add("@StaffActionsId", SqlDbType.Int);
cmd.Parameters["@StaffActionsId"].Value = Session["Id"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
private void getStaffActionsId()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "hrs_RetrieveStaffActionsNew";
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "SAId");
Session["Id"] = ds.Tables["SAId"].Rows[0][0].ToString();
}
private void updateAData()
{
/*try
{*/
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="hrs_UpdateStaffAction";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Session["Id"].ToString();
cmd.Parameters.Add ("@TypeId",SqlDbType.Int);
cmd.Parameters["@TypeId"].Value=Int32.Parse(Session["OrgStaffTypesId"].ToString());
cmd.Parameters.Add ("@LocId",SqlDbType.Int);
cmd.Parameters["@LocId"].Value=lstLocations.SelectedItem.Value;
cmd.Parameters.Add ("@PM",SqlDbType.Int);
cmd.Parameters["@PM"].Value=lstPayMethods.SelectedItem.Value;
if (Session["PeopleId"] != null)
{
cmd.Parameters.Add ("@PeopleId",SqlDbType.Int);
cmd.Parameters["@PeopleId"].Value= Session["PeopleId"].ToString();
}
if (txtStartDate.Text != "")
{
cmd.Parameters.Add("@StartDate", SqlDbType.SmallDateTime);
cmd.Parameters["@StartDate"].Value = txtStartDate.Text;
}
if (txtEndDate.Text.StartsWith("&") == false)
{
cmd.Parameters.Add("@EndDate", SqlDbType.SmallDateTime);
cmd.Parameters["@EndDate"].Value = txtEndDate.Text;
}
cmd.Parameters.Add ("@Vis",SqlDbType.Int);
cmd.Parameters["@Vis"].Value=lstVisibility.SelectedItem.Value;
cmd.Parameters.Add ("@Status",SqlDbType.Int);
cmd.Parameters["@Status"].Value=lstAptStatus.SelectedItem.Value;
cmd.Parameters.Add ("@RolesId",SqlDbType.Int);
cmd.Parameters["@RolesId"].Value=lstRoles.SelectedItem.Value;
cmd.Parameters.Add("@FundsId", SqlDbType.Int);
cmd.Parameters["@FundsId"].Value = lstFunds.SelectedItem.Value;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
/*}
catch (Exception Ex)
{
}*/
}
private void addAData()
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "hrs_AddStaffAction";
cmd.Connection = this.epsDbConn;
if (Session["PeopleId"] != null)
{
cmd.Parameters.Add("@PeopleId", SqlDbType.Int);
cmd.Parameters["@PeopleId"].Value = Session["PeopleId"].ToString();
}
cmd.Parameters.Add("@TypeId", SqlDbType.Int);
cmd.Parameters["@TypeId"].Value = Int32.Parse(Session["OrgStaffTypesId"].ToString());
cmd.Parameters.Add("@LocId", SqlDbType.Int);
cmd.Parameters["@LocId"].Value = lstLocations.SelectedItem.Value;
cmd.Parameters.Add("@Status", SqlDbType.Int);
cmd.Parameters["@Status"].Value = lstAptStatus.SelectedItem.Value;
cmd.Parameters.Add("@PM", SqlDbType.Int);
cmd.Parameters["@PM"].Value = lstPayMethods.SelectedItem.Value;
cmd.Parameters.Add("@RolesId", SqlDbType.Int);
cmd.Parameters["@RolesId"].Value = lstRoles.SelectedItem.Value;
cmd.Parameters.Add("@FundsId", SqlDbType.Int);
cmd.Parameters["@FundsId"].Value = lstFunds.SelectedItem.Value;
cmd.Parameters.Add("@StartDate", SqlDbType.SmallDateTime);
cmd.Parameters["@StartDate"].Value = DateTime.Parse(txtStartDate.Text);
cmd.Parameters.Add("@EndDate", SqlDbType.SmallDateTime);
cmd.Parameters["@EndDate"].Value = DateTime.Parse(txtEndDate.Text);
cmd.Parameters.Add("@Vis", SqlDbType.Int);
cmd.Parameters["@Vis"].Value = lstVisibility.SelectedItem.Value;
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
catch
{
if (txtSalary.Text == "")
{
lblContent1.Text = "You must enter a Salary Amount or click 'Cancel'";
}
}
}
private void addSData()
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "hrs_AddSARevisions";
cmd.Connection = this.epsDbConn;
cmd.Parameters.Add("@StaffActionsId", SqlDbType.Int);
cmd.Parameters["@StaffActionsId"].Value = Session["Id"].ToString();
cmd.Parameters.Add("@StartDate", SqlDbType.SmallDateTime);
if (Session["btnAction"].ToString() == "Update")
{
cmd.Parameters["@StartDate"].Value = DateTime.Parse(txtStartDateS.Text);
}
else
{
cmd.Parameters["@StartDate"].Value = DateTime.Parse(txtStartDate.Text);
}
cmd.Parameters.Add("@PayGradeId", SqlDbType.Int);
cmd.Parameters["@PayGradeId"].Value = lstPayGrades.SelectedItem.Value;
cmd.Parameters.Add("@Salary", SqlDbType.Decimal);
cmd.Parameters["@Salary"].Value = decimal.Parse(txtSalary.Text, NumberStyles.Any);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
catch (Exception Ex)
{
if (Ex.Message.StartsWith("String was not recognized as a valid DateTime."))
{
lblContent2.Text = "Please enter dates in form mm/dd/yyyy.";
}
else lblContent2.Text = Ex.Message;
}
}
private void loadVisibility()
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="ams_RetrieveVisibility";
cmd.Parameters.Add ("@Vis",SqlDbType.Int);
cmd.Parameters["@Vis"].Value=Session["OrgVis"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Visibility");
lstVisibility.DataSource = ds;
lstVisibility.DataMember= "Visibility";
lstVisibility.DataTextField = "Name";
lstVisibility.DataValueField = "Id";
lstVisibility.DataBind();
}
private void loadRoles()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="hrs_RetrieveRolesAll";
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
cmd.Parameters.Add ("@LicenseId",SqlDbType.Int);
cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString();
cmd.Parameters.Add ("@DomainId",SqlDbType.Int);
cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Roles");
lstRoles.DataSource = ds;
lstRoles.DataMember= "Roles";
lstRoles.DataTextField = "Name";
lstRoles.DataValueField = "Id";
lstRoles.DataBind();
}
private void loadSOF()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "fms_RetrieveFunds";
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "Budgets");
lstFunds.DataSource = ds;
lstFunds.DataMember = "Budgets";
lstFunds.DataTextField = "Name";
lstFunds.DataValueField = "Id";
lstFunds.DataBind();
}
private void loadPayGrades()
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="hrs_RetrievePayGrades";
cmd.Parameters.Add ("@OrgStaffTypesId",SqlDbType.Int);
cmd.Parameters["@OrgStaffTypesId"].Value=Int32.Parse(Session["OrgStaffTypesId"].ToString());
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"PayGrades");
lstPayGrades.DataSource = ds;
lstPayGrades.DataMember= "PayGrades";
lstPayGrades.DataTextField = "Name";
lstPayGrades.DataValueField = "Id";
lstPayGrades.DataBind();
}
private void loadLocs()
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_RetrieveLocations";
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
cmd.Parameters.Add ("@LicenseId",SqlDbType.Int);
cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString();
cmd.Parameters.Add ("@DomainId",SqlDbType.Int);
cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Locations");
lstLocations.DataSource = ds;
lstLocations.DataMember= "Locations";
lstLocations.DataTextField = "Name";
lstLocations.DataValueField = "Id";
lstLocations.DataBind();
}
private void loadPayMethods()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = this.epsDbConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "fms_RetrievePayMethods";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "PayMethods");
lstPayMethods.DataSource = ds;
lstPayMethods.DataMember = "PayMethods";
lstPayMethods.DataTextField = "Name";
lstPayMethods.DataValueField = "Id";
lstPayMethods.DataBind();
}
private void Done()
{
Session["PeopleId"]=null;
Response.Redirect (strURL + Session["CSA"].ToString() + ".aspx?");
}
protected void btnCancel_Click(object sender, System.EventArgs e)
{
Done();
}
private void peopleAdd()
{
Session["CallerPeople"]="frmUpdStaffAction";
Response.Redirect (strURL + "frmPeople.aspx?");
}
protected void btnPeople_Click(object sender, System.EventArgs e)
{
peopleAdd();
}
protected void Dropdownlist1_SelectedIndexChanged(object sender, System.EventArgs e)
{
loadPGSalDetails();
if (lblSalMin.ForeColor== Color.Ivory)
{
lblSalMin.ForeColor = Color.White;
lblSalMax.ForeColor = Color.White;
}
else
{
lblSalMin.ForeColor = Color.Ivory;
lblSalMax.ForeColor = Color.Ivory;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Aurora.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using NUnit.Framework;
using CookComputing.XmlRpc;
using System.Security.Permissions;
namespace ntest
{
[XmlRpcUrl("http://localhost/test/")]
public interface ITest
{
[XmlRpcMethod]
string Method1(int x);
}
public interface ITest2 : IXmlRpcProxy
{
[XmlRpcMethod]
string Method1(int x);
}
[TestFixture]
public class ProxyGenTest
{
[TestFixtureSetUp]
public void Setup()
{
StateNameService.Start(5678);
}
[TestFixtureTearDown]
public void TearDown()
{
StateNameService.Stop();
}
[Test]
public void Method1()
{
ITest proxy = (ITest)XmlRpcProxyGen.Create(typeof(ITest));
XmlRpcClientProtocol cp = (XmlRpcClientProtocol)proxy;
Assert.IsTrue(cp is ITest);
Assert.IsTrue(cp is XmlRpcClientProtocol);
}
#if !FX1_0
[Test]
public void Method1Generic()
{
ITest2 proxy = XmlRpcProxyGen.Create<ITest2>();
XmlRpcClientProtocol cp = (XmlRpcClientProtocol)proxy;
Assert.IsTrue(cp is ITest2);
Assert.IsTrue(cp is IXmlRpcProxy);
Assert.IsTrue(cp is XmlRpcClientProtocol);
}
#endif
public interface IParent : IXmlRpcProxy
{
[XmlRpcMethod]
string Foo(int x);
}
public interface IChild : IParent
{
[XmlRpcMethod]
string Bar(int x);
}
[Test]
public void InheritedInterface()
{
// Test problem reported by Sean Rohead. This will throw an exception
// if method Foo in the base class Parent is not implemented
IChild proxy = (IChild)XmlRpcProxyGen.Create(typeof(IChild));
}
[Test]
public void ListMethods()
{
IChild proxy = (IChild)XmlRpcProxyGen.Create(typeof(IChild));
}
[Test]
public void CheckProperties()
{
ITest2 proxy = (ITest2)XmlRpcProxyGen.Create(typeof(ITest2));
X509CertificateCollection certs = proxy.ClientCertificates;
string groupName = proxy.ConnectionGroupName;
#if (!FX1_0)
bool expect100 = proxy.Expect100Continue;
#endif
WebHeaderCollection header = proxy.Headers;
int indentation = proxy.Indentation;
bool keepAlive = proxy.KeepAlive;
XmlRpcNonStandard nonStandard = proxy.NonStandard;
bool preauth = proxy.PreAuthenticate;
Version version = proxy.ProtocolVersion;
IWebProxy webProxy = proxy.Proxy;
CookieContainer container = proxy.CookieContainer;
int timeout = proxy.Timeout;
string url = proxy.Url;
bool useIndent = proxy.UseIndentation;
System.Text.Encoding encoding = proxy.XmlEncoding;
string method = proxy.XmlRpcMethod;
bool useIntTag = proxy.UseIntTag;
// introspection methods
try { proxy.SystemListMethods(); } catch (XmlRpcMissingUrl) { }
try { proxy.SystemMethodSignature("Foo"); } catch (XmlRpcMissingUrl) { }
try { proxy.SystemMethodHelp("Foo"); } catch (XmlRpcMissingUrl) { }
}
public interface IOverrides
{
[XmlRpcMethod("account.info")]
string acct_info(int SITECODE, String username);
[XmlRpcMethod("account.info")]
string acct_info(int SITECODE, int account);
}
public interface IOverridesChild : IOverrides
{
[XmlRpcMethod("account.info")]
new string acct_info(int SITECODE, int account);
}
[Test]
public void Overrides()
{
IOverrides proxy = (IOverrides)XmlRpcProxyGen.Create(typeof(IOverrides));
}
[Test]
public void OverridesChild()
{
IOverridesChild proxy = (IOverridesChild)XmlRpcProxyGen.Create(typeof(IOverridesChild));
}
[Test]
public void MakeSynchronousCalls()
{
IStateName proxy = (IStateName)XmlRpcProxyGen.Create(typeof(IStateName));
string ret1 = proxy.GetStateName(1);
Assert.AreEqual("Alabama", ret1);
string ret2 = proxy.GetStateName("1");
Assert.AreEqual("Alabama", ret2);
}
[Test]
public void SynchronousFaultException()
{
IStateName proxy = (IStateName)XmlRpcProxyGen.Create(typeof(IStateName));
try
{
string ret1 = proxy.GetStateName(100);
Assert.Fail("exception not thrown on sync call");
}
catch (XmlRpcFaultException fex)
{
Assert.AreEqual(1, fex.FaultCode);
Assert.AreEqual("Invalid state number", fex.FaultString);
}
}
class CBInfo
{
public ManualResetEvent _evt;
public Exception _excep;
public string _ret;
public CBInfo(ManualResetEvent evt)
{
_evt = evt;
}
}
void StateNameCallback(IAsyncResult asr)
{
XmlRpcAsyncResult clientResult = (XmlRpcAsyncResult)asr;
IStateName proxy = (IStateName)clientResult.ClientProtocol;
CBInfo info = (CBInfo)asr.AsyncState;
try
{
info._ret = proxy.EndGetStateName(asr);
}
catch (Exception ex)
{
info._excep = ex;
}
info._evt.Set();
}
[Test]
public void MakeAsynchronousCallIsCompleted()
{
IStateName proxy = (IStateName)XmlRpcProxyGen.Create(typeof(IStateName));
IAsyncResult asr1 = proxy.BeginGetStateName(1);
while (asr1.IsCompleted == false)
System.Threading.Thread.Sleep(10);
string ret1 = proxy.EndGetStateName(asr1);
Assert.AreEqual("Alabama", ret1);
}
[Test]
public void MakeAsynchronousCallWait()
{
IStateName proxy = (IStateName)XmlRpcProxyGen.Create(typeof(IStateName));
IAsyncResult asr2 = proxy.BeginGetStateName(1);
asr2.AsyncWaitHandle.WaitOne();
string ret2 = proxy.EndGetStateName(asr2);
Assert.AreEqual("Alabama", ret2);
}
[Test]
public void MakeAsynchronousCallCallback()
{
IStateName proxy = (IStateName)XmlRpcProxyGen.Create(typeof(IStateName));
ManualResetEvent evt = new ManualResetEvent(false);
CBInfo info = new CBInfo(evt);
IAsyncResult asr3 = proxy.BeginGetStateName(1, StateNameCallback, info);
evt.WaitOne();
Assert.AreEqual(null, info._excep, "Async call threw exception");
Assert.AreEqual("Alabama", info._ret);
}
void StateNameCallbackNoState(IAsyncResult asr)
{
XmlRpcAsyncResult clientResult = (XmlRpcAsyncResult)asr;
IStateName proxy = (IStateName)clientResult.ClientProtocol;
try
{
_ret = proxy.EndGetStateName(asr);
}
catch (Exception ex)
{
_excep = ex;
}
_evt.Set();
}
ManualResetEvent _evt;
Exception _excep;
string _ret;
[Test]
public void MakeAsynchronousCallCallbackNoState()
{
IStateName proxy = (IStateName)XmlRpcProxyGen.Create(typeof(IStateName));
_evt = new ManualResetEvent(false);
IAsyncResult asr3 = proxy.BeginGetStateName(1, StateNameCallbackNoState);
_evt.WaitOne();
Assert.AreEqual(null, _excep, "Async call threw exception");
Assert.AreEqual("Alabama", _ret);
}
[Test]
public void AsynchronousFaultException()
{
IStateName proxy = (IStateName)XmlRpcProxyGen.Create(typeof(IStateName));
IAsyncResult asr = proxy.BeginGetStateName(100);
asr.AsyncWaitHandle.WaitOne();
try
{
string ret = proxy.EndGetStateName(asr);
Assert.Fail("exception not thrown on async call");
}
catch (XmlRpcFaultException fex)
{
Assert.AreEqual(1, fex.FaultCode);
Assert.AreEqual("Invalid state number", fex.FaultString);
}
}
[XmlRpcUrl("http://localhost:5678/statename.rem")]
public interface IStateName2 : IXmlRpcProxy
{
[XmlRpcMethod("examples.getStateStruct", StructParams = true)]
string GetStateNames(int state1, int state2, int state3);
}
[Test]
public void MakeStructParamsCall()
{
IStateName2 proxy = (IStateName2)XmlRpcProxyGen.Create(typeof(IStateName2));
string ret = proxy.GetStateNames(1, 2, 3);
Assert.AreEqual("Alabama Alaska Arizona", ret);
}
[Test]
public void FileIOPermission()
{
FileIOPermission f = new FileIOPermission(PermissionState.Unrestricted);
f.Deny();
try
{
IStateName2 proxy = (IStateName2)XmlRpcProxyGen.Create(typeof(IStateName2));
}
finally
{
CodeAccessPermission.RevertDeny();
}
}
}
}
| |
// 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.Threading;
using System.Collections.Generic;
// TODO when we upgrade to C# V6 you can remove this.
// warning CS0420: 'P.x': a reference to a volatile field will not be treated as volatile
// This happens when you pass a _subcribers (a volatile field) to interlocked operations (which are byref).
// This was fixed in C# V6.
#pragma warning disable 0420
namespace System.Diagnostics
{
/// <summary>
/// A DiagnosticListener is something that forwards on events written with DiagnosticSource.
/// It is an IObservable (has Subscribe method), and it also has a Subscribe overloads that
/// lets you specify a 'IsEnabled' predicate that users of DiagnosticSource will use for
/// 'quick checks'.
///
/// The item in the stream is a KeyValuePair[string, object] where the string is the name
/// of the diagnostic item and the object is the payload (typically an anonymous type).
///
/// There may be many DiagnosticListeners in the system, but we encourage the use of
/// The DiagnosticSource.DefaultSource which goes to the DiagnosticListener.DefaultListener.
///
/// If you need to see 'everything' you can subscribe to the 'AllListeners' event that
/// will fire for every live DiagnosticListener in the appdomain (past or present).
///
/// Please See the DiagnosticSource Users Guide
/// https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md
/// for instructions on its use.
/// </summary>
public class DiagnosticListener : DiagnosticSource, IObservable<KeyValuePair<string, object>>, IDisposable
{
/// <summary>
/// When you subscribe to this you get callbacks for all NotificationListeners in the appdomain
/// as well as those that occurred in the past, and all future Listeners created in the future.
/// </summary>
public static IObservable<DiagnosticListener> AllListeners
{
get
{
#if NET46 || NETFX
GC.KeepAlive(HttpHandlerDiagnosticListener.s_instance);
#endif
if (s_allListenerObservable == null)
{
s_allListenerObservable = new AllListenerObservable();
}
return s_allListenerObservable;
}
}
// Subscription implementation
/// <summary>
/// Add a subscriber (Observer). If 'IsEnabled' == null (or not present), then the Source's IsEnabled
/// will always return true.
/// </summary>
public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled)
{
IDisposable subscription;
if (isEnabled == null)
{
subscription = SubscribeInternal(observer, null, null);
}
else
{
Predicate<string> localIsEnabled = isEnabled;
subscription = SubscribeInternal(observer, isEnabled, (name, arg1, arg2) => localIsEnabled(name));
}
return subscription;
}
/// <summary>
/// Add a subscriber (Observer). If 'IsEnabled' == null (or not present), then the Source's IsEnabled
/// will always return true.
/// </summary>
/// <param name="observer">Subscriber (IObserver)</param>
/// <param name="isEnabled">Filters events based on their name (string) and context objects that could be null.
/// Note that producer may first call filter with event name only and null context arguments and filter should
/// return true if consumer is interested in any of such events. Producers that support
/// context-based filtering will invoke isEnabled again with context for more prcise filtering.
/// Use Subscribe overload with name-based filtering if producer does NOT support context-based filtering</param>
public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Func<string, object, object, bool> isEnabled)
{
return isEnabled == null ?
SubscribeInternal(observer, null, null) :
SubscribeInternal(observer, name => IsEnabled(name, null, null), isEnabled);
}
/// <summary>
/// Same as other Subscribe overload where the predicate is assumed to always return true.
/// </summary>
public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer)
{
return SubscribeInternal(observer, null, null);
}
/// <summary>
/// Make a new DiagnosticListener, it is a NotificationSource, which means the returned result can be used to
/// log notifications, but it also has a Subscribe method so notifications can be forwarded
/// arbitrarily. Thus its job is to forward things from the producer to all the listeners
/// (multi-casting). Generally you should not be making your own DiagnosticListener but use the
/// DiagnosticListener.Default, so that notifications are as 'public' as possible.
/// </summary>
public DiagnosticListener(string name)
{
Name = name;
// Insert myself into the list of all Listeners.
lock (s_lock)
{
// Issue the callback for this new diagnostic listener.
var allListenerObservable = s_allListenerObservable;
if (allListenerObservable != null)
allListenerObservable.OnNewDiagnosticListener(this);
// And add it to the list of all past listeners.
_next = s_allListeners;
s_allListeners = this;
}
// Call IsEnabled just so we insure that the DiagnosticSourceEventSource has been
// constructed (and thus is responsive to ETW requests to be enabled).
DiagnosticSourceEventSource.Logger.IsEnabled();
}
/// <summary>
/// Clean up the NotificationListeners. Notification listeners do NOT DIE ON THEIR OWN
/// because they are in a global list (for discoverability). You must dispose them explicitly.
/// Note that we do not do the Dispose(bool) pattern because we frankly don't want to support
/// subclasses that have non-managed state.
/// </summary>
virtual public void Dispose()
{
// Remove myself from the list of all listeners.
lock (s_lock)
{
if (_disposed)
{
return;
}
_disposed = true;
if (s_allListeners == this)
s_allListeners = s_allListeners._next;
else
{
var cur = s_allListeners;
while (cur != null)
{
if (cur._next == this)
{
cur._next = _next;
break;
}
cur = cur._next;
}
}
_next = null;
}
// Indicate completion to all subscribers.
DiagnosticSubscription subscriber = null;
Interlocked.Exchange(ref subscriber, _subscriptions);
while (subscriber != null)
{
subscriber.Observer.OnCompleted();
subscriber = subscriber.Next;
}
// The code above also nulled out all subscriptions.
}
/// <summary>
/// When a DiagnosticListener is created it is given a name. Return this.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Return the name for the ToString() to aid in debugging.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name;
}
#region private
// NotificationSource implementation
/// <summary>
/// Determines whether there are any registered subscribers
/// </summary>
/// <remarks> If there is an expensive setup for the notification,
/// you may call IsEnabled() as the first and most efficient check before doing this setup.
/// Producers may optionally use this check before IsEnabled(string) in the most performance-critical parts of the system
/// to ensure somebody listens to the DiagnosticListener at all.</remarks>
public bool IsEnabled()
{
return _subscriptions != null;
}
/// <summary>
/// Override abstract method
/// </summary>
public override bool IsEnabled(string name)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
{
if (curSubscription.IsEnabled1Arg == null || curSubscription.IsEnabled1Arg(name))
return true;
}
return false;
}
// NotificationSource implementation
/// <summary>
/// Override abstract method
/// </summary>
public override bool IsEnabled(string name, object arg1, object arg2 = null)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
{
if (curSubscription.IsEnabled3Arg == null || curSubscription.IsEnabled3Arg(name, arg1, arg2))
return true;
}
return false;
}
/// <summary>
/// Override abstract method
/// </summary>
public override void Write(string name, object value)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
curSubscription.Observer.OnNext(new KeyValuePair<string, object>(name, value));
}
// Note that Subscriptions are READ ONLY. This means you never update any fields (even on removal!)
private class DiagnosticSubscription : IDisposable
{
internal IObserver<KeyValuePair<string, object>> Observer;
// IsEnabled1Arg and IsEnabled3Arg represent IsEnabled callbacks.
// - IsEnabled1Arg invoked for DiagnosticSource.IsEnabled(string)
// - IsEnabled3Arg invoked for DiagnosticSource.IsEnabled(string, obj, obj)
// Subscriber MUST set both IsEnabled1Arg and IsEnabled3Arg or none of them:
// when Predicate<string> is provided in DiagosticListener.Subscribe,
// - IsEnabled1Arg is set to predicate
// - IsEnabled3Arg falls back to predicate ignoring extra arguments.
// similarly, when Func<string, obj, obj, bool> is provided,
// IsEnabled1Arg falls back to IsEnabled3Arg with null context
// Thus, dispatching is very efficient when producer and consumer agree on number of IsEnabled arguments
// Argument number mismatch between producer/consumer adds extra cost of adding or omitting context parameters
internal Predicate<string> IsEnabled1Arg;
internal Func<string, object, object, bool> IsEnabled3Arg;
internal DiagnosticListener Owner; // The DiagnosticListener this is a subscription for.
internal DiagnosticSubscription Next; // Linked list of subscribers
public void Dispose()
{
// TO keep this lock free and easy to analyze, the linked list is READ ONLY. Thus we copy
for (;;)
{
DiagnosticSubscription subscriptions = Owner._subscriptions;
DiagnosticSubscription newSubscriptions = Remove(subscriptions, this); // Make a new list, with myself removed.
// try to update, but if someone beat us to it, then retry.
if (Interlocked.CompareExchange(ref Owner._subscriptions, newSubscriptions, subscriptions) == subscriptions)
{
#if DEBUG
var cur = newSubscriptions;
while (cur != null)
{
Debug.Assert(!(cur.Observer == Observer && cur.IsEnabled1Arg == IsEnabled1Arg && cur.IsEnabled3Arg == IsEnabled3Arg), "Did not remove subscription!");
cur = cur.Next;
}
#endif
break;
}
}
}
// Create a new linked list where 'subscription has been removed from the linked list of 'subscriptions'.
private static DiagnosticSubscription Remove(DiagnosticSubscription subscriptions, DiagnosticSubscription subscription)
{
if (subscriptions == null)
{
// May happen if the IDisposable returned from Subscribe is Dispose'd again
return null;
}
if (subscriptions.Observer == subscription.Observer &&
subscriptions.IsEnabled1Arg == subscription.IsEnabled1Arg &&
subscriptions.IsEnabled3Arg == subscription.IsEnabled3Arg)
return subscriptions.Next;
#if DEBUG
// Delay a bit. This makes it more likely that races will happen.
for (int i = 0; i < 100; i++)
GC.KeepAlive("");
#endif
return new DiagnosticSubscription() { Observer = subscriptions.Observer, Owner = subscriptions.Owner, IsEnabled1Arg = subscriptions.IsEnabled1Arg, IsEnabled3Arg = subscriptions.IsEnabled3Arg, Next = Remove(subscriptions.Next, subscription) };
}
}
#region AllListenerObservable
/// <summary>
/// Logically AllListenerObservable has a very simple task. It has a linked list of subscribers that want
/// a callback when a new listener gets created. When a new DiagnosticListener gets created it should call
/// OnNewDiagnosticListener so that AllListenerObservable can forward it on to all the subscribers.
/// </summary>
private class AllListenerObservable : IObservable<DiagnosticListener>
{
public IDisposable Subscribe(IObserver<DiagnosticListener> observer)
{
lock (s_lock)
{
// Call back for each existing listener on the new callback (catch-up).
for (DiagnosticListener cur = s_allListeners; cur != null; cur = cur._next)
observer.OnNext(cur);
// Add the observer to the list of subscribers.
_subscriptions = new AllListenerSubscription(this, observer, _subscriptions);
return _subscriptions;
}
}
/// <summary>
/// Called when a new DiagnosticListener gets created to tell anyone who subscribed that this happened.
/// </summary>
/// <param name="diagnosticListener"></param>
internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener)
{
Debug.Assert(Monitor.IsEntered(s_lock)); // We should only be called when we hold this lock
// Simply send a callback to every subscriber that we have a new listener
for (var cur = _subscriptions; cur != null; cur = cur.Next)
cur.Subscriber.OnNext(diagnosticListener);
}
#region private
/// <summary>
/// Remove 'subscription from the list of subscriptions that the observable has. Called when
/// subscriptions are disposed. Returns true if the subscription was removed.
/// </summary>
private bool Remove(AllListenerSubscription subscription)
{
lock (s_lock)
{
if (_subscriptions == subscription)
{
_subscriptions = subscription.Next;
return true;
}
else if (_subscriptions != null)
{
for (var cur = _subscriptions; cur.Next != null; cur = cur.Next)
{
if (cur.Next == subscription)
{
cur.Next = cur.Next.Next;
return true;
}
}
}
// Subscriber likely disposed multiple times
return false;
}
}
/// <summary>
/// One node in the linked list of subscriptions that AllListenerObservable keeps. It is
/// IDisposable, and when that is called it removes itself from the list.
/// </summary>
internal class AllListenerSubscription : IDisposable
{
internal AllListenerSubscription(AllListenerObservable owner, IObserver<DiagnosticListener> subscriber, AllListenerSubscription next)
{
this._owner = owner;
this.Subscriber = subscriber;
this.Next = next;
}
public void Dispose()
{
if (_owner.Remove(this))
{
Subscriber.OnCompleted(); // Called outside of a lock
}
}
private readonly AllListenerObservable _owner; // the list this is a member of.
internal readonly IObserver<DiagnosticListener> Subscriber;
internal AllListenerSubscription Next;
}
private AllListenerSubscription _subscriptions;
#endregion
}
#endregion
private IDisposable SubscribeInternal(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled1Arg, Func<string, object, object, bool> isEnabled3Arg)
{
// If we have been disposed, we silently ignore any subscriptions.
if (_disposed)
{
return new DiagnosticSubscription() { Owner = this };
}
DiagnosticSubscription newSubscription = new DiagnosticSubscription()
{
Observer = observer,
IsEnabled1Arg = isEnabled1Arg,
IsEnabled3Arg = isEnabled3Arg,
Owner = this,
Next = _subscriptions
};
while (Interlocked.CompareExchange(ref _subscriptions, newSubscription, newSubscription.Next) != newSubscription.Next)
newSubscription.Next = _subscriptions;
return newSubscription;
}
private volatile DiagnosticSubscription _subscriptions;
private DiagnosticListener _next; // We keep a linked list of all NotificationListeners (s_allListeners)
private bool _disposed; // Has Dispose been called?
private static DiagnosticListener s_allListeners; // linked list of all instances of DiagnosticListeners.
private static AllListenerObservable s_allListenerObservable; // to make callbacks to this object when listeners come into existence.
private static object s_lock = new object(); // A lock for
#if false
private static readonly DiagnosticListener s_default = new DiagnosticListener("DiagnosticListener.DefaultListener");
#endif
#endregion
}
}
| |
//
// ViewBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Xml;
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.ObjCRuntime;
using Xwt;
using Xwt.Backends;
using MonoMac.CoreGraphics;
using MonoMac.CoreAnimation;
namespace Xwt.Mac
{
public abstract class ViewBackend<T,S>: ViewBackend where T:NSView where S:IWidgetEventSink
{
public new S EventSink {
get { return (S) base.EventSink; }
}
public new T Widget {
get { return (T) base.Widget; }
}
}
public abstract class ViewBackend: IWidgetBackend
{
Widget frontend;
IWidgetEventSink eventSink;
IViewObject viewObject;
WidgetEvent currentEvents;
bool autosize;
Size lastFittingSize;
bool sizeCalcPending = true;
bool sensitive = true;
bool canGetFocus = true;
Xwt.Drawing.Color backgroundColor;
void IBackend.InitializeBackend (object frontend, ApplicationContext context)
{
ApplicationContext = context;
this.frontend = (Widget) frontend;
}
void IWidgetBackend.Initialize (IWidgetEventSink sink)
{
eventSink = (IWidgetEventSink) sink;
Initialize ();
ResetFittingSize ();
canGetFocus = Widget.AcceptsFirstResponder ();
}
// To be called when the widget is a root and is not inside a Xwt window. For example, when it is in a popover or a tooltip
// In that case, the widget has to listen to the change event of the children and resize itself
public void SetAutosizeMode (bool autosize)
{
this.autosize = autosize;
if (autosize)
AutoUpdateSize ();
}
public virtual void Initialize ()
{
}
public IWidgetEventSink EventSink {
get { return eventSink; }
}
public Widget Frontend {
get {
return this.frontend;
}
}
public ApplicationContext ApplicationContext {
get;
private set;
}
public object NativeWidget {
get {
return Widget;
}
}
public NSView Widget {
get { return (NSView) ViewObject.View; }
}
public IViewObject ViewObject {
get { return viewObject; }
set {
viewObject = value;
if (viewObject.Backend == null)
viewObject.Backend = this;
}
}
public bool Visible {
get { return !Widget.Hidden; }
set { Widget.Hidden = !value; }
}
public double Opacity {
get { return Widget.AlphaValue; }
set { Widget.AlphaValue = (float)value; }
}
public virtual bool Sensitive {
get { return sensitive; }
set {
sensitive = value;
UpdateSensitiveStatus (Widget, sensitive && ParentIsSensitive ());
}
}
bool ParentIsSensitive ()
{
IViewObject parent = Widget.Superview as IViewObject;
if (parent == null) {
var wb = Widget.Window as WindowBackend;
return wb == null || wb.Sensitive;
}
if (!parent.Backend.Sensitive)
return false;
return parent.Backend.ParentIsSensitive ();
}
internal void UpdateSensitiveStatus (NSView view, bool parentIsSensitive)
{
if (view is NSControl)
((NSControl)view).Enabled = parentIsSensitive && sensitive;
foreach (var s in view.Subviews) {
if ((s is IViewObject) && (((IViewObject)s).Backend != null))
((IViewObject)s).Backend.UpdateSensitiveStatus (s, parentIsSensitive);
else
UpdateSensitiveStatus (s, sensitive && parentIsSensitive);
}
}
public virtual bool CanGetFocus {
get { return canGetFocus; }
set {
canGetFocus = value;
if (!Widget.AcceptsFirstResponder ())
canGetFocus = false;
}
}
public virtual bool HasFocus {
get {
return Widget.Window != null && Widget.Window.FirstResponder == Widget;
}
}
public virtual void SetFocus ()
{
if (Widget.Window != null && CanGetFocus)
Widget.Window.MakeFirstResponder (Widget);
}
public string TooltipText {
get {
return Widget.ToolTip;
}
set {
Widget.ToolTip = value;
}
}
public void NotifyPreferredSizeChanged ()
{
EventSink.OnPreferredSizeChanged ();
}
internal NSCursor Cursor { get; private set; }
public void SetCursor (CursorType cursor)
{
if (cursor == CursorType.Arrow)
Cursor = NSCursor.ArrowCursor;
else if (cursor == CursorType.Crosshair)
Cursor = NSCursor.CrosshairCursor;
else if (cursor == CursorType.Hand)
Cursor = NSCursor.OpenHandCursor;
else if (cursor == CursorType.IBeam)
Cursor = NSCursor.IBeamCursor;
else if (cursor == CursorType.ResizeDown)
Cursor = NSCursor.ResizeDownCursor;
else if (cursor == CursorType.ResizeUp)
Cursor = NSCursor.ResizeUpCursor;
else if (cursor == CursorType.ResizeLeft)
Cursor = NSCursor.ResizeLeftCursor;
else if (cursor == CursorType.ResizeRight)
Cursor = NSCursor.ResizeRightCursor;
else if (cursor == CursorType.ResizeLeftRight)
Cursor = NSCursor.ResizeLeftRightCursor;
else if (cursor == CursorType.ResizeUpDown)
Cursor = NSCursor.ResizeUpDownCursor;
else if (cursor == CursorType.Invisible)
// TODO: load transparent cursor
Cursor = NSCursor.ArrowCursor;
else if (cursor == CursorType.Move)
Cursor = NSCursor.ClosedHandCursor;
else
Cursor = NSCursor.ArrowCursor;
}
~ViewBackend ()
{
Dispose (false);
}
public void Dispose ()
{
GC.SuppressFinalize (this);
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
}
Size IWidgetBackend.Size {
get { return new Size (Widget.WidgetWidth (), Widget.WidgetHeight ()); }
}
public static NSView GetWidget (IWidgetBackend w)
{
return ((ViewBackend)w).Widget;
}
public static NSView GetWidget (Widget w)
{
return GetWidget ((IWidgetBackend)Toolkit.GetBackend (w));
}
public static NSView GetWidgetWithPlacement (IWidgetBackend childBackend)
{
var backend = (ViewBackend)childBackend;
var child = backend.Widget;
var wrapper = child.Superview as WidgetPlacementWrapper;
if (wrapper != null)
return wrapper;
if (!NeedsAlignmentWrapper (backend.Frontend))
return child;
wrapper = new WidgetPlacementWrapper ();
wrapper.SetChild (child, backend.Frontend);
return wrapper;
}
public static NSView SetChildPlacement (IWidgetBackend childBackend)
{
var backend = (ViewBackend)childBackend;
var child = backend.Widget;
var wrapper = child.Superview as WidgetPlacementWrapper;
var fw = backend.Frontend;
if (!NeedsAlignmentWrapper (fw)) {
if (wrapper != null) {
var parent = wrapper.Superview;
child.RemoveFromSuperview ();
ReplaceSubview (wrapper, child);
}
return child;
}
if (wrapper == null) {
wrapper = new WidgetPlacementWrapper ();
var f = child.Frame;
ReplaceSubview (child, wrapper);
wrapper.SetChild (child, backend.Frontend);
wrapper.Frame = f;
} else
wrapper.UpdateChildPlacement ();
return wrapper;
}
public static void RemoveChildPlacement (NSView w)
{
if (w == null)
return;
if (w is WidgetPlacementWrapper) {
var wp = (WidgetPlacementWrapper)w;
wp.Subviews [0].RemoveFromSuperview ();
}
}
static bool NeedsAlignmentWrapper (Widget fw)
{
return fw.HorizontalPlacement != WidgetPlacement.Fill || fw.VerticalPlacement != WidgetPlacement.Fill || fw.Margin.VerticalSpacing != 0 || fw.Margin.HorizontalSpacing != 0;
}
public virtual void UpdateChildPlacement (IWidgetBackend childBackend)
{
SetChildPlacement (childBackend);
}
public static void ReplaceSubview (NSView oldChild, NSView newChild)
{
var vo = oldChild as IViewObject;
if (vo != null && vo.Backend.Frontend.GetInternalParent () != null) {
var ba = vo.Backend.Frontend.GetInternalParent ().GetBackend () as ViewBackend;
if (ba != null) {
ba.ReplaceChild (oldChild, newChild);
return;
}
}
var f = oldChild.Frame;
oldChild.Superview.ReplaceSubviewWith (oldChild, newChild);
newChild.Frame = f;
}
public virtual void ReplaceChild (NSView oldChild, NSView newChild)
{
var f = oldChild.Frame;
oldChild.Superview.ReplaceSubviewWith (oldChild, newChild);
newChild.Frame = f;
}
FontData customFont;
public virtual object Font {
get {
if (customFont != null)
return customFont;
NSFont font = null;
var widget = Widget;
if (widget is CustomAlignedContainer)
widget = ((CustomAlignedContainer)widget).Child;
if (widget is NSControl)
font = ((NSControl)(object)widget).Font;
else if (widget is NSText)
font = ((NSText)(object)widget).Font;
else
font = NSFont.ControlContentFontOfSize (NSFont.SystemFontSize);
return customFont = FontData.FromFont (font);
}
set {
customFont = (FontData) value;
var widget = Widget;
if (widget is CustomAlignedContainer)
widget = ((CustomAlignedContainer)widget).Child;
if (widget is NSControl)
((NSControl)(object)widget).Font = customFont.Font;
if (widget is NSText)
((NSText)(object)widget).Font = customFont.Font;
ResetFittingSize ();
}
}
public virtual Xwt.Drawing.Color BackgroundColor {
get {
return this.backgroundColor;
}
set {
this.backgroundColor = value;
if (Widget.Layer == null)
Widget.WantsLayer = true;
Widget.Layer.BackgroundColor = value.ToCGColor ();
}
}
#region IWidgetBackend implementation
public Point ConvertToScreenCoordinates (Point widgetCoordinates)
{
var lo = Widget.ConvertPointToBase (new PointF ((float)widgetCoordinates.X, (float)widgetCoordinates.Y));
lo = Widget.Window.ConvertBaseToScreen (lo);
return MacDesktopBackend.ToDesktopRect (new RectangleF (lo.X, lo.Y, 0, Widget.IsFlipped ? 0 : Widget.Frame.Height)).Location;
}
protected virtual Size GetNaturalSize ()
{
if (sizeCalcPending) {
sizeCalcPending = false;
var f = Widget.Frame;
SizeToFit ();
lastFittingSize = new Size (Widget.WidgetWidth (), Widget.WidgetHeight ());
Widget.Frame = f;
}
return lastFittingSize;
}
public virtual Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint)
{
return GetNaturalSize ();
}
protected double minWidth = -1, minHeight = -1;
public void SetMinSize (double width, double height)
{
minWidth = width;
minHeight = height;
}
protected void ResetFittingSize ()
{
sizeCalcPending = true;
}
public void SizeToFit ()
{
OnSizeToFit ();
// if (minWidth != -1 && Widget.Frame.Width < minWidth || minHeight != -1 && Widget.Frame.Height < minHeight)
// Widget.SetFrameSize (new SizeF (Math.Max (Widget.Frame.Width, (float)minWidth), Math.Max (Widget.Frame.Height, (float)minHeight)));
}
protected virtual Size CalcFittingSize ()
{
return Size.Zero;
}
static readonly Selector sizeToFitSel = new Selector ("sizeToFit");
protected virtual void OnSizeToFit ()
{
if (Widget.RespondsToSelector (sizeToFitSel)) {
Messaging.void_objc_msgSend (Widget.Handle, sizeToFitSel.Handle);
} else {
var s = CalcFittingSize ();
if (!s.IsZero)
Widget.SetFrameSize (new SizeF ((float)s.Width, (float)s.Height));
}
}
public void SetSizeRequest (double width, double height)
{
// Nothing to do
}
public virtual void UpdateLayout ()
{
if (autosize)
AutoUpdateSize ();
}
void AutoUpdateSize ()
{ var s = Frontend.Surface.GetPreferredSize ();
Widget.SetFrameSize (new SizeF ((float)s.Width, (float)s.Height));
}
NSObject gotFocusObserver;
public virtual void EnableEvent (object eventId)
{
if (eventId is WidgetEvent) {
WidgetEvent ev = (WidgetEvent) eventId;
currentEvents |= ev;
switch (ev) {
case WidgetEvent.GotFocus:
case WidgetEvent.LostFocus:
SetupFocusEvents (Widget.GetType ());
break;
}
}
}
public virtual void DisableEvent (object eventId)
{
if (eventId is WidgetEvent) {
WidgetEvent ev = (WidgetEvent) eventId;
currentEvents &= ~ev;
}
}
static Selector draggingEnteredSel = new Selector ("draggingEntered:");
static Selector draggingUpdatedSel = new Selector ("draggingUpdated:");
static Selector draggingExitedSel = new Selector ("draggingExited:");
static Selector prepareForDragOperationSel = new Selector ("prepareForDragOperation:");
static Selector performDragOperationSel = new Selector ("performDragOperation:");
static Selector concludeDragOperationSel = new Selector ("concludeDragOperation:");
static Selector becomeFirstResponderSel = new Selector ("becomeFirstResponder");
static Selector resignFirstResponderSel = new Selector ("resignFirstResponder");
static HashSet<Type> typesConfiguredForDragDrop = new HashSet<Type> ();
static HashSet<Type> typesConfiguredForFocusEvents = new HashSet<Type> ();
static void SetupForDragDrop (Type type)
{
lock (typesConfiguredForDragDrop) {
if (typesConfiguredForDragDrop.Add (type)) {
Class c = new Class (type);
c.AddMethod (draggingEnteredSel.Handle, new Func<IntPtr,IntPtr,IntPtr,NSDragOperation> (DraggingEntered), "i@:@");
c.AddMethod (draggingUpdatedSel.Handle, new Func<IntPtr,IntPtr,IntPtr,NSDragOperation> (DraggingUpdated), "i@:@");
c.AddMethod (draggingExitedSel.Handle, new Action<IntPtr,IntPtr,IntPtr> (DraggingExited), "v@:@");
c.AddMethod (prepareForDragOperationSel.Handle, new Func<IntPtr,IntPtr,IntPtr,bool> (PrepareForDragOperation), "B@:@");
c.AddMethod (performDragOperationSel.Handle, new Func<IntPtr,IntPtr,IntPtr,bool> (PerformDragOperation), "B@:@");
c.AddMethod (concludeDragOperationSel.Handle, new Action<IntPtr,IntPtr,IntPtr> (ConcludeDragOperation), "v@:@");
}
}
}
static void SetupFocusEvents (Type type)
{
lock (typesConfiguredForFocusEvents) {
if (typesConfiguredForFocusEvents.Add (type)) {
Class c = new Class (type);
c.AddMethod (becomeFirstResponderSel.Handle, new Func<IntPtr,IntPtr,bool> (OnBecomeFirstResponder), "B@:");
c.AddMethod (resignFirstResponderSel.Handle, new Func<IntPtr,IntPtr,bool> (OnResignFirstResponder), "B@:");
}
}
}
public void DragStart (DragStartData sdata)
{
var lo = Widget.ConvertPointToBase (new PointF (Widget.Bounds.X, Widget.Bounds.Y));
lo = Widget.Window.ConvertBaseToScreen (lo);
var ml = NSEvent.CurrentMouseLocation;
var pb = NSPasteboard.FromName (NSPasteboard.NSDragPasteboardName);
if (pb == null)
throw new InvalidOperationException ("Could not get pasteboard");
if (sdata.Data == null)
throw new ArgumentNullException ("data");
InitPasteboard (pb, sdata.Data);
var img = (NSImage)sdata.ImageBackend;
var pos = new PointF (ml.X - lo.X - (float)sdata.HotX, lo.Y - ml.Y - (float)sdata.HotY + img.Size.Height);
Widget.DragImage (img, pos, new SizeF (0, 0), NSApplication.SharedApplication.CurrentEvent, pb, Widget, true);
}
public void SetDragSource (TransferDataType[] types, DragDropAction dragAction)
{
}
public void SetDragTarget (TransferDataType[] types, DragDropAction dragAction)
{
SetupForDragDrop (Widget.GetType ());
var dtypes = types.Select (t => ToNSDragType (t)).ToArray ();
Widget.RegisterForDraggedTypes (dtypes);
}
static NSDragOperation DraggingEntered (IntPtr sender, IntPtr sel, IntPtr dragInfo)
{
return DraggingUpdated (sender, sel, dragInfo);
}
static NSDragOperation DraggingUpdated (IntPtr sender, IntPtr sel, IntPtr dragInfo)
{
IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
if (ob == null)
return NSDragOperation.None;
var backend = ob.Backend;
NSDraggingInfo di = new NSDraggingInfo (dragInfo);
var types = di.DraggingPasteboard.Types.Select (t => ToXwtDragType (t)).ToArray ();
var pos = new Point (di.DraggingLocation.X, di.DraggingLocation.Y);
if ((backend.currentEvents & WidgetEvent.DragOverCheck) != 0) {
var args = new DragOverCheckEventArgs (pos, types, ConvertAction (di.DraggingSourceOperationMask));
backend.OnDragOverCheck (di, args);
if (args.AllowedAction == DragDropAction.None)
return NSDragOperation.None;
if (args.AllowedAction != DragDropAction.Default)
return ConvertAction (args.AllowedAction);
}
if ((backend.currentEvents & WidgetEvent.DragOver) != 0) {
TransferDataStore store = new TransferDataStore ();
FillDataStore (store, di.DraggingPasteboard, ob.View.RegisteredDragTypes ());
var args = new DragOverEventArgs (pos, store, ConvertAction (di.DraggingSourceOperationMask));
backend.OnDragOver (di, args);
if (args.AllowedAction == DragDropAction.None)
return NSDragOperation.None;
if (args.AllowedAction != DragDropAction.Default)
return ConvertAction (args.AllowedAction);
}
return di.DraggingSourceOperationMask;
}
static void DraggingExited (IntPtr sender, IntPtr sel, IntPtr dragInfo)
{
IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
if (ob != null) {
var backend = ob.Backend;
backend.ApplicationContext.InvokeUserCode (delegate {
backend.eventSink.OnDragLeave (EventArgs.Empty);
});
}
}
static bool PrepareForDragOperation (IntPtr sender, IntPtr sel, IntPtr dragInfo)
{
IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
if (ob == null)
return false;
var backend = ob.Backend;
NSDraggingInfo di = new NSDraggingInfo (dragInfo);
var types = di.DraggingPasteboard.Types.Select (t => ToXwtDragType (t)).ToArray ();
var pos = new Point (di.DraggingLocation.X, di.DraggingLocation.Y);
if ((backend.currentEvents & WidgetEvent.DragDropCheck) != 0) {
var args = new DragCheckEventArgs (pos, types, ConvertAction (di.DraggingSourceOperationMask));
bool res = backend.ApplicationContext.InvokeUserCode (delegate {
backend.eventSink.OnDragDropCheck (args);
});
if (args.Result == DragDropResult.Canceled || !res)
return false;
}
return true;
}
static bool PerformDragOperation (IntPtr sender, IntPtr sel, IntPtr dragInfo)
{
IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
if (ob == null)
return false;
var backend = ob.Backend;
NSDraggingInfo di = new NSDraggingInfo (dragInfo);
var pos = new Point (di.DraggingLocation.X, di.DraggingLocation.Y);
if ((backend.currentEvents & WidgetEvent.DragDrop) != 0) {
TransferDataStore store = new TransferDataStore ();
FillDataStore (store, di.DraggingPasteboard, ob.View.RegisteredDragTypes ());
var args = new DragEventArgs (pos, store, ConvertAction (di.DraggingSourceOperationMask));
backend.ApplicationContext.InvokeUserCode (delegate {
backend.eventSink.OnDragDrop (args);
});
return args.Success;
} else
return false;
}
static void ConcludeDragOperation (IntPtr sender, IntPtr sel, IntPtr dragInfo)
{
Console.WriteLine ("ConcludeDragOperation");
}
protected virtual void OnDragOverCheck (NSDraggingInfo di, DragOverCheckEventArgs args)
{
ApplicationContext.InvokeUserCode (delegate {
eventSink.OnDragOverCheck (args);
});
}
protected virtual void OnDragOver (NSDraggingInfo di, DragOverEventArgs args)
{
ApplicationContext.InvokeUserCode (delegate {
eventSink.OnDragOver (args);
});
}
void InitPasteboard (NSPasteboard pb, TransferDataSource data)
{
pb.ClearContents ();
foreach (var t in data.DataTypes) {
if (t == TransferDataType.Text) {
pb.AddTypes (new string[] { NSPasteboard.NSStringType }, null);
pb.SetStringForType ((string)data.GetValue (t), NSPasteboard.NSStringType);
}
}
}
static void FillDataStore (TransferDataStore store, NSPasteboard pb, string[] types)
{
foreach (var t in types) {
if (!pb.Types.Contains (t))
continue;
if (t == NSPasteboard.NSStringType)
store.AddText (pb.GetStringForType (t));
else if (t == NSPasteboard.NSFilenamesType) {
string data = pb.GetStringForType (t);
XmlDocument doc = new XmlDocument ();
doc.XmlResolver = null; // Avoid DTD validation
doc.LoadXml (data);
store.AddUris (doc.SelectNodes ("/plist/array/string").Cast<XmlElement> ().Select (e => new Uri (e.InnerText)).ToArray ());
}
}
}
static NSDragOperation ConvertAction (DragDropAction action)
{
NSDragOperation res = (NSDragOperation)0;
if ((action & DragDropAction.Copy) != 0)
res |= NSDragOperation.Copy;
if ((action & DragDropAction.Move) != 0)
res |= NSDragOperation.Move;
if ((action & DragDropAction.Link) != 0)
res |= NSDragOperation.Link;
return res;
}
static DragDropAction ConvertAction (NSDragOperation action)
{
if (action == NSDragOperation.AllObsolete)
return DragDropAction.All;
DragDropAction res = (DragDropAction)0;
if ((action & NSDragOperation.Copy) != 0)
res |= DragDropAction.Copy;
if ((action & NSDragOperation.Move) != 0)
res |= DragDropAction.Move;
if ((action & NSDragOperation.Link) != 0)
res |= DragDropAction.Link;
return res;
}
static string ToNSDragType (TransferDataType type)
{
if (type == TransferDataType.Text) return NSPasteboard.NSStringType;
if (type == TransferDataType.Uri) return NSPasteboard.NSFilenamesType;
if (type == TransferDataType.Image) return NSPasteboard.NSPictType;
if (type == TransferDataType.Rtf) return NSPasteboard.NSRtfType;
if (type == TransferDataType.Html) return NSPasteboard.NSHtmlType;
return type.Id;
}
static TransferDataType ToXwtDragType (string type)
{
if (type == NSPasteboard.NSStringType)
return TransferDataType.Text;
if (type == NSPasteboard.NSFilenamesType)
return TransferDataType.Uri;
if (type == NSPasteboard.NSPictType)
return TransferDataType.Image;
if (type == NSPasteboard.NSRtfType)
return TransferDataType.Rtf;
if (type == NSPasteboard.NSHtmlType)
return TransferDataType.Html;
return TransferDataType.FromId (type);
}
static bool OnBecomeFirstResponder (IntPtr sender, IntPtr sel)
{
IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
var canGetIt = ob.Backend.canGetFocus;
if (canGetIt)
ob.Backend.ApplicationContext.InvokeUserCode (ob.Backend.EventSink.OnGotFocus);
return canGetIt;
}
static bool OnResignFirstResponder (IntPtr sender, IntPtr sel)
{
IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
ob.Backend.ApplicationContext.InvokeUserCode (ob.Backend.EventSink.OnLostFocus);
return true;
}
#endregion
}
sealed class WidgetPlacementWrapper: NSControl, IViewObject
{
NSView child;
Widget w;
public WidgetPlacementWrapper ()
{
}
NSView IViewObject.View {
get { return this; }
}
ViewBackend IViewObject.Backend {
get {
var vo = child as IViewObject;
return vo != null ? vo.Backend : null;
}
set {
var vo = child as IViewObject;
if (vo != null)
vo.Backend = value;
}
}
public override bool IsFlipped {
get {
return true;
}
}
public void SetChild (NSView child, Widget w)
{
this.child = child;
this.w = w;
AddSubview (child);
}
public override void SetFrameSize (SizeF newSize)
{
base.SetFrameSize (newSize);
if (w != null)
UpdateChildPlacement ();
}
public void UpdateChildPlacement ()
{
double cheight = Frame.Height - w.Margin.VerticalSpacing;
double cwidth = Frame.Width - w.Margin.HorizontalSpacing;
double cx = w.MarginLeft;
double cy = w.MarginTop;
var s = w.Surface.GetPreferredSize (cwidth, cheight);
if (w.HorizontalPlacement != WidgetPlacement.Fill) {
cx += (cwidth - s.Width) * w.HorizontalPlacement.GetValue ();
cwidth = s.Width;
}
if (w.VerticalPlacement != WidgetPlacement.Fill) {
cy += (cheight - s.Height) * w.VerticalPlacement.GetValue ();
cheight = s.Height;
}
child.Frame = new RectangleF ((float)cx, (float)cy, (float)cwidth, (float)cheight);
}
public override void SizeToFit ()
{
base.SizeToFit ();
}
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
if(!UnityEngine.XR.XRSettings.enabled)
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
namespace System.Net.Http
{
internal static class WinHttpTraceHelper
{
private const string WinHtpTraceEnvironmentVariable = "WINHTTPHANDLER_TRACE";
private static readonly bool s_traceEnabled = IsTraceEnabledViaEnvironmentVariable();
private static bool IsTraceEnabledViaEnvironmentVariable()
{
string env;
try
{
env = Environment.GetEnvironmentVariable(WinHtpTraceEnvironmentVariable);
}
catch (SecurityException)
{
env = null;
}
return !string.IsNullOrEmpty(env);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsTraceEnabled()
{
return s_traceEnabled;
}
public static void Trace(string message)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(message);
}
public static void Trace(string format, object arg0)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(format, arg0);
}
public static void Trace(string format, object arg0, object arg1, object arg2)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(format, arg0, arg1, arg2);
}
public static void TraceCallbackStatus(string message, IntPtr handle, IntPtr context, uint status)
{
if (!IsTraceEnabled())
{
return;
}
Debug.WriteLine(
"{0}: handle=0x{1:X}, context=0x{2:X}, {3}",
message,
handle,
context,
GetStringFromInternetStatus(status));
}
public static void TraceAsyncError(string message, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult)
{
if (!IsTraceEnabled())
{
return;
}
uint apiIndex = (uint)asyncResult.dwResult.ToInt32();
uint error = asyncResult.dwError;
Debug.WriteLine(
"{0}: api={1}, error={2}({3}) \"{4}\"",
message,
GetNameFromApiIndex(apiIndex),
GetNameFromError(error),
error,
WinHttpException.GetErrorMessage((int)error));
}
private static string GetNameFromApiIndex(uint index)
{
switch (index)
{
case Interop.WinHttp.API_RECEIVE_RESPONSE:
return "API_RECEIVE_RESPONSE";
case Interop.WinHttp.API_QUERY_DATA_AVAILABLE:
return "API_QUERY_DATA_AVAILABLE";
case Interop.WinHttp.API_READ_DATA:
return "API_READ_DATA";
case Interop.WinHttp.API_WRITE_DATA:
return "API_WRITE_DATA";
case Interop.WinHttp.API_SEND_REQUEST:
return "API_SEND_REQUEST";
default:
return index.ToString();
}
}
private static string GetNameFromError(uint error)
{
switch (error)
{
case Interop.WinHttp.ERROR_FILE_NOT_FOUND:
return "ERROR_FILE_NOT_FOUND";
case Interop.WinHttp.ERROR_INVALID_HANDLE:
return "ERROR_INVALID_HANDLE";
case Interop.WinHttp.ERROR_INVALID_PARAMETER:
return "ERROR_INVALID_PARAMETER";
case Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER:
return "ERROR_INSUFFICIENT_BUFFER";
case Interop.WinHttp.ERROR_NOT_FOUND:
return "ERROR_NOT_FOUND";
case Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION:
return "WINHTTP_INVALID_OPTION";
case Interop.WinHttp.ERROR_WINHTTP_LOGIN_FAILURE:
return "WINHTTP_LOGIN_FAILURE";
case Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED:
return "WINHTTP_OPERATION_CANCELLED";
case Interop.WinHttp.ERROR_WINHTTP_INCORRECT_HANDLE_STATE:
return "WINHTTP_INCORRECT_HANDLE_STATE";
case Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR:
return "WINHTTP_CONNECTION_ERROR";
case Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST:
return "WINHTTP_RESEND_REQUEST";
case Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED:
return "WINHTTP_CLIENT_AUTH_CERT_NEEDED";
case Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND:
return "WINHTTP_HEADER_NOT_FOUND";
case Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE:
return "WINHTTP_SECURE_FAILURE";
case Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED:
return "WINHTTP_AUTODETECTION_FAILED";
default:
return error.ToString();
}
}
private static string GetStringFromInternetStatus(uint status)
{
switch (status)
{
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RESOLVING_NAME:
return "STATUS_RESOLVING_NAME";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_NAME_RESOLVED:
return "STATUS_NAME_RESOLVED";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER:
return "STATUS_CONNECTING_TO_SERVER";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER:
return "STATUS_CONNECTED_TO_SERVER";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDING_REQUEST:
return "STATUS_SENDING_REQUEST";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_SENT:
return "STATUS_REQUEST_SENT";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE:
return "STATUS_RECEIVING_RESPONSE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED:
return "STATUS_RESPONSE_RECEIVED";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION:
return "STATUS_CLOSING_CONNECTION";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED:
return "STATUS_CONNECTION_CLOSED";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CREATED:
return "STATUS_HANDLE_CREATED";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING:
return "STATUS_HANDLE_CLOSING";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DETECTING_PROXY:
return "STATUS_DETECTING_PROXY";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REDIRECT:
return "STATUS_REDIRECT";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE:
return "STATUS_INTERMEDIATE_RESPONSE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SECURE_FAILURE:
return "STATUS_SECURE_FAILURE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
return "STATUS_HEADERS_AVAILABLE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
return "STATUS_DATA_AVAILABLE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
return "STATUS_READ_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
return "STATUS_WRITE_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
return "STATUS_REQUEST_ERROR";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
return "STATUS_SENDREQUEST_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE:
return "STATUS_GETPROXYFORURL_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE:
return "STATUS_CLOSE_COMPLETE";
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE:
return "STATUS_SHUTDOWN_COMPLETE";
default:
return string.Format("0x{0:X}", status);
}
}
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NodaTime.Text;
using NUnit.Framework;
using NodaTime.Test.Calendars;
namespace NodaTime.Test.Text
{
public class LocalDatePatternTest : PatternTestBase<LocalDate>
{
private static readonly LocalDate SampleLocalDate = new LocalDate(1976, 6, 19);
internal static readonly Data[] InvalidPatternData = {
new Data { Pattern = "", Message = TextErrorMessages.FormatStringEmpty },
new Data { Pattern = "!", Message = TextErrorMessages.UnknownStandardFormat, Parameters = {'!', typeof(LocalDate).FullName! }},
new Data { Pattern = "%", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '%', typeof(LocalDate).FullName! } },
new Data { Pattern = "\\", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { '\\', typeof(LocalDate).FullName! } },
new Data { Pattern = "%%", Message = TextErrorMessages.PercentDoubled },
new Data { Pattern = "%\\", Message = TextErrorMessages.EscapeAtEndOfString },
new Data { Pattern = "MMMMM", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'M', 4 } },
new Data { Pattern = "ddddd", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'd', 4 } },
new Data { Pattern = "M%", Message = TextErrorMessages.PercentAtEndOfString },
new Data { Pattern = "yyyyy", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'y', 4 } },
new Data { Pattern = "uuuuu", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'u', 4 } },
new Data { Pattern = "ggg", Message = TextErrorMessages.RepeatCountExceeded, Parameters = { 'g', 2 } },
new Data { Pattern = "'qwe", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "'qwe\\", Message = TextErrorMessages.EscapeAtEndOfString },
new Data { Pattern = "'qwe\\'", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
// Note incorrect use of "u" (year) instead of "y" (year of era)
new Data { Pattern = "dd MM uuuu gg", Message = TextErrorMessages.EraWithoutYearOfEra },
// Era specifier and calendar specifier in the same pattern.
new Data { Pattern = "dd MM yyyy gg c", Message = TextErrorMessages.CalendarAndEra },
// Invalid patterns directly after the uuuu specifier. This will detect the issue early, but then
// continue and reject it in the normal path.
new Data { Pattern = "uuuu'", Message = TextErrorMessages.MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "uuuu\\", Message = TextErrorMessages.EscapeAtEndOfString },
// Common typo, which is caught in 2.0...
new Data { Pattern = "uuuu-mm-dd", Message = TextErrorMessages.UnquotedLiteral, Parameters = { 'm' } },
// T isn't valid in a date pattern
new Data { Pattern = "uuuu-MM-ddT00:00:00", Message = TextErrorMessages.UnquotedLiteral, Parameters = { 'T' } },
// These became invalid in v2.0, when we decided that y and yyy weren't sensible.
new Data { Pattern = "y M d", Message = TextErrorMessages.InvalidRepeatCount, Parameters = { 'y', 1 } },
new Data { Pattern = "yyy M d", Message = TextErrorMessages.InvalidRepeatCount, Parameters = { 'y', 3 } },
};
internal static Data[] ParseFailureData = {
new Data { Pattern = "yyyy gg", Text = "2011 NodaEra", Message = TextErrorMessages.MismatchedText, Parameters = {'g'} },
new Data { Pattern = "yyyy uuuu gg", Text = "0010 0009 B.C.", Message = TextErrorMessages.InconsistentValues2, Parameters = {'g', 'u', typeof(LocalDate)} },
new Data { Pattern = "uuuu MM dd dddd", Text = "2011 10 09 Saturday", Message = TextErrorMessages.InconsistentDayOfWeekTextValue },
new Data { Pattern = "uuuu MM dd ddd", Text = "2011 10 09 Sat", Message = TextErrorMessages.InconsistentDayOfWeekTextValue },
new Data { Pattern = "uuuu MM dd MMMM", Text = "2011 10 09 January", Message = TextErrorMessages.InconsistentMonthTextValue },
new Data { Pattern = "uuuu MM dd ddd", Text = "2011 10 09 FooBar", Message = TextErrorMessages.MismatchedText, Parameters = {'d'} },
new Data { Pattern = "uuuu MM dd dddd", Text = "2011 10 09 FooBar", Message = TextErrorMessages.MismatchedText, Parameters = {'d'} },
new Data { Pattern = "uuuu/MM/dd", Text = "2011/02-29", Message = TextErrorMessages.DateSeparatorMismatch },
// Don't match a short name against a long pattern
new Data { Pattern = "uuuu MMMM dd", Text = "2011 Oct 09", Message = TextErrorMessages.MismatchedText, Parameters = {'M'} },
// Or vice versa... although this time we match the "Oct" and then fail as we're expecting a space
new Data { Pattern = "uuuu MMM dd", Text = "2011 October 09", Message = TextErrorMessages.MismatchedCharacter, Parameters = {' '}},
// Invalid month even when we've got genitive and non-genitive names to pick from
new Data(2011, 1, 3) { Pattern = "MMMM", Text = "BogusName", Culture = Cultures.GenitiveNameTestCulture, Message = TextErrorMessages.MismatchedText, Parameters = {'M'}},
// Invalid year-of-era, month, day
new Data { Pattern = "yyyy MM dd", Text = "0000 01 01", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 0, 'y', typeof(LocalDate) } },
new Data { Pattern = "yyyy MM dd", Text = "2011 15 29", Message = TextErrorMessages.MonthOutOfRange, Parameters = { 15, 2011 } },
new Data { Pattern = "yyyy MM dd", Text = "2011 02 35", Message = TextErrorMessages.DayOfMonthOutOfRange, Parameters = { 35, 2, 2011 } },
// Year of era can't be negative...
new Data { Pattern = "yyyy MM dd", Text = "-15 01 01", Message = TextErrorMessages.UnexpectedNegative },
// Invalid leap years
new Data { Pattern = "uuuu MM dd", Text = "2011 02 29", Message = TextErrorMessages.DayOfMonthOutOfRange, Parameters = { 29, 2, 2011 } },
new Data { Pattern = "uuuu MM dd", Text = "1900 02 29", Message = TextErrorMessages.DayOfMonthOutOfRange, Parameters = { 29, 2, 1900 } },
// Year of era and two-digit year, but they don't match
new Data { Pattern = "yyyy uu", Text = "2011 10", Message = TextErrorMessages.InconsistentValues2, Parameters = { 'y', 'u', typeof(LocalDate) } },
// Invalid calendar name
new Data { Pattern = "c uuuu MM dd", Text = "2015 01 01", Message = TextErrorMessages.NoMatchingCalendarSystem },
// Invalid year
new Data { Template = new LocalDate(1, 1, 1, CalendarSystem.IslamicBcl), Pattern = "uuuu", Text = "9999", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 9999, 'u', typeof(LocalDate) } },
new Data { Template = new LocalDate(1, 1, 1, CalendarSystem.IslamicBcl), Pattern = "yyyy", Text = "9999", Message = TextErrorMessages.YearOfEraOutOfRange, Parameters = { 9999, "EH", "Hijri" } },
// https://github.com/nodatime/nodatime/issues/414
new Data { Pattern = "yyyy-MM-dd", Text = "1984-00-15", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 0, 'M', typeof(LocalDate) } },
new Data { Pattern = "M/d/yyyy", Text = "00/15/1984", Message = TextErrorMessages.FieldValueOutOfRange, Parameters = { 0, 'M', typeof(LocalDate) } },
// Calendar ID parsing is now ordinal, case-sensitive
new Data(2011, 10, 9) { Pattern = "uuuu MM dd c", Text = "2011 10 09 iso", Message = TextErrorMessages.NoMatchingCalendarSystem },
};
internal static Data[] ParseOnlyData = {
// Alternative era names
new Data(0, 10, 3) { Pattern = "yyyy MM dd gg", Text = "0001 10 03 BCE" },
// Valid leap years
new Data(2000, 2, 29) { Pattern = "uuuu MM dd", Text = "2000 02 29" },
new Data(2004, 2, 29) { Pattern = "uuuu MM dd", Text = "2004 02 29" },
// Month parsing should be case-insensitive
new Data(2011, 10, 3) { Pattern = "uuuu MMM dd", Text = "2011 OcT 03" },
new Data(2011, 10, 3) { Pattern = "uuuu MMMM dd", Text = "2011 OcToBeR 03" },
// Day-of-week parsing should be case-insensitive
new Data(2011, 10, 9) { Pattern = "uuuu MM dd ddd", Text = "2011 10 09 sUN" },
new Data(2011, 10, 9) { Pattern = "uuuu MM dd dddd", Text = "2011 10 09 SuNDaY" },
// Genitive name is an extension of the non-genitive name; parse longer first.
new Data(2011, 1, 10) { Pattern = "uuuu MMMM dd", Text = "2011 MonthName-Genitive 10", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
new Data(2011, 1, 10) { Pattern = "uuuu MMMM dd", Text = "2011 MonthName 10", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
new Data(2011, 1, 10) { Pattern = "uuuu MMM dd", Text = "2011 MN-Gen 10", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
new Data(2011, 1, 10) { Pattern = "uuuu MMM dd", Text = "2011 MN 10", Culture = Cultures.GenitiveNameTestCultureWithLeadingNames },
};
internal static Data[] FormatOnlyData = {
// Would parse back to 2011
new Data(1811, 7, 3) { Pattern = "yy M d", Text = "11 7 3" },
// Tests for the documented 2-digit formatting of BC years
// (Less of an issue since yy became "year of era")
new Data(-94, 7, 3) { Pattern = "yy M d", Text = "95 7 3" },
new Data(-93, 7, 3) { Pattern = "yy M d", Text = "94 7 3" },
};
internal static Data[] FormatAndParseData = {
// Standard patterns
// Invariant culture uses the crazy MM/dd/yyyy format. Blech.
new Data(2011, 10, 20) { Pattern = "d", Text = "10/20/2011" },
new Data(2011, 10, 20) { Pattern = "D", Text = "Thursday, 20 October 2011" },
// Year comes from the template
new Data(2000, 10, 20) { Pattern = "M", Text = "October 20" },
// ISO pattern uses a sensible format
new Data(2011, 10, 20) { StandardPattern = LocalDatePattern.Iso, Pattern = "R", Text = "2011-10-20" },
// Round trip with calendar system
new Data(2011, 10, 20, CalendarSystem.Coptic) { StandardPattern = LocalDatePattern.FullRoundtrip, Pattern = "r", Text = "2011-10-20 (Coptic)" },
// Custom patterns
new Data(2011, 10, 3) { Pattern = "uuuu/MM/dd", Text = "2011/10/03" },
new Data(2011, 10, 3) { Pattern = "uuuu/MM/dd", Text = "2011-10-03", Culture = Cultures.FrCa },
new Data(2011, 10, 3) { Pattern = "uuuuMMdd", Text = "20111003" },
// 2-digit year-of-era patterns
new Data(2001, 7, 3) { Pattern = "yy M d", Text = "01 7 3" },
new Data(2011, 7, 3) { Pattern = "yy M d", Text = "11 7 3" },
new Data(2030, 7, 3) { Pattern = "yy M d", Text = "30 7 3" },
// Cutoff defaults to 30 (at the moment...)
new Data(1931, 7, 3) { Pattern = "yy M d", Text = "31 7 3" },
new Data(1976, 7, 3) { Pattern = "yy M d", Text = "76 7 3" },
// In the first century, we don't skip back a century for "high" two-digit year numbers.
new Data(25, 7, 3) { Pattern = "uu M d", Text = "25 7 3", Template = new LocalDate(50, 1, 1) },
new Data(35, 7, 3) { Pattern = "uu M d", Text = "35 7 3", Template = new LocalDate(50, 1, 1) },
new Data(2000, 10, 3) { Pattern = "MM/dd", Text = "10/03"},
new Data(1885, 10, 3) { Pattern = "MM/dd", Text = "10/03", Template = new LocalDate(1885, 10, 3) },
// When we parse in all of the below tests, we'll use the month and day-of-month if it's provided;
// the template value is specified to allow simple roundtripping. (Day of week doesn't affect what value is parsed; it just validates.)
// Non-genitive month name when there's no "day of month", even if there's a "day of week"
new Data(2011, 1, 3) { Pattern = "MMMM", Text = "FullNonGenName", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3)},
new Data(2011, 1, 3) { Pattern = "MMMM dddd", Text = "FullNonGenName Monday", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
new Data(2011, 1, 3) { Pattern = "MMM", Text = "AbbrNonGenName", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
new Data(2011, 1, 3) { Pattern = "MMM ddd", Text = "AbbrNonGenName Mon", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
// Genitive month name when the pattern includes "day of month"
new Data(2011, 1, 3) { Pattern = "MMMM dd", Text = "FullGenName 03", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
// TODO: Check whether or not this is actually appropriate
new Data(2011, 1, 3) { Pattern = "MMM dd", Text = "AbbrGenName 03", Culture = Cultures.GenitiveNameTestCulture, Template = new LocalDate(2011, 5, 3) },
// Era handling
new Data(2011, 1, 3) { Pattern = "yyyy MM dd gg", Text = "2011 01 03 A.D." },
new Data(2011, 1, 3) { Pattern = "uuuu yyyy MM dd gg", Text = "2011 2011 01 03 A.D." },
new Data(-1, 1, 3) { Pattern = "yyyy MM dd gg", Text = "0002 01 03 B.C." },
// Day of week handling
new Data(2011, 10, 9) { Pattern = "uuuu MM dd dddd", Text = "2011 10 09 Sunday" },
new Data(2011, 10, 9) { Pattern = "uuuu MM dd ddd", Text = "2011 10 09 Sun" },
// Month handling
new Data(2011, 10, 9) { Pattern = "uuuu MMMM dd", Text = "2011 October 09" },
new Data(2011, 10, 9) { Pattern = "uuuu MMM dd", Text = "2011 Oct 09" },
// Year and two-digit year-of-era in the same format. Note that the year
// gives the full year information, so we're not stuck in the 20th/21st century
new Data(1825, 10, 9) { Pattern = "uuuu yy MM/dd", Text = "1825 25 10/09" },
// Negative years
new Data(-43, 3, 15) { Pattern = "uuuu MM dd", Text = "-0043 03 15"},
// Calendar handling
new Data(2011, 10, 9) { Pattern = "c uuuu MM dd", Text = "ISO 2011 10 09" },
new Data(2011, 10, 9) { Pattern = "uuuu MM dd c", Text = "2011 10 09 ISO" },
new Data(2011, 10, 9, CalendarSystem.Coptic) { Pattern = "c uuuu MM dd", Text = "Coptic 2011 10 09" },
new Data(2011, 10, 9, CalendarSystem.Coptic) { Pattern = "uuuu MM dd c", Text = "2011 10 09 Coptic" },
new Data(180, 15, 19, CalendarSystem.Badi) { Pattern = "uuuu MM dd c", Text = "0180 15 19 Badi" },
// Awkward day-of-week handling
// December 14th 2012 was a Friday. Friday is "Foo" or "FooBar" in AwkwardDayOfWeekCulture.
new Data(2012, 12, 14) { Pattern = "ddd uuuu MM dd", Text = "Foo 2012 12 14", Culture = Cultures.AwkwardDayOfWeekCulture },
new Data(2012, 12, 14) { Pattern = "dddd uuuu MM dd", Text = "FooBar 2012 12 14", Culture = Cultures.AwkwardDayOfWeekCulture },
// December 13th 2012 was a Thursday. Friday is "FooBaz" or "FooBa" in AwkwardDayOfWeekCulture.
new Data(2012, 12, 13) { Pattern = "ddd uuuu MM dd", Text = "FooBaz 2012 12 13", Culture = Cultures.AwkwardDayOfWeekCulture },
new Data(2012, 12, 13) { Pattern = "dddd uuuu MM dd", Text = "FooBa 2012 12 13", Culture = Cultures.AwkwardDayOfWeekCulture },
// 3 digit year patterns (odd, but valid)
new Data(12, 1, 2) { Pattern = "uuu MM dd", Text = "012 01 02" },
new Data(-12, 1, 2) { Pattern = "uuu MM dd", Text = "-012 01 02" },
new Data(123, 1, 2) { Pattern = "uuu MM dd", Text = "123 01 02" },
new Data(-123, 1, 2) { Pattern = "uuu MM dd", Text = "-123 01 02" },
new Data(1234, 1, 2) { Pattern = "uuu MM dd", Text = "1234 01 02" },
new Data(-1234, 1, 2) { Pattern = "uuu MM dd", Text = "-1234 01 02" },
};
internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData);
internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData);
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclLongDatePatternGivesSameResultsInNoda(CultureInfo culture)
{
AssertBclNodaEquality(culture, culture.DateTimeFormat.LongDatePattern);
}
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclShortDatePatternGivesSameResultsInNoda(CultureInfo culture)
{
AssertBclNodaEquality(culture, culture.DateTimeFormat.ShortDatePattern);
}
[Test]
public void WithCalendar()
{
var pattern = LocalDatePattern.Iso.WithCalendar(CalendarSystem.Coptic);
var value = pattern.Parse("0284-08-29").Value;
Assert.AreEqual(new LocalDate(284, 8, 29, CalendarSystem.Coptic), value);
}
[Test]
public void CreateWithCurrentCulture()
{
var date = new LocalDate(2017, 8, 23);
using (CultureSaver.SetCultures(Cultures.FrFr))
{
var pattern = LocalDatePattern.CreateWithCurrentCulture("d");
Assert.AreEqual("23/08/2017", pattern.Format(date));
}
using (CultureSaver.SetCultures(Cultures.FrCa))
{
var pattern = LocalDatePattern.CreateWithCurrentCulture("d");
Assert.AreEqual("2017-08-23", pattern.Format(date));
}
}
[Test]
public void ParseNull() => AssertParseNull(LocalDatePattern.Iso);
private void AssertBclNodaEquality(CultureInfo culture, string patternText)
{
// The BCL never seems to use abbreviated month genitive names.
// I think it's reasonable that we do. Hmm.
// See https://github.com/nodatime/nodatime/issues/377
if (patternText.Contains("MMM") && !patternText.Contains("MMMM") &&
culture.DateTimeFormat.AbbreviatedMonthGenitiveNames[SampleLocalDate.Month - 1] != culture.DateTimeFormat.AbbreviatedMonthNames[SampleLocalDate.Month - 1])
{
return;
}
var pattern = LocalDatePattern.Create(patternText, culture);
var calendarSystem = BclCalendars.CalendarSystemForCalendar(culture.Calendar);
if (calendarSystem is null)
{
// We can't map this calendar system correctly yet; the test would be invalid.
return;
}
var sampleDateInCalendar = SampleLocalDate.WithCalendar(calendarSystem);
// To construct a DateTime, we need a time... let's give a non-midnight one to catch
// any unexpected uses of time within the date patterns.
DateTime sampleDateTime = (SampleLocalDate + new LocalTime(2, 3, 5)).ToDateTimeUnspecified();
Assert.AreEqual(sampleDateTime.ToString(patternText, culture), pattern.Format(sampleDateInCalendar));
}
public sealed class Data : PatternTestData<LocalDate>
{
// Default to the start of the year 2000.
protected override LocalDate DefaultTemplate => LocalDatePattern.DefaultTemplateValue;
/// <summary>
/// Initializes a new instance of the <see cref="Data" /> class.
/// </summary>
/// <param name="value">The value.</param>
public Data(LocalDate value) : base(value)
{
}
public Data(int year, int month, int day) : this(new LocalDate(year, month, day))
{
}
public Data(int year, int month, int day, CalendarSystem calendar)
: this(new LocalDate(year, month, day, calendar))
{
}
public Data() : this(LocalDatePattern.DefaultTemplateValue)
{
}
internal override IPattern<LocalDate> CreatePattern() =>
LocalDatePattern.CreateWithInvariantCulture(Pattern!)
.WithTemplateValue(Template)
.WithCulture(Culture);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
#if ENABLE_CECIL
using C = Mono.Cecil;
#endif
namespace Mono.Debugger.Soft
{
/*
* Represents a type in the remote virtual machine.
* It might be better to make this a subclass of Type, but that could be
* difficult as some of our methods like GetMethods () return Mirror objects.
*/
public class TypeMirror : Mirror, IInvokable
{
MethodMirror[] methods;
AssemblyMirror ass;
ModuleMirror module;
FieldInfoMirror[] fields;
PropertyInfoMirror[] properties;
TypeInfo info;
TypeMirror base_type, element_type, gtd;
TypeMirror[] nested;
CustomAttributeDataMirror[] cattrs;
TypeMirror[] ifaces;
Dictionary<TypeMirror, InterfaceMappingMirror> iface_map;
TypeMirror[] type_args;
bool cached_base_type;
bool inited;
#if ENABLE_CECIL
C.TypeDefinition meta;
#endif
internal const BindingFlags DefaultBindingFlags =
BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
internal TypeMirror (VirtualMachine vm, long id) : base (vm, id) {
}
public string Name {
get {
return GetInfo ().name;
}
}
public string Namespace {
get {
return GetInfo ().ns;
}
}
public AssemblyMirror Assembly {
get {
if (ass == null) {
ass = vm.GetAssembly (GetInfo ().assembly);
}
return ass;
}
}
public ModuleMirror Module {
get {
if (module == null) {
module = vm.GetModule (GetInfo ().module);
}
return module;
}
}
public int MetadataToken {
get {
return GetInfo ().token;
}
}
public TypeAttributes Attributes {
get {
return (TypeAttributes)GetInfo ().attributes;
}
}
public TypeMirror BaseType {
get {
if (!cached_base_type) {
base_type = vm.GetType (GetInfo ().base_type);
cached_base_type = true;
}
return base_type;
}
}
public int GetArrayRank () {
GetInfo ();
if (info.rank == 0)
throw new ArgumentException ("Type must be an array type.");
return info.rank;
}
public bool IsAbstract {
get {
return (Attributes & TypeAttributes.Abstract) != 0;
}
}
public bool IsAnsiClass {
get {
return (Attributes & TypeAttributes.StringFormatMask)
== TypeAttributes.AnsiClass;
}
}
public bool IsArray {
get {
return IsArrayImpl ();
}
}
public bool IsAutoClass {
get {
return (Attributes & TypeAttributes.StringFormatMask) == TypeAttributes.AutoClass;
}
}
public bool IsAutoLayout {
get {
return (Attributes & TypeAttributes.LayoutMask) == TypeAttributes.AutoLayout;
}
}
public bool IsByRef {
get {
return IsByRefImpl ();
}
}
public bool IsClass {
get {
if (IsInterface)
return false;
return !IsValueType;
}
}
public bool IsCOMObject {
get {
return IsCOMObjectImpl ();
}
}
public bool IsContextful {
get {
return IsContextfulImpl ();
}
}
public bool IsEnum {
get {
return GetInfo ().is_enum;
}
}
public bool IsExplicitLayout {
get {
return (Attributes & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout;
}
}
public bool IsImport {
get {
return (Attributes & TypeAttributes.Import) != 0;
}
}
public bool IsInterface {
get {
return (Attributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface;
}
}
public bool IsLayoutSequential {
get {
return (Attributes & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout;
}
}
public bool IsMarshalByRef {
get {
return IsMarshalByRefImpl ();
}
}
public bool IsNested {
get {
var masked = (Attributes & TypeAttributes.VisibilityMask);
return masked >= TypeAttributes.NestedPublic && masked <= TypeAttributes.NestedFamORAssem;
}
}
public bool IsNestedAssembly {
get {
return (Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly;
}
}
public bool IsNestedFamANDAssem {
get {
return (Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem;
}
}
public bool IsNestedFamily {
get {
return (Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily;
}
}
public bool IsNestedFamORAssem {
get {
return (Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem;
}
}
public bool IsNestedPrivate {
get {
return (Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate;
}
}
public bool IsNestedPublic {
get {
return (Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic;
}
}
public bool IsNotPublic {
get {
return (Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic;
}
}
public bool IsPointer {
get {
return IsPointerImpl ();
}
}
public bool IsPrimitive {
get {
return IsPrimitiveImpl ();
}
}
public bool IsPublic {
get {
return (Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public;
}
}
public bool IsSealed {
get {
return (Attributes & TypeAttributes.Sealed) != 0;
}
}
public bool IsSerializable {
get {
if ((Attributes & TypeAttributes.Serializable) != 0)
return true;
// FIXME:
return false;
}
}
public bool IsSpecialName {
get {
return (Attributes & TypeAttributes.SpecialName) != 0;
}
}
public bool IsUnicodeClass {
get {
return (Attributes & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass;
}
}
public bool IsValueType {
get {
return IsValueTypeImpl ();
}
}
public bool HasElementType {
get {
return HasElementTypeImpl ();
}
}
// Since protocol version 2.12
public bool IsGenericTypeDefinition {
get {
vm.CheckProtocolVersion (2, 12);
GetInfo ();
return info.is_gtd;
}
}
public bool IsGenericType {
get {
if (vm.Version.AtLeast (2, 12)) {
return GetInfo ().is_generic_type;
} else {
return Name.IndexOf ('`') != -1;
}
}
}
public TypeMirror GetElementType () {
GetInfo ();
if (element_type == null && info.element_type != 0)
element_type = vm.GetType (info.element_type);
return element_type;
}
public TypeMirror GetGenericTypeDefinition () {
vm.CheckProtocolVersion (2, 12);
GetInfo ();
if (gtd == null) {
if (info.gtd == 0)
throw new InvalidOperationException ();
gtd = vm.GetType (info.gtd);
}
return gtd;
}
// Since protocol version 2.15
public TypeMirror[] GetGenericArguments () {
vm.CheckProtocolVersion (2, 15);
if (type_args == null)
type_args = vm.GetTypes (GetInfo ().type_args);
return type_args;
}
public string FullName {
get {
return GetInfo ().full_name;
}
}
public string CSharpName {
get {
if (IsArray) {
var ranks = GetArrayRank ();
if (ranks == 1)
return GetElementType ().CSharpName + "[]";
return GetElementType ().CSharpName + "[" + new string(',', ranks - 1) + "]";
}
if (IsPrimitive) {
switch (Name) {
case "Byte":
return "byte";
case "SByte":
return "sbyte";
case "Char":
return "char";
case "UInt16":
return "ushort";
case "Int16":
return "short";
case "UInt32":
return "uint";
case "Int32":
return "int";
case "UInt64":
return "ulong";
case "Int64":
return "long";
case "Single":
return "float";
case "Double":
return "double";
case "Boolean":
return "bool";
default:
return FullName;
}
}
// FIXME: Only do this for real corlib types
if (Namespace == "System") {
string s = Name;
switch (s) {
case "Decimal":
return "decimal";
case "Object":
return "object";
case "String":
return "string";
default:
return FullName;
}
} else {
return FullName;
}
}
}
public MethodMirror[] GetMethods () {
if (methods == null) {
long[] ids = vm.conn.Type_GetMethods (id);
MethodMirror[] m = new MethodMirror [ids.Length];
for (int i = 0; i < ids.Length; ++i) {
m [i] = vm.GetMethod (ids [i]);
}
methods = m;
}
return methods;
}
// FIXME: Sync this with Type
public MethodMirror GetMethod (string name) {
foreach (var m in GetMethods ())
if (m.Name == name)
return m;
return null;
}
public FieldInfoMirror[] GetFields () {
if (fields != null)
return fields;
string[] names;
long[] types;
int[] attrs;
long[] ids = vm.conn.Type_GetFields (id, out names, out types, out attrs);
FieldInfoMirror[] res = new FieldInfoMirror [ids.Length];
for (int i = 0; i < res.Length; ++i)
res [i] = new FieldInfoMirror (this, ids [i], names [i], vm.GetType (types [i]), (FieldAttributes)attrs [i]);
fields = res;
return fields;
}
public FieldInfoMirror GetField (string name) {
if (name == null)
throw new ArgumentNullException ("name");
foreach (var f in GetFields ())
if (f.Name == name)
return f;
return null;
}
public TypeMirror[] GetNestedTypes ()
{
return GetNestedTypes (DefaultBindingFlags);
}
public TypeMirror[] GetNestedTypes (BindingFlags bindingAttr) {
if (nested != null)
return nested;
// FIXME: bindingAttr
GetInfo ();
var arr = new TypeMirror [info.nested.Length];
for (int i = 0; i < arr.Length; ++i)
arr [i] = vm.GetType (info.nested [i]);
nested = arr;
return nested;
}
public PropertyInfoMirror[] GetProperties () {
return GetProperties (DefaultBindingFlags);
}
public PropertyInfoMirror[] GetProperties (BindingFlags bindingAttr) {
if (properties != null)
return properties;
PropInfo[] info = vm.conn.Type_GetProperties (id);
PropertyInfoMirror[] res = new PropertyInfoMirror [info.Length];
for (int i = 0; i < res.Length; ++i)
res [i] = new PropertyInfoMirror (this, info [i].id, info [i].name, vm.GetMethod (info [i].get_method), vm.GetMethod (info [i].set_method), (PropertyAttributes)info [i].attrs);
properties = res;
return properties;
}
public PropertyInfoMirror GetProperty (string name) {
if (name == null)
throw new ArgumentNullException ("name");
foreach (var p in GetProperties ())
if (p.Name == name)
return p;
return null;
}
public virtual bool IsAssignableFrom (TypeMirror c) {
if (c == null)
throw new ArgumentNullException ("c");
CheckMirror (c);
// This is complex so do it in the debuggee
return vm.conn.Type_IsAssignableFrom (id, c.Id);
}
public Value GetValue (FieldInfoMirror field) {
return GetValues (new FieldInfoMirror [] { field }) [0];
}
public Value[] GetValues (IList<FieldInfoMirror> fields, ThreadMirror thread) {
if (fields == null)
throw new ArgumentNullException ("fields");
foreach (FieldInfoMirror f in fields) {
if (f == null)
throw new ArgumentNullException ("field");
CheckMirror (f);
}
long[] ids = new long [fields.Count];
for (int i = 0; i < fields.Count; ++i)
ids [i] = fields [i].Id;
try {
return vm.DecodeValues (vm.conn.Type_GetValues (id, ids, thread != null ? thread.Id : 0));
} catch (CommandException ex) {
if (ex.ErrorCode == ErrorCode.INVALID_FIELDID)
throw new ArgumentException ("One of the fields is not valid for this type.", "fields");
else
throw;
}
}
public Value[] GetValues (IList<FieldInfoMirror> fields) {
return GetValues (fields, null);
}
/*
* Return the value of the [ThreadStatic] field FIELD on the thread THREAD.
*/
public Value GetValue (FieldInfoMirror field, ThreadMirror thread) {
if (thread == null)
throw new ArgumentNullException ("thread");
CheckMirror (thread);
return GetValues (new FieldInfoMirror [] { field }, thread) [0];
}
public void SetValues (IList<FieldInfoMirror> fields, Value[] values) {
if (fields == null)
throw new ArgumentNullException ("fields");
if (values == null)
throw new ArgumentNullException ("values");
foreach (FieldInfoMirror f in fields) {
if (f == null)
throw new ArgumentNullException ("field");
CheckMirror (f);
}
foreach (Value v in values) {
if (v == null)
throw new ArgumentNullException ("values");
CheckMirror (v);
}
long[] ids = new long [fields.Count];
for (int i = 0; i < fields.Count; ++i)
ids [i] = fields [i].Id;
try {
vm.conn.Type_SetValues (id, ids, vm.EncodeValues (values));
} catch (CommandException ex) {
if (ex.ErrorCode == ErrorCode.INVALID_FIELDID)
throw new ArgumentException ("One of the fields is not valid for this type.", "fields");
else
throw;
}
}
public void SetValue (FieldInfoMirror field, Value value) {
SetValues (new FieldInfoMirror [] { field }, new Value [] { value });
}
public ObjectMirror GetTypeObject () {
return vm.GetObject (vm.conn.Type_GetObject (id));
}
/*
* Return a list of source files without path info, where methods of
* this type are defined. Return an empty list if the information is not
* available.
* This can be used by a debugger to find out which types occur in a
* given source file, to filter the list of methods whose locations
* have to be checked when placing breakpoints.
*/
public string[] GetSourceFiles () {
return GetSourceFiles (false);
}
string[] source_files;
string[] source_files_full_path;
public string[] GetSourceFiles (bool returnFullPaths) {
string[] res = returnFullPaths ? source_files_full_path : source_files;
if (res == null) {
res = vm.conn.Type_GetSourceFiles (id, returnFullPaths);
if (returnFullPaths)
source_files_full_path = res;
else
source_files = res;
}
return res;
}
#if ENABLE_CECIL
public C.TypeDefinition Metadata {
get {
if (meta == null) {
if (Assembly.Metadata == null || MetadataToken == 0)
return null;
meta = (C.TypeDefinition)Assembly.Metadata.MainModule.LookupToken (MetadataToken);
}
return meta;
}
}
#endif
TypeInfo GetInfo () {
if (info == null)
info = vm.conn.Type_GetInfo (id);
return info;
}
protected virtual TypeAttributes GetAttributeFlagsImpl () {
return (TypeAttributes)GetInfo ().attributes;
}
protected virtual bool HasElementTypeImpl () {
return IsArray || IsByRef || IsPointer;
}
protected virtual bool IsArrayImpl () {
return GetInfo ().rank > 0;
}
protected virtual bool IsByRefImpl () {
return GetInfo ().is_byref;
}
protected virtual bool IsCOMObjectImpl () {
return false;
}
protected virtual bool IsPointerImpl () {
return GetInfo ().is_pointer;
}
protected virtual bool IsPrimitiveImpl () {
return GetInfo ().is_primitive;
}
protected virtual bool IsValueTypeImpl ()
{
return GetInfo ().is_valuetype;
}
protected virtual bool IsContextfulImpl ()
{
// FIXME:
return false;
}
protected virtual bool IsMarshalByRefImpl ()
{
// FIXME:
return false;
}
// Same as Enum.GetUnderlyingType ()
public TypeMirror EnumUnderlyingType {
get {
if (!IsEnum)
throw new ArgumentException ("Type is not an enum type.");
foreach (FieldInfoMirror f in GetFields ()) {
if (!f.IsStatic)
return f.FieldType;
}
throw new NotImplementedException ();
}
}
/*
* Creating the custom attributes themselves could modify the behavior of the
* debuggee, so we return objects similar to the CustomAttributeData objects
* used by the reflection-only functionality on .net.
*/
public CustomAttributeDataMirror[] GetCustomAttributes (bool inherit) {
return GetCustomAttrs (null, inherit);
}
public CustomAttributeDataMirror[] GetCustomAttributes (TypeMirror attributeType, bool inherit) {
if (attributeType == null)
throw new ArgumentNullException ("attributeType");
return GetCustomAttrs (attributeType, inherit);
}
void AppendCustomAttrs (IList<CustomAttributeDataMirror> attrs, TypeMirror type, bool inherit)
{
#if ENABLE_CECIL
if (cattrs == null && Metadata != null && !Metadata.HasCustomAttributes)
cattrs = new CustomAttributeDataMirror [0];
#endif
if (cattrs == null) {
CattrInfo[] info = vm.conn.Type_GetCustomAttributes (id, 0, false);
cattrs = CustomAttributeDataMirror.Create (vm, info);
}
foreach (var attr in cattrs) {
if (type == null || attr.Constructor.DeclaringType == type)
attrs.Add (attr);
}
if (inherit && BaseType != null)
BaseType.AppendCustomAttrs (attrs, type, inherit);
}
CustomAttributeDataMirror[] GetCustomAttrs (TypeMirror type, bool inherit) {
var attrs = new List<CustomAttributeDataMirror> ();
AppendCustomAttrs (attrs, type, inherit);
return attrs.ToArray ();
}
public MethodMirror[] GetMethodsByNameFlags (string name, BindingFlags flags, bool ignoreCase) {
if (vm.conn.Version.AtLeast (2, 6)) {
long[] ids = vm.conn.Type_GetMethodsByNameFlags (id, name, (int)flags, ignoreCase);
MethodMirror[] m = new MethodMirror [ids.Length];
for (int i = 0; i < ids.Length; ++i)
m [i] = vm.GetMethod (ids [i]);
return m;
} else {
if ((flags & BindingFlags.IgnoreCase) != 0) {
flags &= ~BindingFlags.IgnoreCase;
ignoreCase = true;
}
if (flags == BindingFlags.Default)
flags = BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.Static;
MethodAttributes access = (MethodAttributes) 0;
bool matchInstance = false;
bool matchStatic = false;
if ((flags & BindingFlags.NonPublic) != 0) {
access |= MethodAttributes.Private;
flags &= ~BindingFlags.NonPublic;
}
if ((flags & BindingFlags.Public) != 0) {
access |= MethodAttributes.Public;
flags &= ~BindingFlags.Public;
}
if ((flags & BindingFlags.Instance) != 0) {
flags &= ~BindingFlags.Instance;
matchInstance = true;
}
if ((flags & BindingFlags.Static) != 0) {
flags &= ~BindingFlags.Static;
matchStatic = true;
}
if ((int) flags != 0)
throw new NotImplementedException ();
var res = new List<MethodMirror> ();
foreach (MethodMirror m in GetMethods ()) {
if ((m.Attributes & access) == (MethodAttributes) 0)
continue;
if (!((matchStatic && m.IsStatic) || (matchInstance && !m.IsStatic)))
continue;
if ((!ignoreCase && m.Name == name) || (ignoreCase && m.Name.Equals (name, StringComparison.CurrentCultureIgnoreCase)))
res.Add (m);
}
return res.ToArray ();
}
}
public Value InvokeMethod (ThreadMirror thread, MethodMirror method, IList<Value> arguments) {
return ObjectMirror.InvokeMethod (vm, thread, method, null, arguments, InvokeOptions.None);
}
public Value InvokeMethod (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options) {
return ObjectMirror.InvokeMethod (vm, thread, method, null, arguments, options);
}
[Obsolete ("Use the overload without the 'vm' argument")]
public IAsyncResult BeginInvokeMethod (VirtualMachine vm, ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options, AsyncCallback callback, object state) {
return ObjectMirror.BeginInvokeMethod (vm, thread, method, null, arguments, options, callback, state);
}
public IAsyncResult BeginInvokeMethod (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options, AsyncCallback callback, object state) {
return ObjectMirror.BeginInvokeMethod (vm, thread, method, null, arguments, options, callback, state);
}
public Value EndInvokeMethod (IAsyncResult asyncResult) {
return ObjectMirror.EndInvokeMethodInternal (asyncResult);
}
public InvokeResult EndInvokeMethodWithResult (IAsyncResult asyncResult) {
return ObjectMirror.EndInvokeMethodInternalWithResult (asyncResult);
}
public Task<Value> InvokeMethodAsync (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options = InvokeOptions.None) {
return ObjectMirror.InvokeMethodAsync (vm, thread, method, null, arguments, options);
}
public Task<InvokeResult> InvokeMethodAsyncWithResult (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options = InvokeOptions.None) {
return ObjectMirror.InvokeMethodAsyncWithResult (vm, thread, method, null, arguments, options);
}
public Value NewInstance (ThreadMirror thread, MethodMirror method, IList<Value> arguments) {
return NewInstance (thread, method, arguments, InvokeOptions.None);
}
public Value NewInstance (ThreadMirror thread, MethodMirror method, IList<Value> arguments, InvokeOptions options) {
if (method == null)
throw new ArgumentNullException ("method");
if (!method.IsConstructor)
throw new ArgumentException ("The method must be a constructor.", "method");
return ObjectMirror.InvokeMethod (vm, thread, method, null, arguments, options);
}
// Since protocol version 2.31
public Value NewInstance () {
return vm.GetObject (vm.conn.Type_CreateInstance (id));
}
// Since protocol version 2.46
public int GetValueSize () {
return vm.conn.Type_GetValueSize (id);
}
// Since protocol version 2.11
public TypeMirror[] GetInterfaces () {
if (ifaces == null)
ifaces = vm.GetTypes (vm.conn.Type_GetInterfaces (id));
return ifaces;
}
// Since protocol version 2.11
public InterfaceMappingMirror GetInterfaceMap (TypeMirror interfaceType) {
if (interfaceType == null)
throw new ArgumentNullException ("interfaceType");
if (!interfaceType.IsInterface)
throw new ArgumentException ("Argument must be an interface.", "interfaceType");
if (IsInterface)
throw new ArgumentException ("'this' type cannot be an interface itself");
if (iface_map == null) {
// Query the info in bulk
GetInterfaces ();
var ids = new long [ifaces.Length];
for (int i = 0; i < ifaces.Length; ++i)
ids [i] = ifaces [i].Id;
var ifacemap = vm.conn.Type_GetInterfaceMap (id, ids);
var imap = new Dictionary<TypeMirror, InterfaceMappingMirror> ();
for (int i = 0; i < ifacemap.Length; ++i) {
IfaceMapInfo info = ifacemap [i];
MethodMirror[] imethods = new MethodMirror [info.iface_methods.Length];
for (int j = 0; j < info.iface_methods.Length; ++j)
imethods [j] = vm.GetMethod (info.iface_methods [j]);
MethodMirror[] tmethods = new MethodMirror [info.iface_methods.Length];
for (int j = 0; j < info.target_methods.Length; ++j)
tmethods [j] = vm.GetMethod (info.target_methods [j]);
InterfaceMappingMirror map = new InterfaceMappingMirror (vm, this, vm.GetType (info.iface_id), imethods, tmethods);
imap [map.InterfaceType] = map;
}
iface_map = imap;
}
InterfaceMappingMirror res;
if (!iface_map.TryGetValue (interfaceType, out res))
throw new ArgumentException ("Interface not found", "interfaceType");
return res;
}
// Return whenever the type initializer of this type has ran
// Since protocol version 2.23
public bool IsInitialized {
get {
vm.CheckProtocolVersion (2, 23);
if (!inited)
inited = vm.conn.Type_IsInitialized (id);
return inited;
}
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
namespace System.Data.SqlClient
{
sealed internal class SqlStream : Stream
{
private SqlDataReader _reader; // reader we will stream off
private int _columnOrdinal;
private long _bytesCol;
private int _bom;
private byte[] _bufferedData;
private bool _processAllRows;
private bool _advanceReader;
private bool _readFirstRow = false;
private bool _endOfColumn = false;
internal SqlStream(SqlDataReader reader, bool addByteOrderMark, bool processAllRows) :
this(0, reader, addByteOrderMark, processAllRows, true)
{
}
internal SqlStream(int columnOrdinal, SqlDataReader reader, bool addByteOrderMark, bool processAllRows, bool advanceReader)
{
_columnOrdinal = columnOrdinal;
_reader = reader;
_bom = addByteOrderMark ? 0xfeff : 0;
_processAllRows = processAllRows;
_advanceReader = advanceReader;
}
override public bool CanRead
{
get
{
return true;
}
}
override public bool CanSeek
{
get
{
return false;
}
}
override public bool CanWrite
{
get
{
return false;
}
}
override public long Length
{
get
{
throw ADP.NotSupported();
}
}
override public long Position
{
get
{
throw ADP.NotSupported();
}
set
{
throw ADP.NotSupported();
}
}
override protected void Dispose(bool disposing)
{
try
{
if (disposing && _advanceReader && _reader != null && !_reader.IsClosed)
{
_reader.Close();
}
_reader = null;
}
finally
{
base.Dispose(disposing);
}
}
override public void Flush()
{
throw ADP.NotSupported();
}
override public int Read(byte[] buffer, int offset, int count)
{
int intCount = 0;
int cBufferedData = 0;
if ((null == _reader))
{
throw ADP.StreamClosed(ADP.Read);
}
if (null == buffer)
{
throw ADP.ArgumentNull(ADP.ParameterBuffer);
}
if ((offset < 0) || (count < 0))
{
throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? ADP.ParameterOffset : ADP.ParameterCount));
}
if (buffer.Length - offset < count)
{
throw ADP.ArgumentOutOfRange(ADP.ParameterCount);
}
// Need to find out if we should add byte order mark or not.
// We need to add this if we are getting ntext xml, not if we are getting binary xml
// Binary Xml always begins with the bytes 0xDF and 0xFF
// If we aren't getting these, then we are getting unicode xml
if (_bom > 0)
{
// Read and buffer the first two bytes
_bufferedData = new byte[2];
cBufferedData = ReadBytes(_bufferedData, 0, 2);
// Check to se if we should add the byte order mark
if ((cBufferedData < 2) || ((_bufferedData[0] == 0xDF) && (_bufferedData[1] == 0xFF)))
{
_bom = 0;
}
while (count > 0)
{
if (_bom > 0)
{
buffer[offset] = (byte)_bom;
_bom >>= 8;
offset++;
count--;
intCount++;
}
else
{
break;
}
}
}
if (cBufferedData > 0)
{
while (count > 0)
{
buffer[offset++] = _bufferedData[0];
intCount++;
count--;
if ((cBufferedData > 1) && (count > 0))
{
buffer[offset++] = _bufferedData[1];
intCount++;
count--;
break;
}
}
_bufferedData = null;
}
intCount += ReadBytes(buffer, offset, count);
return intCount;
}
private static bool AdvanceToNextRow(SqlDataReader reader)
{
Debug.Assert(reader != null && !reader.IsClosed);
// this method skips empty result sets
do
{
if (reader.Read())
{
return true;
}
} while (reader.NextResult());
// no more rows
return false;
}
private int ReadBytes(byte[] buffer, int offset, int count)
{
bool gotData = true;
int intCount = 0;
int cb = 0;
if (_reader.IsClosed || _endOfColumn)
{
return 0;
}
try
{
while (count > 0)
{
// if no bytes were read, get the next row
if (_advanceReader && (0 == _bytesCol))
{
gotData = false;
if (_readFirstRow && !_processAllRows)
{
// for XML column, stop processing after the first row
// no op here - reader is closed after the end of this loop
}
else if (AdvanceToNextRow(_reader))
{
_readFirstRow = true;
if (_reader.IsDBNull(_columnOrdinal))
{
// Handle row with DBNULL as empty data
// for XML column, processing is stopped on the next loop since _readFirstRow is true
continue;
}
// the value is not null, read it
gotData = true;
}
// else AdvanceToNextRow has returned false - no more rows or result sets remained, stop processing
}
if (gotData)
{
cb = (int)_reader.GetBytesInternal(_columnOrdinal, _bytesCol, buffer, offset, count);
if (cb < count)
{
_bytesCol = 0;
gotData = false;
if (!_advanceReader)
{
_endOfColumn = true;
}
}
else
{
Debug.Assert(cb == count);
_bytesCol += cb;
}
// we are guaranteed that cb is < Int32.Max since we always pass in count which is of type Int32 to
// our getbytes interface
count -= (int)cb;
offset += (int)cb;
intCount += (int)cb;
}
else
{
break; // no more data available, we are done
}
}
if (!gotData && _advanceReader)
{
_reader.Close(); // Need to close the reader if we are done reading
}
}
catch (Exception e)
{
if (_advanceReader && ADP.IsCatchableExceptionType(e))
{
_reader.Close();
}
throw;
}
return intCount;
}
internal XmlReader ToXmlReader(bool async = false)
{
return SqlTypes.SqlXml.CreateSqlXmlReader(this, closeInput: true, async: async);
}
override public long Seek(long offset, SeekOrigin origin)
{
throw ADP.NotSupported();
}
override public void SetLength(long value)
{
throw ADP.NotSupported();
}
override public void Write(byte[] buffer, int offset, int count)
{
throw ADP.NotSupported();
}
}
// XmlTextReader does not read all the bytes off the network buffers, so we have to cache it here in the random access
// case. This causes double buffering and is a perf hit, but this is not the high perf way for accessing this type of data.
// In the case of sequential access, we do not have to do any buffering since the XmlTextReader we return can become
// invalid as soon as we move off the current column.
sealed internal class SqlCachedStream : Stream
{
private int _currentPosition; // Position within the current array byte
private int _currentArrayIndex; // Index into the _cachedBytes ArrayList
private List<byte[]> _cachedBytes;
private long _totalLength;
// Reads off from the network buffer and caches bytes. Only reads one column value in the current row.
internal SqlCachedStream(SqlCachedBuffer sqlBuf)
{
_cachedBytes = sqlBuf.CachedBytes;
}
override public bool CanRead
{
get
{
return true;
}
}
override public bool CanSeek
{
get
{
return true;
}
}
override public bool CanWrite
{
get
{
return false;
}
}
override public long Length
{
get
{
return TotalLength;
}
}
override public long Position
{
get
{
long pos = 0;
if (_currentArrayIndex > 0)
{
for (int ii = 0; ii < _currentArrayIndex; ii++)
{
pos += _cachedBytes[ii].Length;
}
}
pos += _currentPosition;
return pos;
}
set
{
if (null == _cachedBytes)
{
throw ADP.StreamClosed(ADP.ParameterSetPosition);
}
SetInternalPosition(value, ADP.ParameterSetPosition);
}
}
override protected void Dispose(bool disposing)
{
try
{
if (disposing && _cachedBytes != null)
_cachedBytes.Clear();
_cachedBytes = null;
_currentPosition = 0;
_currentArrayIndex = 0;
_totalLength = 0;
}
finally
{
base.Dispose(disposing);
}
}
override public void Flush()
{
throw ADP.NotSupported();
}
override public int Read(byte[] buffer, int offset, int count)
{
int cb;
int intCount = 0;
if (null == _cachedBytes)
{
throw ADP.StreamClosed(ADP.Read);
}
if (null == buffer)
{
throw ADP.ArgumentNull(ADP.ParameterBuffer);
}
if ((offset < 0) || (count < 0))
{
throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? ADP.ParameterOffset : ADP.ParameterCount));
}
if (buffer.Length - offset < count)
{
throw ADP.ArgumentOutOfRange(ADP.ParameterCount);
}
if (_cachedBytes.Count <= _currentArrayIndex)
{
return 0; // Everything is read!
}
while (count > 0)
{
if (_cachedBytes[_currentArrayIndex].Length <= _currentPosition)
{
_currentArrayIndex++; // We are done reading this chunk, go to next
if (_cachedBytes.Count > _currentArrayIndex)
{
_currentPosition = 0;
}
else
{
break;
}
}
cb = _cachedBytes[_currentArrayIndex].Length - _currentPosition;
if (cb > count)
cb = count;
Buffer.BlockCopy(_cachedBytes[_currentArrayIndex], _currentPosition, buffer, offset, cb);
_currentPosition += cb;
count -= (int)cb;
offset += (int)cb;
intCount += (int)cb;
}
return intCount;
}
override public long Seek(long offset, SeekOrigin origin)
{
long pos = 0;
if (null == _cachedBytes)
{
throw ADP.StreamClosed(ADP.Read);
}
switch (origin)
{
case SeekOrigin.Begin:
SetInternalPosition(offset, ADP.ParameterOffset);
break;
case SeekOrigin.Current:
pos = offset + Position;
SetInternalPosition(pos, ADP.ParameterOffset);
break;
case SeekOrigin.End:
pos = TotalLength + offset;
SetInternalPosition(pos, ADP.ParameterOffset);
break;
default:
throw ADP.InvalidSeekOrigin(ADP.ParameterOffset);
}
return pos;
}
override public void SetLength(long value)
{
throw ADP.NotSupported();
}
override public void Write(byte[] buffer, int offset, int count)
{
throw ADP.NotSupported();
}
private void SetInternalPosition(long lPos, string argumentName)
{
long pos = lPos;
if (pos < 0)
{
throw new ArgumentOutOfRangeException(argumentName);
}
for (int ii = 0; ii < _cachedBytes.Count; ii++)
{
if (pos > _cachedBytes[ii].Length)
{
pos -= _cachedBytes[ii].Length;
}
else
{
_currentArrayIndex = ii;
_currentPosition = (int)pos;
return;
}
}
if (pos > 0)
throw new ArgumentOutOfRangeException(argumentName);
}
private long TotalLength
{
get
{
if ((_totalLength == 0) && (_cachedBytes != null))
{
long pos = 0;
for (int ii = 0; ii < _cachedBytes.Count; ii++)
{
pos += _cachedBytes[ii].Length;
}
_totalLength = pos;
}
return _totalLength;
}
}
}
sealed internal class SqlStreamingXml
{
private int _columnOrdinal;
private SqlDataReader _reader;
private XmlReader _xmlReader;
private XmlWriter _xmlWriter;
private StringWriter _strWriter;
private long _charsRemoved;
public SqlStreamingXml(int i, SqlDataReader reader)
{
_columnOrdinal = i;
_reader = reader;
}
public void Close()
{
((IDisposable)_xmlWriter).Dispose();
((IDisposable)_xmlReader).Dispose();
_reader = null;
_xmlReader = null;
_xmlWriter = null;
_strWriter = null;
}
public int ColumnOrdinal
{
get
{
return _columnOrdinal;
}
}
public long GetChars(long dataIndex, char[] buffer, int bufferIndex, int length)
{
if (_xmlReader == null)
{
SqlStream sqlStream = new SqlStream(_columnOrdinal, _reader, true /* addByteOrderMark */, false /* processAllRows*/, false /*advanceReader*/);
_xmlReader = sqlStream.ToXmlReader();
_strWriter = new StringWriter((System.IFormatProvider)null);
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.CloseOutput = true; // close the memory stream when done
writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
_xmlWriter = XmlWriter.Create(_strWriter, writerSettings);
}
int charsToSkip = 0;
int cnt = 0;
if (dataIndex < _charsRemoved)
{
throw ADP.NonSeqByteAccess(dataIndex, _charsRemoved, ADP.GetChars);
}
else if (dataIndex > _charsRemoved)
{
charsToSkip = (int)(dataIndex - _charsRemoved);
}
// If buffer parameter is null, we have to return -1 since there is no way for us to know the
// total size up front without reading and converting the XML.
if (buffer == null)
{
return (long)(-1);
}
StringBuilder strBldr = _strWriter.GetStringBuilder();
while (!_xmlReader.EOF)
{
if (strBldr.Length >= (length + charsToSkip))
{
break;
}
// Can't call _xmlWriter.WriteNode here, since it reads all of the data in before returning the first char.
// Do own implementation of WriteNode instead that reads just enough data to return the required number of chars
//_xmlWriter.WriteNode(_xmlReader, true);
// _xmlWriter.Flush();
WriteXmlElement();
if (charsToSkip > 0)
{
// Aggressively remove the characters we want to skip to avoid growing StringBuilder size too much
cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip;
strBldr.Remove(0, cnt);
charsToSkip -= cnt;
_charsRemoved += (long)cnt;
}
}
if (charsToSkip > 0)
{
cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip;
strBldr.Remove(0, cnt);
charsToSkip -= cnt;
_charsRemoved += (long)cnt;
}
if (strBldr.Length == 0)
{
return 0;
}
// At this point charsToSkip must be 0
Debug.Assert(charsToSkip == 0);
cnt = strBldr.Length < length ? strBldr.Length : length;
for (int i = 0; i < cnt; i++)
{
buffer[bufferIndex + i] = strBldr[i];
}
// Remove the characters we have already returned
strBldr.Remove(0, cnt);
_charsRemoved += (long)cnt;
return (long)cnt;
}
// This method duplicates the work of XmlWriter.WriteNode except that it reads one element at a time
// instead of reading the entire node like XmlWriter.
private void WriteXmlElement()
{
if (_xmlReader.EOF)
return;
bool canReadChunk = _xmlReader.CanReadValueChunk;
char[] writeNodeBuffer = null;
// Constants
const int WriteNodeBufferSize = 1024;
_xmlReader.Read();
switch (_xmlReader.NodeType)
{
case XmlNodeType.Element:
_xmlWriter.WriteStartElement(_xmlReader.Prefix, _xmlReader.LocalName, _xmlReader.NamespaceURI);
_xmlWriter.WriteAttributes(_xmlReader, true);
if (_xmlReader.IsEmptyElement)
{
_xmlWriter.WriteEndElement();
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
if (writeNodeBuffer == null)
{
writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = _xmlReader.ReadValueChunk(writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
{
_xmlWriter.WriteChars(writeNodeBuffer, 0, read);
}
}
else
{
_xmlWriter.WriteString(_xmlReader.Value);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_xmlWriter.WriteWhitespace(_xmlReader.Value);
break;
case XmlNodeType.CDATA:
_xmlWriter.WriteCData(_xmlReader.Value);
break;
case XmlNodeType.EntityReference:
_xmlWriter.WriteEntityRef(_xmlReader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
_xmlWriter.WriteProcessingInstruction(_xmlReader.Name, _xmlReader.Value);
break;
case XmlNodeType.DocumentType:
_xmlWriter.WriteDocType(_xmlReader.Name, _xmlReader.GetAttribute("PUBLIC"), _xmlReader.GetAttribute("SYSTEM"), _xmlReader.Value);
break;
case XmlNodeType.Comment:
_xmlWriter.WriteComment(_xmlReader.Value);
break;
case XmlNodeType.EndElement:
_xmlWriter.WriteFullEndElement();
break;
}
_xmlWriter.Flush();
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2016 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
using System;
using System.Linq;
namespace NUnit.Framework.Internal
{
/// <summary>
/// PlatformHelper class is used by the PlatformAttribute class to
/// determine whether a platform is supported.
/// </summary>
public class PlatformHelper
{
private readonly OSPlatform _os;
private readonly RuntimeFramework _rt;
// Set whenever we fail to support a list of platforms
private string _reason = string.Empty;
const string CommonOSPlatforms =
"Win,Win32,Win32S,Win32NT,Win32Windows,Win95,Win98,WinMe,NT3,NT4,NT5,NT6," +
"Win2008Server,Win2008ServerR2,Win2012Server,Win2012ServerR2," +
"Win2K,WinXP,Win2003Server,Vista,Win7,Windows7,Win8,Windows8,"+
"Win8.1,Windows8.1,Win10,Windows10,WindowsServer10,Unix,Linux";
/// <summary>
/// Comma-delimited list of all supported OS platform constants
/// </summary>
public const string OSPlatforms = CommonOSPlatforms + ",Xbox,MacOSX";
/// <summary>
/// Comma-delimited list of all supported Runtime platform constants
/// </summary>
public static readonly string RuntimePlatforms =
"Net,SSCLI,Rotor,Mono,MonoTouch";
/// <summary>
/// Default constructor uses the operating system and
/// common language runtime of the system.
/// </summary>
public PlatformHelper()
{
_os = OSPlatform.CurrentPlatform;
_rt = RuntimeFramework.CurrentFramework;
}
/// <summary>
/// Construct a PlatformHelper for a particular operating
/// system and common language runtime. Used in testing.
/// </summary>
/// <param name="rt">RuntimeFramework to be used</param>
/// <param name="os">OperatingSystem to be used</param>
public PlatformHelper( OSPlatform os, RuntimeFramework rt )
{
_os = os;
_rt = rt;
}
/// <summary>
/// Test to determine if one of a collection of platforms
/// is being used currently.
/// </summary>
/// <param name="platforms"></param>
/// <returns></returns>
public bool IsPlatformSupported( string[] platforms )
{
return platforms.Any( IsPlatformSupported );
}
/// <summary>
/// Tests to determine if the current platform is supported
/// based on a platform attribute.
/// </summary>
/// <param name="platformAttribute">The attribute to examine</param>
/// <returns></returns>
public bool IsPlatformSupported( PlatformAttribute platformAttribute )
{
string include = platformAttribute.Include;
string exclude = platformAttribute.Exclude;
return IsPlatformSupported( include, exclude );
}
/// <summary>
/// Tests to determine if the current platform is supported
/// based on a platform attribute.
/// </summary>
/// <param name="testCaseAttribute">The attribute to examine</param>
/// <returns></returns>
public bool IsPlatformSupported(TestCaseAttribute testCaseAttribute)
{
string include = testCaseAttribute.IncludePlatform;
string exclude = testCaseAttribute.ExcludePlatform;
return IsPlatformSupported(include, exclude);
}
private bool IsPlatformSupported(string include, string exclude)
{
if (include != null && !IsPlatformSupported(include))
{
_reason = string.Format("Only supported on {0}", include);
return false;
}
if (exclude != null && IsPlatformSupported(exclude))
{
_reason = string.Format("Not supported on {0}", exclude);
return false;
}
return true;
}
/// <summary>
/// Test to determine if a particular platform or comma-delimited set of platforms is in use.
/// </summary>
/// <param name="platform">Name of the platform or comma-separated list of platform ids</param>
/// <returns>True if the platform is in use on the system</returns>
public bool IsPlatformSupported( string platform )
{
if ( platform.IndexOf( ',' ) >= 0 )
return IsPlatformSupported( platform.Split(',') );
string platformName = platform.Trim();
bool isSupported;
switch( platformName.ToUpper() )
{
case "WIN":
case "WIN32":
isSupported = _os.IsWindows;
break;
case "WIN32S":
isSupported = _os.IsWin32S;
break;
case "WIN32WINDOWS":
isSupported = _os.IsWin32Windows;
break;
case "WIN32NT":
isSupported = _os.IsWin32NT;
break;
case "WIN95":
isSupported = _os.IsWin95;
break;
case "WIN98":
isSupported = _os.IsWin98;
break;
case "WINME":
isSupported = _os.IsWinME;
break;
case "NT3":
isSupported = _os.IsNT3;
break;
case "NT4":
isSupported = _os.IsNT4;
break;
case "NT5":
isSupported = _os.IsNT5;
break;
case "WIN2K":
isSupported = _os.IsWin2K;
break;
case "WINXP":
isSupported = _os.IsWinXP;
break;
case "WIN2003SERVER":
isSupported = _os.IsWin2003Server;
break;
case "NT6":
isSupported = _os.IsNT6;
break;
case "VISTA":
isSupported = _os.IsVista;
break;
case "WIN2008SERVER":
isSupported = _os.IsWin2008Server;
break;
case "WIN2008SERVERR2":
isSupported = _os.IsWin2008ServerR2;
break;
case "WIN2012SERVER":
isSupported = _os.IsWin2012ServerR1 || _os.IsWin2012ServerR2;
break;
case "WIN2012SERVERR2":
isSupported = _os.IsWin2012ServerR2;
break;
case "WIN7":
case "WINDOWS7":
isSupported = _os.IsWindows7;
break;
case "WINDOWS8":
case "WIN8":
isSupported = _os.IsWindows8;
break;
case "WINDOWS8.1":
case "WIN8.1":
isSupported = _os.IsWindows81;
break;
case "WINDOWS10":
case "WIN10":
isSupported = _os.IsWindows10;
break;
case "WINDOWSSERVER10":
isSupported = _os.IsWindowsServer10;
break;
case "UNIX":
case "LINUX":
isSupported = _os.IsUnix;
break;
case "XBOX":
isSupported = _os.IsXbox;
break;
case "MACOSX":
isSupported = _os.IsMacOSX;
break;
// These bitness tests relate to the process, not the OS.
// We can't use Environment.Is64BitProcess because it's
// only supported in NET 4.0 and higher.
case "64-BIT":
case "64-BIT-PROCESS":
isSupported = IntPtr.Size == 8;
break;
case "32-BIT":
case "32-BIT-PROCESS":
isSupported = IntPtr.Size == 4;
break;
#if NET_4_0 || NET_4_5
// We only support bitness tests of the OS in .NET 4.0 and up
case "64-BIT-OS":
isSupported = Environment.Is64BitOperatingSystem;
break;
case "32-BIT-OS":
isSupported = !Environment.Is64BitOperatingSystem;
break;
#endif
default:
isSupported = IsRuntimeSupported(platformName);
break;
}
if (!isSupported)
_reason = "Only supported on " + platform;
return isSupported;
}
/// <summary>
/// Return the last failure reason. Results are not
/// defined if called before IsSupported( Attribute )
/// is called.
/// </summary>
public string Reason
{
get { return _reason; }
}
private bool IsRuntimeSupported(string platformName)
{
string versionSpecification = null;
string[] parts = platformName.Split('-');
if (parts.Length == 2)
{
platformName = parts[0];
versionSpecification = parts[1];
}
switch (platformName.ToUpper())
{
case "NET":
return IsRuntimeSupported(RuntimeType.Net, versionSpecification);
case "SSCLI":
case "ROTOR":
return IsRuntimeSupported(RuntimeType.SSCLI, versionSpecification);
case "MONO":
return IsRuntimeSupported(RuntimeType.Mono, versionSpecification);
case "MONOTOUCH":
return IsRuntimeSupported(RuntimeType.MonoTouch, versionSpecification);
default:
throw new InvalidPlatformException("Invalid platform name: " + platformName);
}
}
private bool IsRuntimeSupported(RuntimeType runtime, string versionSpecification)
{
Version version = versionSpecification == null
? RuntimeFramework.DefaultVersion
: new Version(versionSpecification);
RuntimeFramework target = new RuntimeFramework(runtime, version);
return _rt.Supports(target);
}
}
}
#endif
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Protocol;
using Thrift.Server;
using Thrift.Transport;
using Thrift.Transport.Server;
using tutorial;
using shared;
using Thrift.Processor;
using System.Diagnostics;
namespace Server
{
public class Program
{
private static ServiceCollection ServiceCollection = new ServiceCollection();
private static ILogger Logger;
public static void Main(string[] args)
{
args = args ?? new string[0];
ServiceCollection.AddLogging(logging => ConfigureLogging(logging));
Logger = ServiceCollection.BuildServiceProvider().GetService<ILoggerFactory>().CreateLogger(nameof(Server));
if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase)))
{
DisplayHelp();
return;
}
using (var source = new CancellationTokenSource())
{
RunAsync(args, source.Token).GetAwaiter().GetResult();
Logger.LogInformation("Press any key to stop...");
Console.ReadLine();
source.Cancel();
}
Logger.LogInformation("Server stopped");
}
private static void ConfigureLogging(ILoggingBuilder logging)
{
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddConsole();
logging.AddDebug();
}
private static void DisplayHelp()
{
Logger.LogInformation(@"
Usage:
Server.exe -help
will diplay help information
Server.exe -tr:<transport> -bf:<buffering> -pr:<protocol>
will run server with specified arguments (tcp transport, no buffering, and binary protocol by default)
Options:
-tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
http - http transport will be used (http address - ""localhost:9090"")
tcptls - tcp transport with tls will be used (host - ""localhost"", port - 9090)
-bf (buffering):
none - (default) no buffering will be used
buffered - buffered transport will be used
framed - framed transport will be used
-pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
multiplexed - multiplexed protocol will be used
Sample:
Server.exe -tr:tcp
");
}
private static async Task RunAsync(string[] args, CancellationToken cancellationToken)
{
var selectedTransport = GetTransport(args);
var selectedBuffering = GetBuffering(args);
var selectedProtocol = GetProtocol(args);
if (selectedTransport == Transport.Http)
{
new HttpServerSample().Run(cancellationToken);
}
else
{
await RunSelectedConfigurationAsync(selectedTransport, selectedBuffering, selectedProtocol, cancellationToken);
}
}
private static Protocol GetProtocol(string[] args)
{
var transport = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1];
Enum.TryParse(transport, true, out Protocol selectedProtocol);
return selectedProtocol;
}
private static Buffering GetBuffering(string[] args)
{
var buffering = args.FirstOrDefault(x => x.StartsWith("-bf"))?.Split(":")?[1];
Enum.TryParse<Buffering>(buffering, out var selectedBuffering);
return selectedBuffering;
}
private static Transport GetTransport(string[] args)
{
var transport = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1];
Enum.TryParse(transport, true, out Transport selectedTransport);
return selectedTransport;
}
private static async Task RunSelectedConfigurationAsync(Transport transport, Buffering buffering, Protocol protocol, CancellationToken cancellationToken)
{
var handler = new CalculatorAsyncHandler();
TServerTransport serverTransport = null;
switch (transport)
{
case Transport.Tcp:
serverTransport = new TServerSocketTransport(9090);
break;
case Transport.NamedPipe:
serverTransport = new TNamedPipeServerTransport(".test");
break;
case Transport.TcpTls:
serverTransport = new TTlsServerSocketTransport(9090, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback);
break;
}
TTransportFactory inputTransportFactory = null;
TTransportFactory outputTransportFactory = null;
switch (buffering)
{
case Buffering.Buffered:
inputTransportFactory = new TBufferedTransport.Factory();
outputTransportFactory = new TBufferedTransport.Factory();
break;
case Buffering.Framed:
inputTransportFactory = new TFramedTransport.Factory();
outputTransportFactory = new TFramedTransport.Factory();
break;
default: // layered transport(s) are optional
Debug.Assert(buffering == Buffering.None, "unhandled case");
break;
}
TProtocolFactory inputProtocolFactory = null;
TProtocolFactory outputProtocolFactory = null;
ITAsyncProcessor processor = null;
switch (protocol)
{
case Protocol.Binary:
inputProtocolFactory = new TBinaryProtocol.Factory();
outputProtocolFactory = new TBinaryProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
break;
case Protocol.Compact:
inputProtocolFactory = new TCompactProtocol.Factory();
outputProtocolFactory = new TCompactProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
break;
case Protocol.Json:
inputProtocolFactory = new TJsonProtocol.Factory();
outputProtocolFactory = new TJsonProtocol.Factory();
processor = new Calculator.AsyncProcessor(handler);
break;
case Protocol.Multiplexed:
inputProtocolFactory = new TBinaryProtocol.Factory();
outputProtocolFactory = new TBinaryProtocol.Factory();
var calcHandler = new CalculatorAsyncHandler();
var calcProcessor = new Calculator.AsyncProcessor(calcHandler);
var sharedServiceHandler = new SharedServiceAsyncHandler();
var sharedServiceProcessor = new SharedService.AsyncProcessor(sharedServiceHandler);
var multiplexedProcessor = new TMultiplexedProcessor();
multiplexedProcessor.RegisterProcessor(nameof(Calculator), calcProcessor);
multiplexedProcessor.RegisterProcessor(nameof(SharedService), sharedServiceProcessor);
processor = multiplexedProcessor;
break;
default:
throw new ArgumentOutOfRangeException(nameof(protocol), protocol, null);
}
try
{
Logger.LogInformation(
$"Selected TAsyncServer with {serverTransport} transport, {processor} processor and {inputProtocolFactory} protocol factories");
var loggerFactory = ServiceCollection.BuildServiceProvider().GetService<ILoggerFactory>();
var server = new TSimpleAsyncServer(
itProcessorFactory: new TSingletonProcessorFactory(processor),
serverTransport: serverTransport,
inputTransportFactory: inputTransportFactory,
outputTransportFactory: outputTransportFactory,
inputProtocolFactory: inputProtocolFactory,
outputProtocolFactory: outputProtocolFactory,
logger: loggerFactory.CreateLogger<TSimpleAsyncServer>());
Logger.LogInformation("Starting the server...");
await server.ServeAsync(cancellationToken);
}
catch (Exception x)
{
Logger.LogInformation(x.ToString());
}
}
private static X509Certificate2 GetCertificate()
{
// due to files location in net core better to take certs from top folder
var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory()));
return new X509Certificate2(certFile, "ThriftTest");
}
private static string GetCertPath(DirectoryInfo di, int maxCount = 6)
{
var topDir = di;
var certFile =
topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories)
.FirstOrDefault();
if (certFile == null)
{
if (maxCount == 0)
throw new FileNotFoundException("Cannot find file in directories");
return GetCertPath(di.Parent, maxCount - 1);
}
return certFile.FullName;
}
private static X509Certificate LocalCertificateSelectionCallback(object sender,
string targetHost, X509CertificateCollection localCertificates,
X509Certificate remoteCertificate, string[] acceptableIssuers)
{
return GetCertificate();
}
private static bool ClientCertValidator(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
private enum Transport
{
Tcp,
NamedPipe,
Http,
TcpTls,
}
private enum Buffering
{
None,
Buffered,
Framed,
}
private enum Protocol
{
Binary,
Compact,
Json,
Multiplexed
}
public class HttpServerSample
{
public void Run(CancellationToken cancellationToken)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseUrls("http://localhost:9090")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.ConfigureLogging((ctx,logging) => ConfigureLogging(logging))
.Build();
Logger.LogTrace("test");
Logger.LogCritical("test");
host.RunAsync(cancellationToken).GetAwaiter().GetResult();
}
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<Calculator.IAsync, CalculatorAsyncHandler>();
services.AddTransient<ITAsyncProcessor, Calculator.AsyncProcessor>();
services.AddTransient<THttpServerTransport, THttpServerTransport>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMiddleware<THttpServerTransport>();
}
}
}
public class CalculatorAsyncHandler : Calculator.IAsync
{
private readonly Dictionary<int, SharedStruct> _log = new Dictionary<int, SharedStruct>();
public CalculatorAsyncHandler()
{
}
public async Task<SharedStruct> getStructAsync(int key,
CancellationToken cancellationToken)
{
Logger.LogInformation("GetStructAsync({0})", key);
return await Task.FromResult(_log[key]);
}
public async Task pingAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("PingAsync()");
await Task.CompletedTask;
}
public async Task<int> addAsync(int num1, int num2, CancellationToken cancellationToken)
{
Logger.LogInformation($"AddAsync({num1},{num2})");
return await Task.FromResult(num1 + num2);
}
public async Task<int> calculateAsync(int logid, Work w, CancellationToken cancellationToken)
{
Logger.LogInformation($"CalculateAsync({logid}, [{w.Op},{w.Num1},{w.Num2}])");
var val = 0;
switch (w.Op)
{
case Operation.ADD:
val = w.Num1 + w.Num2;
break;
case Operation.SUBTRACT:
val = w.Num1 - w.Num2;
break;
case Operation.MULTIPLY:
val = w.Num1 * w.Num2;
break;
case Operation.DIVIDE:
if (w.Num2 == 0)
{
var io = new InvalidOperation
{
WhatOp = (int) w.Op,
Why = "Cannot divide by 0"
};
throw io;
}
val = w.Num1 / w.Num2;
break;
default:
{
var io = new InvalidOperation
{
WhatOp = (int) w.Op,
Why = "Unknown operation"
};
throw io;
}
}
var entry = new SharedStruct
{
Key = logid,
Value = val.ToString()
};
_log[logid] = entry;
return await Task.FromResult(val);
}
public async Task zipAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("ZipAsync() with delay 100mc");
await Task.Delay(100, CancellationToken.None);
}
}
public class SharedServiceAsyncHandler : SharedService.IAsync
{
public async Task<SharedStruct> getStructAsync(int key, CancellationToken cancellationToken)
{
Logger.LogInformation("GetStructAsync({0})", key);
return await Task.FromResult(new SharedStruct()
{
Key = key,
Value = "GetStructAsync"
});
}
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using FluentAssertions;
using LanguageExt;
using NUnit.Framework;
using SJP.Schematic.Core;
using SJP.Schematic.Tests.Utilities.Integration;
namespace SJP.Schematic.Serialization.Tests
{
internal sealed class JsonRelationalDatabaseSerializerTests : SakilaTest
{
private static readonly Lazy<IMapper> _mapper = new(() =>
{
var config = new MapperConfiguration(config => config.AddMaps(typeof(Mapping.RelationalDatabaseProfile).Assembly));
config.AssertConfigurationIsValid();
return new Mapper(config);
});
private static IMapper Mapper { get; } = _mapper.Value;
private static IRelationalDatabaseSerializer Serializer { get; } = new JsonRelationalDatabaseSerializer(Mapper);
[Test]
public async Task Serialize_WhenInvoked_ExportsWithoutError()
{
var db = GetDatabase();
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
var json = Encoding.UTF8.GetString(jsonOutputStream.ToArray());
Assert.Multiple(() =>
{
Assert.That(json, Is.Not.Null);
Assert.That(json, Is.Not.Empty);
});
}
[Test]
public async Task SerializeDeserialize_WhenEmptyDatabaseRoundTripped_ExportsAndParsesWithoutError()
{
var db = new EmptyRelationalDatabase(new IdentifierDefaults(null, null, "main"));
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
db.Should().BeEquivalentTo(importedDb);
}
[Test]
public async Task SerializeDeserialize_WhenEmptyDatabaseRoundTripped_PreservesJsonStructure()
{
var db = new EmptyRelationalDatabase(new IdentifierDefaults(null, null, "main"));
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
var json = Encoding.UTF8.GetString(jsonOutputStream.ToArray());
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
using var jsonOutputStream2 = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream2, importedDb).ConfigureAwait(false);
var reExportedJson = Encoding.UTF8.GetString(jsonOutputStream2.ToArray());
Assert.Multiple(() =>
{
Assert.That(reExportedJson, Is.Not.Null);
Assert.That(reExportedJson, Is.Not.Empty);
Assert.That(reExportedJson, Is.EqualTo(json));
});
}
[Test]
public async Task SerializeDeserialize_WhenRoundTripped_ExportsAndParsesWithoutError()
{
var db = GetDatabase();
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
db.Should().BeEquivalentTo(importedDb);
}
[Test]
public async Task SerializeDeserialize_WhenRoundTripped_PreservesJsonStructure()
{
var db = GetDatabase();
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
var json = Encoding.UTF8.GetString(jsonOutputStream.ToArray());
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
using var jsonOutputStream2 = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream2, importedDb).ConfigureAwait(false);
var reExportedJson = Encoding.UTF8.GetString(jsonOutputStream2.ToArray());
Assert.Multiple(() =>
{
Assert.That(reExportedJson, Is.Not.Null);
Assert.That(reExportedJson, Is.Not.Empty);
Assert.That(reExportedJson, Is.EqualTo(json));
});
}
// the above covers tables and views, but as the test database has no sequences, synonyms and routines we need to implement it
[Test]
public async Task SerializeDeserialize_WhenSequenceRoundTripped_ExportsAndParsesWithoutError()
{
var sequence = new DatabaseSequence(
"test_sequence_name",
1,
10,
Option<decimal>.Some(-10),
Option<decimal>.Some(1000),
true,
20
);
var sequences = new[] { sequence };
var tables = Array.Empty<IRelationalDatabaseTable>();
var views = Array.Empty<IDatabaseView>();
var synonyms = Array.Empty<IDatabaseSynonym>();
var routines = Array.Empty<IDatabaseRoutine>();
var db = new RelationalDatabase(
new IdentifierDefaults(null, null, "main"),
new VerbatimIdentifierResolutionStrategy(),
tables,
views,
sequences,
synonyms,
routines
);
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
db.Should().BeEquivalentTo(importedDb);
}
[Test]
public async Task SerializeDeserialize_WhenSequenceRoundTripped_PreservesJsonStructure()
{
var sequence = new DatabaseSequence(
"test_sequence_name",
1,
10,
Option<decimal>.Some(-10),
Option<decimal>.Some(1000),
true,
20
);
var sequences = new[] { sequence };
var tables = Array.Empty<IRelationalDatabaseTable>();
var views = Array.Empty<IDatabaseView>();
var synonyms = Array.Empty<IDatabaseSynonym>();
var routines = Array.Empty<IDatabaseRoutine>();
var db = new RelationalDatabase(
new IdentifierDefaults(null, null, "main"),
new VerbatimIdentifierResolutionStrategy(),
tables,
views,
sequences,
synonyms,
routines
);
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
var json = Encoding.UTF8.GetString(jsonOutputStream.ToArray());
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
using var jsonOutputStream2 = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream2, importedDb).ConfigureAwait(false);
var reExportedJson = Encoding.UTF8.GetString(jsonOutputStream2.ToArray());
Assert.Multiple(() =>
{
Assert.That(reExportedJson, Is.Not.Null);
Assert.That(reExportedJson, Is.Not.Empty);
Assert.That(reExportedJson, Is.EqualTo(json));
});
}
[Test]
public async Task SerializeDeserialize_WhenSynonymRoundTripped_ExportsAndParsesWithoutError()
{
var synonym = new DatabaseSynonym("test_synonym_name", "test_target_name");
var synonyms = new[] { synonym };
var tables = Array.Empty<IRelationalDatabaseTable>();
var views = Array.Empty<IDatabaseView>();
var sequences = Array.Empty<IDatabaseSequence>();
var routines = Array.Empty<IDatabaseRoutine>();
var db = new RelationalDatabase(
new IdentifierDefaults(null, null, "main"),
new VerbatimIdentifierResolutionStrategy(),
tables,
views,
sequences,
synonyms,
routines
);
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
db.Should().BeEquivalentTo(importedDb);
}
[Test]
public async Task SerializeDeserialize_WhenSynonymRoundTripped_PreservesJsonStructure()
{
var synonym = new DatabaseSynonym("test_synonym_name", "test_target_name");
var synonyms = new[] { synonym };
var tables = Array.Empty<IRelationalDatabaseTable>();
var views = Array.Empty<IDatabaseView>();
var sequences = Array.Empty<IDatabaseSequence>();
var routines = Array.Empty<IDatabaseRoutine>();
var db = new RelationalDatabase(
new IdentifierDefaults(null, null, "main"),
new VerbatimIdentifierResolutionStrategy(),
tables,
views,
sequences,
synonyms,
routines
);
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
var json = Encoding.UTF8.GetString(jsonOutputStream.ToArray());
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
using var jsonOutputStream2 = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream2, importedDb).ConfigureAwait(false);
var reExportedJson = Encoding.UTF8.GetString(jsonOutputStream2.ToArray());
Assert.Multiple(() =>
{
Assert.That(reExportedJson, Is.Not.Null);
Assert.That(reExportedJson, Is.Not.Empty);
Assert.That(reExportedJson, Is.EqualTo(json));
});
}
[Test]
public async Task SerializeDeserialize_WhenRoutineRoundTripped_ExportsAndParsesWithoutError()
{
var routine = new DatabaseRoutine("test_routine_name", "test_routine_definition");
var routines = new[] { routine };
var tables = Array.Empty<IRelationalDatabaseTable>();
var views = Array.Empty<IDatabaseView>();
var sequences = Array.Empty<IDatabaseSequence>();
var synonyms = Array.Empty<IDatabaseSynonym>();
var db = new RelationalDatabase(
new IdentifierDefaults(null, null, "main"),
new VerbatimIdentifierResolutionStrategy(),
tables,
views,
sequences,
synonyms,
routines
);
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
db.Should().BeEquivalentTo(importedDb);
}
[Test]
public async Task SerializeDeserialize_WhenRoutineRoundTripped_PreservesJsonStructure()
{
var routine = new DatabaseRoutine("test_routine_name", "test_routine_definition");
var routines = new[] { routine };
var tables = Array.Empty<IRelationalDatabaseTable>();
var views = Array.Empty<IDatabaseView>();
var sequences = Array.Empty<IDatabaseSequence>();
var synonyms = Array.Empty<IDatabaseSynonym>();
var db = new RelationalDatabase(
new IdentifierDefaults(null, null, "main"),
new VerbatimIdentifierResolutionStrategy(),
tables,
views,
sequences,
synonyms,
routines
);
using var jsonOutputStream = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream, db).ConfigureAwait(false);
var json = Encoding.UTF8.GetString(jsonOutputStream.ToArray());
jsonOutputStream.Seek(0, SeekOrigin.Begin);
var importedDb = await Serializer.DeserializeAsync(jsonOutputStream, new VerbatimIdentifierResolutionStrategy()).ConfigureAwait(false);
using var jsonOutputStream2 = new MemoryStream();
await Serializer.SerializeAsync(jsonOutputStream2, importedDb).ConfigureAwait(false);
var reExportedJson = Encoding.UTF8.GetString(jsonOutputStream2.ToArray());
Assert.Multiple(() =>
{
Assert.That(reExportedJson, Is.Not.Null);
Assert.That(reExportedJson, Is.Not.Empty);
Assert.That(reExportedJson, Is.EqualTo(json));
});
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Its.Log.Instrumentation.Extensions;
namespace Its.Log.Instrumentation
{
/// <summary>
/// A log entry and associated information.
/// </summary>
[Serializable]
public class LogEntry
{
/// <summary>
/// The key used to reference the exception ID within <see cref="Exception.Data" />
/// </summary>
internal const string ExceptionIdKey = ExceptionExtensions.ExceptionDataPrefix + "ExceptionID__";
/// <summary>
/// The creation time of the instance
/// </summary>
private DateTime timeStamp = DateTime.UtcNow;
private string callingMethod = string.Empty;
private Type callingType;
private TraceEventType? eventType;
private AnonymousMethodInfo anonymousMethodInfo;
internal Dictionary<Type, object> extensions;
internal List<KeyValuePair<string, object>> info;
/// <summary>
/// The message
/// </summary>
private string message;
private object subject;
/// <summary>
/// Indicates whether the LogEntry has been posted via Log.Write. This is used to prevent re-posts.
/// </summary>
internal bool HasBeenPosted;
/// <summary>
/// Initializes a new instance of the <see cref="LogEntry"/> class.
/// </summary>
/// <param name="subject">An object of interest to be evaluated for logging.</param>
public LogEntry(object subject)
{
if (subject is LogEntry)
{
throw new ArgumentException("The subject of a LogEntry cannot be another LogEntry");
}
Subject = subject;
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEntry"/> class.
/// </summary>
/// <param name="message">A message to be written to the log.</param>
public LogEntry(string message) : this((object)message)
{
Message = message;
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEntry"/> class.
/// </summary>
/// <param name="comment">A message to be written to the log.</param>
/// <param name="subject">An object of interest to be evaluated for logging.</param>
public LogEntry(string comment, object subject) : this(subject)
{
Message = comment;
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEntry"/> class.
/// </summary>
/// <param name="anonymousMethodInfo">A <see cref="AnonymousMethodInfo" /> to be used to extract context information for the <see cref="LogEntry" />.</param>
internal LogEntry(AnonymousMethodInfo anonymousMethodInfo) : this((object)null)
{
AnonymousMethodInfo = anonymousMethodInfo;
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEntry"/> class.
/// </summary>
/// <param name="subject">The subject.</param>
/// <param name="anonymousMethodInfo">A <see cref="AnonymousMethodInfo" /> to be used to extract context information for the <see cref="LogEntry" />.</param>
internal LogEntry(object subject, AnonymousMethodInfo anonymousMethodInfo) : this(subject)
{
AnonymousMethodInfo = anonymousMethodInfo;
}
/// <summary>
/// Gets or sets the <see cref="Type" /> in whose code the log entry was initiated.
/// </summary>
/// <value>The calling <see cref="Type" />.</value>
public virtual Type CallingType
{
get
{
if (callingType == null && anonymousMethodInfo != null)
{
callingType = anonymousMethodInfo.EnclosingType;
}
return callingType;
}
private set
{
callingType = value;
}
}
/// <summary>
/// Gets or sets the method from which <see cref="Log.Write" /> was called.
/// </summary>
public string CallingMethod
{
get
{
return callingMethod;
}
set
{
callingMethod = value;
}
}
/// <summary>
/// Gets or sets the category.
/// </summary>
/// <value>The category.</value>
[SkipOnNull]
public string Category { get; set; }
/// <summary>
/// Gets or sets the closure info.
/// </summary>
/// <value>The closure info.</value>
internal AnonymousMethodInfo AnonymousMethodInfo
{
get
{
return anonymousMethodInfo;
}
set
{
if (anonymousMethodInfo != value)
{
anonymousMethodInfo = value;
CallingType = anonymousMethodInfo.EnclosingType;
CallingMethod = value.EnclosingMethodName;
}
}
}
/// <summary>
/// Gets or sets the type of the event.
/// </summary>
/// <value>The type of the event.</value>
public TraceEventType EventType
{
get
{
return eventType ?? TraceEventType.Information;
}
set
{
eventType = value;
}
}
/// <summary>
/// Gets the exception id.
/// </summary>
/// <value>The exception id.</value>
/// <remarks>The exception id is unique per <see cref="Exception" /> instance</remarks>
[SkipOnNull]
public Guid? ExceptionId { get; private set; }
/// <summary>
/// Gets or sets the message.
/// </summary>
/// <value>The message.</value>
/// <remarks>IfTypeIs not explicitly set, the <see cref="Message"/> will be generated from the <see cref="Subject" />.</remarks>
[SkipOnNull]
public virtual string Message
{
get
{
return message = (message ??
Subject as string ??
(Subject as Func<String>).Maybe(f => f()));
}
set
{
message = value;
}
}
/// <summary>
/// Gets or sets the object with which the log entry operation is concerned.
/// </summary>
[SkipOnNull]
public virtual object Subject
{
get
{
return subject;
}
set
{
subject = value;
var exception = subject as Exception;
if (exception != null)
{
EnsureExceptionId();
if (eventType == null)
{
if (exception.HasBeenHandled())
{
eventType = TraceEventType.Warning;
}
else if (exception.IsFatal())
{
eventType = TraceEventType.Critical;
}
else
{
EventType = TraceEventType.Error;
}
}
}
}
}
/// <summary>
/// Gets the time stamp.
/// </summary>
/// <value>The time stamp.</value>
public DateTime TimeStamp
{
get
{
return timeStamp;
}
set
{
timeStamp = value;
}
}
/// <summary>
/// Gets the subject, strongly typed.
/// </summary>
/// <typeparam name="T">The <see cref="Type" /> of the subject</typeparam>
/// <returns>The <see cref="Subject" />, strongly typed</returns>
public virtual T GetSubject<T>()
{
if (Subject is T)
{
return (T)Subject;
}
return default(T);
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return Formatter<LogEntry>.Format(this);
}
/// <summary>
/// Adds info to the <see cref="LogEntry"/>.
/// </summary>
/// <param name="label">The label.</param>
/// <param name="value">The value.</param>
public LogEntry AddInfo(string label, object value)
{
if (info == null)
{
info = new List<KeyValuePair<string, object>>();
}
info.Add(new KeyValuePair<string, object>(label, value));
return this;
}
/// <summary>
/// Gets an extension of the specified type if it has been applied to this <see cref="LogEntry" />.
/// </summary>
/// <typeparam name="TExtension">The <see cref="Type" /> of the extension.</typeparam>
/// <returns>An instance of <typeparamref name="TExtension" /> if it has been applied to the <see cref="LogEntry" />; otherwise, null.</returns>
public TExtension GetExtension<TExtension>() where TExtension : class
{
if (extensions == null)
{
return null;
}
object value;
if (!extensions.TryGetValue(typeof (TExtension), out value))
{
return null;
}
return (TExtension) value;
}
/// <summary>
/// Gets information added via extensions to the log entry.
/// </summary>
public IEnumerable<object> Params
{
get
{
if (extensions != null)
{
foreach (var extension in extensions.Values.OfType<Params>())
{
yield return extension;
}
}
if (info != null)
{
foreach (var pair in info)
{
yield return pair;
}
}
}
}
[SkipOnNull]
internal IEnumerable<object> Extensions
{
get
{
if (extensions == null)
{
return null;
}
var es = extensions.Values.Except(Params).ToArray();
if (es.Length == 0)
{
return null;
}
return es;
}
}
[SkipOnNull]
public long? ElapsedMilliseconds
{
get
{
if (EventType == TraceEventType.Stop || EventType == TraceEventType.Verbose)
{
var stopwatch = GetExtension<Stopwatch>();
if (stopwatch != null)
{
return stopwatch.ElapsedMilliseconds;
}
}
return null;
}
}
/// <summary>
/// Determines whether this instance has an extension of the specific <see cref="Type" /> <typeparamref name="TExtension" />.
/// </summary>
/// <typeparam name="TExtension">The <see cref="Type" /> of the extension</typeparam>
/// <returns>
/// <c>true</c> if this instance has the extension; otherwise, <c>false</c>.
/// </returns>
public bool HasExtension<TExtension>()
where TExtension : class, new()
{
if (extensions == null)
{
return false;
}
return extensions.ContainsKey(typeof(TExtension));
}
/// <summary>
/// Gets or adds an extension of the specified type.
/// </summary>
/// <typeparam name="TExtension">The type of the extension.</typeparam>
/// <returns>The extension of type <typeparamref name="TExtension" /> if it has already been added to the log entry; otherwise, a new instsance, which is immediately added to the log entry.</returns>
public TExtension WithExtension<TExtension>()
where TExtension : class, new()
{
if (HasExtension<TExtension>())
{
return GetExtension<TExtension>();
}
return AddExtension<TExtension>();
}
internal TExtension Extend<TExtension>() where TExtension : class, new()
{
// TODO: (Extend) a more performant, clearer WithExtension. test and measure.
object extensionObj;
var type = typeof (TExtension);
if ((extensions ?? (extensions = new Dictionary<Type, object>())).TryGetValue(type, out extensionObj))
{
return extensionObj as TExtension;
}
var extension = new TExtension();
extensions[type] = extension;
return extension;
}
/// <summary>
/// Adds the specified extension to the log entry.
/// </summary>
/// <typeparam name="TExtension">The type of the extension.</typeparam>
/// <param name="ext">The extension to be added.</param>
/// <returns>The same extension instance.</returns>
public TExtension SetExtension<TExtension>(TExtension ext)
where TExtension : class
{
if (extensions == null)
{
extensions = new Dictionary<Type, object>();
}
extensions[ext.GetType()] = ext;
return ext;
}
internal TExtension AddExtension<TExtension>()
where TExtension : class, new()
{
var ext = new TExtension();
return SetExtension(ext);
}
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns>A <see cref="LogEntry" /> which is a clone of this instance.</returns>
internal virtual LogEntry Clone(bool deep)
{
var clone = new LogEntry(Subject)
{
info = info,
Message = Message,
AnonymousMethodInfo = anonymousMethodInfo,
extensions = deep || extensions == null
? extensions
: new Dictionary<Type, object>(extensions)
};
return clone;
}
/// <summary>
/// Ensures that the exception id is initialized.
/// </summary>
private void EnsureExceptionId()
{
if (ExceptionId == null)
{
var ex = Subject as Exception;
while (ex != null)
{
if (ex.Data.Contains(ExceptionIdKey))
{
ExceptionId = (Guid) ex.Data[ExceptionIdKey];
}
ex = ex.InnerException;
}
if (ExceptionId == null)
{
ExceptionId = Guid.NewGuid();
// propagate the exception id back to the exception
GetSubject<Exception>().Data[ExceptionIdKey] = ExceptionId;
}
}
}
}
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H04_SubContinent (editable child object).<br/>
/// This is a generated base class of <see cref="H04_SubContinent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="H05_CountryObjects"/> of type <see cref="H05_CountryColl"/> (1:M relation to <see cref="H06_Country"/>)<br/>
/// This class is an item of <see cref="H03_SubContinentColl"/> collection.
/// </remarks>
[Serializable]
public partial class H04_SubContinent : BusinessBase<H04_SubContinent>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> SubContinent_IDProperty = RegisterProperty<int>(p => p.SubContinent_ID, "SubContinents ID");
/// <summary>
/// Gets the SubContinents ID.
/// </summary>
/// <value>The SubContinents ID.</value>
public int SubContinent_ID
{
get { return GetProperty(SubContinent_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_NameProperty = RegisterProperty<string>(p => p.SubContinent_Name, "SubContinents Name");
/// <summary>
/// Gets or sets the SubContinents Name.
/// </summary>
/// <value>The SubContinents Name.</value>
public string SubContinent_Name
{
get { return GetProperty(SubContinent_NameProperty); }
set { SetProperty(SubContinent_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H05_SubContinent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H05_SubContinent_Child> H05_SubContinent_SingleObjectProperty = RegisterProperty<H05_SubContinent_Child>(p => p.H05_SubContinent_SingleObject, "H05 SubContinent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H05 Sub Continent Single Object ("self load" child property).
/// </summary>
/// <value>The H05 Sub Continent Single Object.</value>
public H05_SubContinent_Child H05_SubContinent_SingleObject
{
get { return GetProperty(H05_SubContinent_SingleObjectProperty); }
private set { LoadProperty(H05_SubContinent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H05_SubContinent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H05_SubContinent_ReChild> H05_SubContinent_ASingleObjectProperty = RegisterProperty<H05_SubContinent_ReChild>(p => p.H05_SubContinent_ASingleObject, "H05 SubContinent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H05 Sub Continent ASingle Object ("self load" child property).
/// </summary>
/// <value>The H05 Sub Continent ASingle Object.</value>
public H05_SubContinent_ReChild H05_SubContinent_ASingleObject
{
get { return GetProperty(H05_SubContinent_ASingleObjectProperty); }
private set { LoadProperty(H05_SubContinent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H05_CountryObjects"/> property.
/// </summary>
public static readonly PropertyInfo<H05_CountryColl> H05_CountryObjectsProperty = RegisterProperty<H05_CountryColl>(p => p.H05_CountryObjects, "H05 Country Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the H05 Country Objects ("self load" child property).
/// </summary>
/// <value>The H05 Country Objects.</value>
public H05_CountryColl H05_CountryObjects
{
get { return GetProperty(H05_CountryObjectsProperty); }
private set { LoadProperty(H05_CountryObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H04_SubContinent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H04_SubContinent"/> object.</returns>
internal static H04_SubContinent NewH04_SubContinent()
{
return DataPortal.CreateChild<H04_SubContinent>();
}
/// <summary>
/// Factory method. Loads a <see cref="H04_SubContinent"/> object from the given H04_SubContinentDto.
/// </summary>
/// <param name="data">The <see cref="H04_SubContinentDto"/>.</param>
/// <returns>A reference to the fetched <see cref="H04_SubContinent"/> object.</returns>
internal static H04_SubContinent GetH04_SubContinent(H04_SubContinentDto data)
{
H04_SubContinent obj = new H04_SubContinent();
// 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="H04_SubContinent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H04_SubContinent()
{
// 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="H04_SubContinent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(SubContinent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(H05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<H05_SubContinent_Child>());
LoadProperty(H05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<H05_SubContinent_ReChild>());
LoadProperty(H05_CountryObjectsProperty, DataPortal.CreateChild<H05_CountryColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H04_SubContinent"/> object from the given <see cref="H04_SubContinentDto"/>.
/// </summary>
/// <param name="data">The H04_SubContinentDto to use.</param>
private void Fetch(H04_SubContinentDto data)
{
// Value properties
LoadProperty(SubContinent_IDProperty, data.SubContinent_ID);
LoadProperty(SubContinent_NameProperty, data.SubContinent_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(H05_SubContinent_SingleObjectProperty, H05_SubContinent_Child.GetH05_SubContinent_Child(SubContinent_ID));
LoadProperty(H05_SubContinent_ASingleObjectProperty, H05_SubContinent_ReChild.GetH05_SubContinent_ReChild(SubContinent_ID));
LoadProperty(H05_CountryObjectsProperty, H05_CountryColl.GetH05_CountryColl(SubContinent_ID));
}
/// <summary>
/// Inserts a new <see cref="H04_SubContinent"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H02_Continent parent)
{
var dto = new H04_SubContinentDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.SubContinent_Name = SubContinent_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IH04_SubContinentDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(SubContinent_IDProperty, resultDto.SubContinent_ID);
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="H04_SubContinent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new H04_SubContinentDto();
dto.SubContinent_ID = SubContinent_ID;
dto.SubContinent_Name = SubContinent_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IH04_SubContinentDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="H04_SubContinent"/> 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<IH04_SubContinentDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(SubContinent_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
}
}
| |
using System;
using System.Data;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Security;
using Rainbow.Framework.Settings.Cache;
using Rainbow.Framework.Site.Data;
using Rainbow.Framework.Web.UI.WebControls;
using Rainbow.Framework.Providers.RainbowSiteMapProvider;
using History=Rainbow.Framework.History;
using Label=System.Web.UI.WebControls.Label;
using LinkButton=System.Web.UI.WebControls.LinkButton;
using Localize=Rainbow.Framework.Web.UI.WebControls.Localize;
namespace Rainbow.Content.Web.Modules.AddModule
{
/// <summary>
/// This module has been built by John Mandia (www.whitelightsolutions.com)
/// It allows administrators to give permission to selected roles to add modules to pages
/// </summary>
[History("jminond", "12/5/2005", "Added DropDownList to combos")]
[History("jminond", "march 2005", "Changes for moving Tab to Page")]
public class AddPage : PortalModuleControl
{
#region Controls
/// <summary>
///
/// </summary>
protected Localize tabParentLabel;
/// <summary>
///
/// </summary>
protected Localize tabVisibleLabel;
/// <summary>
///
/// </summary>
protected DropDownList PermissionDropDown;
/// <summary>
///
/// </summary>
protected Localize tabTitleLabel;
/// <summary>
///
/// </summary>
protected TextBox TabTitleTextBox;
/// <summary>
///
/// </summary>
protected LinkButton AddTabButton;
/// <summary>
///
/// </summary>
protected Label lblErrorNotAllowed;
/// <summary>
///
/// </summary>
protected DropDownList parentTabDropDown;
/// <summary>
///
/// </summary>
protected Localize lbl_ShowMobile;
/// <summary>
///
/// </summary>
protected CheckBox cb_ShowMobile;
/// <summary>
///
/// </summary>
protected Localize lbl_MobileTabName;
/// <summary>
///
/// </summary>
protected TextBox tb_MobileTabName;
/// <summary>
///
/// </summary>
protected Localize Literal1;
/// <summary>
///
/// </summary>
protected RadioButtonList rbl_JumpToTab;
/// <summary>
///
/// </summary>
protected Localize moduleError;
#endregion
#region Page Load
/// <summary>
/// The Page_Load event handler on this User Control is used to
/// load all the modules that are currently on this tab
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Page_Load(object sender, EventArgs e)
{
// If first visit to the page, update all entries
if (Page.IsPostBack == false)
{
BindData();
TabTitleTextBox.Text = General.GetString("TAB_NAME", "New Tab Name");
}
}
#endregion
/// <summary>
/// Bind data and load miscellanous data
/// </summary>
public void LoadAddPageModule()
{
BindData();
TabTitleTextBox.Text = General.GetString("TAB_NAME", "New Tab Name");
AddTabButton.Click += new EventHandler(AddTabButton_Click);
}
#region Methods
/// <summary>
/// The BindData helper method is used to update the tab's
/// layout panes with the current configuration information
/// </summary>
private void BindData()
{
// Populate the "ParentTab" Data
DataTable dt_Pages = new PagesDB().GetPagesFlatTable(portalSettings.PortalID);
DataColumn[] keys = new DataColumn[2];
keys[0] = dt_Pages.Columns["PageID"];
dt_Pages.PrimaryKey = keys;
parentTabDropDown.DataSource = dt_Pages;
//parentTabDropDown.DataValueField = "PageID";
//parentTabDropDown.DataTextField = "PageOrder";
parentTabDropDown.DataBind();
parentTabDropDown.Items.Insert(1, "Root");
//dt_Pages = null;
// Preselects current tab as parent
// Changes for Grischa Brockhaus copied by Mike Stone 7/1/2005
if (parentTabDropDown.SelectedIndex <= 0)
{
int currentTab = portalSettings.ActivePage.PageID;
parentTabDropDown.SelectedValue = (currentTab.ToString());
}
// parentTabDropDown.Items.FindByValue(currentTab .ToString()).Selected = true;
// Translate
//parentTabDropDown.Item(0).Text =General.GetString("ROOT_LEVEL", "Root Level", parentTabDropDown);
}
#endregion
#region Events
/// <summary>
/// The AddTabButton_Click server event handler
/// on this page is used to add a new portal module
/// into the tab
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AddTabButton_Click(Object sender, EventArgs e)
{
if (Page.IsValid)
{
// Hide error message in case there was a previous error.
moduleError.Visible = false;
// This allows the user to pick what type of people can view the module being added.
// If Authorised Roles is selected from the dropdown then every role that has view permission for the
// Add Role module will be added to the view permissions of the module being added.
string viewPermissionRoles = PermissionDropDown.SelectedValue.ToString();
if (viewPermissionRoles == "Authorised Roles")
{
viewPermissionRoles = PortalSecurity.GetViewPermissions(ModuleID);
}
try
{
// New tabs go to the end of the list
PageItem t = new PageItem();
t.Name = TabTitleTextBox.Text;
t.ID = -1;
t.Order = 990000;
// Get Parent Tab Id Convert only once used many times
int parentTabID = int.Parse(parentTabDropDown.SelectedValue);
// write tab to database
PagesDB tabs = new PagesDB();
//t.ID = tabs.AddTab(portalSettings.PortalID, t.Name, viewPermissionRoles, t.Order);
// Changed to use new method in TabsDB.cs now all parms are possible
// By Mike Stone (mstone@kaskaskia.edu) - 30/12/2004
t.ID =
tabs.AddPage(portalSettings.PortalID, parentTabID, t.Name, t.Order, viewPermissionRoles,
cb_ShowMobile.Checked, tb_MobileTabName.Text);
//TODO.. the only way to update a parent id is throught update :S
// Changed to AddTab method now supports the parm
// Mike Stone - 30/12/2004
//tabs.UpdateTab(portalSettings.PortalID, t.ID, parentTabID, t.Name, t.Order, viewPermissionRoles, t.Name, false);
//Invalidate cache
// Changed to access form directly
// mike stone - 30/12/2004
// Cache.Remove(Rainbow.Framework.Settings.Cache.Key.TabSettings(parentTabID));
// Copied to here 29/12/2004 by Mike Stone
CurrentCache.RemoveAll("_TabNavigationSettings_");
//Debug.WriteLine("************* Remove " + Key.TabSettings(parentTabID));
//Clear SiteMaps Cache
RainbowSiteMapProvider.ClearAllRainbowSiteMapCaches();
//Jump to Page option
string returnTab = string.Empty;
if (rbl_JumpToTab.SelectedValue.ToString() == "Yes")
{
// Redirect to New Page/Tab - Mike Stone 30/12/2004
// modified by Hongwei Shen 9/25/2005
// returnTab = HttpUrlBuilder.BuildUrl("~/DesktopDefault.aspx", t.ID, "SelectedTabID=" + t.ID.ToString());
string newPage = "~/" + t.Name.Trim().Replace(" ", "_") + ".aspx";
returnTab = HttpUrlBuilder.BuildUrl(newPage, t.ID);
}
else
{
// Do NOT Redirect to New Form - Mike Stone 30/12/2004
// I guess every .aspx page needs to have a module tied to it.
// or you will get an error about edit access denied.
// Modified by Hongwei Shen 9/25/2005 to fix: QueryString["tabID"] maybe null.
// returnTab = HttpUrlBuilder.BuildUrl("~/DesktopDefault.aspx", int.Parse(Request.QueryString["tabID"]), "SelectedTabID=" + t.ID.ToString());
returnTab =
HttpUrlBuilder.BuildUrl("~/DesktopDefault.aspx", PageID, "SelectedTabID=" + t.ID.ToString());
}
Response.Redirect(returnTab);
}
catch (Exception ex)
{
moduleError.Visible = true;
ErrorHandler.Publish(LogLevel.Error,
"There was an error with the Add Tab Module while trying to add a new tab.", ex);
return;
}
// Reload page to pick up changes
Response.Redirect(Request.RawUrl, false);
}
}
#endregion
#region General Implementation
/// <summary>
/// Gets the GUID for this module.
/// </summary>
/// <value></value>
public override Guid GuidID
{
get { return new Guid("{A1E37A0F-4EE9-4b83-9482-43466FC21E08}"); }
}
/// <summary>
/// Marks This Module To Be An Admin Module
/// </summary>
public override bool AdminModule
{
get { return true; }
}
/// <summary>
/// Public constructor. Sets base settings for module.
/// </summary>
public AddPage()
{
}
#endregion
#region Web Form Designer generated code
/// <summary>
/// Raises OnInitEvent
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
this.PermissionDropDown.Items.Add("All Users");
this.PermissionDropDown.Items.Add("Authenticated Users");
this.PermissionDropDown.Items.Add("Unauthenticated Users");
this.PermissionDropDown.Items.Add("Authorised Roles");
this.PermissionDropDown.SelectedIndex = 1;
this.AddTabButton.Click += new EventHandler(this.AddTabButton_Click);
this.Load += new EventHandler(this.Page_Load);
// Call base init procedure
base.OnInit(e);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public class Executor
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Contains the script to execute functions in.
/// </summary>
protected IScript m_Script;
protected Dictionary<string, scriptEvents> m_eventFlagsMap = new Dictionary<string, scriptEvents>();
[Flags]
public enum scriptEvents : int
{
None = 0,
attach = 1,
collision = 16,
collision_end = 32,
collision_start = 64,
control = 128,
dataserver = 256,
email = 512,
http_response = 1024,
land_collision = 2048,
land_collision_end = 4096,
land_collision_start = 8192,
at_target = 16384,
at_rot_target = 16777216,
listen = 32768,
money = 65536,
moving_end = 131072,
moving_start = 262144,
not_at_rot_target = 524288,
not_at_target = 1048576,
remote_data = 8388608,
run_time_permissions = 268435456,
state_entry = 1073741824,
state_exit = 2,
timer = 4,
touch = 8,
touch_end = 536870912,
touch_start = 2097152,
transaction_result = 33554432,
object_rez = 4194304
}
// Cache functions by keeping a reference to them in a dictionary
private Dictionary<string, MethodInfo> Events = new Dictionary<string, MethodInfo>();
private Dictionary<string, scriptEvents> m_stateEvents = new Dictionary<string, scriptEvents>();
public Executor(IScript script)
{
m_Script = script;
initEventFlags();
}
public scriptEvents GetStateEventFlags(string state)
{
//m_log.Debug("Get event flags for " + state);
// Check to see if we've already computed the flags for this state
scriptEvents eventFlags = scriptEvents.None;
if (m_stateEvents.ContainsKey(state))
{
m_stateEvents.TryGetValue(state, out eventFlags);
return eventFlags;
}
Type type=m_Script.GetType();
// Fill in the events for this state, cache the results in the map
foreach (KeyValuePair<string, scriptEvents> kvp in m_eventFlagsMap)
{
string evname = state + "_event_" + kvp.Key;
//m_log.Debug("Trying event "+evname);
try
{
MethodInfo mi = type.GetMethod(evname);
if (mi != null)
{
//m_log.Debug("Found handler for " + kvp.Key);
eventFlags |= kvp.Value;
}
}
catch(Exception)
{
//m_log.Debug("Exeption in GetMethod:\n"+e.ToString());
}
}
// Save the flags we just computed and return the result
if (eventFlags != 0)
m_stateEvents.Add(state, eventFlags);
//m_log.Debug("Returning {0:x}", eventFlags);
return (eventFlags);
}
public void ExecuteEvent(string state, string FunctionName, object[] args)
{
// IMPORTANT: Types and MemberInfo-derived objects require a LOT of memory.
// Instead use RuntimeTypeHandle, RuntimeFieldHandle and RunTimeHandle (IntPtr) instead!
string EventName = state + "_event_" + FunctionName;
//#if DEBUG
//m_log.Debug("ScriptEngine: Script event function name: " + EventName);
//#endif
if (Events.ContainsKey(EventName) == false)
{
// Not found, create
Type type = m_Script.GetType();
try
{
MethodInfo mi = type.GetMethod(EventName);
Events.Add(EventName, mi);
}
catch
{
// m_log.Error("Event "+EventName+" not found.");
// Event name not found, cache it as not found
Events.Add(EventName, null);
}
}
// Get event
MethodInfo ev = null;
Events.TryGetValue(EventName, out ev);
if (ev == null) // No event by that name!
{
//m_log.Debug("ScriptEngine Can not find any event named: \String.Empty + EventName + "\String.Empty);
return;
}
//cfk 2-7-08 dont need this right now and the default Linux build has DEBUG defined
#if DEBUG
//m_log.Debug("ScriptEngine: Executing function name: " + EventName);
#endif
// Found
try
{
ev.Invoke(m_Script, args);
}
catch(EventAbortException)
{
}
catch (TargetInvocationException tie)
{
// Grab the inner exception and rethrow it, unless the inner
// exception is an EventAbortException as this indicates event
// invocation termination due to a state change.
// DO NOT THROW JUST THE INNER EXCEPTION!
// FriendlyErrors depends on getting the whole exception!
//
if (!(tie.InnerException is EventAbortException))
{
throw;
}
}
}
protected void initEventFlags()
{
// Initialize the table if it hasn't already been done
if (m_eventFlagsMap.Count > 0)
{
return;
}
m_eventFlagsMap.Add("attach", scriptEvents.attach);
m_eventFlagsMap.Add("at_rot_target", scriptEvents.at_rot_target);
m_eventFlagsMap.Add("at_target", scriptEvents.at_target);
// m_eventFlagsMap.Add("changed",(long)scriptEvents.changed);
m_eventFlagsMap.Add("collision", scriptEvents.collision);
m_eventFlagsMap.Add("collision_end", scriptEvents.collision_end);
m_eventFlagsMap.Add("collision_start", scriptEvents.collision_start);
m_eventFlagsMap.Add("control", scriptEvents.control);
m_eventFlagsMap.Add("dataserver", scriptEvents.dataserver);
m_eventFlagsMap.Add("email", scriptEvents.email);
m_eventFlagsMap.Add("http_response", scriptEvents.http_response);
m_eventFlagsMap.Add("land_collision", scriptEvents.land_collision);
m_eventFlagsMap.Add("land_collision_end", scriptEvents.land_collision_end);
m_eventFlagsMap.Add("land_collision_start", scriptEvents.land_collision_start);
// m_eventFlagsMap.Add("link_message",scriptEvents.link_message);
m_eventFlagsMap.Add("listen", scriptEvents.listen);
m_eventFlagsMap.Add("money", scriptEvents.money);
m_eventFlagsMap.Add("moving_end", scriptEvents.moving_end);
m_eventFlagsMap.Add("moving_start", scriptEvents.moving_start);
m_eventFlagsMap.Add("not_at_rot_target", scriptEvents.not_at_rot_target);
m_eventFlagsMap.Add("not_at_target", scriptEvents.not_at_target);
// m_eventFlagsMap.Add("no_sensor",(long)scriptEvents.no_sensor);
// m_eventFlagsMap.Add("on_rez",(long)scriptEvents.on_rez);
m_eventFlagsMap.Add("remote_data", scriptEvents.remote_data);
m_eventFlagsMap.Add("run_time_permissions", scriptEvents.run_time_permissions);
// m_eventFlagsMap.Add("sensor",(long)scriptEvents.sensor);
m_eventFlagsMap.Add("state_entry", scriptEvents.state_entry);
m_eventFlagsMap.Add("state_exit", scriptEvents.state_exit);
m_eventFlagsMap.Add("timer", scriptEvents.timer);
m_eventFlagsMap.Add("touch", scriptEvents.touch);
m_eventFlagsMap.Add("touch_end", scriptEvents.touch_end);
m_eventFlagsMap.Add("touch_start", scriptEvents.touch_start);
m_eventFlagsMap.Add("transaction_result", scriptEvents.transaction_result);
m_eventFlagsMap.Add("object_rez", scriptEvents.object_rez);
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class ExtendRecordingRequest2Decoder
{
public const ushort BLOCK_LENGTH = 36;
public const ushort TEMPLATE_ID = 64;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private ExtendRecordingRequest2Decoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public ExtendRecordingRequest2Decoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public ExtendRecordingRequest2Decoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int RecordingIdId()
{
return 3;
}
public static int RecordingIdSinceVersion()
{
return 0;
}
public static int RecordingIdEncodingOffset()
{
return 16;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long RecordingId()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public static int StreamIdId()
{
return 4;
}
public static int StreamIdSinceVersion()
{
return 0;
}
public static int StreamIdEncodingOffset()
{
return 24;
}
public static int StreamIdEncodingLength()
{
return 4;
}
public static string StreamIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int StreamIdNullValue()
{
return -2147483648;
}
public static int StreamIdMinValue()
{
return -2147483647;
}
public static int StreamIdMaxValue()
{
return 2147483647;
}
public int StreamId()
{
return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian);
}
public static int SourceLocationId()
{
return 5;
}
public static int SourceLocationSinceVersion()
{
return 0;
}
public static int SourceLocationEncodingOffset()
{
return 28;
}
public static int SourceLocationEncodingLength()
{
return 4;
}
public static string SourceLocationMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public SourceLocation SourceLocation()
{
return (SourceLocation)_buffer.GetInt(_offset + 28, ByteOrder.LittleEndian);
}
public static int AutoStopId()
{
return 6;
}
public static int AutoStopSinceVersion()
{
return 0;
}
public static int AutoStopEncodingOffset()
{
return 32;
}
public static int AutoStopEncodingLength()
{
return 4;
}
public static string AutoStopMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public BooleanType AutoStop()
{
return (BooleanType)_buffer.GetInt(_offset + 32, ByteOrder.LittleEndian);
}
public static int ChannelId()
{
return 7;
}
public static int ChannelSinceVersion()
{
return 0;
}
public static string ChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ChannelHeaderLength()
{
return 4;
}
public int ChannelLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetChannel(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetChannel(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string Channel()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[ExtendRecordingRequest2](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("RecordingId=");
builder.Append(RecordingId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='streamId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("StreamId=");
builder.Append(StreamId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='sourceLocation', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=28, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=BEGIN_ENUM, name='SourceLocation', referencedName='null', description='Source location for recorded stream.', id=-1, version=0, deprecated=0, encodedLength=4, offset=28, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("SourceLocation=");
builder.Append(SourceLocation());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='autoStop', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=32, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=BEGIN_ENUM, name='BooleanType', referencedName='null', description='Language independent boolean type.', id=-1, version=0, deprecated=0, encodedLength=4, offset=32, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("AutoStop=");
builder.Append(AutoStop());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='channel', referencedName='null', description='null', id=7, version=0, deprecated=0, encodedLength=0, offset=36, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Channel=");
builder.Append(Channel());
Limit(originalLimit);
return builder;
}
}
}
| |
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
using Microsoft.Samples.RssPlatform.ScreenSaver.Rss;
namespace Microsoft.Samples.RssPlatform.ScreenSaver.UI
{
/// <summary>
/// Encapsulates the rendering of a list of items. Each item's description is shown in a list, and a single item is selected.
/// </summary>
/// <typeparam name="T">The type of item that this ItemListView will draw.</typeparam>
public class ItemListView<T> : IDisposable where T : IItem
{
private const float percentOfArticleDisplayBoxToFillWithText = 0.5f;
private const float percentOfFontHeightForSelectionBox = 1.5f;
private const int padding = 20;
// Where to draw
private Point location;
private Size size;
private FeedList feeds;
private Font itemFont;
private Font titleFont;
private Color backColor;
private Color borderColor;
private Color foreColor;
private Color titleBackColor;
private Color titleForeColor;
private Color selectedForeColor;
private Color selectedBackColor;
private float itemFontHeight;
// The maximum number of articles that will be displayed (defines viewport)
private int maxItemsToShow;
// The current first index of the article visible in viewport
private int firstItemToShow = 0;
// The minimum number of articles that will be displayed
// If there are fewer than this then there will be blank space in the display
private int minItemsToShow;
private int NumArticles { get { return Math.Min(feeds.CurrentFeed.Items.Count, maxItemsToShow); } }
private int NumArticleRows { get { return Math.Max(NumArticles, minItemsToShow); } }
public Point Location { get { return location; } set { location = value; } }
public Size Size { get { return size; } set { size = value; } }
public Color ForeColor { get { return foreColor; } set { foreColor = value; } }
public Color BackColor { get { return backColor; } set { backColor = value; } }
public Color BorderColor { get { return borderColor; } set { borderColor = value; } }
public Color TitleForeColor { get { return titleForeColor; } set { titleForeColor = value; } }
public Color TitleBackColor { get { return titleBackColor; } set { titleBackColor = value; } }
public Color SelectedForeColor { get { return selectedForeColor; } set { selectedForeColor = value; } }
public Color SelectedBackColor { get { return selectedBackColor; } set { selectedBackColor = value; } }
public int MaxItemsToShow { get { return maxItemsToShow; } set { maxItemsToShow = value; } }
public int MinItemsToShow { get { return minItemsToShow; } set { minItemsToShow = value; } }
public int RowHeight
{
get
{
// There is one row for each item plus 2 rows for the title.
return size.Height / (NumArticleRows + 2);
}
}
public Font ItemFont
{
get
{
// Choose a font for each of the item titles that will fit all numItems
// of them (plus some slack for the title) in the control
itemFontHeight = (float)(percentOfArticleDisplayBoxToFillWithText * RowHeight);
if (itemFont == null || itemFont.Size != itemFontHeight)
{
itemFont = new Font("Microsoft Sans Serif", itemFontHeight, GraphicsUnit.Pixel);
}
return itemFont;
}
}
public Font TitleFont
{
get
{
// Choose a font for the title text.
// This font will be twice as big as the ItemFont
float titleFontHeight = (float)(percentOfArticleDisplayBoxToFillWithText * 2 * RowHeight);
if (titleFont == null || titleFont.Size != titleFontHeight)
{
titleFont = new Font("Segoe UI", titleFontHeight, FontStyle.Italic ,GraphicsUnit.Pixel);
//titleFont = new Font("Microsoft Sans Serif", titleFontHeight, GraphicsUnit.Pixel);
}
return titleFont;
}
}
public ItemListView(FeedList feeds)
{
this.feeds = feeds;
}
public void Paint(PaintEventArgs args)
{
Graphics g = args.Graphics;
// Settings to make the text drawing look nice
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
DrawBackground(g);
IList<RssItem> items = feeds.CurrentFeed.Items;
// Determine the viewport for display
int index = feeds.CurrentItemIndex + 1;
if (firstItemToShow < index - maxItemsToShow) // selection at bottom
firstItemToShow = Math.Max(index - maxItemsToShow, 0);
else if (firstItemToShow >= index) // selection at top
firstItemToShow = feeds.CurrentItemIndex;
index = firstItemToShow;
// Draw each article's description
int row = 0;
while (row < maxItemsToShow && index < items.Count)
{
DrawItemTitle(g, row++, feeds.CurrentFeed.Items[index++]);
}
// Draw the title text
DrawTitle(g);
}
/// <summary>
/// Draws a box and border ontop of which the text of the items can be drawn.
/// </summary>
/// <param name="g">The Graphics object to draw onto</param>
private void DrawBackground(Graphics g)
{
using (Brush backBrush = new SolidBrush(BackColor))
using (Pen borderPen = new Pen(BorderColor, 4))
{
g.FillRectangle(backBrush, new Rectangle(Location.X + 4, Location.Y + 4, Size.Width - 8, Size.Height - 8));
g.DrawRectangle(borderPen, new Rectangle(Location, Size));
}
}
/// <summary>
/// Draws the title of the item with the given index.
/// </summary>
/// <param name="g">The Graphics object to draw onto</param>
/// <param name="index">The index of the item in the list</param>
private void DrawItemTitle(Graphics g, int row, RssItem rssItem)
{
// Set formatting and layout
StringFormat stringFormat = new StringFormat(StringFormatFlags.LineLimit);
stringFormat.Trimming = StringTrimming.EllipsisCharacter;
Rectangle articleRect = new Rectangle(Location.X + padding, Location.Y + (int)(row * RowHeight) + padding, Size.Width - (2 * padding), (int)(percentOfFontHeightForSelectionBox * itemFontHeight));
// Select color and draw border if current index is selected
Color textBrushColor = ForeColor;
if (rssItem == feeds.CurrentItem)
{
textBrushColor = SelectedForeColor;
using (Brush backBrush = new SolidBrush(SelectedBackColor))
{
g.FillRectangle(backBrush, articleRect);
}
}
// Draw the title of the item
string textToDraw = rssItem.Title;
if (rssItem.Enclosure != null)
{
bool exists;
//rssItem.Enclosure.Refresh();
exists = rssItem.Enclosure.Exists;
//exists = System.IO.File.Exists(rssItem.Enclosure.FullName);
textToDraw += " (" + (exists) + ")";
}
using (Brush textBrush = new SolidBrush(textBrushColor))
{
g.DrawString(textToDraw, ItemFont, textBrush, articleRect, stringFormat);
}
}
/// <summary>
/// Draws a title bar.
/// </summary>
/// <param name="g">The Graphics object to draw onto</param>
private void DrawTitle(Graphics g)
{
Point titleLocation = new Point(Location.X + padding, Location.Y + Size.Height - (RowHeight) - padding);
Size titleSize = new Size(Size.Width - (2 * padding), 2 * RowHeight);
Rectangle titleRectangle = new Rectangle(titleLocation, titleSize);
// Draw the title box and the selected item box
using (Brush titleBackBrush = new SolidBrush(TitleBackColor))
{
g.FillRectangle(titleBackBrush, titleRectangle);
}
// Draw the title text
StringFormat titleFormat = new StringFormat(StringFormatFlags.LineLimit);
titleFormat.Alignment = StringAlignment.Far;
titleFormat.Trimming = StringTrimming.EllipsisCharacter;
using (Brush titleBrush = new SolidBrush(TitleForeColor))
{
g.DrawString(feeds.CurrentFeed.Title, TitleFont, titleBrush, titleRectangle, titleFormat);
}
}
/// <summary>
/// Dispose all disposable fields
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (itemFont != null)
{
itemFont.Dispose();
itemFont = null;
}
if (TitleFont != null)
{
titleFont.Dispose();
titleFont = null;
}
}
}
}
}
| |
namespace Microsoft.Azure.Management.Blueprint
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for PublishedBlueprintsOperations.
/// </summary>
public static partial class ManagementGroupPublishedBlueprintsExtensions
{
/// <summary>
/// Publish a new version of the Blueprint with the latest artifacts. Published
/// Blueprints are immutable.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
public static PublishedBlueprint CreateInManagementGroup(this IPublishedBlueprintsOperations operations, string managementGroupName, string blueprintName, string versionId)
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
return operations.CreateAsync(scope, blueprintName, versionId).GetAwaiter().GetResult();
}
/// <summary>
/// Publish a new version of the Blueprint with the latest artifacts. Published
/// Blueprints are immutable.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
/// <param name='publishedBlueprint'>
/// published blueprint object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublishedBlueprint> CreateInManagementGroupAsync(this IPublishedBlueprintsOperations operations, string managementGroupName, string blueprintName, string versionId, PublishedBlueprint publishedBlueprint = default(PublishedBlueprint), CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
using (var _result = await operations.CreateWithHttpMessagesAsync(scope, blueprintName, versionId, publishedBlueprint, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a published Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
public static PublishedBlueprint GetInManagementGroup(this IPublishedBlueprintsOperations operations, string managementGroupName, string blueprintName, string versionId)
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
return operations.GetAsync(scope, blueprintName, versionId).GetAwaiter().GetResult();
}
/// <summary>
/// Get a published Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublishedBlueprint> GetInManagementGroupAsync(this IPublishedBlueprintsOperations operations, string managementGroupName, string blueprintName, string versionId, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
using (var _result = await operations.GetWithHttpMessagesAsync(scope, blueprintName, versionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete a published Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
public static PublishedBlueprint DeleteInManagementGroup(this IPublishedBlueprintsOperations operations, string managementGroupName, string blueprintName, string versionId)
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
return operations.DeleteAsync(scope, blueprintName, versionId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete a published Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublishedBlueprint> DeleteInManagementGroupAsync(this IPublishedBlueprintsOperations operations, string managementGroupName, string blueprintName, string versionId, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
using (var _result = await operations.DeleteWithHttpMessagesAsync(scope, blueprintName, versionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List published versions of given Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
public static IPage<PublishedBlueprint> ListInManagementGroup(this IPublishedBlueprintsOperations operations, string managementGroupName, string blueprintName)
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
return operations.ListAsync(scope, blueprintName).GetAwaiter().GetResult();
}
/// <summary>
/// List published versions of given Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='managementGroupName'>
/// azure managementGroup name, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublishedBlueprint>> ListInManagementGroupAsync(this IPublishedBlueprintsOperations operations, string managementGroupName, string blueprintName, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);
using (var _result = await operations.ListWithHttpMessagesAsync(scope, blueprintName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.EventQueue;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class GroupsMessagingModule : ISharedRegionModule, IGroupsMessagingModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_sceneList = new List<Scene>();
private IMessageTransferModule m_msgTransferModule = null;
private IGroupsServicesConnector m_groupData = null;
// Config Options
private bool m_groupMessagingEnabled = false;
private bool m_debugEnabled = true;
#region IRegionModuleBase Members
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
// if groups aren't enabled, we're not needed.
// if we're not specified as the connector to use, then we're not wanted
if ((groupsConfig.GetBoolean("Enabled", false) == false)
|| (groupsConfig.GetString("MessagingModule", "Default") != Name))
{
m_groupMessagingEnabled = false;
return;
}
m_groupMessagingEnabled = groupsConfig.GetBoolean("MessagingEnabled", true);
if (!m_groupMessagingEnabled)
{
return;
}
m_log.Info("[GROUPS-MESSAGING]: Initializing GroupsMessagingModule");
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true);
}
m_log.Info("[GROUPS-MESSAGING]: GroupsMessagingModule starting up");
}
public void AddRegion(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
scene.RegisterModuleInterface<IGroupsMessagingModule>(this);
}
public void RegionLoaded(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>();
// No groups module, no groups messaging
if (m_groupData == null)
{
m_log.Error("[GROUPS-MESSAGING]: Could not get IGroupsServicesConnector, GroupsMessagingModule is now disabled.");
Close();
m_groupMessagingEnabled = false;
return;
}
m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
// No message transfer module, no groups messaging
if (m_msgTransferModule == null)
{
m_log.Error("[GROUPS-MESSAGING]: Could not get MessageTransferModule");
Close();
m_groupMessagingEnabled = false;
return;
}
m_sceneList.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
}
public void RemoveRegion(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_sceneList.Remove(scene);
}
public void Close()
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.Debug("[GROUPS-MESSAGING]: Shutting down GroupsMessagingModule module.");
foreach (Scene scene in m_sceneList)
{
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
}
m_sceneList.Clear();
m_groupData = null;
m_msgTransferModule = null;
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "GroupsMessagingModule"; }
}
#endregion
#region ISharedRegionModule Members
public void PostInitialise()
{
// NoOp
}
#endregion
/// <summary>
/// Not really needed, but does confirm that the group exists.
/// </summary>
public bool StartGroupChatSession(UUID agentID, UUID groupID)
{
if (m_debugEnabled)
m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID, groupID, null);
if (groupInfo != null)
{
return true;
}
else
{
return false;
}
}
public void SendMessageToGroup(GridInstantMessage im, UUID groupID)
{
if (m_debugEnabled)
m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
foreach (GroupMembersData member in m_groupData.GetGroupMembers(UUID.Zero, groupID))
{
if (m_groupData.hasAgentDroppedGroupChatSession(member.AgentID, groupID))
{
// Don't deliver messages to people who have dropped this session
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} has dropped session, not delivering to them", member.AgentID);
continue;
}
// Copy Message
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = groupID.Guid;
msg.fromAgentName = im.fromAgentName;
msg.message = im.message;
msg.dialog = im.dialog;
msg.offline = im.offline;
msg.ParentEstateID = im.ParentEstateID;
msg.Position = im.Position;
msg.RegionID = im.RegionID;
msg.binaryBucket = im.binaryBucket;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.fromAgentID = im.fromAgentID;
msg.fromGroup = true;
msg.toAgentID = member.AgentID.Guid;
IClientAPI client = GetActiveClient(member.AgentID);
if (client == null)
{
// If they're not local, forward across the grid
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} via Grid", member.AgentID);
m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { });
}
else
{
// Deliver locally, directly
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", client.Name);
ProcessMessageFromGroupSession(msg);
}
}
}
#region SimGridEventHandlers
private void OnNewClient(IClientAPI client)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage registered for {0}", client.Name);
client.OnInstantMessage += OnInstantMessage;
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
// The instant message module will only deliver messages of dialog types:
// MessageFromAgent, StartTyping, StopTyping, MessageFromObject
//
// Any other message type will not be delivered to a client by the
// Instant Message Module
if (m_debugEnabled)
{
m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
DebugGridInstantMessage(msg);
}
// Incoming message from a group
if ((msg.fromGroup == true) &&
((msg.dialog == (byte)InstantMessageDialog.SessionSend)
|| (msg.dialog == (byte)InstantMessageDialog.SessionAdd)
|| (msg.dialog == (byte)InstantMessageDialog.SessionDrop)))
{
ProcessMessageFromGroupSession(msg);
}
}
private void ProcessMessageFromGroupSession(GridInstantMessage msg)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID);
UUID AgentID = new UUID(msg.fromAgentID);
UUID GroupID = new UUID(msg.imSessionID);
switch (msg.dialog)
{
case (byte)InstantMessageDialog.SessionAdd:
m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID);
break;
case (byte)InstantMessageDialog.SessionDrop:
m_groupData.AgentDroppedFromGroupChatSession(AgentID, GroupID);
break;
case (byte)InstantMessageDialog.SessionSend:
if (!m_groupData.hasAgentDroppedGroupChatSession(AgentID, GroupID)
&& !m_groupData.hasAgentBeenInvitedToGroupChatSession(AgentID, GroupID)
)
{
// Agent not in session and hasn't dropped from session
// Add them to the session for now, and Invite them
m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID);
UUID toAgentID = new UUID(msg.toAgentID);
IClientAPI activeClient = GetActiveClient(toAgentID);
if (activeClient != null)
{
GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero, GroupID, null);
if (groupInfo != null)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Sending chatterbox invite instant message");
// Force? open the group session dialog???
// and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg);
IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>();
eq.ChatterboxInvitation(
GroupID
, groupInfo.GroupName
, new UUID(msg.fromAgentID)
, msg.message
, new UUID(msg.toAgentID)
, msg.fromAgentName
, msg.dialog
, msg.timestamp
, msg.offline == 1
, (int)msg.ParentEstateID
, msg.Position
, 1
, new UUID(msg.imSessionID)
, msg.fromGroup
, Utils.StringToBytes(groupInfo.GroupName)
);
eq.ChatterBoxSessionAgentListUpdates(
new UUID(GroupID)
, new UUID(msg.fromAgentID)
, new UUID(msg.toAgentID)
, false //canVoiceChat
, false //isModerator
, false //text mute
);
}
}
}
else if (!m_groupData.hasAgentDroppedGroupChatSession(AgentID, GroupID))
{
// User hasn't dropped, so they're in the session,
// maybe we should deliver it.
IClientAPI client = GetActiveClient(new UUID(msg.toAgentID));
if (client != null)
{
// Deliver locally, directly
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} locally", client.Name);
client.SendInstantMessage(msg);
}
else
{
m_log.WarnFormat("[GROUPS-MESSAGING]: Received a message over the grid for a client that isn't here: {0}", msg.toAgentID);
}
}
break;
default:
m_log.WarnFormat("[GROUPS-MESSAGING]: I don't know how to proccess a {0} message.", ((InstantMessageDialog)msg.dialog).ToString());
break;
}
}
#endregion
#region ClientEvents
private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
{
if (m_debugEnabled)
{
m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
DebugGridInstantMessage(im);
}
// Start group IM session
if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart))
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS-MESSAGING]: imSessionID({0}) toAgentID({1})", im.imSessionID, im.toAgentID);
UUID GroupID = new UUID(im.imSessionID);
UUID AgentID = new UUID(im.fromAgentID);
GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero, GroupID, null);
if (groupInfo != null)
{
m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID);
ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID);
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
queue.ChatterBoxSessionAgentListUpdates(
GroupID
, AgentID
, new UUID(im.toAgentID)
, false //canVoiceChat
, false //isModerator
, false //text mute
);
}
}
// Send a message from locally connected client to a group
if ((im.dialog == (byte)InstantMessageDialog.SessionSend))
{
UUID GroupID = new UUID(im.imSessionID);
UUID AgentID = new UUID(im.fromAgentID);
if (m_debugEnabled)
m_log.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", GroupID, im.imSessionID.ToString());
//If this agent is sending a message, then they want to be in the session
m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID);
SendMessageToGroup(im, GroupID);
}
}
#endregion
void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap moderatedMap = new OSDMap(4);
moderatedMap.Add("voice", OSD.FromBoolean(false));
OSDMap sessionMap = new OSDMap(4);
sessionMap.Add("moderated_mode", moderatedMap);
sessionMap.Add("session_name", OSD.FromString(groupName));
sessionMap.Add("type", OSD.FromInteger(0));
sessionMap.Add("voice_enabled", OSD.FromBoolean(false));
OSDMap bodyMap = new OSDMap(4);
bodyMap.Add("session_id", OSD.FromUUID(groupID));
bodyMap.Add("temp_session_id", OSD.FromUUID(groupID));
bodyMap.Add("success", OSD.FromBoolean(true));
bodyMap.Add("session_info", sessionMap);
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
if (queue != null)
{
queue.Enqueue(EventQueueHelper.buildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
}
}
private void DebugGridInstantMessage(GridInstantMessage im)
{
// Don't log any normal IMs (privacy!)
if (m_debugEnabled && im.dialog != (byte)InstantMessageDialog.MessageFromAgent)
{
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromGroup({0})", im.fromGroup ? "True" : "False");
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: Dialog({0})", ((InstantMessageDialog)im.dialog).ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentID({0})", im.fromAgentID.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentName({0})", im.fromAgentName.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: imSessionID({0})", im.imSessionID.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: message({0})", im.message.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: offline({0})", im.offline.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: toAgentID({0})", im.toAgentID.ToString());
m_log.WarnFormat("[GROUPS-MESSAGING]: IM: binaryBucket({0})", OpenMetaverse.Utils.BytesToHexString(im.binaryBucket, "BinaryBucket"));
}
}
#region Client Tools
/// <summary>
/// Try to find an active IClientAPI reference for agentID giving preference to root connections
/// </summary>
private IClientAPI GetActiveClient(UUID agentID)
{
if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Looking for local client {0}", agentID);
IClientAPI child = null;
// Try root avatar first
foreach (Scene scene in m_sceneList)
{
if (scene.Entities.ContainsKey(agentID) &&
scene.Entities[agentID] is ScenePresence)
{
ScenePresence user = (ScenePresence)scene.Entities[agentID];
if (!user.IsChildAgent)
{
if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Found root agent for client : {0}", user.ControllingClient.Name);
return user.ControllingClient;
}
else
{
if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Found child agent for client : {0}", user.ControllingClient.Name);
child = user.ControllingClient;
}
}
}
// If we didn't find a root, then just return whichever child we found, or null if none
if (child == null)
{
if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Could not find local client for agent : {0}", agentID);
}
else
{
if (m_debugEnabled) m_log.WarnFormat("[GROUPS-MESSAGING]: Returning child agent for client : {0}", child.Name);
}
return child;
}
#endregion
}
}
| |
using System;
using System.Web;
using umbraco.presentation.LiveEditing;
using umbraco.BasePages;
using umbraco.cms.businesslogic.web;
namespace umbraco.presentation
{
/// <summary>
/// A custom HttpResponseBase class
///
/// The only reason this class exists is for backwards compatibility. Previously this used to
/// inherit from HttpResponseWrapper which is incorrect since it is not unit testable and means that
/// it still has a reliance on the real HttpResponse object which means that the UmbracoContext still has
/// a reliance on the real HttpContext.
/// </summary>
[Obsolete("This class is no longer used")]
public class UmbracoResponse : HttpResponseBase
{
private readonly HttpResponseBase _response;
#region Contructor
public UmbracoResponse(HttpResponseBase response)
{
_response = response;
}
public UmbracoResponse(HttpResponse response)
{
_response = new HttpResponseWrapper(response);
}
#endregion
#region Wrapped methods
public override void AddCacheDependency(params System.Web.Caching.CacheDependency[] dependencies)
{
base.AddCacheDependency(dependencies);
}
public override void AddCacheItemDependencies(string[] cacheKeys)
{
base.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheItemDependencies(System.Collections.ArrayList cacheKeys)
{
base.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheItemDependency(string cacheKey)
{
base.AddCacheItemDependency(cacheKey);
}
public override void AddFileDependencies(string[] filenames)
{
base.AddFileDependencies(filenames);
}
public override void AddFileDependencies(System.Collections.ArrayList filenames)
{
base.AddFileDependencies(filenames);
}
public override void AddFileDependency(string filename)
{
base.AddFileDependency(filename);
}
public override void AddHeader(string name, string value)
{
base.AddHeader(name, value);
}
public override void AppendCookie(HttpCookie cookie)
{
base.AppendCookie(cookie);
}
public override void AppendHeader(string name, string value)
{
base.AppendHeader(name, value);
}
public override void AppendToLog(string param)
{
base.AppendToLog(param);
}
public override string ApplyAppPathModifier(string virtualPath)
{
return base.ApplyAppPathModifier(virtualPath);
}
public override void BinaryWrite(byte[] buffer)
{
base.BinaryWrite(buffer);
}
public override bool Buffer
{
get
{
return base.Buffer;
}
set
{
base.Buffer = value;
}
}
public override bool BufferOutput
{
get
{
return base.BufferOutput;
}
set
{
base.BufferOutput = value;
}
}
public override HttpCachePolicyBase Cache
{
get
{
return base.Cache;
}
}
public override string CacheControl
{
get
{
return base.CacheControl;
}
set
{
base.CacheControl = value;
}
}
public override string Charset
{
get
{
return base.Charset;
}
set
{
base.Charset = value;
}
}
public override void Clear()
{
base.Clear();
}
public override void ClearContent()
{
base.ClearContent();
}
public override void ClearHeaders()
{
base.ClearHeaders();
}
public override void Close()
{
base.Close();
}
public override System.Text.Encoding ContentEncoding
{
get
{
return base.ContentEncoding;
}
set
{
base.ContentEncoding = value;
}
}
public override string ContentType
{
get
{
return base.ContentType;
}
set
{
base.ContentType = value;
}
}
public override HttpCookieCollection Cookies
{
get
{
return base.Cookies;
}
}
public override void DisableKernelCache()
{
base.DisableKernelCache();
}
public override void End()
{
base.End();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int Expires
{
get
{
return base.Expires;
}
set
{
base.Expires = value;
}
}
public override DateTime ExpiresAbsolute
{
get
{
return base.ExpiresAbsolute;
}
set
{
base.ExpiresAbsolute = value;
}
}
public override System.IO.Stream Filter
{
get
{
return base.Filter;
}
set
{
base.Filter = value;
}
}
public override void Flush()
{
base.Flush();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override System.Text.Encoding HeaderEncoding
{
get
{
return base.HeaderEncoding;
}
set
{
base.HeaderEncoding = value;
}
}
public override System.Collections.Specialized.NameValueCollection Headers
{
get
{
return base.Headers;
}
}
public override bool IsClientConnected
{
get
{
return base.IsClientConnected;
}
}
public override bool IsRequestBeingRedirected
{
get
{
return base.IsRequestBeingRedirected;
}
}
public override System.IO.TextWriter Output
{
get
{
return base.Output;
}
set
{
base.Output = value;
}
}
public override System.IO.Stream OutputStream
{
get
{
return base.OutputStream;
}
}
public override void Pics(string value)
{
base.Pics(value);
}
public override void Redirect(string url)
{
base.Redirect(url);
}
public override void Redirect(string url, bool endResponse)
{
base.Redirect(url, endResponse);
}
public override string RedirectLocation
{
get
{
return base.RedirectLocation;
}
set
{
base.RedirectLocation = value;
}
}
public override void RedirectPermanent(string url)
{
base.RedirectPermanent(url);
}
public override void RedirectPermanent(string url, bool endResponse)
{
base.RedirectPermanent(url, endResponse);
}
public override void RedirectToRoute(object routeValues)
{
base.RedirectToRoute(routeValues);
}
public override void RedirectToRoute(string routeName)
{
base.RedirectToRoute(routeName);
}
public override void RedirectToRoute(string routeName, object routeValues)
{
base.RedirectToRoute(routeName, routeValues);
}
public override void RedirectToRoute(string routeName, System.Web.Routing.RouteValueDictionary routeValues)
{
base.RedirectToRoute(routeName, routeValues);
}
public override void RedirectToRoute(System.Web.Routing.RouteValueDictionary routeValues)
{
base.RedirectToRoute(routeValues);
}
public override void RedirectToRoutePermanent(object routeValues)
{
base.RedirectToRoutePermanent(routeValues);
}
public override void RedirectToRoutePermanent(string routeName)
{
base.RedirectToRoutePermanent(routeName);
}
public override void RedirectToRoutePermanent(string routeName, object routeValues)
{
base.RedirectToRoutePermanent(routeName, routeValues);
}
public override void RedirectToRoutePermanent(string routeName, System.Web.Routing.RouteValueDictionary routeValues)
{
base.RedirectToRoutePermanent(routeName, routeValues);
}
public override void RedirectToRoutePermanent(System.Web.Routing.RouteValueDictionary routeValues)
{
base.RedirectToRoutePermanent(routeValues);
}
public override void RemoveOutputCacheItem(string path)
{
base.RemoveOutputCacheItem(path);
}
public override void RemoveOutputCacheItem(string path, string providerName)
{
base.RemoveOutputCacheItem(path, providerName);
}
public override void SetCookie(HttpCookie cookie)
{
base.SetCookie(cookie);
}
public override string Status
{
get
{
return base.Status;
}
set
{
base.Status = value;
}
}
public override int StatusCode
{
get
{
return base.StatusCode;
}
set
{
base.StatusCode = value;
}
}
public override string StatusDescription
{
get
{
return base.StatusDescription;
}
set
{
base.StatusDescription = value;
}
}
public override int SubStatusCode
{
get
{
return base.SubStatusCode;
}
set
{
base.SubStatusCode = value;
}
}
public override bool SuppressContent
{
get
{
return base.SuppressContent;
}
set
{
base.SuppressContent = value;
}
}
public override string ToString()
{
return base.ToString();
}
public override void TransmitFile(string filename)
{
base.TransmitFile(filename);
}
public override void TransmitFile(string filename, long offset, long length)
{
base.TransmitFile(filename, offset, length);
}
public override bool TrySkipIisCustomErrors
{
get
{
return base.TrySkipIisCustomErrors;
}
set
{
base.TrySkipIisCustomErrors = value;
}
}
public override void Write(char ch)
{
base.Write(ch);
}
public override void Write(char[] buffer, int index, int count)
{
base.Write(buffer, index, count);
}
public override void Write(object obj)
{
base.Write(obj);
}
public override void Write(string s)
{
base.Write(s);
}
public override void WriteFile(IntPtr fileHandle, long offset, long size)
{
base.WriteFile(fileHandle, offset, size);
}
public override void WriteFile(string filename)
{
base.WriteFile(filename);
}
public override void WriteFile(string filename, bool readIntoMemory)
{
base.WriteFile(filename, readIntoMemory);
}
public override void WriteFile(string filename, long offset, long size)
{
base.WriteFile(filename, offset, size);
}
public override void WriteSubstitution(HttpResponseSubstitutionCallback callback)
{
base.WriteSubstitution(callback);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
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;
public static IRetryPolicy QueueOperationRetryPolicy;
static AzureQueueDefaultPolicies()
{
MaxQueueOperationRetries = 5;
PauseBetweenQueueOperationRetries = TimeSpan.FromMilliseconds(100);
QueueOperationRetryPolicy = new LinearRetry(PauseBetweenQueueOperationRetries, MaxQueueOperationRetries); // 5 x 100ms
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; }
private string connectionString { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
private readonly Logger logger;
private readonly CloudQueueClient queueOperationsClient;
private CloudQueue queue;
/// <summary>
/// Constructor.
/// </summary>
/// <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>
public AzureQueueDataManager(string queueName, string storageConnectionString)
{
AzureStorageUtils.ValidateQueueName(queueName);
logger = LogManager.GetLogger(this.GetType().Name, LoggerType.Runtime);
QueueName = queueName;
connectionString = storageConnectionString;
queueOperationsClient = AzureStorageUtils.GetCloudQueueClient(
connectionString,
AzureQueueDefaultPolicies.QueueOperationRetryPolicy,
AzureQueueDefaultPolicies.QueueOperationTimeout,
logger);
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="queueName">Name of the queue to be connected to.</param>
/// <param name="deploymentId">The deployment id of the Azure service hosting this silo. It will be concatenated to the queueName.</param>
/// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param>
public AzureQueueDataManager(string queueName, string deploymentId, string storageConnectionString)
{
AzureStorageUtils.ValidateQueueName(queueName);
logger = LogManager.GetLogger(this.GetType().Name, LoggerType.Runtime);
QueueName = deploymentId + "-" + queueName;
AzureStorageUtils.ValidateQueueName(QueueName);
connectionString = storageConnectionString;
queueOperationsClient = AzureStorageUtils.GetCloudQueueClient(
connectionString,
AzureQueueDefaultPolicies.QueueOperationRetryPolicy,
AzureQueueDefaultPolicies.QueueOperationTimeout,
logger);
}
/// <summary>
/// Initializes the connection to the queue.
/// </summary>
public async Task InitQueueAsync()
{
var startTime = DateTime.UtcNow;
try
{
// Retrieve a reference to a queue.
// Not sure if this is a blocking call or not. Did not find an alternative async API. Should probably use BeginListQueuesSegmented.
var myQueue = queueOperationsClient.GetQueueReference(QueueName);
// Create the queue if it doesn't already exist.
bool didCreate = await Task<bool>.Factory.FromAsync(myQueue.BeginCreateIfNotExists, myQueue.EndCreateIfNotExists, null);
queue = myQueue;
logger.Info(ErrorCode.AzureQueue_01, "{0} Azure storage queue {1}", (didCreate ? "Created" : "Attached to"), QueueName);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "CreateIfNotExist", ErrorCode.AzureQueue_02);
}
finally
{
CheckAlertSlowAccess(startTime, "InitQueue_Async");
}
}
/// <summary>
/// Deletes the queue.
/// </summary>
public async Task DeleteQueue()
{
var startTime = DateTime.UtcNow;
if (logger.IsVerbose2) logger.Verbose2("Deleting queue: {0}", QueueName);
try
{
// that way we don't have first to create the queue to be able later to delete it.
CloudQueue queueRef = queue ?? queueOperationsClient.GetQueueReference(QueueName);
var exists = Task<bool>.Factory.FromAsync(queueRef.BeginExists, queueRef.EndExists, null);
if (await exists)
{
await Task.Factory.FromAsync(queueRef.BeginDelete, queueRef.EndDelete, null);
logger.Info(ErrorCode.AzureQueue_03, "Deleted Azure Queue {0}", QueueName);
}
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "DeleteQueue", ErrorCode.AzureQueue_04);
}
finally
{
CheckAlertSlowAccess(startTime, "DeleteQueue");
}
}
/// <summary>
/// Clears the queue.
/// </summary>
public async Task ClearQueue()
{
var startTime = DateTime.UtcNow;
if (logger.IsVerbose2) logger.Verbose2("Clearing a queue: {0}", QueueName);
try
{
// that way we don't have first to create the queue to be able later to delete it.
CloudQueue queueRef = queue ?? queueOperationsClient.GetQueueReference(QueueName);
await Task.Factory.FromAsync(queueRef.BeginClear, queueRef.EndClear, null);
logger.Info(ErrorCode.AzureQueue_05, "Cleared Azure Queue {0}", QueueName);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "ClearQueue", ErrorCode.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(CloudQueueMessage message)
{
var startTime = DateTime.UtcNow;
if (logger.IsVerbose2) logger.Verbose2("Adding message {0} to queue: {1}", message, QueueName);
try
{
await Task.Factory.FromAsync(
queue.BeginAddMessage, queue.EndAddMessage, message, null);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "AddQueueMessage", ErrorCode.AzureQueue_07);
}
finally
{
CheckAlertSlowAccess(startTime, "AddQueueMessage");
}
}
/// <summary>
/// Peeks in the queue for latest message, without dequeueing it.
/// </summary>
public async Task<CloudQueueMessage> PeekQueueMessage()
{
var startTime = DateTime.UtcNow;
if (logger.IsVerbose2) logger.Verbose2("Peeking a message from queue: {0}", QueueName);
try
{
return await Task<CloudQueueMessage>.Factory.FromAsync(
queue.BeginPeekMessage, queue.EndPeekMessage, null);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "PeekQueueMessage", ErrorCode.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<CloudQueueMessage> GetQueueMessage()
{
var startTime = DateTime.UtcNow;
if (logger.IsVerbose2) logger.Verbose2("Getting a message from queue: {0}", QueueName);
try
{
// http://msdn.microsoft.com/en-us/library/ee758456.aspx
// If no messages are visible in the queue, GetMessage returns null.
return await Task<CloudQueueMessage>.Factory.FromAsync(
queue.BeginGetMessage, queue.EndGetMessage, null);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "GetQueueMessage", ErrorCode.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<CloudQueueMessage>> GetQueueMessages(int count = -1)
{
var startTime = DateTime.UtcNow;
if (count == -1)
{
count = CloudQueueMessage.MaxNumberOfMessagesToPeek;
}
if (logger.IsVerbose2) logger.Verbose2("Getting up to {0} messages from queue: {1}", count, QueueName);
try
{
return await Task<IEnumerable<CloudQueueMessage>>.Factory.FromAsync(
queue.BeginGetMessages, queue.EndGetMessages, count, null);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "GetQueueMessages", ErrorCode.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(CloudQueueMessage message)
{
var startTime = DateTime.UtcNow;
if (logger.IsVerbose2) logger.Verbose2("Deleting a message from queue: {0}", QueueName);
try
{
await Task.Factory.FromAsync(
queue.BeginDeleteMessage, queue.EndDeleteMessage, message.Id, message.PopReceipt, null);
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "DeleteMessage", ErrorCode.AzureQueue_11);
}
finally
{
CheckAlertSlowAccess(startTime, "DeleteQueueMessage");
}
}
internal async Task GetAndDeleteQueueMessage()
{
CloudQueueMessage 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.IsVerbose2) logger.Verbose2("GetApproximateMessageCount a message from queue: {0}", QueueName);
try
{
await Task.Factory.FromAsync(queue.BeginFetchAttributes, queue.EndFetchAttributes, null);
return queue.ApproximateMessageCount.HasValue ? queue.ApproximateMessageCount.Value : 0;
}
catch (Exception exc)
{
ReportErrorAndRethrow(exc, "FetchAttributes", ErrorCode.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(ErrorCode.AzureQueue_13, "Slow access to Azure queue {0} for {1}, which took {2}.", QueueName, operation, timeSpan);
}
}
private void ReportErrorAndRethrow(Exception exc, string operation, ErrorCode errorCode)
{
var errMsg = String.Format(
"Error doing {0} for Azure storage queue {1} " + Environment.NewLine
+ "Exception = {2}", operation, QueueName, exc);
logger.Error(errorCode, errMsg, exc);
throw new AggregateException(errMsg, exc);
}
}
}
| |
//
// ImageLoaderThread.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Larry Ewing <lewing@novell.com>
// Ettore Perazzoli <ettore@src.gnome.org>
//
// Copyright (C) 2003-2010 Novell, Inc.
// Copyright (C) 2009-2010 Ruben Vermeersch
// Copyright (C) 2003-2006 Larry Ewing
// Copyright (C) 2003 Ettore Perazzoli
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using FSpot.Imaging;
using Gdk;
using Gtk;
using Hyena;
namespace FSpot.Imaging
{
public class ImageLoaderThread : IImageLoaderThread
{
#region Private members.
static List<ImageLoaderThread> instances = new List<ImageLoaderThread> ();
/* The thread used to handle the requests. */
Thread worker_thread;
/* The request queue; it's shared between the threads so it
needs to be locked prior to access. */
List<RequestItem> queue;
/* A dict of all the requests; note that the current request
isn't in the dict. */
Dictionary<SafeUri, RequestItem> requests_by_uri;
/* Current request. Request currently being handled by the
auxiliary thread. Should be modified only by the auxiliary
thread (the GTK thread can only read it). */
RequestItem current_request;
/* The queue of processed requests. */
readonly Queue processed_requests;
/* This is used by the helper thread to notify the main GLib
thread that there are pending items in the
`processed_requests' queue. */
ThreadNotify pending_notify;
/* Whether a notification is pending on `pending_notify'
already or not. */
bool pending_notify_notified;
volatile bool should_cancel;
readonly IImageFileFactory imageFileFactory;
#endregion
#region Public API
public event PixbufLoadedHandler OnPixbufLoaded;
public ImageLoaderThread (IImageFileFactory imageFileFactory)
{
this.imageFileFactory = imageFileFactory;
queue = new List<RequestItem> ();
requests_by_uri = new Dictionary<SafeUri, RequestItem> ();
// requests_by_path = Hashtable.Synchronized (new Hashtable ());
processed_requests = new Queue ();
pending_notify = new ThreadNotify (new Gtk.ReadyEvent (HandleProcessedRequests));
instances.Add (this);
}
void StartWorker ()
{
if (worker_thread != null) {
return;
}
should_cancel = false;
worker_thread = new Thread (new ThreadStart (WorkerThread));
worker_thread.Start ();
}
int block_count;
public void PushBlock ()
{
Interlocked.Increment (ref block_count);
}
public void PopBlock ()
{
if (Interlocked.Decrement (ref block_count) == 0) {
lock (queue) {
Monitor.Pulse (queue);
}
}
}
public void Cleanup ()
{
should_cancel = true;
if (worker_thread != null) {
lock (queue) {
Monitor.Pulse (queue);
}
worker_thread.Join ();
}
worker_thread = null;
}
public static void CleanAll ()
{
foreach (var thread in instances) {
thread.Cleanup ();
}
}
public void Request (SafeUri uri, int order)
{
Request (uri, order, 0, 0);
}
public virtual void Request (SafeUri uri, int order, int width, int height)
{
lock (queue) {
if (InsertRequest (uri, order, width, height)) {
Monitor.Pulse (queue);
}
}
}
public void Cancel (SafeUri uri)
{
lock (queue) {
RequestItem r = requests_by_uri [uri];
if (r != null) {
requests_by_uri.Remove (uri);
queue.Remove (r);
r.Dispose ();
}
}
}
#endregion
#region Private utility methods.
protected virtual void ProcessRequest (RequestItem request)
{
Pixbuf orig_image;
try {
using (var img = imageFileFactory.Create (request.Uri)) {
if (request.Width > 0) {
orig_image = img.Load (request.Width, request.Height);
} else {
orig_image = img.Load ();
}
}
} catch (GLib.GException e) {
Log.Exception (e);
return;
}
if (orig_image == null) {
return;
}
request.Result = orig_image;
}
/* Insert the request in the queue, return TRUE if the queue actually grew.
NOTE: Lock the queue before calling. */
bool InsertRequest (SafeUri uri, int order, int width, int height)
{
StartWorker ();
/* Check if this is the same as the request currently being processed. */
lock (processed_requests) {
if (current_request != null && current_request.Uri == uri) {
return false;
}
}
/* Check if a request for this path has already been queued. */
RequestItem existing_request;
if (requests_by_uri.TryGetValue (uri, out existing_request)) {
/* FIXME: At least for now, this shouldn't happen. */
if (existing_request.Order != order) {
Log.WarningFormat ("BUG: Filing another request of order {0} (previously {1}) for `{2}'",
order, existing_request.Order, uri);
}
queue.Remove (existing_request);
queue.Add (existing_request);
return false;
}
/* New request, just put it on the queue with the right order. */
RequestItem new_request = new RequestItem (uri, order, width, height);
queue.Add (new_request);
lock (queue) {
requests_by_uri.Add (uri, new_request);
}
return true;
}
/* The worker thread's main function. */
void WorkerThread ()
{
Log.Debug (ToString (), "Worker starting");
try {
while (!should_cancel) {
lock (processed_requests) {
if (current_request != null) {
processed_requests.Enqueue (current_request);
if (! pending_notify_notified) {
pending_notify.WakeupMain ();
pending_notify_notified = true;
}
current_request = null;
}
}
lock (queue) {
while ((queue.Count == 0 || block_count > 0) && !should_cancel) {
Monitor.Wait (queue);
}
if (should_cancel) {
return;
}
int pos = queue.Count - 1;
current_request = queue [pos];
queue.RemoveAt (pos);
requests_by_uri.Remove (current_request.Uri);
}
ProcessRequest (current_request);
}
} catch (ThreadAbortException) {
//Aborting
}
}
protected virtual void EmitLoaded (Queue results)
{
if (OnPixbufLoaded != null) {
foreach (RequestItem r in results) {
OnPixbufLoaded (this, r);
}
}
}
void HandleProcessedRequests ()
{
Queue results;
lock (processed_requests) {
/* Copy the queued items out of the shared queue so we hold the lock for
as little time as possible. */
results = processed_requests.Clone () as Queue;
processed_requests.Clear ();
pending_notify_notified = false;
}
EmitLoaded (results);
foreach (RequestItem request in results){
request.Dispose ();
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Common
{
using JetBrains.Annotations;
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using NLog.Internal;
using NLog.Time;
using NLog.Targets;
/// <summary>
/// NLog internal logger.
///
/// Writes to file, console or custom text writer (see <see cref="InternalLogger.LogWriter"/>)
/// </summary>
/// <remarks>
/// Don't use <see cref="ExceptionHelper.MustBeRethrown"/> as that can lead to recursive calls - stackoverflow
/// </remarks>
public static partial class InternalLogger
{
private static readonly object LockObject = new object();
private static string _logFile;
/// <summary>
/// Initializes static members of the InternalLogger class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static InternalLogger()
{
Reset();
}
/// <summary>
/// Set the config of the InternalLogger with defaults and config.
/// </summary>
public static void Reset()
{
// TODO: Extract class - InternalLoggerConfigurationReader
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
LogToConsole = GetSetting("nlog.internalLogToConsole", "NLOG_INTERNAL_LOG_TO_CONSOLE", false);
LogToConsoleError = GetSetting("nlog.internalLogToConsoleError", "NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR", false);
LogLevel = GetSetting("nlog.internalLogLevel", "NLOG_INTERNAL_LOG_LEVEL", LogLevel.Info);
LogFile = GetSetting("nlog.internalLogFile", "NLOG_INTERNAL_LOG_FILE", string.Empty);
LogToTrace = GetSetting("nlog.internalLogToTrace", "NLOG_INTERNAL_LOG_TO_TRACE", false);
IncludeTimestamp = GetSetting("nlog.internalLogIncludeTimestamp", "NLOG_INTERNAL_INCLUDE_TIMESTAMP", true);
Info("NLog internal logger initialized.");
#else
LogLevel = LogLevel.Info;
LogToConsole = false;
LogToConsoleError = false;
LogFile = string.Empty;
IncludeTimestamp = true;
#endif
ExceptionThrowWhenWriting = false;
LogWriter = null;
LogMessageReceived = null;
}
/// <summary>
/// Gets or sets the minimal internal log level.
/// </summary>
/// <example>If set to <see cref="NLog.LogLevel.Info"/>, then messages of the levels <see cref="NLog.LogLevel.Info"/>, <see cref="NLog.LogLevel.Error"/> and <see cref="NLog.LogLevel.Fatal"/> will be written.</example>
public static LogLevel LogLevel { get => _logLevel; set => _logLevel = value ?? LogLevel.Info; }
private static LogLevel _logLevel;
/// <summary>
/// Gets or sets a value indicating whether internal messages should be written to the console output stream.
/// </summary>
/// <remarks>Your application must be a console application.</remarks>
public static bool LogToConsole { get; set; }
/// <summary>
/// Gets or sets a value indicating whether internal messages should be written to the console error stream.
/// </summary>
/// <remarks>Your application must be a console application.</remarks>
public static bool LogToConsoleError { get; set; }
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Gets or sets a value indicating whether internal messages should be written to the <see cref="System.Diagnostics"/>.Trace
/// </summary>
public static bool LogToTrace { get; set; }
#endif
/// <summary>
/// Gets or sets the file path of the internal log file.
/// </summary>
/// <remarks>A value of <see langword="null" /> value disables internal logging to a file.</remarks>
public static string LogFile
{
get
{
return _logFile;
}
set
{
_logFile = value;
#if !SILVERLIGHT
if (!string.IsNullOrEmpty(_logFile))
{
CreateDirectoriesIfNeeded(_logFile);
}
#endif
}
}
/// <summary>
/// Gets or sets the text writer that will receive internal logs.
/// </summary>
public static TextWriter LogWriter { get; set; }
/// <summary>
/// Event written to the internal log.
/// Please note that the event is not triggered when then event hasn't the minimal log level set by <see cref="LogLevel"/>
/// </summary>
public static event EventHandler<InternalLoggerMessageEventArgs> LogMessageReceived;
/// <summary>
/// Gets or sets a value indicating whether timestamp should be included in internal log output.
/// </summary>
public static bool IncludeTimestamp { get; set; }
/// <summary>
/// Is there an <see cref="Exception"/> thrown when writing the message?
/// </summary>
internal static bool ExceptionThrowWhenWriting { get; private set; }
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the specified level.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Log(LogLevel level, [Localizable(false)] string message, params object[] args)
{
Write(null, level, message, args);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the specified level.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="message">Log message.</param>
public static void Log(LogLevel level, [Localizable(false)] string message)
{
Write(null, level, message, null);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the specified level.
/// <paramref name="messageFunc"/> will be only called when logging is enabled for level <paramref name="level"/>.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="messageFunc">Function that returns the log message.</param>
public static void Log(LogLevel level, [Localizable(false)] Func<string> messageFunc)
{
if (IsLogLevelEnabled(level))
{
Write(null, level, messageFunc(), null);
}
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the specified level.
/// <paramref name="messageFunc"/> will be only called when logging is enabled for level <paramref name="level"/>.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="level">Log level.</param>
/// <param name="messageFunc">Function that returns the log message.</param>
public static void Log(Exception ex, LogLevel level, [Localizable(false)] Func<string> messageFunc)
{
if (IsLogLevelEnabled(level))
{
Write(ex, level, messageFunc(), null);
}
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the specified level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="level">Log level.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Log(Exception ex, LogLevel level, [Localizable(false)] string message, params object[] args)
{
Write(ex, level, message, args);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the specified level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="level">Log level.</param>
/// <param name="message">Log message.</param>
public static void Log(Exception ex, LogLevel level, [Localizable(false)] string message)
{
Write(ex, level, message, null);
}
/// <summary>
/// Write to internallogger.
/// </summary>
/// <param name="ex">optional exception to be logged.</param>
/// <param name="level">level</param>
/// <param name="message">message</param>
/// <param name="args">optional args for <paramref name="message"/></param>
private static void Write([CanBeNull]Exception ex, LogLevel level, string message, [CanBeNull]object[] args)
{
if (!IsLogLevelEnabled(level))
{
return;
}
if (IsSeriousException(ex))
{
//no logging!
return;
}
var hasActiveLoggersWithLine = HasActiveLoggersWithLine();
var hasEventListeners = HasEventListeners();
if (!hasActiveLoggersWithLine && !hasEventListeners)
{
return;
}
try
{
var fullMessage = CreateFullMessage(message, args);
if (hasActiveLoggersWithLine)
{
WriteLogLine(ex, level, fullMessage);
}
if (hasEventListeners)
{
var loggerContext = args?.Length > 0 ? args[0] as IInternalLoggerContext : null;
LogMessageReceived?.Invoke(null, new InternalLoggerMessageEventArgs(fullMessage, level, ex, loggerContext?.GetType(), loggerContext?.Name));
ex?.MarkAsLoggedToInternalLogger();
}
}
catch (Exception exception)
{
ExceptionThrowWhenWriting = true;
// no log looping.
// we have no place to log the message to so we ignore it
if (exception.MustBeRethrownImmediately())
{
throw;
}
}
}
private static void WriteLogLine(Exception ex, LogLevel level, string message)
{
try
{
string line = CreateLogLine(ex, level, message);
WriteToLogFile(line);
WriteToTextWriter(line);
#if !NETSTANDARD1_3
WriteToConsole(line);
WriteToErrorConsole(line);
#endif
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
WriteToTrace(line);
#endif
ex?.MarkAsLoggedToInternalLogger();
}
catch (Exception exception)
{
ExceptionThrowWhenWriting = true;
// no log looping.
// we have no place to log the message to so we ignore it
if (exception.MustBeRethrownImmediately())
{
throw;
}
}
}
/// <summary>
/// Create log line with timestamp, exception message etc (if configured)
/// </summary>
private static string CreateLogLine([CanBeNull]Exception ex, LogLevel level, string fullMessage)
{
const string timeStampFormat = "yyyy-MM-dd HH:mm:ss.ffff";
const string fieldSeparator = " ";
if (IncludeTimestamp)
{
return string.Concat(
TimeSource.Current.Time.ToString(timeStampFormat, CultureInfo.InvariantCulture),
fieldSeparator,
level.ToString(),
fieldSeparator,
fullMessage,
ex != null ? " Exception: " : "",
ex?.ToString() ?? "");
}
else
{
return string.Concat(
level.ToString(),
fieldSeparator,
fullMessage,
ex != null ? " Exception: " : "",
ex?.ToString() ?? "");
}
}
private static string CreateFullMessage(string message, object[] args)
{
var formattedMessage =
(args == null) ? message : string.Format(CultureInfo.InvariantCulture, message, args);
return formattedMessage;
}
/// <summary>
/// Determine if logging should be avoided because of exception type.
/// </summary>
/// <param name="exception">The exception to check.</param>
/// <returns><c>true</c> if logging should be avoided; otherwise, <c>false</c>.</returns>
private static bool IsSeriousException(Exception exception)
{
return exception != null && exception.MustBeRethrownImmediately();
}
/// <summary>
/// Determine if logging is enabled for given LogLevel
/// </summary>
/// <param name="logLevel">The <see cref="LogLevel"/> for the log event.</param>
/// <returns><c>true</c> if logging is enabled; otherwise, <c>false</c>.</returns>
private static bool IsLogLevelEnabled(LogLevel logLevel)
{
return !ReferenceEquals(_logLevel, LogLevel.Off) && logLevel >= _logLevel;
}
/// <summary>
/// Determine if logging is enabled.
/// </summary>
/// <returns><c>true</c> if logging is enabled; otherwise, <c>false</c>.</returns>
internal static bool HasActiveLoggers()
{
return HasActiveLoggersWithLine() || HasEventListeners();
}
private static bool HasEventListeners()
{
return LogMessageReceived != null;
}
internal static bool HasActiveLoggersWithLine()
{
return !string.IsNullOrEmpty(LogFile) ||
LogToConsole ||
LogToConsoleError ||
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
LogToTrace ||
#endif
LogWriter != null;
}
/// <summary>
/// Write internal messages to the log file defined in <see cref="LogFile"/>.
/// </summary>
/// <param name="message">Message to write.</param>
/// <remarks>
/// Message will be logged only when the property <see cref="LogFile"/> is not <c>null</c>, otherwise the
/// method has no effect.
/// </remarks>
private static void WriteToLogFile(string message)
{
var logFile = LogFile;
if (string.IsNullOrEmpty(logFile))
{
return;
}
lock (LockObject)
{
using (var textWriter = File.AppendText(logFile))
{
textWriter.WriteLine(message);
}
}
}
/// <summary>
/// Write internal messages to the <see cref="System.IO.TextWriter"/> defined in <see cref="LogWriter"/>.
/// </summary>
/// <param name="message">Message to write.</param>
/// <remarks>
/// Message will be logged only when the property <see cref="LogWriter"/> is not <c>null</c>, otherwise the
/// method has no effect.
/// </remarks>
private static void WriteToTextWriter(string message)
{
var writer = LogWriter;
if (writer == null)
{
return;
}
lock (LockObject)
{
writer.WriteLine(message);
}
}
#if !NETSTANDARD1_3
/// <summary>
/// Write internal messages to the <see cref="System.Console"/>.
/// </summary>
/// <param name="message">Message to write.</param>
/// <remarks>
/// Message will be logged only when the property <see cref="LogToConsole"/> is <c>true</c>, otherwise the
/// method has no effect.
/// </remarks>
private static void WriteToConsole(string message)
{
if (!LogToConsole)
{
return;
}
NLog.Targets.ConsoleTargetHelper.WriteLineThreadSafe(Console.Out, message);
}
#endif
#if !NETSTANDARD1_3
/// <summary>
/// Write internal messages to the <see cref="System.Console.Error"/>.
/// </summary>
/// <param name="message">Message to write.</param>
/// <remarks>
/// Message will be logged when the property <see cref="LogToConsoleError"/> is <c>true</c>, otherwise the
/// method has no effect.
/// </remarks>
private static void WriteToErrorConsole(string message)
{
if (!LogToConsoleError)
{
return;
}
NLog.Targets.ConsoleTargetHelper.WriteLineThreadSafe(Console.Error, message);
}
#endif
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
/// <summary>
/// Write internal messages to the <see cref="System.Diagnostics.Trace"/>.
/// </summary>
/// <param name="message">A message to write.</param>
/// <remarks>
/// Works when property <see cref="LogToTrace"/> set to true.
/// The <see cref="System.Diagnostics.Trace"/> is used in Debug and Release configuration.
/// The <see cref="System.Diagnostics.Debug"/> works only in Debug configuration and this is reason why is replaced by <see cref="System.Diagnostics.Trace"/>.
/// in DEBUG
/// </remarks>
private static void WriteToTrace(string message)
{
if (!LogToTrace)
{
return;
}
System.Diagnostics.Trace.WriteLine(message, "NLog");
}
#endif
/// <summary>
/// Logs the assembly version and file version of the given Assembly.
/// </summary>
/// <param name="assembly">The assembly to log.</param>
public static void LogAssemblyVersion(Assembly assembly)
{
try
{
#if SILVERLIGHT || __IOS__ || __ANDROID__ || NETSTANDARD1_0
Info(assembly.FullName);
#else
var fileVersionInfo = !string.IsNullOrEmpty(assembly.Location) ?
System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location) : null;
Info("{0}. File version: {1}. Product version: {2}. GlobalAssemblyCache: {3}",
assembly.FullName,
fileVersionInfo?.FileVersion,
fileVersionInfo?.ProductVersion,
assembly.GlobalAssemblyCache);
#endif
}
catch (Exception ex)
{
Error(ex, "Error logging version of assembly {0}.", assembly.FullName);
}
}
private static string GetAppSettings(string configName)
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD
try
{
return System.Configuration.ConfigurationManager.AppSettings[configName];
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
{
throw;
}
}
#endif
return null;
}
private static string GetSettingString(string configName, string envName)
{
try
{
string settingValue = GetAppSettings(configName);
if (settingValue != null)
return settingValue;
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
{
throw;
}
}
try
{
string settingValue = EnvironmentHelper.GetSafeEnvironmentVariable(envName);
if (!string.IsNullOrEmpty(settingValue))
return settingValue;
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
{
throw;
}
}
return null;
}
private static LogLevel GetSetting(string configName, string envName, LogLevel defaultValue)
{
string value = GetSettingString(configName, envName);
if (value == null)
{
return defaultValue;
}
try
{
return LogLevel.FromString(value);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
return defaultValue;
}
}
private static T GetSetting<T>(string configName, string envName, T defaultValue)
{
string value = GetSettingString(configName, envName);
if (value == null)
{
return defaultValue;
}
try
{
return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
return defaultValue;
}
}
#if !SILVERLIGHT
private static void CreateDirectoriesIfNeeded(string filename)
{
try
{
if (LogLevel == LogLevel.Off)
{
return;
}
string parentDirectory = Path.GetDirectoryName(filename);
if (!string.IsNullOrEmpty(parentDirectory))
{
Directory.CreateDirectory(parentDirectory);
}
}
catch (Exception exception)
{
Error(exception, "Cannot create needed directories to '{0}'.", filename);
if (exception.MustBeRethrownImmediately())
{
throw;
}
}
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using ErrorCode = Interop.NCrypt.ErrorCode;
namespace Microsoft.Win32.SafeHandles
{
/// <summary>
/// Base class for NCrypt handles which need to support being pseudo-duplicated. This class is not for
/// external use (instead applications should consume the concrete subclasses of this class).
/// </summary>
/// <remarks>
/// Since NCrypt handles do not have a native DuplicateHandle type call, we need to do manual
/// reference counting in managed code whenever we hand out an extra reference to one of these handles.
/// This class wraps up the logic to correctly duplicate and free these handles to simluate a native
/// duplication.
///
/// Each open handle object can be thought of as being in one of three states:
/// 1. Owner - created via the marshaler, traditional style safe handle. Notably, only one owner
/// handle exists for a given native handle.
/// 2. Duplicate - points at a handle in the Holder state. Releasing a handle in the duplicate state
/// results only in decrementing the reference count of the holder, not in a release
/// of the native handle.
/// 3. Holder - holds onto a native handle and is referenced by handles in the duplicate state.
/// When all duplicate handles are closed, the holder handle releases the native
/// handle. A holder handle will never be finalized, since this results in a race
/// between the finalizers of the duplicate handles and the holder handle. Instead,
/// it relies upon all of the duplicate handles to be finalized and decriment the
/// ref count to zero. Instances of a holder handle should never be referenced by
/// anything but a duplicate handle.
/// </remarks>
public abstract class SafeNCryptHandle : SafeHandle
{
private enum OwnershipState
{
/// <summary>
/// The safe handle owns the native handle outright. This must be value 0, as this is the
/// state the marshaler will place the handle in when marshaling back a SafeHandle
/// </summary>
Owner = 0,
/// <summary>
/// The safe handle does not own the native handle, but points to a Holder which does
/// </summary>
Duplicate,
/// <summary>
/// The safe handle owns the native handle, but shares it with other Duplicate handles
/// </summary>
Holder
}
private OwnershipState _ownershipState;
/// <summary>
/// If the handle is a Duplicate, this points at the safe handle which actually owns the native handle.
/// </summary>
private SafeNCryptHandle _holder;
protected SafeNCryptHandle() : base(IntPtr.Zero, true)
{
return;
}
/// <summary>
/// Wrapper for the _holder field which ensures that we're in a consistent state
/// </summary>
private SafeNCryptHandle Holder
{
get
{
Debug.Assert((_ownershipState == OwnershipState.Duplicate && _holder != null) ||
(_ownershipState != OwnershipState.Duplicate && _holder == null));
Debug.Assert(_holder == null || _holder._ownershipState == OwnershipState.Holder);
return _holder;
}
set
{
#if DEBUG
Debug.Assert(value.IsValidOpenState);
#endif
Debug.Assert(_ownershipState != OwnershipState.Duplicate);
Debug.Assert(value._ownershipState == OwnershipState.Holder);
_holder = value;
_ownershipState = OwnershipState.Duplicate;
}
}
#if DEBUG
/// <summary>
/// Ensure the state of the handle is consistent for an open handle
/// </summary>
private bool IsValidOpenState
{
get
{
switch (_ownershipState)
{
// Owner handles do not have a holder
case OwnershipState.Owner:
return Holder == null && !IsInvalid && !IsClosed;
// Duplicate handles have valid open holders with the same raw handle value
case OwnershipState.Duplicate:
bool acquiredHolder = false;
try
{
IntPtr holderRawHandle = IntPtr.Zero;
if (Holder != null)
{
Holder.DangerousAddRef(ref acquiredHolder);
holderRawHandle = Holder.DangerousGetHandle();
}
bool holderValid = Holder != null &&
!Holder.IsInvalid &&
!Holder.IsClosed &&
holderRawHandle != IntPtr.Zero &&
holderRawHandle == handle;
return holderValid && !IsInvalid && !IsClosed;
}
finally
{
if (acquiredHolder)
{
Holder.DangerousRelease();
}
}
// Holder handles do not have a holder
case OwnershipState.Holder:
return Holder == null && !IsInvalid && !IsClosed;
// Unknown ownership state
default:
return false;
}
}
}
#endif
/// <summary>
/// Duplicate a handle
/// </summary>
/// <remarks>
/// #NCryptHandleDuplicationAlgorithm
///
/// Duplicating a handle performs different operations depending upon the state of the handle:
///
/// * Owner - Allocate two new handles, a holder and a duplicate.
/// - Suppress finalization on the holder
/// - Transition into the duplicate state
/// - Use the new holder as the holder for both this handle and the duplicate
/// - Increment the reference count on the holder
///
/// * Duplicate - Allocate a duplicate handle
/// - Increment the reference count of our holder
/// - Assign the duplicate's holder to be our holder
///
/// * Holder - Specifically disallowed. Holders should only ever be referenced by duplicates,
/// so duplication will occur on the duplicate rather than the holder handle.
/// </remarks>
internal T Duplicate<T>() where T : SafeNCryptHandle, new()
{
#if DEBUG
Debug.Assert(IsValidOpenState);
#endif
Debug.Assert(_ownershipState != OwnershipState.Holder);
Debug.Assert(typeof(T) == this.GetType());
if (_ownershipState == OwnershipState.Owner)
{
return DuplicateOwnerHandle<T>();
}
else
{
// If we're not an owner handle, and we're being duplicated then we must be a duplicate handle.
return DuplicateDuplicatedHandle<T>();
}
}
/// <summary>
/// Duplicate a safe handle which is already duplicated.
///
/// See code:Microsoft.Win32.SafeHandles.SafeNCryptHandle#NCryptHandleDuplicationAlgorithm for
/// details about the algorithm.
/// </summary>
private T DuplicateDuplicatedHandle<T>() where T : SafeNCryptHandle, new()
{
#if DEBUG
Debug.Assert(IsValidOpenState);
#endif
Debug.Assert(_ownershipState == OwnershipState.Duplicate);
Debug.Assert(typeof(T) == this.GetType());
bool addedRef = false;
T duplicate = new T();
// We need to do this operation in a CER, since we need to make sure that if the AddRef occurs
// that the duplicated handle will always point back to the Holder, otherwise the Holder will leak
// since it will never have its ref count reduced to zero.
try { }
finally
{
Holder.DangerousAddRef(ref addedRef);
duplicate.SetHandle(Holder.DangerousGetHandle());
duplicate.Holder = Holder; // Transitions to OwnershipState.Duplicate
}
return duplicate;
}
/// <summary>
/// Duplicate a safe handle which is currently the exclusive owner of a native handle
///
/// See code:Microsoft.Win32.SafeHandles.SafeNCryptHandle#NCryptHandleDuplicationAlgorithm for
/// details about the algorithm.
/// </summary>
private T DuplicateOwnerHandle<T>() where T : SafeNCryptHandle, new()
{
#if DEBUG
Debug.Assert(IsValidOpenState);
#endif
Debug.Assert(_ownershipState == OwnershipState.Owner);
Debug.Assert(typeof(T) == this.GetType());
bool addRef = false;
T holder = new T();
T duplicate = new T();
// We need to do this operation in a CER in order to ensure that everybody's state stays consistent
// with the current view of the world. If the state of the various handles gets out of sync, then
// we'll end up leaking since reference counts will not be set up properly.
try { }
finally
{
// Setup a holder safe handle to ref count the native handle
holder._ownershipState = OwnershipState.Holder;
holder.SetHandle(DangerousGetHandle());
GC.SuppressFinalize(holder);
// Transition into the duplicate state, referencing the holder. The initial reference count
// on the holder will refer to the original handle so there is no need to AddRef here.
Holder = holder; // Transitions to OwnershipState.Duplicate
// The duplicate handle will also reference the holder
holder.DangerousAddRef(ref addRef);
duplicate.SetHandle(holder.DangerousGetHandle());
duplicate.Holder = holder; // Transitions to OwnershipState.Duplicate
}
return duplicate;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
}
/// <summary>
/// Release the handle
/// </summary>
/// <remarks>
/// Similar to duplication, releasing a handle performs different operations based upon the state
/// of the handle.
///
/// * Owner - Simply call the release P/Invoke method
/// * Duplicate - Decrement the reference count of the current holder
/// * Holder - Call the release P/Invoke. Note that ReleaseHandle on a holder implies a reference
/// count of zero.
/// </remarks>
protected override bool ReleaseHandle()
{
if (_ownershipState == OwnershipState.Duplicate)
{
Holder.DangerousRelease();
return true;
}
else
{
return ReleaseNativeHandle();
}
}
/// <summary>
/// Perform the actual release P/Invoke
/// </summary>
protected abstract bool ReleaseNativeHandle();
/// <summary>
/// Since all NCrypt handles are released the same way, no sense in writing the same code three times.
/// </summary>
internal bool ReleaseNativeWithNCryptFreeObject()
{
ErrorCode errorCode = Interop.NCrypt.NCryptFreeObject(handle);
bool success = (errorCode == ErrorCode.ERROR_SUCCESS);
Debug.Assert(success);
return success;
}
}
/// <summary>
/// Safe handle representing an NCRYPT_KEY_HANDLE
/// </summary>
public sealed class SafeNCryptKeyHandle : SafeNCryptHandle
{
internal SafeNCryptKeyHandle Duplicate()
{
return Duplicate<SafeNCryptKeyHandle>();
}
protected override bool ReleaseNativeHandle()
{
return ReleaseNativeWithNCryptFreeObject();
}
}
/// <summary>
/// Safe handle representing an NCRYPT_PROV_HANDLE
/// </summary>
public sealed class SafeNCryptProviderHandle : SafeNCryptHandle
{
internal SafeNCryptProviderHandle Duplicate()
{
return Duplicate<SafeNCryptProviderHandle>();
}
internal void SetHandleValue(IntPtr newHandleValue)
{
Debug.Assert(newHandleValue != IntPtr.Zero);
Debug.Assert(!IsClosed);
Debug.Assert(handle == IntPtr.Zero);
SetHandle(newHandleValue);
}
protected override bool ReleaseNativeHandle()
{
return ReleaseNativeWithNCryptFreeObject();
}
}
/// <summary>
/// Safe handle representing an NCRYPT_SECRET_HANDLE
/// </summary>
public sealed class SafeNCryptSecretHandle : SafeNCryptHandle
{
protected override bool ReleaseNativeHandle()
{
return ReleaseNativeWithNCryptFreeObject();
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils
{
using System;
using System.Collections.Generic;
using System.IO;
internal delegate SparseStream SparseStreamOpenDelegate();
/// <summary>
/// Represents a sparse stream.
/// </summary>
/// <remarks>A sparse stream is a logically contiguous stream where some parts of the stream
/// aren't stored. The unstored parts are implicitly zero-byte ranges.</remarks>
public abstract class SparseStream : Stream
{
/// <summary>
/// Gets the parts of the stream that are stored.
/// </summary>
/// <remarks>This may be an empty enumeration if all bytes are zero.</remarks>
public abstract IEnumerable<StreamExtent> Extents
{
get;
}
/// <summary>
/// Converts any stream into a sparse stream.
/// </summary>
/// <param name="stream">The stream to convert.</param>
/// <param name="takeOwnership"><c>true</c> to have the new stream dispose the wrapped
/// stream when it is disposed.</param>
/// <returns>A sparse stream.</returns>
/// <remarks>The returned stream has the entire wrapped stream as a
/// single extent.</remarks>
public static SparseStream FromStream(Stream stream, Ownership takeOwnership)
{
return new SparseWrapperStream(stream, takeOwnership, null);
}
/// <summary>
/// Converts any stream into a sparse stream.
/// </summary>
/// <param name="stream">The stream to convert.</param>
/// <param name="takeOwnership"><c>true</c> to have the new stream dispose the wrapped
/// stream when it is disposed.</param>
/// <param name="extents">The set of extents actually stored in <c>stream</c>.</param>
/// <returns>A sparse stream.</returns>
/// <remarks>The returned stream has the entire wrapped stream as a
/// single extent.</remarks>
public static SparseStream FromStream(Stream stream, Ownership takeOwnership, IEnumerable<StreamExtent> extents)
{
return new SparseWrapperStream(stream, takeOwnership, extents);
}
/// <summary>
/// Efficiently pumps data from a sparse stream to another stream.
/// </summary>
/// <param name="inStream">The sparse stream to pump from.</param>
/// <param name="outStream">The stream to pump to.</param>
/// <remarks><paramref name="outStream"/> must support seeking.</remarks>
public static void Pump(Stream inStream, Stream outStream)
{
Pump(inStream, outStream, Sizes.Sector);
}
/// <summary>
/// Efficiently pumps data from a sparse stream to another stream.
/// </summary>
/// <param name="inStream">The stream to pump from.</param>
/// <param name="outStream">The stream to pump to.</param>
/// <param name="chunkSize">The smallest sequence of zero bytes that will be skipped when writing to <paramref name="outStream"/>.</param>
/// <remarks><paramref name="outStream"/> must support seeking.</remarks>
public static void Pump(Stream inStream, Stream outStream, int chunkSize)
{
StreamPump pump = new StreamPump(inStream, outStream, chunkSize);
pump.Run();
}
/// <summary>
/// Wraps a sparse stream in a read-only wrapper, preventing modification.
/// </summary>
/// <param name="toWrap">The stream to make read-only.</param>
/// <param name="ownership">Whether to transfer responsibility for calling Dispose on <c>toWrap</c>.</param>
/// <returns>The read-only stream.</returns>
public static SparseStream ReadOnly(SparseStream toWrap, Ownership ownership)
{
return new SparseReadOnlyWrapperStream(toWrap, ownership);
}
/// <summary>
/// Clears bytes from the stream.
/// </summary>
/// <param name="count">The number of bytes (from the current position) to clear.</param>
/// <remarks>
/// <para>Logically equivalent to writing <c>count</c> null/zero bytes to the stream, some
/// implementations determine that some (or all) of the range indicated is not actually
/// stored. There is no direct, automatic, correspondence to clearing bytes and them
/// not being represented as an 'extent' - for example, the implementation of the underlying
/// stream may not permit fine-grained extent storage.</para>
/// <para>It is always safe to call this method to 'zero-out' a section of a stream, regardless of
/// the underlying stream implementation.</para>
/// </remarks>
public virtual void Clear(int count)
{
Write(new byte[count], 0, count);
}
/// <summary>
/// Gets the parts of a stream that are stored, within a specified range.
/// </summary>
/// <param name="start">The offset of the first byte of interest.</param>
/// <param name="count">The number of bytes of interest.</param>
/// <returns>An enumeration of stream extents, indicating stored bytes.</returns>
public virtual IEnumerable<StreamExtent> GetExtentsInRange(long start, long count)
{
return StreamExtent.Intersect(Extents, new StreamExtent[] { new StreamExtent(start, count) });
}
private class SparseReadOnlyWrapperStream : SparseStream
{
private SparseStream _wrapped;
private Ownership _ownsWrapped;
public SparseReadOnlyWrapperStream(SparseStream wrapped, Ownership ownsWrapped)
{
_wrapped = wrapped;
_ownsWrapped = ownsWrapped;
}
public override bool CanRead
{
get { return _wrapped.CanRead; }
}
public override bool CanSeek
{
get { return _wrapped.CanSeek; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get { return _wrapped.Length; }
}
public override long Position
{
get
{
return _wrapped.Position;
}
set
{
_wrapped.Position = value;
}
}
public override IEnumerable<StreamExtent> Extents
{
get { return _wrapped.Extents; }
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
return _wrapped.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _wrapped.Seek(offset, origin);
}
public override void SetLength(long value)
{
throw new InvalidOperationException("Attempt to change length of read-only stream");
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new InvalidOperationException("Attempt to write to read-only stream");
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _ownsWrapped == Ownership.Dispose && _wrapped != null)
{
_wrapped.Dispose();
_wrapped = null;
}
}
finally
{
base.Dispose(disposing);
}
}
}
private class SparseWrapperStream : SparseStream
{
private Stream _wrapped;
private Ownership _ownsWrapped;
private List<StreamExtent> _extents;
public SparseWrapperStream(Stream wrapped, Ownership ownsWrapped, IEnumerable<StreamExtent> extents)
{
_wrapped = wrapped;
_ownsWrapped = ownsWrapped;
if (extents != null)
{
_extents = new List<StreamExtent>(extents);
}
}
public override bool CanRead
{
get { return _wrapped.CanRead; }
}
public override bool CanSeek
{
get { return _wrapped.CanSeek; }
}
public override bool CanWrite
{
get { return _wrapped.CanWrite; }
}
public override long Length
{
get { return _wrapped.Length; }
}
public override long Position
{
get
{
return _wrapped.Position;
}
set
{
_wrapped.Position = value;
}
}
public override IEnumerable<StreamExtent> Extents
{
get
{
if (_extents != null)
{
return _extents;
}
else
{
SparseStream wrappedAsSparse = _wrapped as SparseStream;
if (wrappedAsSparse != null)
{
return wrappedAsSparse.Extents;
}
else
{
return new StreamExtent[] { new StreamExtent(0, _wrapped.Length) };
}
}
}
}
public override void Flush()
{
_wrapped.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _wrapped.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _wrapped.Seek(offset, origin);
}
public override void SetLength(long value)
{
_wrapped.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_extents != null)
{
throw new InvalidOperationException("Attempt to write to stream with explicit extents");
}
_wrapped.Write(buffer, offset, count);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _ownsWrapped == Ownership.Dispose && _wrapped != null)
{
_wrapped.Dispose();
_wrapped = null;
}
}
finally
{
base.Dispose(disposing);
}
}
}
}
}
| |
namespace Vernash
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.radioButton3 = new System.Windows.Forms.RadioButton();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.button1 = new System.Windows.Forms.Button();
this.numHashLength = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.txtTextHash = new System.Windows.Forms.TextBox();
this.txtText = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.button7 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button10 = new System.Windows.Forms.Button();
this.txtOutput = new System.Windows.Forms.TextBox();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.button12 = new System.Windows.Forms.Button();
this.button11 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.txtPassword = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.button8 = new System.Windows.Forms.Button();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.label5 = new System.Windows.Forms.Label();
this.txt3DEStext = new System.Windows.Forms.TextBox();
this.txt3DESpass = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.button5 = new System.Windows.Forms.Button();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveOutputToFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.encryptAFileToAnotherFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.decryptAFileToAnotherFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearOutputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyOutputToTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.vernashToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.encryptWithVernashToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.decryptToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.shuffleTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.unShuffleTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numHashLength)).BeginInit();
this.groupBox3.SuspendLayout();
this.statusStrip.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabControl1.SuspendLayout();
this.tabPage3.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.radioButton3);
this.groupBox1.Controls.Add(this.radioButton2);
this.groupBox1.Controls.Add(this.radioButton1);
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Controls.Add(this.numHashLength);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.txtTextHash);
this.groupBox1.Location = new System.Drawing.Point(6, 6);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(525, 199);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Generate an Hash";
//
// radioButton3
//
this.radioButton3.AutoSize = true;
this.radioButton3.Location = new System.Drawing.Point(7, 174);
this.radioButton3.Name = "radioButton3";
this.radioButton3.Size = new System.Drawing.Size(84, 17);
this.radioButton3.TabIndex = 6;
this.radioButton3.TabStop = true;
this.radioButton3.Text = "using SHA-1";
this.radioButton3.UseVisualStyleBackColor = true;
//
// radioButton2
//
this.radioButton2.AutoSize = true;
this.radioButton2.Location = new System.Drawing.Point(7, 151);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(76, 17);
this.radioButton2.TabIndex = 5;
this.radioButton2.Text = "using MD5";
this.radioButton2.UseVisualStyleBackColor = true;
//
// radioButton1
//
this.radioButton1.AutoSize = true;
this.radioButton1.Checked = true;
this.radioButton1.Location = new System.Drawing.Point(7, 105);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(92, 17);
this.radioButton1.TabIndex = 1;
this.radioButton1.TabStop = true;
this.radioButton1.Text = "using Vernash";
this.radioButton1.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.Location = new System.Drawing.Point(405, 171);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(114, 22);
this.button1.TabIndex = 4;
this.button1.Text = "Generate";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// numHashLength
//
this.numHashLength.Location = new System.Drawing.Point(105, 125);
this.numHashLength.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numHashLength.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numHashLength.Name = "numHashLength";
this.numHashLength.Size = new System.Drawing.Size(125, 20);
this.numHashLength.TabIndex = 3;
this.numHashLength.Value = new decimal(new int[] {
32,
0,
0,
0});
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(31, 127);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(68, 13);
this.label2.TabIndex = 2;
this.label2.Text = "Hash Length";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(28, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Text";
//
// txtTextHash
//
this.txtTextHash.Location = new System.Drawing.Point(7, 32);
this.txtTextHash.Multiline = true;
this.txtTextHash.Name = "txtTextHash";
this.txtTextHash.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtTextHash.Size = new System.Drawing.Size(512, 67);
this.txtTextHash.TabIndex = 2;
this.txtTextHash.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtTextHash_KeyPress);
//
// txtText
//
this.txtText.AllowDrop = true;
this.txtText.Location = new System.Drawing.Point(12, 66);
this.txtText.Multiline = true;
this.txtText.Name = "txtText";
this.txtText.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtText.Size = new System.Drawing.Size(525, 141);
this.txtText.TabIndex = 2;
this.txtText.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtText_KeyPress);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(9, 50);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(28, 13);
this.label4.TabIndex = 2;
this.label4.Text = "Text";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.button7);
this.groupBox3.Controls.Add(this.button6);
this.groupBox3.Controls.Add(this.button4);
this.groupBox3.Controls.Add(this.button10);
this.groupBox3.Controls.Add(this.txtOutput);
this.groupBox3.Location = new System.Drawing.Point(12, 272);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(552, 148);
this.groupBox3.TabIndex = 2;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Output";
//
// button7
//
this.button7.Location = new System.Drawing.Point(215, 118);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(90, 22);
this.button7.TabIndex = 3;
this.button7.Text = "Clear Output";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(311, 118);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(90, 22);
this.button6.TabIndex = 2;
this.button6.Text = "Save To File";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(407, 118);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(139, 22);
this.button4.TabIndex = 1;
this.button4.Text = "Copy Output To Text";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// button10
//
this.button10.Location = new System.Drawing.Point(119, 118);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(90, 22);
this.button10.TabIndex = 7;
this.button10.Text = "Clear Text";
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.button10_Click);
//
// txtOutput
//
this.txtOutput.BackColor = System.Drawing.SystemColors.Window;
this.txtOutput.Location = new System.Drawing.Point(6, 16);
this.txtOutput.Multiline = true;
this.txtOutput.Name = "txtOutput";
this.txtOutput.ReadOnly = true;
this.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtOutput.Size = new System.Drawing.Size(540, 96);
this.txtOutput.TabIndex = 4;
//
// openFileDialog
//
this.openFileDialog.Filter = "All Files|*.*";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "Vernash File|*.vsh|All Files|*.*";
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1});
this.statusStrip.Location = new System.Drawing.Point(0, 425);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(572, 22);
this.statusStrip.TabIndex = 3;
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(39, 17);
this.toolStripStatusLabel1.Text = "Ready";
//
// tabPage2
//
this.tabPage2.Controls.Add(this.groupBox1);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(544, 213);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Hash";
this.tabPage2.UseVisualStyleBackColor = true;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.checkBox1);
this.tabPage1.Controls.Add(this.button12);
this.tabPage1.Controls.Add(this.button11);
this.tabPage1.Controls.Add(this.label4);
this.tabPage1.Controls.Add(this.txtText);
this.tabPage1.Controls.Add(this.button3);
this.tabPage1.Controls.Add(this.button2);
this.tabPage1.Controls.Add(this.txtPassword);
this.tabPage1.Controls.Add(this.label3);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(544, 213);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Vernash";
this.tabPage1.UseVisualStyleBackColor = true;
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Checked = true;
this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox1.Location = new System.Drawing.Point(68, 5);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(58, 17);
this.checkBox1.TabIndex = 12;
this.checkBox1.Text = "hidden";
this.checkBox1.UseVisualStyleBackColor = true;
this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
//
// button12
//
this.button12.Location = new System.Drawing.Point(418, 34);
this.button12.Name = "button12";
this.button12.Size = new System.Drawing.Size(114, 22);
this.button12.TabIndex = 6;
this.button12.Text = "UnShuffle";
this.button12.UseVisualStyleBackColor = true;
this.button12.Click += new System.EventHandler(this.button12_Click);
//
// button11
//
this.button11.Location = new System.Drawing.Point(418, 5);
this.button11.Name = "button11";
this.button11.Size = new System.Drawing.Size(114, 22);
this.button11.TabIndex = 5;
this.button11.Text = "Shuffle";
this.button11.UseVisualStyleBackColor = true;
this.button11.Click += new System.EventHandler(this.button11_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(300, 34);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(114, 22);
this.button3.TabIndex = 4;
this.button3.Text = "DeCrypt";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(300, 6);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(114, 22);
this.button2.TabIndex = 3;
this.button2.Text = "EnCrypt";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// txtPassword
//
this.txtPassword.Location = new System.Drawing.Point(12, 27);
this.txtPassword.Name = "txtPassword";
this.txtPassword.PasswordChar = '*';
this.txtPassword.Size = new System.Drawing.Size(273, 20);
this.txtPassword.TabIndex = 1;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(9, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(53, 13);
this.label3.TabIndex = 11;
this.label3.Text = "Password";
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Location = new System.Drawing.Point(12, 27);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(552, 239);
this.tabControl1.TabIndex = 4;
//
// tabPage3
//
this.tabPage3.Controls.Add(this.button8);
this.tabPage3.Controls.Add(this.checkBox2);
this.tabPage3.Controls.Add(this.label5);
this.tabPage3.Controls.Add(this.txt3DEStext);
this.tabPage3.Controls.Add(this.txt3DESpass);
this.tabPage3.Controls.Add(this.label6);
this.tabPage3.Controls.Add(this.button5);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Size = new System.Drawing.Size(544, 213);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "TripleDES";
this.tabPage3.UseVisualStyleBackColor = true;
//
// button8
//
this.button8.Location = new System.Drawing.Point(422, 33);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(114, 22);
this.button8.TabIndex = 18;
this.button8.Text = "DeCrypt";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.button8_Click);
//
// checkBox2
//
this.checkBox2.AutoSize = true;
this.checkBox2.Checked = true;
this.checkBox2.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox2.Location = new System.Drawing.Point(68, 5);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(58, 17);
this.checkBox2.TabIndex = 17;
this.checkBox2.Text = "hidden";
this.checkBox2.UseVisualStyleBackColor = true;
this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(9, 50);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(28, 13);
this.label5.TabIndex = 15;
this.label5.Text = "Text";
//
// txt3DEStext
//
this.txt3DEStext.Location = new System.Drawing.Point(12, 66);
this.txt3DEStext.Multiline = true;
this.txt3DEStext.Name = "txt3DEStext";
this.txt3DEStext.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txt3DEStext.Size = new System.Drawing.Size(525, 141);
this.txt3DEStext.TabIndex = 14;
this.txt3DEStext.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txt3DEStext_KeyPress);
//
// txt3DESpass
//
this.txt3DESpass.Location = new System.Drawing.Point(12, 27);
this.txt3DESpass.Name = "txt3DESpass";
this.txt3DESpass.PasswordChar = '*';
this.txt3DESpass.Size = new System.Drawing.Size(273, 20);
this.txt3DESpass.TabIndex = 13;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(9, 8);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(53, 13);
this.label6.TabIndex = 16;
this.label6.Text = "Password";
//
// button5
//
this.button5.Location = new System.Drawing.Point(422, 5);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(114, 22);
this.button5.TabIndex = 0;
this.button5.Text = "EnCrypt";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.vernashToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(572, 24);
this.menuStrip1.TabIndex = 5;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openFileToolStripMenuItem,
this.saveOutputToFileToolStripMenuItem,
this.encryptAFileToAnotherFileToolStripMenuItem,
this.decryptAFileToAnotherFileToolStripMenuItem,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// openFileToolStripMenuItem
//
this.openFileToolStripMenuItem.Name = "openFileToolStripMenuItem";
this.openFileToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F8;
this.openFileToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
this.openFileToolStripMenuItem.Text = "Open File";
this.openFileToolStripMenuItem.Click += new System.EventHandler(this.openFileToolStripMenuItem_Click);
//
// saveOutputToFileToolStripMenuItem
//
this.saveOutputToFileToolStripMenuItem.Name = "saveOutputToFileToolStripMenuItem";
this.saveOutputToFileToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
this.saveOutputToFileToolStripMenuItem.Text = "Save Output to File";
this.saveOutputToFileToolStripMenuItem.Click += new System.EventHandler(this.saveOutputToFileToolStripMenuItem_Click);
//
// encryptAFileToAnotherFileToolStripMenuItem
//
this.encryptAFileToAnotherFileToolStripMenuItem.Name = "encryptAFileToAnotherFileToolStripMenuItem";
this.encryptAFileToAnotherFileToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
this.encryptAFileToAnotherFileToolStripMenuItem.Text = "EnCrypt a File";
this.encryptAFileToAnotherFileToolStripMenuItem.Click += new System.EventHandler(this.encryptAFileToAnotherFileToolStripMenuItem_Click);
//
// decryptAFileToAnotherFileToolStripMenuItem
//
this.decryptAFileToAnotherFileToolStripMenuItem.Name = "decryptAFileToAnotherFileToolStripMenuItem";
this.decryptAFileToAnotherFileToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
this.decryptAFileToAnotherFileToolStripMenuItem.Text = "Decrypt a File";
this.decryptAFileToAnotherFileToolStripMenuItem.Click += new System.EventHandler(this.decryptAFileToAnotherFileToolStripMenuItem_Click);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.clearTextToolStripMenuItem,
this.clearOutputToolStripMenuItem,
this.copyOutputToTextToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "Edit";
//
// clearTextToolStripMenuItem
//
this.clearTextToolStripMenuItem.Name = "clearTextToolStripMenuItem";
this.clearTextToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.clearTextToolStripMenuItem.Text = "Clear Text";
this.clearTextToolStripMenuItem.Click += new System.EventHandler(this.clearTextToolStripMenuItem_Click);
//
// clearOutputToolStripMenuItem
//
this.clearOutputToolStripMenuItem.Name = "clearOutputToolStripMenuItem";
this.clearOutputToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.clearOutputToolStripMenuItem.Text = "Clear Output";
this.clearOutputToolStripMenuItem.Click += new System.EventHandler(this.clearOutputToolStripMenuItem_Click);
//
// copyOutputToTextToolStripMenuItem
//
this.copyOutputToTextToolStripMenuItem.Name = "copyOutputToTextToolStripMenuItem";
this.copyOutputToTextToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.copyOutputToTextToolStripMenuItem.Text = "Copy Output to Text";
this.copyOutputToTextToolStripMenuItem.Click += new System.EventHandler(this.copyOutputToTextToolStripMenuItem_Click);
//
// vernashToolStripMenuItem
//
this.vernashToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.encryptWithVernashToolStripMenuItem,
this.decryptToolStripMenuItem,
this.shuffleTextToolStripMenuItem,
this.unShuffleTextToolStripMenuItem});
this.vernashToolStripMenuItem.Name = "vernashToolStripMenuItem";
this.vernashToolStripMenuItem.Size = new System.Drawing.Size(61, 20);
this.vernashToolStripMenuItem.Text = "Vernash";
//
// encryptWithVernashToolStripMenuItem
//
this.encryptWithVernashToolStripMenuItem.Name = "encryptWithVernashToolStripMenuItem";
this.encryptWithVernashToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F2;
this.encryptWithVernashToolStripMenuItem.Size = new System.Drawing.Size(170, 22);
this.encryptWithVernashToolStripMenuItem.Text = "Encrypt";
this.encryptWithVernashToolStripMenuItem.Click += new System.EventHandler(this.encryptWithVernashToolStripMenuItem_Click);
//
// decryptToolStripMenuItem
//
this.decryptToolStripMenuItem.Name = "decryptToolStripMenuItem";
this.decryptToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F3;
this.decryptToolStripMenuItem.Size = new System.Drawing.Size(170, 22);
this.decryptToolStripMenuItem.Text = "Decrypt";
this.decryptToolStripMenuItem.Click += new System.EventHandler(this.decryptToolStripMenuItem_Click);
//
// shuffleTextToolStripMenuItem
//
this.shuffleTextToolStripMenuItem.Name = "shuffleTextToolStripMenuItem";
this.shuffleTextToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F4;
this.shuffleTextToolStripMenuItem.Size = new System.Drawing.Size(170, 22);
this.shuffleTextToolStripMenuItem.Text = "Shuffle Text";
this.shuffleTextToolStripMenuItem.Click += new System.EventHandler(this.shuffleTextToolStripMenuItem_Click);
//
// unShuffleTextToolStripMenuItem
//
this.unShuffleTextToolStripMenuItem.Name = "unShuffleTextToolStripMenuItem";
this.unShuffleTextToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5;
this.unShuffleTextToolStripMenuItem.Size = new System.Drawing.Size(170, 22);
this.unShuffleTextToolStripMenuItem.Text = "UnShuffle Text";
this.unShuffleTextToolStripMenuItem.Click += new System.EventHandler(this.unShuffleTextToolStripMenuItem_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(572, 447);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.groupBox3);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.MaximizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Vernash v0.5";
this.Shown += new System.EventHandler(this.Form1_Shown);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numHashLength)).EndInit();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.tabPage2.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout();
this.tabControl1.ResumeLayout(false);
this.tabPage3.ResumeLayout(false);
this.tabPage3.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtTextHash;
private System.Windows.Forms.NumericUpDown numHashLength;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox txtText;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.TextBox txtOutput;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox txtPassword;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.Button button11;
private System.Windows.Forms.Button button12;
private System.Windows.Forms.RadioButton radioButton2;
private System.Windows.Forms.RadioButton radioButton1;
private System.Windows.Forms.RadioButton radioButton3;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem encryptAFileToAnotherFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem decryptAFileToAnotherFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clearTextToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clearOutputToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveOutputToFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyOutputToTextToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem vernashToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem encryptWithVernashToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem decryptToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem shuffleTextToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem unShuffleTextToolStripMenuItem;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.CheckBox checkBox2;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txt3DEStext;
private System.Windows.Forms.TextBox txt3DESpass;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Button button8;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEditor;
using Object = UnityEngine.Object;
using System.Globalization;
using TangentMode = UnityEditor.AnimationUtility.TangentMode;
namespace UnityEditor.VFX
{
[Serializable]
public class SerializableType : ISerializationCallbackReceiver
{
public static implicit operator SerializableType(Type value)
{
return new SerializableType(value);
}
public static implicit operator Type(SerializableType value)
{
return value != null ? value.m_Type : null;
}
private SerializableType() {}
public SerializableType(Type type)
{
m_Type = type;
}
public SerializableType(string typeText)
{
m_SerializableType = typeText;
OnAfterDeserialize();
}
public virtual void OnBeforeSerialize()
{
m_SerializableType = m_Type != null ? m_Type.AssemblyQualifiedName : string.Empty;
}
public virtual void OnAfterDeserialize()
{
m_Type = GetType(m_SerializableType);
}
public static Type GetType(string name)
{
Type type = Type.GetType(name);
if (type == null && !string.IsNullOrEmpty(name)) // if type wasn't found, resolve the assembly (to use VFX package assembly name instead)
{
string[] splitted = name.Split(',');
// Replace the assembly with the one containing VFXGraph type which will be either "Unity.VisualEffect.Graph.Editor" or "Unity.VisualEffect.Graph.Editor-testable"
splitted[1] = typeof(VFXGraph).Assembly.GetName().Name;
name = string.Join(",", splitted);
type = Type.GetType(name);
if (type == null) // resolve runtime type if editor assembly didnt work
{
splitted[1] = splitted[1].Replace(".Editor", ".Runtime");
name = string.Join(",", splitted);
type = Type.GetType(name);
}
// If from here we still haven't found the type, try a last time with the name only.
if (type == null)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
foreach (Assembly assembly in currentDomain.GetAssemblies())
{
type = assembly.GetType(splitted[0]);
if (type != null)
return type;
}
}
if (type == null)
Debug.LogErrorFormat("Cannot get Type from name: {0}", name);
}
return type;
}
public string text
{
get { OnBeforeSerialize(); return m_SerializableType; }
}
[NonSerialized]
private Type m_Type;
[SerializeField]
private string m_SerializableType;
}
[Serializable]
public class VFXSerializableObject
{
private VFXSerializableObject() {}
public VFXSerializableObject(Type type, object obj) : this(type)
{
Set(obj);
}
public VFXSerializableObject(Type type)
{
m_Type = type;
}
public object Get()
{
return VFXSerializer.Load(m_Type, m_SerializableObject, m_CachedValue);
}
public T Get<T>()
{
return (T)Get();
}
public bool Set(object obj)
{
var newValue = string.Empty;
if (obj != null)
{
Type type = m_Type;
if (!type.IsAssignableFrom(obj.GetType()))
{
if (obj is UnityEngine.Object && (obj as UnityEngine.Object == null))
{
// Some object couldn't be loaded. just ignore it.
}
else if (obj is Texture && typeof(Texture).IsAssignableFrom(type))
{
}
else
{
throw new ArgumentException(string.Format("Cannot assign an object of type {0} to VFXSerializedObject of type {1}", obj.GetType(), (Type)m_Type));
}
}
newValue = VFXSerializer.Save(obj);
}
m_CachedValue = obj;
if (m_SerializableObject != newValue)
{
m_SerializableObject = newValue;
return true;
}
return false;
}
public Type type
{
get { return m_Type; }
}
[SerializeField]
private SerializableType m_Type;
[SerializeField]
private string m_SerializableObject;
private object m_CachedValue;
}
public static class VFXSerializer
{
[System.Serializable]
public struct TypedSerializedData
{
public string data;
public string type; // TODO This should have used SerializableType!
public static TypedSerializedData Null = new TypedSerializedData();
}
[Serializable]
private struct ObjectWrapper
{
public UnityEngine.Object obj;
}
[System.Serializable]
class AnimCurveWrapper
{
[System.Serializable]
public struct Keyframe
{
public float time;
public float value;
public float inTangent;
public float outTangent;
public int tangentMode;
public TangentMode leftTangentMode;
public TangentMode rightTangentMode;
public bool broken;
}
public Keyframe[] frames;
public WrapMode preWrapMode;
public WrapMode postWrapMode;
public int version;
}
[System.Serializable]
class GradientWrapper
{
[System.Serializable]
public struct ColorKey
{
public Color color;
public float time;
}
[System.Serializable]
public struct AlphaKey
{
public float alpha;
public float time;
}
public ColorKey[] colorKeys;
public AlphaKey[] alphaKeys;
public GradientMode gradientMode;
}
public static TypedSerializedData SaveWithType(object obj)
{
TypedSerializedData data = new TypedSerializedData();
data.data = VFXSerializer.Save(obj);
data.type = obj.GetType().AssemblyQualifiedName;
return data;
}
public static object LoadWithType(TypedSerializedData data, object oldValue)
{
if (!string.IsNullOrEmpty(data.data))
{
System.Type type = SerializableType.GetType(data.type);
if (type == null)
{
Debug.LogError("Can't find type " + data.type);
return null;
}
return VFXSerializer.Load(type, data.data, oldValue);
}
return null;
}
public static string Save(object obj)
{
if (obj == null)
return string.Empty;
if (obj.GetType().IsPrimitive)
{
return string.Format(CultureInfo.InvariantCulture, "{0}", obj);
}
else if (obj is UnityEngine.Object) //type is a unity object
{
if ((obj as UnityEngine.Object) == null)
{
return string.Empty;
}
ObjectWrapper wrapper = new ObjectWrapper { obj = obj as UnityEngine.Object };
var json = EditorJsonUtility.ToJson(wrapper);
return json;
}
else if (obj is AnimationCurve)
{
AnimCurveWrapper sac = new AnimCurveWrapper();
AnimationCurve curve = obj as AnimationCurve;
sac.frames = new AnimCurveWrapper.Keyframe[curve.keys.Length];
for (int i = 0; i < curve.keys.Length; ++i)
{
sac.frames[i].time = curve.keys[i].time;
sac.frames[i].value = curve.keys[i].value;
sac.frames[i].inTangent = curve.keys[i].inTangent;
sac.frames[i].outTangent = curve.keys[i].outTangent;
sac.frames[i].tangentMode = 0; // Not used
sac.frames[i].leftTangentMode = AnimationUtility.GetKeyLeftTangentMode(curve, i);
sac.frames[i].rightTangentMode = AnimationUtility.GetKeyRightTangentMode(curve, i);
sac.frames[i].broken = AnimationUtility.GetKeyBroken(curve, i);
}
sac.preWrapMode = curve.preWrapMode;
sac.postWrapMode = curve.postWrapMode;
sac.version = 1;
return JsonUtility.ToJson(sac);
}
else if (obj is Gradient)
{
GradientWrapper gw = new GradientWrapper();
Gradient gradient = obj as Gradient;
gw.gradientMode = gradient.mode;
gw.colorKeys = new GradientWrapper.ColorKey[gradient.colorKeys.Length];
for (int i = 0; i < gradient.colorKeys.Length; ++i)
{
gw.colorKeys[i].color = gradient.colorKeys[i].color;
gw.colorKeys[i].time = gradient.colorKeys[i].time;
}
gw.alphaKeys = new GradientWrapper.AlphaKey[gradient.alphaKeys.Length];
for (int i = 0; i < gradient.alphaKeys.Length; ++i)
{
gw.alphaKeys[i].alpha = gradient.alphaKeys[i].alpha;
gw.alphaKeys[i].time = gradient.alphaKeys[i].time;
}
return JsonUtility.ToJson(gw);
}
else if (obj is string)
{
return "\"" + ((string)obj).Replace("\"", "\\\"") + "\"";
}
else if (obj is SerializableType)
{
return "\"" + ((SerializableType)obj).text + "\"";
}
else if (obj.GetType().IsArrayOrList())
{
IList list = (IList)obj;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append('[');
for (int i = 0; i < list.Count; ++i)
{
sb.Append(Save(list[i]));
sb.Append(',');
}
sb.Length = sb.Length - 1;
sb.Append(']');
return sb.ToString();
}
else
{
return EditorJsonUtility.ToJson(obj);
}
}
const int kBrokenMask = 1 << 0;
const int kLeftTangentMask = 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4;
const int kRightTangentMask = 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8;
public static object Load(System.Type type, string text, object oldValue)
{
if (type == null)
return null;
if (type.IsPrimitive)
{
if (string.IsNullOrEmpty(text))
try
{
return Activator.CreateInstance(type);
}
catch (MissingMethodException)
{
Debug.LogError(type.Name + " Doesn't seem to have a default constructor");
throw;
}
return Convert.ChangeType(text, type, CultureInfo.InvariantCulture);
}
else if (typeof(UnityEngine.Object).IsAssignableFrom(type))
{
object obj = new ObjectWrapper();
EditorJsonUtility.FromJsonOverwrite(text, obj);
return ((ObjectWrapper)obj).obj;
}
else if (type.IsAssignableFrom(typeof(AnimationCurve)))
{
AnimCurveWrapper sac = new AnimCurveWrapper();
JsonUtility.FromJsonOverwrite(text, sac);
AnimationCurve curve = oldValue != null ? (AnimationCurve)oldValue : new AnimationCurve();
if (sac.frames != null)
{
Keyframe[] keys = new UnityEngine.Keyframe[sac.frames.Length];
for (int i = 0; i < sac.frames.Length; ++i)
{
keys[i].time = sac.frames[i].time;
keys[i].value = sac.frames[i].value;
keys[i].inTangent = sac.frames[i].inTangent;
keys[i].outTangent = sac.frames[i].outTangent;
if (sac.version == 1)
{
AnimationUtility.SetKeyLeftTangentMode(ref keys[i], sac.frames[i].leftTangentMode);
AnimationUtility.SetKeyRightTangentMode(ref keys[i], sac.frames[i].rightTangentMode);
AnimationUtility.SetKeyBroken(ref keys[i], sac.frames[i].broken);
}
else
{
AnimationUtility.SetKeyLeftTangentMode(ref keys[i], (TangentMode)((sac.frames[i].tangentMode & kLeftTangentMask) >> 1));
AnimationUtility.SetKeyRightTangentMode(ref keys[i], (TangentMode)((sac.frames[i].tangentMode & kRightTangentMask) >> 5));
AnimationUtility.SetKeyBroken(ref keys[i], (sac.frames[i].tangentMode & kBrokenMask) != 0);
}
}
curve.keys = keys;
curve.preWrapMode = sac.preWrapMode;
curve.postWrapMode = sac.postWrapMode;
}
return curve;
}
else if (type.IsAssignableFrom(typeof(Gradient)))
{
GradientWrapper gw = new GradientWrapper();
Gradient gradient = oldValue != null ? (Gradient)oldValue : new Gradient();
JsonUtility.FromJsonOverwrite(text, gw);
gradient.mode = gw.gradientMode;
GradientColorKey[] colorKeys = null;
if (gw.colorKeys != null)
{
colorKeys = new GradientColorKey[gw.colorKeys.Length];
for (int i = 0; i < gw.colorKeys.Length; ++i)
{
colorKeys[i].color = gw.colorKeys[i].color;
colorKeys[i].time = gw.colorKeys[i].time;
}
}
else
colorKeys = new GradientColorKey[0];
GradientAlphaKey[] alphaKeys = null;
if (gw.alphaKeys != null)
{
alphaKeys = new GradientAlphaKey[gw.alphaKeys.Length];
for (int i = 0; i < gw.alphaKeys.Length; ++i)
{
alphaKeys[i].alpha = gw.alphaKeys[i].alpha;
alphaKeys[i].time = gw.alphaKeys[i].time;
}
}
else
alphaKeys = new GradientAlphaKey[0];
gradient.SetKeys(colorKeys, alphaKeys);
return gradient;
}
else if (type == typeof(string))
{
return text.Substring(1, text.Length - 2).Replace("\\\"", "\"");
}
else if (type == typeof(SerializableType))
{
var obj = new SerializableType(text.Substring(1, text.Length - 2));
return obj;
}
else if (type.IsArrayOrList())
{
List<string> elements = ParseArray(text);
if (elements == null)
return null;
if (type.IsArray)
{
int listCount = elements.Count;
Array arrayObj = (Array)Activator.CreateInstance(type, new object[] { listCount });
for (int index = 0; index < listCount; index++)
{
arrayObj.SetValue(Load(type.GetElementType(), elements[index], null), index);
}
return arrayObj;
}
else //List
{
int listCount = elements.Count;
IList listObj = (Array)Activator.CreateInstance(type, new object[] { listCount });
for (int index = 0; index < listCount; index++)
{
listObj.Add(Load(type.GetElementType(), elements[index], null));
}
return listObj;
}
}
else
{
try
{
object obj = Activator.CreateInstance(type);
EditorJsonUtility.FromJsonOverwrite(text, obj);
return obj;
}
catch (MissingMethodException)
{
Debug.LogError(type.Name + " Doesn't seem to have a default constructor");
throw;
}
}
}
internal static List<string> ParseArray(string arrayText)
{
List<string> elements = new List<string>();
int cur = 0;
bool isInString = false;
bool ignoreNext = false;
int depth = 0; // depth of []
int bracketDepth = 0; //depth of {}
int prevElementStart = 0;
foreach (char c in arrayText)
{
switch (c)
{
case '{':
ignoreNext = false;
if (!isInString)
bracketDepth++;
break;
case '}':
ignoreNext = false;
if (!isInString)
bracketDepth--;
break;
case '[':
ignoreNext = false;
if (!isInString && bracketDepth == 0)
{
depth++;
if (depth == 1)
prevElementStart = cur + 1;
}
break;
case ']':
ignoreNext = false;
if (!isInString && bracketDepth == 0)
{
depth--;
if (depth < 0)
goto error;
if (depth == 0)
elements.Add(arrayText.Substring(prevElementStart, cur - prevElementStart));
}
return elements;
case ',':
ignoreNext = false;
if (!isInString && bracketDepth == 0)
{
elements.Add(arrayText.Substring(prevElementStart, cur - prevElementStart));
prevElementStart = cur + 1;
}
break;
case '"':
if (!isInString)
isInString = true;
else if (!ignoreNext)
isInString = false;
break;
case '\\':
if (isInString)
{
ignoreNext = !ignoreNext;
}
break;
default:
ignoreNext = false;
break;
}
++cur;
}
error:
Debug.LogError("Couln't parse array" + arrayText + " from " + cur);
return null;
}
}
}
| |
//The MIT License(MIT)
//Copyright(c) 2016 Alberto Rodriguez & LiveCharts Contributors
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using LiveCharts.Charts;
using LiveCharts.Definitions.Charts;
using LiveCharts.Dtos;
namespace LiveCharts
{
/// <summary>
/// Provides an axis that displays separators based upon configured windows
/// </summary>
public class WindowAxisCore : AxisCore
{
private IAxisWindow _selectedWindow;
private IAxisWindow SelectedWindow
{
get { return _selectedWindow; }
set
{
if (Equals(_selectedWindow, value)) return;
_selectedWindow = value;
((IWindowAxisView)View).SetSelectedWindow(value);
}
}
/// <summary>
///
/// </summary>
public List<AxisWindow> Windows { get; set; }
/// <summary>
///
/// </summary>
/// <param name="view"></param>
public WindowAxisCore(IAxisView view) : base(view)
{
}
/// <summary>
///
/// </summary>
internal override CoreMargin PrepareChart(AxisOrientation source, ChartCore chart)
{
if (!(Math.Abs(TopLimit - BotLimit) > S * .01) || !ShowLabels) return new CoreMargin();
var currentMargin = new CoreMargin();
var tolerance = S / 10;
InitializeGarbageCollector();
// Determine which magnitude and unit to use
var m = (!double.IsNaN(View.Unit) ? View.Unit : Magnitude);
var u = (!double.IsNaN(View.Unit) ? View.Unit : 1);
// Calculate the separator indices
var indices = CalculateSeparatorIndices(chart, source, u);
// Draw the separators
foreach (var index in indices)
{
DrawSeparator(index, tolerance, currentMargin, source);
}
return currentMargin;
}
internal IEnumerable<double> CalculateSeparatorIndices(ChartCore chart, AxisOrientation source, double unit)
{
if (!double.IsNaN(Separator.Step)) throw new Exception("Step should be NaN for WindowAxis separators");
if (Windows == null) return Enumerable.Empty<double>();
// Holder for the calculated separator indices and the proposed window
var supportedSeparatorCount = 0;
var separatorIndices = new List<double>();
IAxisWindow proposedWindow = AxisWindows.EmptyWindow;
// Build a range of possible separator indices
var start = (long) Math.Floor(BotLimit);
var count = (long) Math.Floor(TopLimit - (EvaluatesUnitWidth ? unit : 0.0) - BotLimit);
var end = start + count - 1;
var rangeIndices = LongRange(start, end).Select(i => (double)i);
// Make sure we have at least 2 separators to show
if (Windows != null && count > 1)
{
foreach (var window in Windows)
{
IEnumerable<double> proposedSeparatorIndices;
// Calculate the number of supported separators.
supportedSeparatorCount = (int)Math.Floor(chart.ControlSize.Width / (window.MinimumSeparatorWidth * CleanFactor));
// Try go get separators. Continue if the window invalidated.
if (!window.TryGetSeparatorIndices(rangeIndices, supportedSeparatorCount, out proposedSeparatorIndices)) continue;
// Double check whether the window exceeded the maximum separator count.
// It might be it does not respect the supportedSeparatorCount parameter.
separatorIndices = proposedSeparatorIndices.ToList();
if (supportedSeparatorCount < separatorIndices.Count) continue;
// Pick this window. It is the first who passed both validations and our best candidate
proposedWindow = window;
break;
}
}
if (proposedWindow == null)
{
// All variables are still set to defaults
}
// Force the step of 1, as our prepare chart will filter the X axis for valid separators, and will skip a few
S = 1;
Magnitude = Math.Pow(10, Math.Floor(Math.Log(supportedSeparatorCount) / Math.Log(10)));
SelectedWindow = proposedWindow;
return separatorIndices;
}
private IEnumerable<long> LongRange(long start, long end)
{
for (long i = start; i <= end; i++)
{
yield return i;
}
}
private void DrawSeparator(double x, double tolerance, CoreMargin currentMargin, AxisOrientation source)
{
SeparatorElementCore elementCore;
var key = Math.Round(x / tolerance) * tolerance;
if (!Cache.TryGetValue(key, out elementCore))
{
elementCore = new DateSeparatorElementCore { IsNew = true };
Cache[key] = elementCore;
}
else
{
elementCore.IsNew = false;
}
// Determine whether this separator is a header now
((DateSeparatorElementCore)elementCore).IsHeader = SelectedWindow.IsHeader(x);
View.RenderSeparator(elementCore, Chart);
elementCore.Key = key;
elementCore.Value = x;
elementCore.GarbageCollectorIndex = GarbageCollectorIndex;
var labelsMargin = elementCore.View.UpdateLabel(SelectedWindow.FormatAxisLabel(x), this, source);
currentMargin.Width = labelsMargin.TakenWidth > currentMargin.Width
? labelsMargin.TakenWidth
: currentMargin.Width;
currentMargin.Height = labelsMargin.TakenHeight > currentMargin.Height
? labelsMargin.TakenHeight
: currentMargin.Height;
currentMargin.Left = labelsMargin.Left > currentMargin.Left
? labelsMargin.Left
: currentMargin.Left;
currentMargin.Right = labelsMargin.Right > currentMargin.Right
? labelsMargin.Right
: currentMargin.Right;
currentMargin.Top = labelsMargin.Top > currentMargin.Top
? labelsMargin.Top
: currentMargin.Top;
currentMargin.Bottom = labelsMargin.Bottom > currentMargin.Bottom
? labelsMargin.Bottom
: currentMargin.Bottom;
if (LastAxisMax == null)
{
elementCore.State = SeparationState.InitialAdd;
return;
}
elementCore.State = SeparationState.Keep;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.Data;
using gView.Framework.Geometry;
using gView.SDEWrapper.a10;
using gView.Framework.system;
using gView.Framework.IO;
using System.IO;
namespace gView.Interoperability.Sde.a10
{
[gView.Framework.system.RegisterPlugIn("CE42218B-6962-48c9-9BAC-39E4C5003AE5")]
public class SdeDataset : DatasetMetadata, IFeatureDataset, IDisposable, IDataset2, IPersistable, IPlugInDependencies
{
private string _connStr = "",_errMsg="";
//private SmartSdeConnection _sConnection;
//private SdeConnection _current = null;
private List<IDatasetElement> _elements = new List<IDatasetElement>();
private DatasetState _state = DatasetState.unknown;
public SdeDataset()
{
}
~SdeDataset()
{
this.Dispose();
}
/*
internal SdeConnection AllocConnection()
{
if (_sConnection == null) return null;
return _current = _sConnection.AllocConnection();
}
internal void FreeConnection()
{
if (_sConnection == null) return;
_current = null;
_sConnection.FreeConnection();
}
*/
internal SE_COORDREF GetSeCoordRef(ArcSdeConnection connection, string table, string spatialColumnName, ref SE_ENVELOPE envelope)
{
_errMsg = "";
if (connection == null || connection.SeConnection.handle == IntPtr.Zero)
{
_errMsg = "GetSeCoordRef:\n No Connection allocated!";
return new SE_COORDREF();
}
SE_COORDREF coordRef = new SE_COORDREF();
SE_LAYERINFO layerInfo = new SE_LAYERINFO();
Int32 _err_no = 0;
try
{
_err_no = Wrapper10.SE_coordref_create(ref coordRef);
if (_err_no != 0) return new SE_COORDREF();
_err_no = Wrapper10.SE_layerinfo_create(coordRef, ref layerInfo);
if (_err_no != 0) return new SE_COORDREF();
_err_no = Wrapper10.SE_layer_get_info(connection.SeConnection, table, spatialColumnName, layerInfo);
if (_err_no != 0) return new SE_COORDREF();
_err_no = Wrapper10.SE_layerinfo_get_coordref(layerInfo, coordRef);
if (_err_no != 0) return new SE_COORDREF();
_err_no = Wrapper10.SE_coordref_get_xy_envelope(coordRef, ref envelope);
if (_err_no != 0) return new SE_COORDREF();
return coordRef;
}
catch (Exception ex)
{
_errMsg = "GetSeCoordRef:\n " + ex.Message + "\n" + ex.StackTrace;
return new SE_COORDREF();
}
finally
{
if (layerInfo.handle != IntPtr.Zero) Wrapper10.SE_layerinfo_free(layerInfo);
if (_err_no != 0)
{
if (coordRef.handle != IntPtr.Zero) Wrapper10.SE_coordref_free(coordRef);
_errMsg = Wrapper10.GetErrorMsg(new SE_CONNECTION(), _err_no);
}
}
}
internal void FreeSeCoordRef(SE_COORDREF coordRef)
{
if (coordRef.handle != IntPtr.Zero)
Wrapper10.SE_coordref_free(coordRef);
coordRef.handle = IntPtr.Zero;
}
internal ISpatialReference GetLayerSpatialReference(SE_CONNECTION connection, string table, string spatialColumnName)
{
_errMsg = "";
if (connection.handle == IntPtr.Zero)
{
_errMsg = "GetLayerSpatialReference:\n No Connection allocated!";
return null;
}
SE_COORDREF coordRef = new SE_COORDREF();
SE_LAYERINFO layerInfo = new SE_LAYERINFO();
Int32 _err_no = 0;
try
{
_err_no = Wrapper10.SE_coordref_create(ref coordRef);
if (_err_no != 0) return null;
_err_no = Wrapper10.SE_layerinfo_create(coordRef, ref layerInfo);
if (_err_no != 0) return null;
_err_no = Wrapper10.SE_layer_get_info(connection, table, spatialColumnName, layerInfo);
if (_err_no != 0) return null;
_err_no = Wrapper10.SE_layerinfo_get_coordref(layerInfo, coordRef);
if (_err_no != 0) return null;
System.Int32 srid = 0;
_err_no = Wrapper10.SE_coordref_get_srid(coordRef, ref srid);
if (_err_no != 0) return null;
byte[] description = new byte[1024 * 4];
_err_no = Wrapper10.SE_coordref_get_description(coordRef, description);
if (_err_no != 0) return null;
string wkt = Functions.GetASCIIString(description);
ISpatialReference sRef = gView.Framework.Geometry.SpatialReference.FromWKT(wkt);
return sRef;
}
catch (Exception ex)
{
_errMsg = "GetLayerSpatialReference:\n " + ex.Message + "\n" + ex.StackTrace;
return null;
}
finally
{
if (layerInfo.handle != IntPtr.Zero) Wrapper10.SE_layerinfo_free(layerInfo);
if (coordRef.handle != IntPtr.Zero) Wrapper10.SE_coordref_free(coordRef);
if (_err_no != 0)
{
_errMsg = Wrapper10.GetErrorMsg(new SE_CONNECTION(), _err_no);
}
}
}
#region IFeatureDataset Member
public gView.Framework.Geometry.IEnvelope Envelope
{
get
{
Envelope env = null;
foreach (IDatasetElement element in _elements)
{
if (element.Class is IFeatureClass && ((IFeatureClass)element.Class).Envelope != null)
{
if (env == null)
{
env = new Envelope(((IFeatureClass)element.Class).Envelope);
}
else
{
env.Union(((IFeatureClass)element.Class).Envelope);
}
}
}
return env == null ? new Envelope() : env;
}
}
public gView.Framework.Geometry.ISpatialReference SpatialReference
{
get;
set;
}
#endregion
#region IDataset Member
public void Dispose()
{
ArcSdeConnection.DisposePool(_connStr, this);
_elements.Clear();
GC.SuppressFinalize(this);
}
public string ConnectionString
{
get
{
return _connStr;
}
set
{
_connStr = value;
if (_connStr.ToLower().StartsWith("sde:"))
{
_connStr = _connStr.Substring(4, _connStr.Length - 4);
}
}
}
public string DatasetGroupName
{
get { return "ESRI Sde"; }
}
public string DatasetName
{
get { return "ESRI Spatial Database Engine"; }
}
public string ProviderName
{
get { return "ESRI"; }
}
public DatasetState State
{
get { return _state; }
}
public bool Open()
{
if (_connStr == "") return false;
//if (_sConnection != null)
//{
// _sConnection.Dispose();
//}
//_sConnection = new SmartSdeConnection(_connStr);
_state = DatasetState.opened;
return true;
}
public string lastErrorMsg
{
get { return _errMsg; }
}
public int order
{
get
{
return 0;
}
set
{
}
}
public IDatasetEnum DatasetEnum
{
get { return null; }
}
public List<IDatasetElement> Elements
{
get
{
if (_elements.Count == 0)
{
IntPtr ptr = new IntPtr(0);
System.Int32 num = 0;
//SdeConnection conn = _sConnection.AllocConnection();
//if (conn == null) return _elements;
using (ArcSdeConnection conn = new ArcSdeConnection(_connStr))
{
if (!conn.Open(this))
{
throw new Exception("can't open: " + conn.LastErrorMessage);
//return _elements;
}
System.Int32 status = Wrapper10.SE_layer_get_info_list(conn.SeConnection, ref ptr, ref num);
if (status != 0)
{
SE_ERROR seErr=new SE_ERROR();
long x = Wrapper10.SE_connection_get_ext_error(conn.SeConnection, ref seErr);
string error = Wrapper10.GetErrorMsg(conn.SeConnection, status);
throw new Exception(error);
//return _elements;
}
unsafe
{
IntPtr* layerInfo = (System.IntPtr*)ptr;
for (int i = 0; i < num; i++)
{
try
{
SE_LAYERINFO seLayerInfo = new SE_LAYERINFO();
seLayerInfo.handle = (System.IntPtr)layerInfo[i];
SdeFeatureClass fc = new SdeFeatureClass(this, conn.SeConnection, seLayerInfo);
if (fc.Name != "")
{
_elements.Add(new DatasetElement(fc));
}
}
catch { }
}
}
conn.Close();
}
if (num > 0) Wrapper10.SE_layer_free_info_list(num, ptr);
}
return _elements;
}
}
public string Query_FieldPrefix
{
get { return ""; }
}
public string Query_FieldPostfix
{
get { return ""; }
}
public gView.Framework.FDB.IDatabase Database
{
get { return null; }
}
public IDatasetElement this[string title]
{
get
{
SE_LAYERINFO layerInfo = new SE_LAYERINFO();
try
{
SdeFeatureClass fc = null;
//SdeConnection connection = _sConnection.AllocConnection();
using (ArcSdeConnection connection = new ArcSdeConnection(_connStr))
{
if (connection.Open(this))
{
if (Wrapper10.SE_layerinfo_create(new SE_COORDREF(), ref layerInfo) != 0) return null;
if (Wrapper10.SE_layer_get_info(connection.SeConnection, title, "", layerInfo) != 0) return null;
fc = new SdeFeatureClass(this, connection.SeConnection, layerInfo);
}
connection.Close();
}
//_sConnection.FreeConnection();
return new DatasetElement(fc);
}
finally
{
if (layerInfo.handle != IntPtr.Zero) Wrapper10.SE_layerinfo_free(layerInfo);
}
}
}
public void RefreshClasses()
{
}
#endregion
#region IDataset2 Member
public IDataset2 EmptyCopy()
{
SdeDataset dataset = new SdeDataset();
dataset.ConnectionString = this.ConnectionString;
dataset.Open();
return dataset;
}
public void AppendElement(string elementName)
{
if (_elements == null) _elements = new List<IDatasetElement>();
foreach (IDatasetElement e in _elements)
{
if (e.Title == elementName) return;
}
IDatasetElement element = this[elementName];
if (element != null) _elements.Add(element);
}
#endregion
#region IPersistable Member
public void Load(IPersistStream stream)
{
string connectionString = (string)stream.Load("connectionstring", "");
this.ConnectionString = connectionString;
this.Open();
}
public void Save(IPersistStream stream)
{
stream.Save("connectionstring", _connStr);
}
#endregion
#region IPlugInDependencies Member
public bool HasUnsolvedDependencies()
{
return SdeDataset.hasUnsolvedDependencies;
}
#endregion
public static bool hasUnsolvedDependencies
{
get
{
try
{
//if (!gView.Framework.system.Wow.Is64BitOperatingSystem)
// return true;
//FileInfo fi = new FileInfo("sde83.dll");
//if (!fi.Exists) return true;
//fi = new FileInfo("pe83.dll");
//if (!fi.Exists) return true;
//fi = new FileInfo("sg83.dll");
//if (!fi.Exists) return true;
FileInfo fi = new FileInfo("sde.dll");
if (!fi.Exists) return true;
fi = new FileInfo("pe.dll");
if (!fi.Exists) return true;
fi = new FileInfo("sg.dll");
if (!fi.Exists) return true;
return false;
}
catch (Exception ex)
{
return true;
}
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ProxyHwnd.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Base class for all the Win32 and office Controls.
//
//
// Only true ROOT object should derive from this class
// NOTE: In the case when ProxyHwnd.ElementProviderFromPoint
// returns provider of type ProxyFragment we MUST do the further drilling ourselves
// since UIAutomation will not (and correctly!!!) do it. (see ProxyFragment's
// comments on how to implement this and WindowsListView.cs for example)
//
// Class ProxyHwnd: ProxyFragment, IRawElementProviderAdviseEvents
// AdviseEventAdded
// AdviseEventRemoved
//
//
//
// History:
// 07/01/2003 : a-jeanp Created
// 08/21/03: alexsn Class explanations
//
//---------------------------------------------------------------------------
// PRESHARP: In order to avoid generating warnings about unkown message numbers and unknown pragmas.
#pragma warning disable 1634, 1691
using System;
using System.Text;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using System.Collections;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Globalization;
using System.ComponentModel;
using MS.Win32;
namespace MS.Internal.AutomationProxies
{
#region ProxyHwnd
// Base Class for all the Windows Control that handle context.
// Implements the default behavior
class ProxyHwnd : ProxyFragment, IRawElementProviderAdviseEvents
{
// ------------------------------------------------------
//
// Constructors
//
// ------------------------------------------------------
#region Constructors
internal ProxyHwnd (IntPtr hwnd, ProxyFragment parent, int item)
: base (hwnd, parent, item)
{
}
#endregion
//------------------------------------------------------
//
// Patterns Implementation
//
//------------------------------------------------------
#region ProxyHwnd Methods
// ------------------------------------------------------
//
// Internal Methods
//
// ------------------------------------------------------
// Advises proxy that an event has been added.
// Maps the Automation Events into WinEvents and add those to the list of WinEvents notification hooks
internal virtual void AdviseEventAdded (AutomationEvent eventId, AutomationProperty [] aidProps)
{
// No RawElementBase creation callback, exit from here
if (_createOnEvent == null)
{
return;
}
int cEvents = 0;
WinEventTracker.EvtIdProperty [] aEvents;
// Gets an Array of WinEvents to trap on a per window handle basis
if (eventId == AutomationElement.AutomationPropertyChangedEvent)
{
aEvents = PropertyToWinEvent (aidProps, out cEvents);
}
else
{
aEvents = EventToWinEvent (eventId, out cEvents);
}
// If we have WinEvents to trap, add those to the list of WinEvent
// notification list
if (cEvents > 0)
{
WinEventTracker.AddToNotificationList (_hwnd, _createOnEvent, aEvents, cEvents);
}
}
// Advises proxy that an event has been removed.
internal virtual void AdviseEventRemoved(AutomationEvent eventId, AutomationProperty [] aidProps)
{
// No RawElementBase creation callback, exit from here
if (_createOnEvent == null)
{
return;
}
int cEvents;
WinEventTracker.EvtIdProperty [] aEvents;
// Gets an Array of WinEvents to trap on a per window handle basis
if (eventId == AutomationElement.AutomationPropertyChangedEvent)
{
aEvents = PropertyToWinEvent (aidProps, out cEvents);
}
else
{
aEvents = EventToWinEvent (eventId, out cEvents);
}
// If we have WinEvents to remove, remive those to the list of WinEvent
// notification list
if (cEvents > 0)
{
WinEventTracker.RemoveToNotificationList (_hwnd, aEvents, null, cEvents);
}
}
// Returns a proxy element corresponding to the specified screen coordinates.
// For an hwnd element, the default behavior is to let UIAutomation do the work.
internal override ProxySimple ElementProviderFromPoint (int x, int y)
{
// Optimisation. If the point is within the client area return this, otherwise it could the the
// non client area. It would be better to return null all the time but this will lead to
// object to be created twice.
return PtInClientRect (_hwnd, x, y) ? this : null;
}
internal override string GetAccessKey()
{
string accessKey = base.GetAccessKey();
if ((bool)GetElementProperty(AutomationElement.IsKeyboardFocusableProperty))
{
if (string.IsNullOrEmpty(accessKey))
{
accessKey = GetLabelAccessKey(_hwnd);
}
}
return accessKey;
}
// Process all the Element Properties
internal override object GetElementProperty (AutomationProperty idProp)
{
// if the hwnd is a winform, then return the Winform id otherwise let
// UIAutomation do the job
if (idProp == AutomationElement.AutomationIdProperty)
{
// [....] have a special way to obtain the id
if (WindowsFormsHelper.IsWindowsFormsControl(_hwnd, ref _windowsForms))
{
string sPersistentID = WindowsFormsHelper.WindowsFormsID (_hwnd);
return string.IsNullOrEmpty(sPersistentID) ? null : sPersistentID;
}
}
else if (idProp == AutomationElement.NameProperty)
{
string name;
// If this is a [....] control and the AccessibleName is set, use it.
if (WindowsFormsHelper.IsWindowsFormsControl(_hwnd, ref _windowsForms))
{
name = GetAccessibleName(NativeMethods.CHILD_SELF);
if (!string.IsNullOrEmpty(name))
{
return name;
}
}
// Only hwnd's can be labeled.
name = LocalizedName;
// PerSharp/PreFast will flag this as a warning 6507/56507: Prefer 'string.IsNullOrEmpty(name)' over checks for null and/or emptiness.
// It is valid to set LocalizedName to an empty string. LocalizedName being an
// empty string will prevent the SendMessage(WM_GETTEXT) call.
#pragma warning suppress 6507
if (name == null && GetParent() == null)
{
if (_fControlHasLabel)
{
IntPtr label = Misc.GetLabelhwnd(_hwnd);
name = Misc.GetControlName(label, true);
if (!string.IsNullOrEmpty(name))
{
_controlLabel = label;
}
}
else
{
name = Misc.ProxyGetText(_hwnd);
}
}
// If name is still null, and we have an IAccessible, try it:
// this picks up names on HWNDs set through Dynamic Annotation
// (eg. on the richedits in Windows Mail), and holds us over till
// we add DA support to UIA properly.
if (String.IsNullOrEmpty(name))
{
name = GetAccessibleName(NativeMethods.CHILD_SELF);
}
return name;
}
// Only hwnd's can be labeled.
else if (idProp == AutomationElement.LabeledByProperty && _fControlHasLabel)
{
// This is called to make sure that _controlLabel gets set.
object name = GetElementProperty(AutomationElement.NameProperty);
// If a control has a LocalizedName, the _controlLabel will not get set.
// So look for it now.
if (_controlLabel == IntPtr.Zero && name != null && GetParent() == null)
{
_controlLabel = Misc.GetLabelhwnd(_hwnd);
}
// If we have a cached _controlLabel that means that the name property we just got
// was retreived from the label of the control and not its text or something else. If this
// is the case expose it as the label.
if (_controlLabel != IntPtr.Zero)
{
return AutomationInteropProvider.HostProviderFromHandle(_controlLabel);
}
}
else if (idProp == AutomationElement.IsOffscreenProperty)
{
if (!SafeNativeMethods.IsWindowVisible(_hwnd))
{
return true;
}
IntPtr hwndParent = Misc.GetParent(_hwnd);
// Check if rect is within rect of parent. Don't do this for top-level windows,
// however, since the win32 desktop hwnd claims to have a rect only as large as the
// primary monitor, making hwnds on other monitors seem clipped.
if (hwndParent != IntPtr.Zero && hwndParent != UnsafeNativeMethods.GetDesktopWindow())
{
NativeMethods.Win32Rect parentRect = NativeMethods.Win32Rect.Empty;
if (Misc.GetClientRectInScreenCoordinates(hwndParent, ref parentRect) && !parentRect.IsEmpty)
{
Rect itemRect = BoundingRectangle;
if (!itemRect.IsEmpty && !Misc.IsItemVisible(ref parentRect, ref itemRect))
{
return true;
}
}
}
}
return base.GetElementProperty(idProp);
}
// Gets the controls help text
internal override string HelpText
{
get
{
int idChild = Misc.GetWindowId(_hwnd);
string text = Misc.GetItemToolTipText(_hwnd, IntPtr.Zero, idChild);
if (string.IsNullOrEmpty(text))
{
text = Misc.GetItemToolTipText(_hwnd, IntPtr.Zero, 0);
}
if (string.IsNullOrEmpty(text))
{
Accessible acc = Accessible.Wrap(AccessibleObject);
if (acc != null)
{
text = acc.Description;
}
}
return text;
}
}
#endregion
#region IRawElementProviderAdviseEvents Interface
// ------------------------------------------------------
//
// IRawElementProviderAdviseEvents interface implementation
//
// ------------------------------------------------------
// Advises event sinks that an event has been added.
void IRawElementProviderAdviseEvents.AdviseEventAdded(int eventIdAsInt, int[] propertiesAsInts)
{
AutomationEvent eventId = AutomationEvent.LookupById(eventIdAsInt);
AutomationProperty [] properties = null;
if (propertiesAsInts != null)
{
properties = new AutomationProperty[propertiesAsInts.Length];
for (int i = 0; i < propertiesAsInts.Length; i++)
{
properties[i] = AutomationProperty.LookupById(propertiesAsInts[i]);
}
}
//ProxyHwnd.AdviseEventAdded
AdviseEventAdded (eventId, properties);
}
// Advises event sinks that an event has been removed.
void IRawElementProviderAdviseEvents.AdviseEventRemoved(int eventIdAsInt, int[] propertiesAsInts)
{
AutomationEvent eventId = AutomationEvent.LookupById(eventIdAsInt);
AutomationProperty [] properties = null;
if (propertiesAsInts != null)
{
properties = new AutomationProperty[propertiesAsInts.Length];
for (int i = 0; i < propertiesAsInts.Length; i++)
{
properties[i] = AutomationProperty.LookupById(propertiesAsInts[i]);
}
}
//ProxyHwnd.AdviseEventRemoved
AdviseEventRemoved (eventId, properties);
}
#endregion
// ------------------------------------------------------
//
// Internal Fields
//
// ------------------------------------------------------
#region Internal Fields
// Callback into the Proxy code to create a raw element based on a WinEvent callback parameters
internal WinEventTracker.ProxyRaiseEvents _createOnEvent = null;
#endregion
// ------------------------------------------------------
//
// Protected Methods
//
// ------------------------------------------------------
#region Protected Methods
// Picks a WinEvent to track for a UIA property
protected virtual int [] PropertyToWinEvent (AutomationProperty idProp)
{
if (idProp == AutomationElement.HasKeyboardFocusProperty)
{
return new int [] { NativeMethods.EventObjectFocus };
}
else if (idProp == AutomationElement.NameProperty)
{
return new int[] { NativeMethods.EventObjectNameChange };
}
else if (idProp == ValuePattern.ValueProperty || idProp == RangeValuePattern.ValueProperty)
{
return new int[] { NativeMethods.EventObjectValueChange };
}
else if (idProp == AutomationElement.IsOffscreenProperty)
{
return new int[] { NativeMethods.EventObjectLocationChange };
}
else if (idProp == ExpandCollapsePattern.ExpandCollapseStateProperty)
{
return new int [] { NativeMethods.EventObjectStateChange,
NativeMethods.EventObjectShow,
NativeMethods.EventObjectHide};
}
// Windows sent OBJECT_VALUECHANGE for changes in the scroll bar with the idObject set to the scroll bar id of the originator
else if ((idProp == ScrollPattern.HorizontalScrollPercentProperty ||
idProp == ScrollPattern.VerticalScrollPercentProperty) ||
idProp == ScrollPattern.HorizontalViewSizeProperty ||
idProp == ScrollPattern.VerticalViewSizeProperty )
{
return new int [] { NativeMethods.EventObjectValueChange };
}
else if (idProp == SelectionItemPattern.IsSelectedProperty)
{
return new int [] { NativeMethods.EventObjectSelectionAdd,
NativeMethods.EventObjectSelectionRemove,
NativeMethods.EventObjectSelection};
}
else if (idProp == TogglePattern.ToggleStateProperty)
{
return new int[] { NativeMethods.EventSystemCaptureEnd,
NativeMethods.EventObjectStateChange };
}
return null;
}
// Builds a list of Win32 WinEvents to process a UIAutomation Event.
protected virtual WinEventTracker.EvtIdProperty [] EventToWinEvent (AutomationEvent idEvent, out int cEvent)
{
// Fill this variable with a WinEvent id if found
int idWinEvent = 0;
if (idEvent == SelectionItemPattern.ElementSelectedEvent)
{
cEvent = 2;
return new WinEventTracker.EvtIdProperty[2]
{
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectSelection, idEvent),
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectStateChange, idEvent)
};
}
else if (idEvent == SelectionItemPattern.ElementAddedToSelectionEvent)
{
// For some control, the Event Selection is sent instead of SelectionAdd
// Trap both.
cEvent = 2;
return new WinEventTracker.EvtIdProperty [2]
{
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectSelectionAdd, idEvent),
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectSelection, idEvent)
};
}
else if (idEvent == SelectionItemPattern.ElementRemovedFromSelectionEvent)
{
idWinEvent = NativeMethods.EventObjectSelectionRemove;
}
else if (idEvent == SelectionPattern.InvalidatedEvent)
{
idWinEvent = NativeMethods.EventObjectSelectionWithin;
}
else if (idEvent == InvokePattern.InvokedEvent)
{
cEvent = 4;
return new WinEventTracker.EvtIdProperty[4] {
new WinEventTracker.EvtIdProperty (NativeMethods.EventSystemCaptureEnd, idEvent), // For SysHeaders
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectStateChange, idEvent),
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectValueChange, idEvent), // For WindowsScrollBarBits
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectInvoke, idEvent)
};
}
else if (idEvent == AutomationElement.StructureChangedEvent)
{
cEvent = 3;
return new WinEventTracker.EvtIdProperty[3] {
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectCreate, idEvent),
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectDestroy, idEvent),
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectReorder, idEvent)
};
}
else if (idEvent == TextPattern.TextSelectionChangedEvent)
{
cEvent = 2;
return new WinEventTracker.EvtIdProperty[2] {
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectLocationChange, idEvent),
new WinEventTracker.EvtIdProperty (NativeMethods.EventObjectTextSelectionChanged, idEvent)
};
}
else
{
cEvent = 0;
return null;
}
// found one and only one
cEvent = 1;
return new WinEventTracker.EvtIdProperty [1] { new WinEventTracker.EvtIdProperty (idWinEvent, idEvent) };
}
// Check if a point is within the client Rect of a window
static protected bool PtInClientRect (IntPtr hwnd, int x, int y)
{
NativeMethods.Win32Rect rc = new NativeMethods.Win32Rect ();
if (!Misc.GetClientRect(hwnd, ref rc))
{
return false;
}
if (!Misc.MapWindowPoints(hwnd, IntPtr.Zero, ref rc, 2))
{
return false;
}
return x >= rc.left && x < rc.right && y >= rc.top && y < rc.bottom;
}
#endregion
// ------------------------------------------------------
//
// Private Methods
//
// ------------------------------------------------------
#region Private Methods
// Get the access key of the associated label (if there is
// an associated label).
static protected string GetLabelAccessKey(IntPtr hwnd)
{
string accessKey = string.Empty;
IntPtr label = Misc.GetLabelhwnd(hwnd);
if (label != IntPtr.Zero)
{
string labelText = Misc.ProxyGetText(label);
if (!string.IsNullOrEmpty(labelText))
{
accessKey = Misc.AccessKey(labelText);
}
}
return accessKey;
}
// Builds a list of Win32 WinEvents to process changes in properties changes values.
// Returns an array of Events to Set. The number of valid entries in this array is pass back in cEvents
private WinEventTracker.EvtIdProperty [] PropertyToWinEvent (AutomationProperty [] aProps, out int cEvent)
{
ArrayList alEvents = new ArrayList (16);
foreach (AutomationProperty idProp in aProps)
{
int [] evtId = PropertyToWinEvent (idProp);
for (int i = 0; evtId != null && i < evtId.Length; i++)
{
alEvents.Add (new WinEventTracker.EvtIdProperty (evtId [i], idProp));
}
}
WinEventTracker.EvtIdProperty [] aEvtIdProperties = new WinEventTracker.EvtIdProperty [alEvents.Count];
cEvent = alEvents.Count;
for (int i = 0; i < cEvent; i++)
{
aEvtIdProperties [i] = (WinEventTracker.EvtIdProperty) alEvents [i];
}
return aEvtIdProperties;
}
#endregion
// ------------------------------------------------------
//
// Private Fields
//
// ------------------------------------------------------
#region Private Fields
// True if the control has an associated label.
protected bool _fControlHasLabel = true;
// The hwnd of static text that is functioning as a label for a control.
// This is initialized in GetElementProperty for the Name property and
// used by the LabeledBy property.
// If !_fControlHasLabel, _controlLabel will be IntPtr.Zero.
private IntPtr _controlLabel;
#endregion
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal class XPathParser
{
private XPathScanner _scanner;
private XPathParser(XPathScanner scanner)
{
_scanner = scanner;
}
public static AstNode ParseXPathExpression(string xpathExpression)
{
XPathScanner scanner = new XPathScanner(xpathExpression);
XPathParser parser = new XPathParser(scanner);
AstNode result = parser.ParseExpression(null);
if (scanner.Kind != XPathScanner.LexKind.Eof)
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
return result;
}
public static AstNode ParseXPathPattern(string xpathPattern)
{
XPathScanner scanner = new XPathScanner(xpathPattern);
XPathParser parser = new XPathParser(scanner);
AstNode result = parser.ParsePattern();
if (scanner.Kind != XPathScanner.LexKind.Eof)
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
return result;
}
// --------------- Expression Parsing ----------------------
//The recursive is like
//ParseOrExpr->ParseAndExpr->ParseEqualityExpr->ParseRelationalExpr...->ParseFilterExpr->ParsePredicate->ParseExpression
//So put 200 limitation here will max cause about 2000~3000 depth stack.
private int _parseDepth = 0;
private const int MaxParseDepth = 200;
private AstNode ParseExpression(AstNode qyInput)
{
if (++_parseDepth > MaxParseDepth)
{
throw XPathException.Create(SR.Xp_QueryTooComplex);
}
AstNode result = ParseOrExpr(qyInput);
--_parseDepth;
return result;
}
//>> OrExpr ::= ( OrExpr 'or' )? AndExpr
private AstNode ParseOrExpr(AstNode qyInput)
{
AstNode opnd = ParseAndExpr(qyInput);
do
{
if (!TestOp("or"))
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.OR, opnd, ParseAndExpr(qyInput));
} while (true);
}
//>> AndExpr ::= ( AndExpr 'and' )? EqualityExpr
private AstNode ParseAndExpr(AstNode qyInput)
{
AstNode opnd = ParseEqualityExpr(qyInput);
do
{
if (!TestOp("and"))
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.AND, opnd, ParseEqualityExpr(qyInput));
} while (true);
}
//>> EqualityOp ::= '=' | '!='
//>> EqualityExpr ::= ( EqualityExpr EqualityOp )? RelationalExpr
private AstNode ParseEqualityExpr(AstNode qyInput)
{
AstNode opnd = ParseRelationalExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Eq ? Operator.Op.EQ :
_scanner.Kind == XPathScanner.LexKind.Ne ? Operator.Op.NE :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseRelationalExpr(qyInput));
} while (true);
}
//>> RelationalOp ::= '<' | '>' | '<=' | '>='
//>> RelationalExpr ::= ( RelationalExpr RelationalOp )? AdditiveExpr
private AstNode ParseRelationalExpr(AstNode qyInput)
{
AstNode opnd = ParseAdditiveExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Lt ? Operator.Op.LT :
_scanner.Kind == XPathScanner.LexKind.Le ? Operator.Op.LE :
_scanner.Kind == XPathScanner.LexKind.Gt ? Operator.Op.GT :
_scanner.Kind == XPathScanner.LexKind.Ge ? Operator.Op.GE :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseAdditiveExpr(qyInput));
} while (true);
}
//>> AdditiveOp ::= '+' | '-'
//>> AdditiveExpr ::= ( AdditiveExpr AdditiveOp )? MultiplicativeExpr
private AstNode ParseAdditiveExpr(AstNode qyInput)
{
AstNode opnd = ParseMultiplicativeExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Plus ? Operator.Op.PLUS :
_scanner.Kind == XPathScanner.LexKind.Minus ? Operator.Op.MINUS :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseMultiplicativeExpr(qyInput));
} while (true);
}
//>> MultiplicativeOp ::= '*' | 'div' | 'mod'
//>> MultiplicativeExpr ::= ( MultiplicativeExpr MultiplicativeOp )? UnaryExpr
private AstNode ParseMultiplicativeExpr(AstNode qyInput)
{
AstNode opnd = ParseUnaryExpr(qyInput);
do
{
Operator.Op op = (
_scanner.Kind == XPathScanner.LexKind.Star ? Operator.Op.MUL :
TestOp("div") ? Operator.Op.DIV :
TestOp("mod") ? Operator.Op.MOD :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseUnaryExpr(qyInput));
} while (true);
}
//>> UnaryExpr ::= UnionExpr | '-' UnaryExpr
private AstNode ParseUnaryExpr(AstNode qyInput)
{
bool minus = false;
while (_scanner.Kind == XPathScanner.LexKind.Minus)
{
NextLex();
minus = !minus;
}
if (minus)
{
return new Operator(Operator.Op.MUL, ParseUnionExpr(qyInput), new Operand(-1));
}
else
{
return ParseUnionExpr(qyInput);
}
}
//>> UnionExpr ::= ( UnionExpr '|' )? PathExpr
private AstNode ParseUnionExpr(AstNode qyInput)
{
AstNode opnd = ParsePathExpr(qyInput);
do
{
if (_scanner.Kind != XPathScanner.LexKind.Union)
{
return opnd;
}
NextLex();
AstNode opnd2 = ParsePathExpr(qyInput);
CheckNodeSet(opnd.ReturnType);
CheckNodeSet(opnd2.ReturnType);
opnd = new Operator(Operator.Op.UNION, opnd, opnd2);
} while (true);
}
private static bool IsNodeType(XPathScanner scaner)
{
return (
scaner.Prefix.Length == 0 && (
scaner.Name == "node" ||
scaner.Name == "text" ||
scaner.Name == "processing-instruction" ||
scaner.Name == "comment"
)
);
}
//>> PathOp ::= '/' | '//'
//>> PathExpr ::= LocationPath |
//>> FilterExpr ( PathOp RelativeLocationPath )?
private AstNode ParsePathExpr(AstNode qyInput)
{
AstNode opnd;
if (IsPrimaryExpr(_scanner))
{ // in this moment we should distinct LocationPas vs FilterExpr (which starts from is PrimaryExpr)
opnd = ParseFilterExpr(qyInput);
if (_scanner.Kind == XPathScanner.LexKind.Slash)
{
NextLex();
opnd = ParseRelativeLocationPath(opnd);
}
else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash)
{
NextLex();
opnd = ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, opnd));
}
}
else
{
opnd = ParseLocationPath(null);
}
return opnd;
}
//>> FilterExpr ::= PrimaryExpr | FilterExpr Predicate
private AstNode ParseFilterExpr(AstNode qyInput)
{
AstNode opnd = ParsePrimaryExpr(qyInput);
while (_scanner.Kind == XPathScanner.LexKind.LBracket)
{
// opnd must be a query
opnd = new Filter(opnd, ParsePredicate(opnd));
}
return opnd;
}
//>> Predicate ::= '[' Expr ']'
private AstNode ParsePredicate(AstNode qyInput)
{
AstNode opnd;
// we have predicates. Check that input type is NodeSet
CheckNodeSet(qyInput.ReturnType);
PassToken(XPathScanner.LexKind.LBracket);
opnd = ParseExpression(qyInput);
PassToken(XPathScanner.LexKind.RBracket);
return opnd;
}
//>> LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
private AstNode ParseLocationPath(AstNode qyInput)
{
if (_scanner.Kind == XPathScanner.LexKind.Slash)
{
NextLex();
AstNode opnd = new Root();
if (IsStep(_scanner.Kind))
{
opnd = ParseRelativeLocationPath(opnd);
}
return opnd;
}
else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash)
{
NextLex();
return ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, new Root()));
}
else
{
return ParseRelativeLocationPath(qyInput);
}
} // ParseLocationPath
//>> PathOp ::= '/' | '//'
//>> RelativeLocationPath ::= ( RelativeLocationPath PathOp )? Step
private AstNode ParseRelativeLocationPath(AstNode qyInput)
{
AstNode opnd = qyInput;
do
{
opnd = ParseStep(opnd);
if (XPathScanner.LexKind.SlashSlash == _scanner.Kind)
{
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd);
}
else if (XPathScanner.LexKind.Slash == _scanner.Kind)
{
NextLex();
}
else
{
break;
}
}
while (true);
return opnd;
}
private static bool IsStep(XPathScanner.LexKind lexKind)
{
return (
lexKind == XPathScanner.LexKind.Dot ||
lexKind == XPathScanner.LexKind.DotDot ||
lexKind == XPathScanner.LexKind.At ||
lexKind == XPathScanner.LexKind.Axe ||
lexKind == XPathScanner.LexKind.Star ||
lexKind == XPathScanner.LexKind.Name // NodeTest is also Name
);
}
//>> Step ::= '.' | '..' | ( AxisName '::' | '@' )? NodeTest Predicate*
private AstNode ParseStep(AstNode qyInput)
{
AstNode opnd;
if (XPathScanner.LexKind.Dot == _scanner.Kind)
{ //>> '.'
NextLex();
opnd = new Axis(Axis.AxisType.Self, qyInput);
}
else if (XPathScanner.LexKind.DotDot == _scanner.Kind)
{ //>> '..'
NextLex();
opnd = new Axis(Axis.AxisType.Parent, qyInput);
}
else
{ //>> ( AxisName '::' | '@' )? NodeTest Predicate*
Axis.AxisType axisType = Axis.AxisType.Child;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.At: //>> '@'
axisType = Axis.AxisType.Attribute;
NextLex();
break;
case XPathScanner.LexKind.Axe: //>> AxisName '::'
axisType = GetAxis();
NextLex();
break;
}
XPathNodeType nodeType = (
axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute :
// axisType == Axis.AxisType.Namespace ? XPathNodeType.Namespace : // No Idea why it's this way but otherwise Axes doesn't work
/* default: */ XPathNodeType.Element
);
opnd = ParseNodeTest(qyInput, axisType, nodeType);
while (XPathScanner.LexKind.LBracket == _scanner.Kind)
{
opnd = new Filter(opnd, ParsePredicate(opnd));
}
}
return opnd;
}
//>> NodeTest ::= NameTest | 'comment ()' | 'text ()' | 'node ()' | 'processing-instruction (' Literal ? ')'
private AstNode ParseNodeTest(AstNode qyInput, Axis.AxisType axisType, XPathNodeType nodeType)
{
string nodeName, nodePrefix;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.Name:
if (_scanner.CanBeFunction && IsNodeType(_scanner))
{
nodePrefix = string.Empty;
nodeName = string.Empty;
nodeType = (
_scanner.Name == "comment" ? XPathNodeType.Comment :
_scanner.Name == "text" ? XPathNodeType.Text :
_scanner.Name == "node" ? XPathNodeType.All :
_scanner.Name == "processing-instruction" ? XPathNodeType.ProcessingInstruction :
/* default: */ XPathNodeType.Root
);
Debug.Assert(nodeType != XPathNodeType.Root);
NextLex();
PassToken(XPathScanner.LexKind.LParens);
if (nodeType == XPathNodeType.ProcessingInstruction)
{
if (_scanner.Kind != XPathScanner.LexKind.RParens)
{ //>> 'processing-instruction (' Literal ')'
CheckToken(XPathScanner.LexKind.String);
nodeName = _scanner.StringValue;
NextLex();
}
}
PassToken(XPathScanner.LexKind.RParens);
}
else
{
nodePrefix = _scanner.Prefix;
nodeName = _scanner.Name;
NextLex();
if (nodeName == "*")
{
nodeName = string.Empty;
}
}
break;
case XPathScanner.LexKind.Star:
nodePrefix = string.Empty;
nodeName = string.Empty;
NextLex();
break;
default:
throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText);
}
return new Axis(axisType, qyInput, nodePrefix, nodeName, nodeType);
}
private static bool IsPrimaryExpr(XPathScanner scanner)
{
return (
scanner.Kind == XPathScanner.LexKind.String ||
scanner.Kind == XPathScanner.LexKind.Number ||
scanner.Kind == XPathScanner.LexKind.Dollar ||
scanner.Kind == XPathScanner.LexKind.LParens ||
scanner.Kind == XPathScanner.LexKind.Name && scanner.CanBeFunction && !IsNodeType(scanner)
);
}
//>> PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall
private AstNode ParsePrimaryExpr(AstNode qyInput)
{
Debug.Assert(IsPrimaryExpr(_scanner));
AstNode opnd = null;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.String:
opnd = new Operand(_scanner.StringValue);
NextLex();
break;
case XPathScanner.LexKind.Number:
opnd = new Operand(_scanner.NumberValue);
NextLex();
break;
case XPathScanner.LexKind.Dollar:
NextLex();
CheckToken(XPathScanner.LexKind.Name);
opnd = new Variable(_scanner.Name, _scanner.Prefix);
NextLex();
break;
case XPathScanner.LexKind.LParens:
NextLex();
opnd = ParseExpression(qyInput);
if (opnd.Type != AstNode.AstType.ConstantOperand)
{
opnd = new Group(opnd);
}
PassToken(XPathScanner.LexKind.RParens);
break;
case XPathScanner.LexKind.Name:
if (_scanner.CanBeFunction && !IsNodeType(_scanner))
{
opnd = ParseMethod(null);
}
break;
}
Debug.Assert(opnd != null, "IsPrimaryExpr() was true. We should recognize this lex.");
return opnd;
}
private AstNode ParseMethod(AstNode qyInput)
{
List<AstNode> argList = new List<AstNode>();
string name = _scanner.Name;
string prefix = _scanner.Prefix;
PassToken(XPathScanner.LexKind.Name);
PassToken(XPathScanner.LexKind.LParens);
if (_scanner.Kind != XPathScanner.LexKind.RParens)
{
do
{
argList.Add(ParseExpression(qyInput));
if (_scanner.Kind == XPathScanner.LexKind.RParens)
{
break;
}
PassToken(XPathScanner.LexKind.Comma);
} while (true);
}
PassToken(XPathScanner.LexKind.RParens);
if (prefix.Length == 0)
{
ParamInfo pi;
if (s_functionTable.TryGetValue(name, out pi))
{
int argCount = argList.Count;
if (argCount < pi.Minargs)
{
throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText);
}
if (pi.FType == Function.FunctionType.FuncConcat)
{
for (int i = 0; i < argCount; i++)
{
AstNode arg = (AstNode)argList[i];
if (arg.ReturnType != XPathResultType.String)
{
arg = new Function(Function.FunctionType.FuncString, arg);
}
argList[i] = arg;
}
}
else
{
if (pi.Maxargs < argCount)
{
throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText);
}
if (pi.ArgTypes.Length < argCount)
{
argCount = pi.ArgTypes.Length; // argument we have the type specified (can be < pi.Minargs)
}
for (int i = 0; i < argCount; i++)
{
AstNode arg = (AstNode)argList[i];
if (
pi.ArgTypes[i] != XPathResultType.Any &&
pi.ArgTypes[i] != arg.ReturnType
)
{
switch (pi.ArgTypes[i])
{
case XPathResultType.NodeSet:
if (!(arg is Variable) && !(arg is Function && arg.ReturnType == XPathResultType.Any))
{
throw XPathException.Create(SR.Xp_InvalidArgumentType, name, _scanner.SourceText);
}
break;
case XPathResultType.String:
arg = new Function(Function.FunctionType.FuncString, arg);
break;
case XPathResultType.Number:
arg = new Function(Function.FunctionType.FuncNumber, arg);
break;
case XPathResultType.Boolean:
arg = new Function(Function.FunctionType.FuncBoolean, arg);
break;
}
argList[i] = arg;
}
}
}
return new Function(pi.FType, argList);
}
}
return new Function(prefix, name, argList);
}
// --------------- Pattern Parsing ----------------------
//>> Pattern ::= ( Pattern '|' )? LocationPathPattern
private AstNode ParsePattern()
{
AstNode opnd = ParseLocationPathPattern();
do
{
if (_scanner.Kind != XPathScanner.LexKind.Union)
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.UNION, opnd, ParseLocationPathPattern());
} while (true);
}
//>> LocationPathPattern ::= '/' | RelativePathPattern | '//' RelativePathPattern | '/' RelativePathPattern
//>> | IdKeyPattern (('/' | '//') RelativePathPattern)?
private AstNode ParseLocationPathPattern()
{
AstNode opnd = null;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.Slash:
NextLex();
opnd = new Root();
if (_scanner.Kind == XPathScanner.LexKind.Eof || _scanner.Kind == XPathScanner.LexKind.Union)
{
return opnd;
}
break;
case XPathScanner.LexKind.SlashSlash:
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, new Root());
break;
case XPathScanner.LexKind.Name:
if (_scanner.CanBeFunction)
{
opnd = ParseIdKeyPattern();
if (opnd != null)
{
switch (_scanner.Kind)
{
case XPathScanner.LexKind.Slash:
NextLex();
break;
case XPathScanner.LexKind.SlashSlash:
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd);
break;
default:
return opnd;
}
}
}
break;
}
return ParseRelativePathPattern(opnd);
}
//>> IdKeyPattern ::= 'id' '(' Literal ')' | 'key' '(' Literal ',' Literal ')'
private AstNode ParseIdKeyPattern()
{
Debug.Assert(_scanner.CanBeFunction);
List<AstNode> argList = new List<AstNode>();
if (_scanner.Prefix.Length == 0)
{
if (_scanner.Name == "id")
{
ParamInfo pi = (ParamInfo)s_functionTable["id"];
NextLex();
PassToken(XPathScanner.LexKind.LParens);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(_scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.RParens);
return new Function(pi.FType, argList);
}
if (_scanner.Name == "key")
{
NextLex();
PassToken(XPathScanner.LexKind.LParens);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(_scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.Comma);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(_scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.RParens);
return new Function("", "key", argList);
}
}
return null;
}
//>> PathOp ::= '/' | '//'
//>> RelativePathPattern ::= ( RelativePathPattern PathOp )? StepPattern
private AstNode ParseRelativePathPattern(AstNode qyInput)
{
AstNode opnd = ParseStepPattern(qyInput);
if (XPathScanner.LexKind.SlashSlash == _scanner.Kind)
{
NextLex();
opnd = ParseRelativePathPattern(new Axis(Axis.AxisType.DescendantOrSelf, opnd));
}
else if (XPathScanner.LexKind.Slash == _scanner.Kind)
{
NextLex();
opnd = ParseRelativePathPattern(opnd);
}
return opnd;
}
//>> StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate*
//>> ChildOrAttributeAxisSpecifier ::= @ ? | ('child' | 'attribute') '::'
private AstNode ParseStepPattern(AstNode qyInput)
{
AstNode opnd;
Axis.AxisType axisType = Axis.AxisType.Child;
switch (_scanner.Kind)
{
case XPathScanner.LexKind.At: //>> '@'
axisType = Axis.AxisType.Attribute;
NextLex();
break;
case XPathScanner.LexKind.Axe: //>> AxisName '::'
axisType = GetAxis();
if (axisType != Axis.AxisType.Child && axisType != Axis.AxisType.Attribute)
{
throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText);
}
NextLex();
break;
}
XPathNodeType nodeType = (
axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute :
/* default: */ XPathNodeType.Element
);
opnd = ParseNodeTest(qyInput, axisType, nodeType);
while (XPathScanner.LexKind.LBracket == _scanner.Kind)
{
opnd = new Filter(opnd, ParsePredicate(opnd));
}
return opnd;
}
// --------------- Helper methods ----------------------
void CheckToken(XPathScanner.LexKind t)
{
if (_scanner.Kind != t)
{
throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText);
}
}
void PassToken(XPathScanner.LexKind t)
{
CheckToken(t);
NextLex();
}
void NextLex()
{
_scanner.NextLex();
}
private bool TestOp(string op)
{
return (
_scanner.Kind == XPathScanner.LexKind.Name &&
_scanner.Prefix.Length == 0 &&
_scanner.Name.Equals(op)
);
}
void CheckNodeSet(XPathResultType t)
{
if (t != XPathResultType.NodeSet && t != XPathResultType.Any)
{
throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText);
}
}
// ----------------------------------------------------------------
private static readonly XPathResultType[] s_temparray1 = Array.Empty<XPathResultType>();
private static readonly XPathResultType[] s_temparray2 = { XPathResultType.NodeSet };
private static readonly XPathResultType[] s_temparray3 = { XPathResultType.Any };
private static readonly XPathResultType[] s_temparray4 = { XPathResultType.String };
private static readonly XPathResultType[] s_temparray5 = { XPathResultType.String, XPathResultType.String };
private static readonly XPathResultType[] s_temparray6 = { XPathResultType.String, XPathResultType.Number, XPathResultType.Number };
private static readonly XPathResultType[] s_temparray7 = { XPathResultType.String, XPathResultType.String, XPathResultType.String };
private static readonly XPathResultType[] s_temparray8 = { XPathResultType.Boolean };
private static readonly XPathResultType[] s_temparray9 = { XPathResultType.Number };
private class ParamInfo
{
private Function.FunctionType _ftype;
private int _minargs;
private int _maxargs;
private XPathResultType[] _argTypes;
public Function.FunctionType FType { get { return _ftype; } }
public int Minargs { get { return _minargs; } }
public int Maxargs { get { return _maxargs; } }
public XPathResultType[] ArgTypes { get { return _argTypes; } }
internal ParamInfo(Function.FunctionType ftype, int minargs, int maxargs, XPathResultType[] argTypes)
{
_ftype = ftype;
_minargs = minargs;
_maxargs = maxargs;
_argTypes = argTypes;
}
} //ParamInfo
private static Dictionary<string, ParamInfo> s_functionTable = CreateFunctionTable();
private static Dictionary<string, ParamInfo> CreateFunctionTable()
{
Dictionary<string, ParamInfo> table = new Dictionary<string, ParamInfo>(36);
table.Add("last", new ParamInfo(Function.FunctionType.FuncLast, 0, 0, s_temparray1));
table.Add("position", new ParamInfo(Function.FunctionType.FuncPosition, 0, 0, s_temparray1));
table.Add("name", new ParamInfo(Function.FunctionType.FuncName, 0, 1, s_temparray2));
table.Add("namespace-uri", new ParamInfo(Function.FunctionType.FuncNameSpaceUri, 0, 1, s_temparray2));
table.Add("local-name", new ParamInfo(Function.FunctionType.FuncLocalName, 0, 1, s_temparray2));
table.Add("count", new ParamInfo(Function.FunctionType.FuncCount, 1, 1, s_temparray2));
table.Add("id", new ParamInfo(Function.FunctionType.FuncID, 1, 1, s_temparray3));
table.Add("string", new ParamInfo(Function.FunctionType.FuncString, 0, 1, s_temparray3));
table.Add("concat", new ParamInfo(Function.FunctionType.FuncConcat, 2, 100, s_temparray4));
table.Add("starts-with", new ParamInfo(Function.FunctionType.FuncStartsWith, 2, 2, s_temparray5));
table.Add("contains", new ParamInfo(Function.FunctionType.FuncContains, 2, 2, s_temparray5));
table.Add("substring-before", new ParamInfo(Function.FunctionType.FuncSubstringBefore, 2, 2, s_temparray5));
table.Add("substring-after", new ParamInfo(Function.FunctionType.FuncSubstringAfter, 2, 2, s_temparray5));
table.Add("substring", new ParamInfo(Function.FunctionType.FuncSubstring, 2, 3, s_temparray6));
table.Add("string-length", new ParamInfo(Function.FunctionType.FuncStringLength, 0, 1, s_temparray4));
table.Add("normalize-space", new ParamInfo(Function.FunctionType.FuncNormalize, 0, 1, s_temparray4));
table.Add("translate", new ParamInfo(Function.FunctionType.FuncTranslate, 3, 3, s_temparray7));
table.Add("boolean", new ParamInfo(Function.FunctionType.FuncBoolean, 1, 1, s_temparray3));
table.Add("not", new ParamInfo(Function.FunctionType.FuncNot, 1, 1, s_temparray8));
table.Add("true", new ParamInfo(Function.FunctionType.FuncTrue, 0, 0, s_temparray8));
table.Add("false", new ParamInfo(Function.FunctionType.FuncFalse, 0, 0, s_temparray8));
table.Add("lang", new ParamInfo(Function.FunctionType.FuncLang, 1, 1, s_temparray4));
table.Add("number", new ParamInfo(Function.FunctionType.FuncNumber, 0, 1, s_temparray3));
table.Add("sum", new ParamInfo(Function.FunctionType.FuncSum, 1, 1, s_temparray2));
table.Add("floor", new ParamInfo(Function.FunctionType.FuncFloor, 1, 1, s_temparray9));
table.Add("ceiling", new ParamInfo(Function.FunctionType.FuncCeiling, 1, 1, s_temparray9));
table.Add("round", new ParamInfo(Function.FunctionType.FuncRound, 1, 1, s_temparray9));
return table;
}
private static Dictionary<string, Axis.AxisType> s_AxesTable = CreateAxesTable();
private static Dictionary<string, Axis.AxisType> CreateAxesTable()
{
Dictionary<string, Axis.AxisType> table = new Dictionary<string, Axis.AxisType>(13);
table.Add("ancestor", Axis.AxisType.Ancestor);
table.Add("ancestor-or-self", Axis.AxisType.AncestorOrSelf);
table.Add("attribute", Axis.AxisType.Attribute);
table.Add("child", Axis.AxisType.Child);
table.Add("descendant", Axis.AxisType.Descendant);
table.Add("descendant-or-self", Axis.AxisType.DescendantOrSelf);
table.Add("following", Axis.AxisType.Following);
table.Add("following-sibling", Axis.AxisType.FollowingSibling);
table.Add("namespace", Axis.AxisType.Namespace);
table.Add("parent", Axis.AxisType.Parent);
table.Add("preceding", Axis.AxisType.Preceding);
table.Add("preceding-sibling", Axis.AxisType.PrecedingSibling);
table.Add("self", Axis.AxisType.Self);
return table;
}
private Axis.AxisType GetAxis()
{
Debug.Assert(_scanner.Kind == XPathScanner.LexKind.Axe);
Axis.AxisType axis;
if (!s_AxesTable.TryGetValue(_scanner.Name, out axis))
{
throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText);
}
return axis;
}
}
}
| |
using Lucene.Net.Support;
using System;
using Lucene.Net.Diagnostics;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// A memory-resident <see cref="IndexOutput"/> implementation.
/// <para/>
/// @lucene.internal
/// </summary>
public class RAMOutputStream : IndexOutput
{
internal const int BUFFER_SIZE = 1024;
private RAMFile file;
private byte[] currentBuffer;
private int currentBufferIndex;
private int bufferPosition;
private long bufferStart;
private int bufferLength;
private BufferedChecksum crc = new BufferedChecksum(new CRC32());
/// <summary>
/// Construct an empty output buffer. </summary>
public RAMOutputStream()
: this(new RAMFile())
{
}
public RAMOutputStream(RAMFile f)
{
file = f;
// make sure that we switch to the
// first needed buffer lazily
currentBufferIndex = -1;
currentBuffer = null;
}
/// <summary>
/// Copy the current contents of this buffer to the named output. </summary>
public virtual void WriteTo(DataOutput @out)
{
Flush();
long end = file.length;
long pos = 0;
int buffer = 0;
while (pos < end)
{
int length = BUFFER_SIZE;
long nextPos = pos + length;
if (nextPos > end) // at the last buffer
{
length = (int)(end - pos);
}
@out.WriteBytes(file.GetBuffer(buffer++), length);
pos = nextPos;
}
}
/// <summary>
/// Copy the current contents of this buffer to output
/// byte array
/// </summary>
public virtual void WriteTo(byte[] bytes, int offset)
{
Flush();
long end = file.length;
long pos = 0;
int buffer = 0;
int bytesUpto = offset;
while (pos < end)
{
int length = BUFFER_SIZE;
long nextPos = pos + length;
if (nextPos > end) // at the last buffer
{
length = (int)(end - pos);
}
System.Buffer.BlockCopy(file.GetBuffer(buffer++), 0, bytes, bytesUpto, length);
bytesUpto += length;
pos = nextPos;
}
}
/// <summary>
/// Resets this to an empty file. </summary>
public virtual void Reset()
{
currentBuffer = null;
currentBufferIndex = -1;
bufferPosition = 0;
bufferStart = 0;
bufferLength = 0;
file.Length = 0;
crc.Reset();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Flush();
}
}
[Obsolete("(4.1) this method will be removed in Lucene 5.0")]
public override void Seek(long pos)
{
// set the file length in case we seek back
// and flush() has not been called yet
SetFileLength();
if (pos < bufferStart || pos >= bufferStart + bufferLength)
{
currentBufferIndex = (int)(pos / BUFFER_SIZE);
SwitchCurrentBuffer();
}
bufferPosition = (int)(pos % BUFFER_SIZE);
}
public override long Length
{
get => file.length;
set
{
}
}
public override void WriteByte(byte b)
{
if (bufferPosition == bufferLength)
{
currentBufferIndex++;
SwitchCurrentBuffer();
}
crc.Update(b);
currentBuffer[bufferPosition++] = b;
}
public override void WriteBytes(byte[] b, int offset, int len)
{
if (Debugging.AssertsEnabled) Debugging.Assert(b != null);
crc.Update(b, offset, len);
while (len > 0)
{
if (bufferPosition == bufferLength)
{
currentBufferIndex++;
SwitchCurrentBuffer();
}
int remainInBuffer = currentBuffer.Length - bufferPosition;
int bytesToCopy = len < remainInBuffer ? len : remainInBuffer;
System.Buffer.BlockCopy(b, offset, currentBuffer, bufferPosition, bytesToCopy);
offset += bytesToCopy;
len -= bytesToCopy;
bufferPosition += bytesToCopy;
}
}
private void SwitchCurrentBuffer()
{
if (currentBufferIndex == file.NumBuffers)
{
currentBuffer = file.AddBuffer(BUFFER_SIZE);
}
else
{
currentBuffer = file.GetBuffer(currentBufferIndex);
}
bufferPosition = 0;
bufferStart = (long)BUFFER_SIZE * (long)currentBufferIndex;
bufferLength = currentBuffer.Length;
}
private void SetFileLength()
{
long pointer = bufferStart + bufferPosition;
if (pointer > file.length)
{
file.Length = pointer;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Flush()
{
SetFileLength();
}
public override long GetFilePointer()
{
return currentBufferIndex < 0 ? 0 : bufferStart + bufferPosition;
}
/// <summary>
/// Returns byte usage of all buffers. </summary>
public virtual long GetSizeInBytes()
{
return (long)file.NumBuffers * (long)BUFFER_SIZE;
}
public override long Checksum => crc.Value;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Tests
{
public abstract partial class HashSet_Generic_Tests<T> : ISet_Generic_Tests<T>
{
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void HashSet_Generic_Constructor_int(int capacity)
{
HashSet<T> set = new HashSet<T>(capacity);
Assert.Equal(0, set.Count);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void HashSet_Generic_Constructor_int_AddUpToAndBeyondCapacity(int capacity)
{
HashSet<T> set = new HashSet<T>(capacity);
AddToCollection(set, capacity);
Assert.Equal(capacity, set.Count);
AddToCollection(set, capacity + 1);
Assert.Equal(capacity + 1, set.Count);
}
[Fact]
public void HashSet_Generic_Constructor_Capacity_ToNextPrimeNumber()
{
// Highest pre-computed number + 1.
const int Capacity = 7199370;
var set = new HashSet<T>(Capacity);
// Assert that the HashTable's capacity is set to the descendant prime number of the given one.
const int NextPrime = 7199371;
Assert.Equal(NextPrime, set.EnsureCapacity(0));
}
[Fact]
public void HashSet_Generic_Constructor_int_Negative_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void HashSet_Generic_Constructor_int_IEqualityComparer(int capacity)
{
IEqualityComparer<T> comparer = GetIEqualityComparer();
HashSet<T> set = new HashSet<T>(capacity, comparer);
Assert.Equal(0, set.Count);
if (comparer == null)
Assert.Equal(EqualityComparer<T>.Default, set.Comparer);
else
Assert.Equal(comparer, set.Comparer);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void HashSet_Generic_Constructor_int_IEqualityComparer_AddUpToAndBeyondCapacity(int capacity)
{
IEqualityComparer<T> comparer = GetIEqualityComparer();
HashSet<T> set = new HashSet<T>(capacity, comparer);
AddToCollection(set, capacity);
Assert.Equal(capacity, set.Count);
AddToCollection(set, capacity + 1);
Assert.Equal(capacity + 1, set.Count);
}
[Fact]
public void HashSet_Generic_Constructor_int_IEqualityComparer_Negative_ThrowsArgumentOutOfRangeException()
{
IEqualityComparer<T> comparer = GetIEqualityComparer();
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1, comparer));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue, comparer));
}
#region TryGetValue
[Fact]
public void HashSet_Generic_TryGetValue_Contains()
{
T value = CreateT(1);
HashSet<T> set = new HashSet<T> { value };
T equalValue = CreateT(1);
T actualValue;
Assert.True(set.TryGetValue(equalValue, out actualValue));
Assert.Equal(value, actualValue);
if (!typeof(T).IsValueType)
{
Assert.Same((object)value, (object)actualValue);
}
}
[Fact]
public void HashSet_Generic_TryGetValue_Contains_OverwriteOutputParam()
{
T value = CreateT(1);
HashSet<T> set = new HashSet<T> { value };
T equalValue = CreateT(1);
T actualValue = CreateT(2);
Assert.True(set.TryGetValue(equalValue, out actualValue));
Assert.Equal(value, actualValue);
if (!typeof(T).IsValueType)
{
Assert.Same((object)value, (object)actualValue);
}
}
[Fact]
public void HashSet_Generic_TryGetValue_NotContains()
{
T value = CreateT(1);
HashSet<T> set = new HashSet<T> { value };
T equalValue = CreateT(2);
T actualValue;
Assert.False(set.TryGetValue(equalValue, out actualValue));
Assert.Equal(default(T), actualValue);
}
[Fact]
public void HashSet_Generic_TryGetValue_NotContains_OverwriteOutputParam()
{
T value = CreateT(1);
HashSet<T> set = new HashSet<T> { value };
T equalValue = CreateT(2);
T actualValue = equalValue;
Assert.False(set.TryGetValue(equalValue, out actualValue));
Assert.Equal(default(T), actualValue);
}
#endregion
#region EnsureCapacity
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void EnsureCapacity_Generic_RequestingLargerCapacity_DoesNotInvalidateEnumeration(int setLength)
{
HashSet<T> set = (HashSet<T>)(GenericISetFactory(setLength));
var capacity = set.EnsureCapacity(0);
IEnumerator valuesEnum = set.GetEnumerator();
IEnumerator valuesListEnum = new List<T>(set).GetEnumerator();
set.EnsureCapacity(capacity + 1); // Verify EnsureCapacity does not invalidate enumeration
while (valuesEnum.MoveNext())
{
valuesListEnum.MoveNext();
Assert.Equal(valuesListEnum.Current, valuesEnum.Current);
}
}
[Fact]
public void EnsureCapacity_Generic_NegativeCapacityRequested_Throws()
{
var set = new HashSet<T>();
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => set.EnsureCapacity(-1));
}
[Fact]
public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedZero_ReturnsZero()
{
var set = new HashSet<T>();
Assert.Equal(0, set.EnsureCapacity(0));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedNonZero_CapacityIsSetToAtLeastTheRequested(int requestedCapacity)
{
var set = new HashSet<T>();
Assert.InRange(set.EnsureCapacity(requestedCapacity), requestedCapacity, int.MaxValue);
}
[Theory]
[InlineData(3)]
[InlineData(7)]
public void EnsureCapacity_Generic_RequestedCapacitySmallerThanCurrent_CapacityUnchanged(int currentCapacity)
{
HashSet<T> set;
// assert capacity remains the same when ensuring a capacity smaller or equal than existing
for (int i = 0; i <= currentCapacity; i++)
{
set = new HashSet<T>(currentCapacity);
Assert.Equal(currentCapacity, set.EnsureCapacity(i));
}
}
[Theory]
[InlineData(7)]
[InlineData(89)]
public void EnsureCapacity_Generic_ExistingCapacityRequested_SameValueReturned(int capacity)
{
var set = new HashSet<T>(capacity);
Assert.Equal(capacity, set.EnsureCapacity(capacity));
set = (HashSet<T>)GenericISetFactory(capacity);
Assert.Equal(capacity, set.EnsureCapacity(capacity));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
public void EnsureCapacity_Generic_EnsureCapacityCalledTwice_ReturnsSameValue(int setLength)
{
HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
int capacity = set.EnsureCapacity(0);
Assert.Equal(capacity, set.EnsureCapacity(0));
set = (HashSet<T>)GenericISetFactory(setLength);
capacity = set.EnsureCapacity(setLength);
Assert.Equal(capacity, set.EnsureCapacity(setLength));
set = (HashSet<T>)GenericISetFactory(setLength);
capacity = set.EnsureCapacity(setLength + 1);
Assert.Equal(capacity, set.EnsureCapacity(setLength + 1));
}
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(7)]
[InlineData(8)]
public void EnsureCapacity_Generic_HashsetNotEmpty_RequestedSmallerThanCount_ReturnsAtLeastSizeOfCount(int setLength)
{
HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
Assert.InRange(set.EnsureCapacity(setLength - 1), setLength, int.MaxValue);
}
[Theory]
[InlineData(7)]
[InlineData(20)]
public void EnsureCapacity_Generic_HashsetNotEmpty_SetsToAtLeastTheRequested(int setLength)
{
HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
// get current capacity
int currentCapacity = set.EnsureCapacity(0);
// assert we can update to a larger capacity
int newCapacity = set.EnsureCapacity(currentCapacity * 2);
Assert.InRange(newCapacity, currentCapacity * 2, int.MaxValue);
}
[Fact]
public void EnsureCapacity_Generic_CapacityIsSetToPrimeNumberLargerOrEqualToRequested()
{
var set = new HashSet<T>();
Assert.Equal(17, set.EnsureCapacity(17));
set = new HashSet<T>();
Assert.Equal(17, set.EnsureCapacity(15));
set = new HashSet<T>();
Assert.Equal(17, set.EnsureCapacity(13));
}
[Theory]
[InlineData(2)]
[InlineData(10)]
public void EnsureCapacity_Generic_GrowCapacityWithFreeList(int setLength)
{
HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength);
// Remove the first element to ensure we have a free list.
Assert.True(set.Remove(set.ElementAt(0)));
int currentCapacity = set.EnsureCapacity(0);
Assert.True(currentCapacity > 0);
int newCapacity = set.EnsureCapacity(currentCapacity + 1);
Assert.True(newCapacity > currentCapacity);
}
#endregion
}
}
| |
/*
* 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 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.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using OpenMetaverse;
using Nini.Config;
using InWorldz.JWT;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Framework.Console
{
public class ConsoleConnection
{
public int last;
public long lastLineSeen;
public bool newConnection = true;
public AsyncHttpRequest request = null;
}
// A console that uses REST interfaces
//
public class RemoteConsole : CommandConsole
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IHttpServer m_Server;
private IConfigSource m_Config;
private List<string> m_Scrollback;
private ManualResetEvent m_DataEvent;
private List<string> m_InputData;
private long m_LineNumber;
private Dictionary<UUID, ConsoleConnection> m_Connections;
private string m_AllowedOrigin;
private JWTSignatureUtil m_sigUtil;
public RemoteConsole(string defaultPrompt) : base(defaultPrompt)
{
m_Server = null;
m_Config = null;
m_Scrollback = new List<string>();
m_DataEvent = new ManualResetEvent(false);
m_InputData = new List<string>();
m_LineNumber = 0;
m_Connections = new Dictionary<UUID, ConsoleConnection>();
m_AllowedOrigin = String.Empty;
m_sigUtil = new JWTSignatureUtil(publicKeyPath: "./server.crt");
}
public void ReadConfig(IConfigSource config)
{
m_Config = config;
IConfig netConfig = m_Config.Configs["Network"];
if (netConfig == null)
return;
m_AllowedOrigin = netConfig.GetString("ConsoleAllowedOrigin", String.Empty);
}
public void SetServer(IHttpServer server)
{
m_Server = server;
m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession);
m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession);
m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
}
internal void ResponseReady()
{
List<AsyncHttpRequest> requests = new List<AsyncHttpRequest>();
lock (m_Connections)
{
foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
{
ConsoleConnection connection = kvp.Value;
if (connection.request != null)
{
requests.Add(connection.request);
connection.request = null;
}
}
}
foreach (AsyncHttpRequest request in requests)
{
request.SendResponse(ProcessEvents(request));
}
}
public override void Output(string text, string level)
{
lock (m_Scrollback)
{
while (m_Scrollback.Count >= 1000)
m_Scrollback.RemoveAt(0);
m_LineNumber++;
m_Scrollback.Add(String.Format("{0}", m_LineNumber) + ":" + level + ":" + text);
}
FireOnOutput(text.Trim());
System.Console.WriteLine(text.Trim());
ResponseReady();
}
public override void Output(string text)
{
Output(text, "normal");
}
public override string ReadLine(string p, bool isCommand, bool e)
{
if (isCommand)
Output("+++" + p);
else
Output("-++" + p);
m_DataEvent.WaitOne();
string cmdinput;
lock (m_InputData)
{
if (m_InputData.Count == 0)
{
m_DataEvent.Reset();
return String.Empty;
}
cmdinput = m_InputData[0];
m_InputData.RemoveAt(0);
if (m_InputData.Count == 0)
m_DataEvent.Reset();
}
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
if (cmd.Length != 0)
{
int i;
for (i = 0; i < cmd.Length; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
return String.Empty;
}
}
return cmdinput;
}
private Hashtable CheckOrigin(Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
result["access_control_allow_origin"] = m_AllowedOrigin;
return result;
}
/* TODO: Figure out how PollServiceHTTPHandler can access the request headers
* in order to use m_AllowedOrigin as a regular expression
private Hashtable CheckOrigin(Hashtable headers, Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
{
if (headers.ContainsKey("origin"))
{
string origin = headers["origin"].ToString();
if (Regex.IsMatch(origin, m_AllowedOrigin))
result["access_control_allow_origin"] = origin;
}
}
return result;
}
*/
private void DoExpire()
{
List<UUID> expired = new List<UUID>();
List<AsyncHttpRequest> requests = new List<AsyncHttpRequest>();
lock (m_Connections)
{
foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
{
if (System.Environment.TickCount - kvp.Value.last > 500000)
expired.Add(kvp.Key);
}
foreach (UUID id in expired)
{
ConsoleConnection connection = m_Connections[id];
m_Connections.Remove(id);
CloseConnection(id);
if (connection.request != null)
{
requests.Add(connection.request);
connection.request = null;
}
}
}
foreach (AsyncHttpRequest request in requests)
{
request.SendResponse(ProcessEvents(request));
}
}
private Hashtable HandleHttpStartSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = String.Empty;
reply["int_response_code"] = 401;
reply["content_type"] = "text/plain";
var headers = (Hashtable)request["headers"];
if (headers.ContainsKey("Authorization"))
{
var authHeader = headers["Authorization"].ToString();
if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
{
m_log.Warn($"[REMOTECONSOLE] StartSession JWT Authorization header format failure from '{headers["remote_addr"]}'.");
return reply;
}
try
{
var token = new JWToken(authHeader.Substring(7), m_sigUtil);
// TODO: Make the scope strings come from some central list that can be registered into?
if (!(token.HasValidSignature && token.IsNotExpired && token.Payload.Scope == "remote-console"))
{
m_log.Warn($"[REMOTECONSOLE] StartSession invalid/expired/wrong scope JWToken from '{headers["remote_addr"]}'.");
return reply;
}
m_log.Info($"[REMOTECONSOLE] StartSession access granted via JWT to '{token.Payload.Username}' from '{headers["remote_addr"]}'.");
}
catch (JWTokenException jte)
{
m_log.Error($"[REMOTECONSOLE] Failure with JWToken in StartSession from '{headers["remote_addr"]}': {jte}");
return reply;
}
}
else if (request.ContainsKey("USER") && request.ContainsKey("PASS"))
{
string username = post["USER"].ToString();
string password = post["PASS"].ToString();
// Validate the username/password pair
if (Util.AuthenticateAsSystemUser(username, password) == false)
return reply;
m_log.Warn($"[REMOTECONSOLE] StartSession access granted via legacy system username and password to '{username}' from '{headers["remote_addr"]}'.");
}
else
{
return reply;
}
ConsoleConnection c = new ConsoleConnection();
c.last = System.Environment.TickCount;
c.lastLineSeen = 0;
UUID sessionID = UUID.Random();
lock (m_Connections)
{
m_Connections[sessionID] = c;
}
string uri = "/ReadResponses/" + sessionID.ToString() + "/";
IRequestHandler handler = new AsyncRequestHandler("POST", uri, AsyncReadResponses);
m_Server.AddStreamHandler(handler);
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, String.Empty, String.Empty);
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement(String.Empty, "ConsoleSession", String.Empty);
xmldoc.AppendChild(rootElement);
XmlElement id = xmldoc.CreateElement(String.Empty, "SessionID", String.Empty);
id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
rootElement.AppendChild(id);
XmlElement prompt = xmldoc.CreateElement(String.Empty, "Prompt", String.Empty);
prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));
rootElement.AppendChild(prompt);
rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable HandleHttpCloseSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = String.Empty;
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
JWToken token = null;
var headers = (Hashtable)request["headers"];
if (headers.ContainsKey("Authorization"))
{
var authHeader = headers["Authorization"].ToString();
if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
{
m_log.Warn($"[REMOTECONSOLE] CloseSession JWT Authorization header format failure from '{headers["remote_addr"]}'.");
return reply;
}
try
{
token = new JWToken(authHeader.Substring(7), m_sigUtil);
// TODO: Make the scope strings come from some central list that can be registered into?
if (!(token.HasValidSignature && token.IsNotExpired && token.Payload.Scope == "remote-console"))
{
m_log.Warn($"[REMOTECONSOLE] CloseSession invalid/expired/wrong scope JWToken from '{headers["remote_addr"]}'.");
return reply;
}
m_log.Info($"[REMOTECONSOLE] CloseSession for session '{post["ID"]}' accessed via JWT by '{token.Payload.Username}' from '{headers["remote_addr"]}'.");
}
catch (JWTokenException jte)
{
m_log.Error($"[REMOTECONSOLE] Failure with JWToken in CloseSession from '{headers["remote_addr"]}': {jte}");
return reply;
}
}
else
{
m_log.Warn($"[REMOTECONSOLE] CloseSession for session '{post["ID"]}' from '{headers["remote_addr"]}' being accessed without Authorization header!");
}
// BUG: Longstanding issue: if someone gets ahold of, or guesses, the ID and/or JWT of another user they can close the console.
// The only way I can think to close this bug is to associate each session with something the user cannot change. Not sure, but maybe the IP address of the connection would work?
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
lock (m_Connections)
{
if (m_Connections.ContainsKey(id))
{
ConsoleConnection connection = m_Connections[id];
m_Connections.Remove(id);
CloseConnection(id);
if (connection.request != null)
{
AsyncHttpRequest req = connection.request;
connection.request = null;
req.SendResponse(ProcessEvents(req));
}
}
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, String.Empty, String.Empty);
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement(String.Empty, "ConsoleSession", String.Empty);
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement(String.Empty, "Result", String.Empty);
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
m_log.Info($"[REMOTECONSOLE] CloseSession successful for user '{token?.Payload.Username}' with session '{id}' from '{headers["remote_addr"]}'.");
return reply;
}
private Hashtable HandleHttpSessionCommand(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = String.Empty;
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
var headers = (Hashtable)request["headers"];
if (headers.ContainsKey("Authorization"))
{
var authHeader = headers["Authorization"].ToString();
if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
{
m_log.Warn($"[REMOTECONSOLE] SessionCommand JWT Authorization header format failure from '{headers["remote_addr"]}'.");
return reply;
}
try
{
var token = new JWToken(authHeader.Substring(7), m_sigUtil);
// TODO: Make the scope strings come from some central list that can be registered into?
if (!(token.HasValidSignature && token.IsNotExpired && token.Payload.Scope == "remote-console"))
{
m_log.Warn($"[REMOTECONSOLE] SessionCommand invalid/expired/wrong scope JWToken from '{headers["remote_addr"]}'.");
return reply;
}
m_log.Info($"[REMOTECONSOLE] SessionCommand for session '{post["ID"]}' accessed via JWT by '{token.Payload.Username}' from '{headers["remote_addr"]}' with command '{post["COMMAND"]}'.");
}
catch (JWTokenException jte)
{
m_log.Error($"[REMOTECONSOLE] Failure with JWToken in SessionCommand from '{headers["remote_addr"]}': {jte}");
return reply;
}
}
else
{
m_log.Warn($"[REMOTECONSOLE] SessionCommand for session '{post["ID"]}' from '{headers["remote_addr"]}' being accessed without Authorization header!");
}
// BUG: Longstanding issue: if someone gets ahold of, or guesses, the ID of another user they can send comamnds to the console.
// The only way I can think to close this bug is to associate each session with something the user cannot change. Not sure, but maybe the IP address of the connection would work?
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(id))
return reply;
}
if (post["COMMAND"] == null)
return reply;
lock (m_InputData)
{
m_DataEvent.Set();
m_InputData.Add(post["COMMAND"].ToString());
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, String.Empty, String.Empty);
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement(String.Empty, "ConsoleSession", String.Empty);
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement(String.Empty, "Result", String.Empty);
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
private Hashtable DecodePostString(string data)
{
Hashtable result = new Hashtable();
string[] terms = data.Split(new char[] { '&' });
foreach (string term in terms)
{
string[] elems = term.Split(new char[] { '=' });
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
result[name] = value;
}
return result;
}
public void CloseConnection(UUID id)
{
try
{
string uri = "/ReadResponses/" + id.ToString() + "/";
m_Server.RemoveStreamHandler("POST", uri);
}
catch (Exception)
{
}
}
public void AsyncReadResponses(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
int pos1 = path.IndexOf("/"); // /ReadResponses
int pos2 = path.IndexOf("/", pos1 + 1); // /ReadResponses/
int pos3 = path.IndexOf("/", pos2 + 1); // /ReadResponses/<UUID>/
int len = pos3 - pos2 - 1;
string uri_tmp = path.Substring(pos2 + 1, len);
var authHeader = httpRequest.Headers.Get("Authorization");
if (authHeader != null)
{
if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
{
m_log.Warn($"[REMOTECONSOLE] ReadResponses JWT Authorization header format failure from '{httpRequest.RemoteIPEndPoint}'.");
return;
}
try
{
var token = new JWToken(authHeader.Substring(7), m_sigUtil);
// TODO: Make the scope strings come from some central list that can be registered into?
if (!(token.HasValidSignature && token.IsNotExpired && token.Payload.Scope == "remote-console"))
{
m_log.Warn($"[REMOTECONSOLE] ReadResponses invalid/expired/wrong scope JWToken from '{httpRequest.RemoteIPEndPoint}'.");
return;
}
m_log.Info($"[REMOTECONSOLE] ReadResponses for session '{uri_tmp}' accessed via JWT by '{token.Payload.Username}' from '{httpRequest.RemoteIPEndPoint}'.");
}
catch (JWTokenException jte)
{
m_log.Error($"[REMOTECONSOLE] Failure with JWToken in ReadResponses from '{httpRequest.RemoteIPEndPoint}': {jte}");
return;
}
}
else
{
m_log.Warn($"[REMOTECONSOLE] ReadResponses for session '{uri_tmp}' from '{httpRequest.RemoteIPEndPoint}' being accessed without Authorization header!");
}
// BUG: Longstanding issue: if someone gets ahold of, or guesses, the ID of another user they can send comamnds to the console.
// The only way I can think to close this bug is to associate each session with something the user cannot change. Not sure, but maybe the IP address of the connection would work?
UUID sessionID;
if (UUID.TryParse(uri_tmp, out sessionID) == false)
return;
// Create the new request
AsyncHttpRequest newRequest =
new AsyncHttpRequest(server, httpRequest, httpResponse, sessionID, TimeoutHandler, 60 * 1000);
AsyncHttpRequest currentRequest = null;
lock (m_Connections)
{
ConsoleConnection connection = null;
m_Connections.TryGetValue(sessionID, out connection);
if (connection == null)
return;
currentRequest = connection.request;
connection.request = newRequest;
}
// If there was a request already posted, signal it.
if (currentRequest != null)
{
currentRequest.SendResponse(ProcessEvents(currentRequest));
}
}
private void TimeoutHandler(AsyncHttpRequest pRequest)
{
UUID sessionid = pRequest.AgentID;
lock (m_Connections)
{
ConsoleConnection connection = null;
m_Connections.TryGetValue(sessionid, out connection);
if (connection == null)
return;
if (connection.request == pRequest)
connection.request = null;
}
pRequest.SendResponse(ProcessEvents(pRequest));
}
private Hashtable ProcessEvents(AsyncHttpRequest pRequest)
{
UUID sessionID = pRequest.AgentID;
// Is there data to send back? Then send it.
if (HasEvents(pRequest.RequestID, sessionID))
return (GetEvents(pRequest.RequestID, sessionID));
else
return (NoEvents(pRequest.RequestID, sessionID));
}
private bool HasEvents(UUID RequestID, UUID sessionID)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return false;
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen < m_LineNumber)
return true;
return false;
}
private Hashtable GetEvents(UUID RequestID, UUID sessionID)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return NoEvents(RequestID, UUID.Zero);
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen >= m_LineNumber)
return NoEvents(RequestID, UUID.Zero);
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, String.Empty, String.Empty);
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement(String.Empty, "ConsoleSession", String.Empty);
if (c.newConnection)
{
c.newConnection = false;
Output("+++" + DefaultPrompt);
}
lock (m_Scrollback)
{
long startLine = m_LineNumber - m_Scrollback.Count;
long sendStart = startLine;
if (sendStart < c.lastLineSeen)
sendStart = c.lastLineSeen;
for (long i = sendStart; i < m_LineNumber; i++)
{
XmlElement res = xmldoc.CreateElement(String.Empty, "Line", String.Empty);
long line = i + 1;
res.SetAttribute("Number", line.ToString());
res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
rootElement.AppendChild(res);
}
}
c.lastLineSeen = m_LineNumber;
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "application/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
private Hashtable NoEvents(UUID RequestID, UUID id)
{
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, String.Empty, String.Empty);
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement(String.Empty, "ConsoleSession", String.Empty);
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "text/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.DDF
{
using System;
using System.IO;
using System.Text;
using NPOI.Util;
/// <summary>
/// The BSE record is related closely to the EscherBlipRecord and stores
/// extra information about the blip. A blip record is actually stored inside
/// the BSE record even though the BSE record isn't actually a container record.
/// @author Glen Stampoultzis
/// @see EscherBlipRecord
/// </summary>
public class EscherBSERecord : EscherRecord
{
public const short RECORD_ID = unchecked((short)0xF007);
public const String RECORD_DESCRIPTION = "MsofbtBSE";
public const byte BT_ERROR = 0;
public const byte BT_UNKNOWN = 1;
public const byte BT_EMF = 2;
public const byte BT_WMF = 3;
public const byte BT_PICT = 4;
public const byte BT_JPEG = 5;
public const byte BT_PNG = 6;
public const byte BT_DIB = 7;
private byte field_1_blipTypeWin32;
private byte field_2_blipTypeMacOS;
private byte[] field_3_uid; // 16 bytes
private short field_4_tag;
private int field_5_size;
private int field_6_ref;
private int field_7_offset;
private byte field_8_usage;
private byte field_9_name;
private byte field_10_unused2;
private byte field_11_unused3;
private EscherBlipRecord field_12_blipRecord;
private byte[] _remainingData;
/// <summary>
/// This method deSerializes the record from a byte array.
/// </summary>
/// <param name="data">The byte array containing the escher record information</param>
/// <param name="offset">The starting offset into data</param>
/// <param name="recordFactory">May be null since this is not a container record.</param>
/// <returns>The number of bytes Read from the byte array.</returns>
public override int FillFields(byte[] data, int offset,
IEscherRecordFactory recordFactory
)
{
int bytesRemaining = ReadHeader(data, offset);
int pos = offset + 8;
field_1_blipTypeWin32 = data[pos];
field_2_blipTypeMacOS = data[pos + 1];
field_3_uid = new byte[16];
Array.Copy(data, pos + 2, field_3_uid, 0, 16);
field_4_tag = LittleEndian.GetShort(data, pos + 18);
field_5_size = LittleEndian.GetInt(data, pos + 20);
field_6_ref = LittleEndian.GetInt(data, pos + 24);
field_7_offset = LittleEndian.GetInt(data, pos + 28);
field_8_usage = data[pos + 32];
field_9_name = data[pos + 33];
field_10_unused2 = data[pos + 34];
field_11_unused3 = data[pos + 35];
bytesRemaining -= 36;
int bytesRead = 0;
if (bytesRemaining > 0)
{
field_12_blipRecord = (EscherBlipRecord)recordFactory.CreateRecord(data, pos + 36);
bytesRead = field_12_blipRecord.FillFields(data, pos + 36, recordFactory);
}
pos += 36 + bytesRead;
bytesRemaining -= bytesRead;
_remainingData = new byte[bytesRemaining];
Array.Copy(data, pos, _remainingData, 0, bytesRemaining);
return bytesRemaining + 8 + 36 + (field_12_blipRecord == null ? 0 : field_12_blipRecord.RecordSize);
}
/// <summary>
/// This method Serializes this escher record into a byte array.
/// </summary>
/// <param name="offset">The offset into
/// data to start writing the record data to</param>
/// <param name="data">The byte array to Serialize to.</param>
/// <param name="listener">a listener for begin and end serialization events.</param>
/// <returns>The number of bytes written.</returns>
public override int Serialize(int offset, byte[] data, EscherSerializationListener listener)
{
listener.BeforeRecordSerialize(offset, RecordId, this);
if (_remainingData == null)
_remainingData = new byte[0];
LittleEndian.PutShort(data, offset, Options);
LittleEndian.PutShort(data, offset + 2, RecordId);
if (_remainingData == null) _remainingData = new byte[0];
int blipSize = field_12_blipRecord == null ? 0 : field_12_blipRecord.RecordSize;
int remainingBytes = _remainingData.Length + 36 + blipSize;
LittleEndian.PutInt(data, offset + 4, remainingBytes);
data[offset + 8] = field_1_blipTypeWin32;
data[offset + 9] = field_2_blipTypeMacOS;
for (int i = 0; i < 16; i++)
data[offset + 10 + i] = field_3_uid[i];
LittleEndian.PutShort(data, offset + 26, field_4_tag);
LittleEndian.PutInt(data, offset + 28, field_5_size);
LittleEndian.PutInt(data, offset + 32, field_6_ref);
LittleEndian.PutInt(data, offset + 36, field_7_offset);
data[offset + 40] = field_8_usage;
data[offset + 41] = field_9_name;
data[offset + 42] = field_10_unused2;
data[offset + 43] = field_11_unused3;
int bytesWritten = 0;
if (field_12_blipRecord != null)
{
bytesWritten = field_12_blipRecord.Serialize(offset + 44, data);
}
if (_remainingData == null)
_remainingData = new byte[0];
Array.Copy(_remainingData, 0, data, offset + 44 + bytesWritten, _remainingData.Length);
int pos = offset + 8 + 36 + _remainingData.Length + bytesWritten;
listener.AfterRecordSerialize(pos, RecordId, pos - offset, this);
return pos - offset;
}
/// <summary>
/// Returns the number of bytes that are required to Serialize this record.
/// </summary>
/// <value>Number of bytes</value>
public override int RecordSize
{
get
{
int field_12_size = 0;
if (field_12_blipRecord != null)
{
field_12_size = field_12_blipRecord.RecordSize;
}
int remaining_size = 0;
if (_remainingData != null)
{
remaining_size = _remainingData.Length;
}
return 8 + 1 + 1 + 16 + 2 + 4 + 4 + 4 + 1 + 1 +
1 + 1 + field_12_size + remaining_size;
}
}
/// <summary>
/// The short name for this record
/// </summary>
/// <value></value>
public override String RecordName
{
get { return "BSE"; }
}
/// <summary>
/// Gets or sets the expected blip type under windows (failure to match this blip type will result in
/// Excel converting to this format).
/// </summary>
/// <value>The blip type win32.</value>
public byte BlipTypeWin32
{
get { return field_1_blipTypeWin32; }
set { field_1_blipTypeWin32 = value; }
}
/// <summary>
/// Gets or sets the expected blip type under MacOS (failure to match this blip type will result in
/// Excel converting to this format).
/// </summary>
/// <value>The blip type mac OS.</value>
public byte BlipTypeMacOS
{
get { return field_2_blipTypeMacOS; }
set { field_2_blipTypeMacOS = value; }
}
/// <summary>
/// Gets or sets 16 byte MD4 checksum.
/// </summary>
/// <value>The UID.</value>
public byte[] UID
{
get { return field_3_uid; }
set { field_3_uid = value; }
}
/// <summary>
/// Gets or sets the tag. (Unused)
/// </summary>
/// <value>The tag.</value>
public short Tag
{
get { return field_4_tag; }
set { field_4_tag = value; }
}
/// <summary>
/// Gets or sets Blip size in stream..
/// </summary>
/// <value>The size.</value>
public int Size
{
get { return field_5_size; }
set { field_5_size = value; }
}
/// <summary>
/// Gets or sets the reference count of this blip.
/// </summary>
/// <value>The ref.</value>
public int Ref
{
get { return field_6_ref; }
set { field_6_ref = value; }
}
/// <summary>
/// Gets or sets the offset in the delay stream..
/// </summary>
/// <value>The offset.</value>
public int Offset
{
get { return field_7_offset; }
set { field_7_offset = value; }
}
/// <summary>
/// Defines the way this blip is used.
/// </summary>
/// <value>The usage.</value>
public byte Usage
{
get { return field_8_usage; }
set { field_8_usage = value; }
}
/// <summary>
/// Gets or sets the blip name.
/// </summary>
/// <value>The name.</value>
public byte Name
{
get { return field_9_name; }
set { field_9_name = value; }
}
/// <summary>
/// Gets or sets the unused2.
/// </summary>
/// <value>The unused2.</value>
public byte Unused2
{
get { return field_10_unused2; }
set { field_10_unused2 = value; }
}
/// <summary>
/// Gets or sets the unused3.
/// </summary>
/// <value>The unused3.</value>
public byte Unused3
{
get { return field_11_unused3; }
set { field_11_unused3 = value; }
}
/// <summary>
/// Gets or sets the blip record.
/// </summary>
/// <value>The blip record.</value>
public EscherBlipRecord BlipRecord
{
get { return field_12_blipRecord; }
set { field_12_blipRecord = value; }
}
/// <summary>
/// Gets or sets any remaining data in this record.
/// </summary>
/// <value>The remaining data.</value>
public byte[] RemainingData
{
get { return _remainingData; }
set { _remainingData = value; }
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
String nl = Environment.NewLine;
String extraData;
using (MemoryStream b = new MemoryStream())
{
try
{
HexDump.Dump(this._remainingData, 0, b, 0);
//extraData = b.ToString();
extraData = Encoding.UTF8.GetString(b.ToArray());
}
catch (Exception e)
{
extraData = e.ToString();
}
return GetType().Name + ":" + nl +
" RecordId: 0x" + HexDump.ToHex(RECORD_ID) + nl +
" Version: 0x" + HexDump.ToHex(Version) + '\n' +
" Instance: 0x" + HexDump.ToHex(Instance) + '\n' +
" BlipTypeWin32: " + field_1_blipTypeWin32 + nl +
" BlipTypeMacOS: " + field_2_blipTypeMacOS + nl +
" SUID: " + HexDump.ToHex(field_3_uid) + nl +
" Tag: " + field_4_tag + nl +
" Size: " + field_5_size + nl +
" Ref: " + field_6_ref + nl +
" Offset: " + field_7_offset + nl +
" Usage: " + field_8_usage + nl +
" Name: " + field_9_name + nl +
" Unused2: " + field_10_unused2 + nl +
" Unused3: " + field_11_unused3 + nl +
" blipRecord: " + (field_12_blipRecord == null ? "null" : field_12_blipRecord.ToString()) + nl +
" Extra Data:" + nl + extraData;
}
}
public override String ToXml(String tab)
{
StringBuilder builder = new StringBuilder();
builder.Append(tab).Append(FormatXmlRecordHeader(GetType().Name, HexDump.ToHex(RecordId), HexDump.ToHex(Version), HexDump.ToHex(Instance)))
.Append(tab).Append("\t").Append("<BlipTypeWin32>").Append(field_1_blipTypeWin32).Append("</BlipTypeWin32>\n")
.Append(tab).Append("\t").Append("<BlipTypeMacOS>").Append(field_2_blipTypeMacOS).Append("</BlipTypeMacOS>\n")
.Append(tab).Append("\t").Append("<SUID>").Append(field_3_uid == null ? "" : HexDump.ToHex(field_3_uid)).Append("</SUID>\n")
.Append(tab).Append("\t").Append("<Tag>").Append(field_4_tag).Append("</Tag>\n")
.Append(tab).Append("\t").Append("<Size>").Append(field_5_size).Append("</Size>\n")
.Append(tab).Append("\t").Append("<Ref>").Append(field_6_ref).Append("</Ref>\n")
.Append(tab).Append("\t").Append("<Offset>").Append(field_7_offset).Append("</Offset>\n")
.Append(tab).Append("\t").Append("<Usage>").Append(field_8_usage).Append("</Usage>\n")
.Append(tab).Append("\t").Append("<Name>").Append(field_9_name).Append("</Name>\n")
.Append(tab).Append("\t").Append("<Unused2>").Append(field_10_unused2).Append("</Unused2>\n")
.Append(tab).Append("\t").Append("<Unused3>").Append(field_11_unused3).Append("</Unused3>\n");
builder.Append(tab).Append("</").Append(GetType().Name).Append(">\n");
return builder.ToString();
}
/// <summary>
/// Retrieve the string representation given a blip id.
/// </summary>
/// <param name="b">The b.</param>
/// <returns></returns>
public String GetBlipType(byte b)
{
switch (b)
{
case BT_ERROR:
return " ERROR";
case BT_UNKNOWN:
return " UNKNOWN";
case BT_EMF:
return " EMF";
case BT_WMF:
return " WMF";
case BT_PICT:
return " PICT";
case BT_JPEG:
return " JPEG";
case BT_PNG:
return " PNG";
case BT_DIB:
return " DIB";
default:
if (b < 32)
return " NotKnown";
else
return " Client";
}
}
}
}
| |
using System;
using System.Text;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
[TestFixture]
public class Gost3410Test
: ITest
{
private static readonly byte[] hashmessage = Hex.Decode("3042453136414534424341374533364339313734453431443642453241453435");
private static byte[] zeroTwo(int length)
{
byte[] data = new byte[length];
data[data.Length - 1] = 0x02;
return data;
}
private class Gost3410_TEST1_512
: ITest
{
public string Name
{
get { return "Gost3410-TEST1-512"; }
}
FixedSecureRandom init_random = FixedSecureRandom.From(Hex.Decode("00005EC900007341"), zeroTwo(64));
FixedSecureRandom random = FixedSecureRandom.From(Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"));
FixedSecureRandom keyRandom = FixedSecureRandom.From(Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"));
IBigInteger pValue = new BigInteger("EE8172AE8996608FB69359B89EB82A69854510E2977A4D63BC97322CE5DC3386EA0A12B343E9190F23177539845839786BB0C345D165976EF2195EC9B1C379E3", 16);
IBigInteger qValue = new BigInteger("98915E7EC8265EDFCDA31E88F24809DDB064BDC7285DD50D7289F0AC6F49DD2D", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("3e5f895e276d81d2d52c0763270a458157b784c57abdbd807bc44fd43a32ac06",16);
IBigInteger s = new BigInteger("3f0dd5d4400d47c08e4ce505ff7434b6dbf729592e37c74856dab85115a60955",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(512, 1, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (parameters.ValidationParameters == null)
{
return new SimpleTestResult(false, Name + "validation parameters wrong");
}
if (parameters.ValidationParameters.C != 29505
|| parameters.ValidationParameters.X0 != 24265)
{
return new SimpleTestResult(false, Name + "validation parameters values wrong");
}
if (!init_random.IsExhausted)
{
return new SimpleTestResult(false, Name
+ ": unexpected number of bytes used from 'init_random'.");
}
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
if (!keyRandom.IsExhausted)
{
return new SimpleTestResult(false, Name
+ ": unexpected number of bytes used from 'keyRandom'.");
}
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer gost3410 = new Gost3410Signer();
gost3410.Init(true, param);
IBigInteger[] sig = gost3410.GenerateSignature(hashmessage);
if (!random.IsExhausted)
{
return new SimpleTestResult(false, Name
+ ": unexpected number of bytes used from 'random'.");
}
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
gost3410.Init(false, pair.Public);
if (gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
private class Gost3410_TEST2_512
: ITest
{
public string Name
{
get { return "Gost3410-TEST2-512"; }
}
FixedSecureRandom init_random = FixedSecureRandom.From(Hex.Decode("000000003DFC46F1000000000000000D"), zeroTwo(64));
FixedSecureRandom random = FixedSecureRandom.From(Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"));
FixedSecureRandom keyRandom = FixedSecureRandom.From(Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"));
IBigInteger pValue = new BigInteger("8b08eb135af966aab39df294538580c7da26765d6d38d30cf1c06aae0d1228c3316a0e29198460fad2b19dc381c15c888c6dfd0fc2c565abb0bf1faff9518f85", 16);
IBigInteger qValue = new BigInteger("931a58fb6f0dcdf2fe7549bc3f19f4724b56898f7f921a076601edb18c93dc75", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("7c07c8cf035c2a1cb2b7fae5807ac7cd623dfca7a1a68f6d858317822f1ea00d",16);
IBigInteger s = new BigInteger("7e9e036a6ff87dbf9b004818252b1f6fc310bdd4d17cb8c37d9c36c7884de60c",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(512, 2, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!init_random.IsExhausted)
{
return new SimpleTestResult(false, Name
+ ": unexpected number of bytes used from 'init_random'.");
}
if (parameters.ValidationParameters == null)
{
return new SimpleTestResult(false, Name + ": validation parameters wrong");
}
if (parameters.ValidationParameters.CL != 13
|| parameters.ValidationParameters.X0L != 1039943409)
{
return new SimpleTestResult(false, Name + ": validation parameters values wrong");
}
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
if (!keyRandom.IsExhausted)
{
return new SimpleTestResult(false, Name
+ ": unexpected number of bytes used from 'keyRandom'.");
}
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!random.IsExhausted)
{
return new SimpleTestResult(false, Name
+ ": unexpected number of bytes used from 'random'.");
}
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (!Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(false, Name + ": verification fails");
}
return new SimpleTestResult(true, Name + ": Okay");
}
}
private class Gost3410_TEST1_1024
: ITest
{
public string Name
{
get { return "Gost3410-TEST1-1024"; }
}
private class SecureRandomImpl1 : SecureRandom
{
bool firstInt = true;
public override int NextInt()
{
string x0 = "0xA565";
string c = "0x538B";
if (firstInt)
{
firstInt = false;
return NumberParsing.DecodeIntFromHex(x0);
}
return NumberParsing.DecodeIntFromHex(c);
}
public override void NextBytes(byte[] bytes)
{
byte[] d = Hex.Decode("02");
Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length);
}
};
SecureRandom init_random = new SecureRandomImpl1();
private class SecureRandomImpl2 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A");
int i;
for (i = 0; i < (bytes.Length - k.Length); i += k.Length)
{
Array.Copy(k, 0, bytes, i, k.Length);
}
if (i > bytes.Length)
{
Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length));
}
else
{
Array.Copy(k, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom random = new SecureRandomImpl2();
private class SecureRandomImpl3 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046");
int i;
for (i = 0; i < (bytes.Length - x.Length); i += x.Length)
{
Array.Copy(x, 0, bytes, i, x.Length);
}
if (i > bytes.Length)
{
Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length));
}
else
{
Array.Copy(x, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom keyRandom = new SecureRandomImpl3();
IBigInteger pValue = new BigInteger("ab8f37938356529e871514c1f48c5cbce77b2f4fc9a2673ac2c1653da8984090c0ac73775159a26bef59909d4c9846631270e16653a6234668f2a52a01a39b921490e694c0f104b58d2e14970fccb478f98d01e975a1028b9536d912de5236d2dd2fc396b77153594d4178780e5f16f718471e2111c8ce64a7d7e196fa57142d", 16);
IBigInteger qValue = new BigInteger("bcc02ca0ce4f0753ec16105ee5d530aa00d39f3171842ab2c334a26b5f576e0f", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("a8790aabbd5a998ff524bad048ac69cd1faff2dab048265c8d60d1471c44a9ee",16);
IBigInteger s = new BigInteger("30df5ba32ac77170b9632559bef7d37620017756dff3fea1088b4267db0944b8",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(1024, 1, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
private class Gost3410_TEST2_1024
: ITest
{
public string Name
{
get { return "Gost3410-TEST2-1024"; }
}
private class SecureRandomImpl4 : SecureRandom
{
bool firstLong = true;
public override long NextLong()
{
string x0 = "0x3DFC46F1";
string c = "0xD";
if (firstLong)
{
firstLong = false;
return NumberParsing.DecodeLongFromHex(x0);
}
return NumberParsing.DecodeLongFromHex(c);
}
public override void NextBytes(byte[] bytes)
{
byte[] d = Hex.Decode("02");
Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length);
}
};
SecureRandom init_random = new SecureRandomImpl4();
private class SecureRandomImpl5 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A");
int i;
for (i = 0; i < (bytes.Length - k.Length); i += k.Length)
{
Array.Copy(k, 0, bytes, i, k.Length);
}
if (i > bytes.Length)
{
Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length));
}
else
{
Array.Copy(k, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom random = new SecureRandomImpl5();
private class SecureRandomImpl6 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046");
int i;
for (i = 0; i < (bytes.Length - x.Length); i += x.Length)
{
Array.Copy(x, 0, bytes, i, x.Length);
}
if (i > bytes.Length)
{
Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length));
}
else
{
Array.Copy(x, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom keyRandom = new SecureRandomImpl6();
IBigInteger pValue = new BigInteger("e2c4191c4b5f222f9ac2732562f6d9b4f18e7fb67a290ea1e03d750f0b9806755fc730d975bf3faa606d05c218b35a6c3706919aab92e0c58b1de4531c8fa8e7af43c2bff016251e21b2870897f6a27ac4450bca235a5b748ad386e4a0e4dfcb09152435abcfe48bd0b126a8122c7382f285a9864615c66decddf6afd355dfb7", 16);
IBigInteger qValue = new BigInteger("931a58fb6f0dcdf2fe7549bc3f19f4724b56898f7f921a076601edb18c93dc75", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("81d69a192e9c7ac21fc07da41bd07e230ba6a94eb9f3c1fd104c7bd976733ca5",16);
IBigInteger s = new BigInteger("315c879c8414f35feb4deb15e7cc0278c48e6ca1596325d6959338d860b0c47a",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(1024, 2, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
private class Gost3410_AParam
: ITest
{
public string Name
{
get { return "Gost3410-AParam"; }
}
private class SecureRandomImpl7 : SecureRandom
{
bool firstLong = true;
public override long NextLong()
{
string x0 = "0x520874F5";
string c = "0xEE39ADB3";
if (firstLong)
{
firstLong = false;
return NumberParsing.DecodeLongFromHex(x0);
}
return NumberParsing.DecodeLongFromHex(c);
}
public override void NextBytes(byte[] bytes)
{
byte[] d = Hex.Decode("02");
Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length);
}
};
SecureRandom init_random = new SecureRandomImpl7();
private class SecureRandomImpl8 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A");
int i;
for (i = 0; i < (bytes.Length - k.Length); i += k.Length)
{
Array.Copy(k, 0, bytes, i, k.Length);
}
if (i > bytes.Length)
{
Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length));
}
else
{
Array.Copy(k, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom random = new SecureRandomImpl8();
private class SecureRandomImpl9 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046");
int i;
for (i = 0; i < (bytes.Length - x.Length); i += x.Length)
{
Array.Copy(x, 0, bytes, i, x.Length);
}
if (i > bytes.Length)
{
Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length));
}
else
{
Array.Copy(x, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom keyRandom = new SecureRandomImpl9();
IBigInteger pValue = new BigInteger("b4e25efb018e3c8b87505e2a67553c5edc56c2914b7e4f89d23f03f03377e70a2903489dd60e78418d3d851edb5317c4871e40b04228c3b7902963c4b7d85d52b9aa88f2afdbeb28da8869d6df846a1d98924e925561bd69300b9ddd05d247b5922d967cbb02671881c57d10e5ef72d3e6dad4223dc82aa1f7d0294651a480df", 16);
IBigInteger qValue = new BigInteger("972432a437178b30bd96195b773789ab2fff15594b176dd175b63256ee5af2cf", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("64a8856628e5669d85f62cd763dd4a99bc56d33dc0e1859122855d141e9e4774",16);
IBigInteger s = new BigInteger("319ebac97092b288d469a4b988248794f60c865bc97858d9a3135c6d1a1bf2dd",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(1024, 2, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
private class Gost3410_BParam
: ITest
{
public string Name
{
get { return "Gost3410-BParam"; }
}
private class SecureRandomImpl10 : SecureRandom
{
bool firstLong = true;
public override long NextLong()
{
string x0 = "0x5B977CDB";
string c = "0x6E9692DD";
if (firstLong)
{
firstLong = false;
return NumberParsing.DecodeLongFromHex(x0);
}
return NumberParsing.DecodeLongFromHex(c);
}
public override void NextBytes(byte[] bytes)
{
byte[] d = Hex.Decode("bc3cbbdb7e6f848286e19ad9a27a8e297e5b71c53dd974cdf60f937356df69cbc97a300ccc71685c553046147f11568c4fddf363d9d886438345a62c3b75963d6546adfabf31b31290d12cae65ecb8309ef66782");
Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length);
}
};
SecureRandom init_random = new SecureRandomImpl10();
private class SecureRandomImpl11 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A");
int i;
for (i = 0; i < (bytes.Length - k.Length); i += k.Length)
{
Array.Copy(k, 0, bytes, i, k.Length);
}
if (i > bytes.Length)
{
Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length));
}
else
{
Array.Copy(k, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom random = new SecureRandomImpl11();
private class SecureRandomImpl12 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046");
int i;
for (i = 0; i < (bytes.Length - x.Length); i += x.Length)
{
Array.Copy(x, 0, bytes, i, x.Length);
}
if (i > bytes.Length)
{
Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length));
}
else
{
Array.Copy(x, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom keyRandom = new SecureRandomImpl12();
IBigInteger pValue = new BigInteger("c6971fc57524b30c9018c5e621de15499736854f56a6f8aee65a7a404632b3540f09020f67f04dc2e6783b141dceffd21a703035b7d0187c6e12cb4229922bafdb2225b73e6b23a0de36e20047065aea000c1a374283d0ad8dc1981e3995f0bb8c72526041fcb98ae6163e1e71a669d8364e9c4c3188f673c5f8ee6fadb41abf", 16);
IBigInteger qValue = new BigInteger("b09d634c10899cd7d4c3a7657403e05810b07c61a688bab2c37f475e308b0607", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("860d82c60e9502cd00c0e9e1f6563feafec304801974d745c5e02079946f729e",16);
IBigInteger s = new BigInteger("7ef49264ef022801aaa03033cd97915235fbab4c823ed936b0f360c22114688a",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(1024, 2, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
private class Gost3410_CParam
: ITest
{
public string Name
{
get { return "Gost3410-CParam"; }
}
private class SecureRandomImpl13 : SecureRandom
{
bool firstLong = true;
public override long NextLong()
{
string x0 = "0x43848744";
string c = "0xB50A826D";
if (firstLong)
{
firstLong = false;
return NumberParsing.DecodeLongFromHex(x0);
}
return NumberParsing.DecodeLongFromHex(c);
}
public override void NextBytes(byte[] bytes)
{
byte[] d = Hex.Decode("7F575E8194BC5BDF");
Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length);
}
};
SecureRandom init_random = new SecureRandomImpl13();
private class SecureRandomImpl14 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A");
int i;
for (i = 0; i < (bytes.Length - k.Length); i += k.Length)
{
Array.Copy(k, 0, bytes, i, k.Length);
}
if (i > bytes.Length)
{
Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length));
}
else
{
Array.Copy(k, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom random = new SecureRandomImpl14();
private class SecureRandomImpl15 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046");
int i;
for (i = 0; i < (bytes.Length - x.Length); i += x.Length)
{
Array.Copy(x, 0, bytes, i, x.Length);
}
if (i > bytes.Length)
{
Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length));
}
else
{
Array.Copy(x, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom keyRandom = new SecureRandomImpl15();
IBigInteger pValue = new BigInteger("9d88e6d7fe3313bd2e745c7cdd2ab9ee4af3c8899e847de74a33783ea68bc30588ba1f738c6aaf8ab350531f1854c3837cc3c860ffd7e2e106c3f63b3d8a4c034ce73942a6c3d585b599cf695ed7a3c4a93b2b947b7157bb1a1c043ab41ec8566c6145e938a611906de0d32e562494569d7e999a0dda5c879bdd91fe124df1e9", 16);
IBigInteger qValue = new BigInteger("fadd197abd19a1b4653eecf7eca4d6a22b1f7f893b641f901641fbb555354faf", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("4deb95a0b35e7ed7edebe9bef5a0f93739e16b7ff27fe794d989d0c13159cfbc",16);
IBigInteger s = new BigInteger("e1d0d30345c24cfeb33efde3deee5fbbda78ddc822b719d860cd0ba1fb6bd43b",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(1024, 2, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
private class Gost3410_DParam
: ITest
{
public string Name
{
get { return "Gost3410-DParam"; }
}
private class SecureRandomImpl16 : SecureRandom
{
bool firstLong = true;
public override long NextLong()
{
string x0 = "0x13DA8B9D";
string c = "0xA0E9DE4B";
if (firstLong)
{
firstLong = false;
return NumberParsing.DecodeLongFromHex(x0);
}
return NumberParsing.DecodeLongFromHex(c);
}
public override void NextBytes(byte[] bytes)
{
byte[] d = Hex.Decode("41ab97857f42614355d32db0b1069f109a4da283676c7c53a68185b4");
Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length);
}
};
SecureRandom init_random = new SecureRandomImpl16();
private class SecureRandomImpl17 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A");
int i;
for (i = 0; i < (bytes.Length - k.Length); i += k.Length)
{
Array.Copy(k, 0, bytes, i, k.Length);
}
if (i > bytes.Length)
{
Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length));
}
else
{
Array.Copy(k, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom random = new SecureRandomImpl17();
private class SecureRandomImpl18 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046");
int i;
for (i = 0; i < (bytes.Length - x.Length); i += x.Length)
{
Array.Copy(x, 0, bytes, i, x.Length);
}
if (i > bytes.Length)
{
Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length));
}
else
{
Array.Copy(x, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom keyRandom = new SecureRandomImpl18();
IBigInteger pValue = new BigInteger("80f102d32b0fd167d069c27a307adad2c466091904dbaa55d5b8cc7026f2f7a1919b890cb652c40e054e1e9306735b43d7b279eddf9102001cd9e1a831fe8a163eed89ab07cf2abe8242ac9dedddbf98d62cddd1ea4f5f15d3a42a6677bdd293b24260c0f27c0f1d15948614d567b66fa902baa11a69ae3bceadbb83e399c9b5", 16);
IBigInteger qValue = new BigInteger("f0f544c418aac234f683f033511b65c21651a6078bda2d69bb9f732867502149", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("712592d285b792e33b8a9a11e8e6c4f512ddf0042972bbfd1abb0a93e8fc6f54",16);
IBigInteger s = new BigInteger("2cf26758321258b130d5612111339f09ceb8668241f3482e38baa56529963f07",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(1024, 2, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
private class Gost3410_AExParam
: ITest
{
public string Name
{
get { return "Gost3410-AExParam"; }
}
private class SecureRandomImpl19 : SecureRandom
{
bool firstLong = true;
public override long NextLong()
{
string x0 = "0xD05E9F14";
string c = "0x46304C5F";
if (firstLong)
{
firstLong = false;
return NumberParsing.DecodeLongFromHex(x0);
}
return NumberParsing.DecodeLongFromHex(c);
}
public override void NextBytes(byte[] bytes)
{
byte[] d = Hex.Decode("35ab875399cda33c146ca629660e5a5e5c07714ca326db032dd6751995cdb90a612b9228932d8302704ec24a5def7739c5813d83");
Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length);
}
};
SecureRandom init_random = new SecureRandomImpl19();
private class SecureRandomImpl20 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A");
int i;
for (i = 0; i < (bytes.Length - k.Length); i += k.Length)
{
Array.Copy(k, 0, bytes, i, k.Length);
}
if (i > bytes.Length)
{
Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length));
}
else
{
Array.Copy(k, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom random = new SecureRandomImpl20();
private class SecureRandomImpl21 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046");
int i;
for (i = 0; i < (bytes.Length - x.Length); i += x.Length)
{
Array.Copy(x, 0, bytes, i, x.Length);
}
if (i > bytes.Length)
{
Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length));
}
else
{
Array.Copy(x, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom keyRandom = new SecureRandomImpl21();
IBigInteger pValue = new BigInteger("ca3b3f2eee9fd46317d49595a9e7518e6c63d8f4eb4d22d10d28af0b8839f079f8289e603b03530784b9bb5a1e76859e4850c670c7b71c0df84ca3e0d6c177fe9f78a9d8433230a883cd82a2b2b5c7a3306980278570cdb79bf01074a69c9623348824b0c53791d53c6a78cab69e1cfb28368611a397f50f541e16db348dbe5f", 16);
IBigInteger qValue = new BigInteger("cae4d85f80c147704b0ca48e85fb00a9057aa4acc44668e17f1996d7152690d9", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("90892707282f433398488f19d31ac48523a8e2ded68944e0da91c6895ee7045e",16);
IBigInteger s = new BigInteger("3be4620ee88f1ee8f9dd63c7d145b7e554839feeca125049118262ea4651e9de",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(1024, 2, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
private class Gost3410_BExParam
: ITest
{
public string Name
{
get { return "Gost3410-BExParam"; }
}
private class SecureRandomImpl22 : SecureRandom
{
bool firstLong = true;
public override long NextLong()
{
string x0 = "0x7A007804";
string c = "0xD31A4FF7";
if (firstLong)
{
firstLong = false;
return NumberParsing.DecodeLongFromHex(x0);
}
return NumberParsing.DecodeLongFromHex(c);
}
public override void NextBytes(byte[] bytes)
{
byte[] d = Hex.Decode("7ec123d161477762838c2bea9dbdf33074af6d41d108a066a1e7a07ab3048de2");
Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length);
}
};
SecureRandom init_random = new SecureRandomImpl22();
private class SecureRandomImpl23 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A");
int i;
for (i = 0; i < (bytes.Length - k.Length); i += k.Length)
{
Array.Copy(k, 0, bytes, i, k.Length);
}
if (i > bytes.Length)
{
Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length));
}
else
{
Array.Copy(k, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom random = new SecureRandomImpl23();
private class SecureRandomImpl24 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046");
int i;
for (i = 0; i < (bytes.Length - x.Length); i += x.Length)
{
Array.Copy(x, 0, bytes, i, x.Length);
}
if (i > bytes.Length)
{
Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length));
}
else
{
Array.Copy(x, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom keyRandom = new SecureRandomImpl24();
IBigInteger pValue = new BigInteger("9286dbda91eccfc3060aa5598318e2a639f5ba90a4ca656157b2673fb191cd0589ee05f4cef1bd13508408271458c30851ce7a4ef534742bfb11f4743c8f787b11193ba304c0e6bca25701bf88af1cb9b8fd4711d89f88e32b37d95316541bf1e5dbb4989b3df13659b88c0f97a3c1087b9f2d5317d557dcd4afc6d0a754e279", 16);
IBigInteger qValue = new BigInteger("c966e9b3b8b7cdd82ff0f83af87036c38f42238ec50a876cd390e43d67b6013f", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("8f79a582513df84dc247bcb624340cc0e5a34c4324a20ce7fe3ab8ff38a9db71",16);
IBigInteger s = new BigInteger("7508d22fd6cbb45efd438cb875e43f137247088d0f54b29a7c91f68a65b5fa85",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(1024, 2, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
private class Gost3410_CExParam
: ITest
{
public string Name
{
get { return "Gost3410-CExParam"; }
}
private class SecureRandomImpl25 : SecureRandom
{
bool firstLong = true;
public override long NextLong()
{
string x0 = "0x162AB910";
string c = "0x93F828D3";
if (firstLong)
{
firstLong = false;
return NumberParsing.DecodeLongFromHex(x0);
}
return NumberParsing.DecodeLongFromHex(c);
}
public override void NextBytes(byte[] bytes)
{
byte[] d = Hex.Decode("ca82cce78a738bc46f103d53b9bf809745ec845e4f6da462606c51f60ecf302e31204b81");
Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length);
}
};
SecureRandom init_random = new SecureRandomImpl25();
private class SecureRandomImpl26 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A");
int i;
for (i = 0; i < (bytes.Length - k.Length); i += k.Length)
{
Array.Copy(k, 0, bytes, i, k.Length);
}
if (i > bytes.Length)
{
Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length));
}
else
{
Array.Copy(k, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom random = new SecureRandomImpl26();
private class SecureRandomImpl27 : SecureRandom
{
public override void NextBytes(byte[] bytes)
{
byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046");
int i;
for (i = 0; i < (bytes.Length - x.Length); i += x.Length)
{
Array.Copy(x, 0, bytes, i, x.Length);
}
if (i > bytes.Length)
{
Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length));
}
else
{
Array.Copy(x, 0, bytes, i, bytes.Length - i);
}
}
};
SecureRandom keyRandom = new SecureRandomImpl27();
IBigInteger pValue = new BigInteger("b194036ace14139d36d64295ae6c50fc4b7d65d8b340711366ca93f383653908ee637be428051d86612670ad7b402c09b820fa77d9da29c8111a8496da6c261a53ed252e4d8a69a20376e6addb3bdcd331749a491a184b8fda6d84c31cf05f9119b5ed35246ea4562d85928ba1136a8d0e5a7e5c764ba8902029a1336c631a1d", 16);
IBigInteger qValue = new BigInteger("96120477df0f3896628e6f4a88d83c93204c210ff262bccb7dae450355125259", 16);
public ITestResult Perform()
{
IBigInteger r = new BigInteger("169fdb2dc09f690b71332432bfec806042e258fa9a21dafe73c6abfbc71407d9",16);
IBigInteger s = new BigInteger("9002551808ae40d19f6f31fb67e4563101243cf07cffd5f2f8ff4c537b0c9866",16);
Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator();
pGen.Init(1024, 2, init_random);
Gost3410Parameters parameters = pGen.GenerateParameters();
if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
{
return new SimpleTestResult(false, Name + ": p or q wrong");
}
Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator();
Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters);
Gost3410KeyGen.Init(genParam);
IAsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
Gost3410Signer Gost3410 = new Gost3410Signer();
Gost3410.Init(true, param);
IBigInteger[] sig = Gost3410.GenerateSignature(hashmessage);
if (!r.Equals(sig[0]))
{
return new SimpleTestResult(false, Name
+ ": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[0].ToString(16));
}
if (!s.Equals(sig[1]))
{
return new SimpleTestResult(false, Name
+ ": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s.ToString(16) + SimpleTest.NewLine
+ " got : " + sig[1].ToString(16));
}
Gost3410.Init(false, pair.Public);
if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
return new SimpleTestResult(true, Name + ": Okay");
}
else
{
return new SimpleTestResult(false, Name + ": verification fails");
}
}
}
ITest[] tests =
{
new Gost3410_TEST1_512(),
new Gost3410_TEST2_512(),
// new Gost3410_TEST1_1024(),
// new Gost3410_TEST2_1024(),
// new Gost3410_AParam(),
// new Gost3410_BParam(),
// new Gost3410_CParam(),
// new Gost3410_DParam(),
// new Gost3410_AExParam(),
// new Gost3410_BExParam(),
// new Gost3410_CExParam()
};
public string Name
{
get { return "Gost3410"; }
}
public ITestResult Perform()
{
for (int i = 0; i != tests.Length; i++)
{
ITestResult result = tests[i].Perform();
if (!result.IsSuccessful())
{
return result;
}
}
return new SimpleTestResult(true, "Gost3410: Okay");
}
public static void Main(
string[] args)
{
ITest test = new Gost3410Test();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading;
using Axiom.Core;
using Axiom.Graphics;
using Axiom.MathLib;
using Axiom.Animating;
using Multiverse.Base;
using Multiverse.Config;
using Multiverse.Gui;
using Multiverse.Interface;
#endregion
namespace Multiverse.BetaWorld.Gui {
/// <summary>
/// Class that represents a static text widget attached to an
/// Axiom node and associated with a Multiverse world object.
/// </summary>
public class AttachedWidget : IDisposable
{
long oid;
Node node;
protected Window widget;
bool nodeVisible = false;
bool drawWidget = false;
public AttachedWidget(long oid, Window widget)
{
this.oid = oid;
this.widget = widget;
WindowManager.Instance.AttachWindow(widget);
}
public virtual void Dispose() {
WindowManager.Instance.DestroyWindow(widget);
}
public virtual void SetPosition(float screenX, float screenY, float screenZ) {
screenX = (float)Math.Floor(screenX - widget.Width / 2);
screenY = (float)Math.Floor(screenY - widget.Height / 2);
widget.Position = new Point(screenX, screenY);
widget.ZValue = screenZ;
}
public long Oid {
get {
return oid;
}
}
public string Name {
get {
return widget.Name;
}
}
public Node Node {
get {
return node;
}
set {
node = value;
}
}
public bool NodeVisible {
get {
return nodeVisible;
}
set {
nodeVisible = value;
widget.Visible = drawWidget && nodeVisible;
}
}
public bool Visible {
get {
return drawWidget && nodeVisible;
}
set {
drawWidget = value;
widget.Visible = drawWidget && nodeVisible;
}
}
public Window Widget {
get {
return widget;
}
}
}
public class BubbleTextNode : AttachedWidget
{
long expireTime;
public BubbleTextNode(long oid) :
base(oid, new WLBubbleText("bubblechat." + oid))
{
widget.Position = new Point(0, 0);
widget.MaximumSize = new Size(200, 200);
widget.Alpha = 0.9f;
//widget.BackgroundColors = new ColorRect(ColorEx.White);
//widget.FrameEnabled = true;
//widget.BackgroundEnabled = true;
widget.Visible = true;
}
public bool IsExpired(long now) {
// return false;
return (now > expireTime);
}
public void SetText(string text, long expire) {
widget.Visible = true;
if (widget is WLBubbleText) {
WLBubbleText bubbleTextWidget = (WLBubbleText)widget;
bubbleTextWidget.SetText(text);
}
expireTime = expire;
}
public void SetFont(Font font) {
if (widget is WLBubbleText) {
WLBubbleText bubbleTextWidget = (WLBubbleText)widget;
bubbleTextWidget.SetFont(font);
}
}
}
public class NameNode : AttachedWidget {
public NameNode(long oid)
:
base(oid, new WLNameText("name." + oid)) {
widget.Position = new Point(0, 0);
widget.Alpha = 1.0f;
//widget.FrameEnabled = false;
//widget.BackgroundEnabled = false;
widget.Visible = false;
// FIXME
//ZOrderedStaticText textWidget = (ZOrderedStaticText)widget;
//textWidget.SetTextColor(ColorEx.Cyan);
//textWidget.HorizontalFormat = HorizontalTextFormat.Centered;
}
public void SetText(string text) {
// widget.Visible = true;
if (widget is WLNameText) {
WLNameText nameTextWidget = (WLNameText)widget;
nameTextWidget.SetText(text);
}
}
public void SetFont(Font font) {
if (widget is WLNameText)
((WLNameText)widget).SetFont(font);
}
}
/// <summary>
/// Scene object that wraps the widget for use in visibility tests and
/// attachment to other objects.
/// </summary>
public class WidgetSceneObject : MovableObject
{
// AxisAlignedBox box = new AxisAlignedBox(Vector3.Zero, Vector3.Zero);
AttachedWidget widgetNode;
AxisAlignedBox boundingBox;
public WidgetSceneObject() {
boundingBox = new AxisAlignedBox();
boundingBox.IsNull = false;
}
public override void NotifyCurrentCamera(Camera camera) {
if (!camera.IsObjectVisible(GetWorldBoundingBox(true))) {
widgetNode.NodeVisible = false;
} else {
widgetNode.NodeVisible = true;
}
}
public override void UpdateRenderQueue(RenderQueue queue) {
}
public override AxisAlignedBox GetWorldBoundingBox(bool derive) {
return base.GetWorldBoundingBox(derive);
}
public AttachedWidget WidgetNode {
get {
return widgetNode;
}
set {
widgetNode = value;
this.Name = widgetNode.Name;
}
}
/// <summary>
/// Get the bounding box of this MovableObject.
/// </summary>
/// <remarks>
/// The returned bounding box will be modified, so be sure
/// to return a new object, instead of our own.
/// </remarks>
public override AxisAlignedBox BoundingBox {
get {
return (AxisAlignedBox)boundingBox.Clone();
}
}
public override float BoundingRadius {
get {
return 1.0f;
}
}
}
#if TEMP_DISABLED
public class DummyScrollbar : Scrollbar {
public DummyScrollbar(string name) : base(name) {
}
/// <summary>
/// Create a <see cref="PushButton"/> based widget to use as the decreaseButton button for this scroll bar.
/// </summary>
/// <returns>A custom PushButton implementation.</returns>
protected override PushButton CreateDecreaseButton() {
throw new NotImplementedException();
}
/// <summary>
/// Create a <see cref="PushButton"/> based widget to use as the increaseButton button for this scroll bar.
/// </summary>
/// <returns>A custom PushButton implementation.</returns>
protected override PushButton CreateIncreaseButton() {
throw new NotImplementedException();
}
/// <summary>
/// Create a <see cref="Thumb"/> based widget to use as the thumb for this scroll bar.
/// </summary>
/// <returns>A custom thumb implementation.</returns>
protected override Thumb CreateThumb() {
throw new NotImplementedException();
}
/// <summary>
/// Given window location <paramref name="point"/>, return a value indicating what change should be made to the scroll bar.
/// </summary>
/// <param name="point">Point object describing a pixel position in window space.</param>
/// <returns>
/// - -1 to indicate scroll bar position should be moved to a lower value.
/// - 0 to indicate scroll bar position should not be changed.
/// - +1 to indicate scroll bar position should be moved to a higher value.
/// </returns>
protected override float GetAdjustDirectionFromPoint(CrayzEdsGui.Base.Point point) {
throw new NotImplementedException();
}
/// <summary>
/// Return the value that best represents current scroll bar position given the current location of the thumb.
/// </summary>
/// <returns>float value that, given the thumb widget position, best represents the current position for the scroll bar.</returns>
protected override float GetPositionFromThumb() {
throw new NotImplementedException();
}
/// <summary>
/// Layout the scroll bar component widgets
/// </summary>
protected override void LayoutComponentWidgets() {
// noop
}
/// <summary>
/// Update the size and location of the thumb to properly represent the current state of the scroll bar.
/// </summary>
protected override void UpdateThumb() {
// noop
}
protected override void DrawSelf(float z) {
// noop
}
}
#endif
#if DISABLED
/// <summary>
/// Class that acts like a static text widget, but handles its quads
/// by creating a billboard attached to an Axiom Node instead of
/// just drawing them to the screen.
/// </summary>
public class NameWidget : StaticText
{
MultiverseRenderer renderer;
TextBillboardSet textBillboard;
SceneNode node;
public NameWidget(SceneNode node, string name) : base(name) {
this.node = node;
textBillboard = new TextBillboardSet("NameBar/" + name);
node.AttachObject(textBillboard);
Renderer tmp = GuiSystem.Instance.Renderer;
Debug.Assert(tmp is MultiverseRenderer, "Not using multiverse renderer");
renderer = (MultiverseRenderer)tmp;
}
protected override void DrawSelf(float z) {
renderer.SetSceneObject(textBillboard);
try {
MetricsMode tmp = this.MetricsMode;
this.MetricsMode = MetricsMode.Absolute;
renderer.SetWidgetSize(this.Size);
this.MetricsMode = tmp;
Logger.Log(0, "Calling DrawSelf: node = " + node);
// base.DrawSelf(z);
Logger.Log(0, "Done calling DrawSelf");
} finally {
renderer.SetSceneObject(null);
}
}
#region Methods for Scrollbars
/// <summary>
/// Create and return a pointer to a Scrollbar widget for use as
/// vertical scroll bar
/// </summary>
/// <returns></returns>
protected override Scrollbar CreateVertScrollbar() {
return new DummyScrollbar("dummy");
}
/// <summary>
/// Create and return a pointer to a Scrollbar widget for use as
/// horizontal scroll bar
/// </summary>
/// <returns></returns>
protected override Scrollbar CreateHorzScrollbar() {
return new DummyScrollbar("dummy");
}
#endregion
public TextBillboardSet TextBillboard {
get {
return textBillboard;
}
set {
textBillboard = value;
}
}
}
#endif
public abstract class WidgetManager
{
protected Client client;
protected WorldManager worldManager;
protected Window window;
private bool visible = false;
public WidgetManager(Window rootWindow, Client client,
WorldManager worldManager) {
this.client = client;
this.worldManager = worldManager;
this.window = rootWindow;
}
protected bool SetWidgetPosition(AttachedWidget widgetNode,
Vector3 widgetOffset, Point pixelOffset) {
Vector3 widgetPosition = widgetNode.Node.DerivedPosition + widgetOffset;
float screenX, screenY, screenZ;
if (!client.GetScreenPosition(widgetPosition, out screenX, out screenY, out screenZ)) {
widgetNode.Visible = false;
return false;
}
screenX = screenX * window.Width + pixelOffset.x;
screenY = screenY * window.Height + pixelOffset.y;
if ((screenX > window.Width) || (screenX < 0.0f) ||
(screenY > window.Height) || (screenY < 0.0f)) {
widgetNode.Visible = false;
return false;
}
widgetNode.SetPosition(screenX, screenY, screenZ);
return true;
}
protected bool SetWidgetPosition(AttachedWidget widgetNode, Vector3 widgetOffset) {
Point zero = new Point(0, 0);
return SetWidgetPosition(widgetNode, widgetOffset, zero);
}
public bool Visible {
get {
return visible;
}
set {
visible = value;
}
}
}
// FIXME: Locking
public class NameManager : WidgetManager
{
private Font font;
private Dictionary<long, NameNode> nameDictionary;
public NameManager(Window rootWindow, Client client,
WorldManager worldManager) :
base(rootWindow, client, worldManager)
{
// Renderer that can be used to render stuff to a mesh
// meshRenderer = new MultiverseRenderer(rootWindow);
// font = new MultiverseFont("MV-Tahoma-30", "Tahoma", 30, meshRenderer,
// FontFlags.None, (char)32, (char)127);
// fontMaterial = (Material)MaterialManager.Instance.Create("font-material");
// SetupFontMaterial();
nameDictionary = new Dictionary<long, NameNode>();
if (FontManager.Instance.ContainsKey("NameFont"))
font = FontManager.Instance.GetFont("NameFont");
else
font = FontManager.Instance.CreateFont2("NameFont", "Verdana", 10);
}
#if DISABLED
private void SetupFontMaterial() {
Technique technique = fontMaterial.CreateTechnique();
Pass pass = technique.CreatePass();
TextureUnitState texUnitState = pass.CreateTextureUnitState();
texUnitState.SetTextureName(font.TextureName);
// texUnitState.SetAlphaOperation(LayerBlendOperation.AlphaBlend);
// texUnitState.SetTextureFiltering(FilterOptions.Linear);
texUnitState.TextureAddressing = TextureAddressing.Clamp;
texUnitState.TextureMatrix = Matrix4.Identity;
texUnitState.TextureCoordSet = 0;
// renderSystem.SetTextureCoordCalculation( 0, TexCoordCalcMethod.None );
// renderSystem.SetTextureUnitFiltering(0, FilterOptions.Linear, FilterOptions.Linear, FilterOptions.Point);
// renderSystem.SetAlphaRejectSettings(0, CompareFunction.AlwaysPass, 0);
// renderSystem.SetTextureBlendMode( 0, unitState.ColorBlendMode );
// renderSystem.SetTextureBlendMode( 0, unitState.AlphaBlendMode );
//
// // enable alpha blending
// renderSystem.SetSceneBlending(SceneBlendFactor.SourceAlpha, SceneBlendFactor.OneMinusSourceAlpha);
}
#endif
public void Tick(float timeSinceLastFrame, long now) {
lock (nameDictionary) {
// Draw the name elements
foreach (AttachedWidget node in nameDictionary.Values)
UpdateNode(node, now);
}
}
private bool IsTargeted(long oid) {
return (client.Target != null && client.Target.Oid == oid);
}
/// <summary>
/// Lock on the name dictionary is held already
/// </summary>
/// <param name="widgetNode"></param>
/// <param name="now"></param>
private void UpdateNode(AttachedWidget widgetNode, long now) {
const float MaxFadeRange = 40 * Client.OneMeter;
const float MinFadeRange = 20 * Client.OneMeter;
const float MaxFadeRangeSquared = MaxFadeRange * MaxFadeRange;
const float MinFadeRangeSquared = MinFadeRange * MinFadeRange;
ColorEx[] SelectedColors = new ColorEx[4];
SelectedColors[0] = new ColorEx(1, 0, 1.0f, 1.0f);
SelectedColors[1] = new ColorEx(1, 0, 0.9f, 0.9f);
SelectedColors[2] = new ColorEx(1, 0, 0.8f, 0.8f);
SelectedColors[3] = new ColorEx(1, 0, 0.7f, 0.7f);
ColorEx StandardColor = new ColorEx(1, 0, 0.9f, 0.9f);
Axiom.MathLib.Vector3 ray =
widgetNode.Node.DerivedPosition - client.Camera.DerivedPosition;
if (!IsTargeted(widgetNode.Oid)) {
// Don't show if they are too far away or if they are the player,
// unless they are selected
if (widgetNode.Oid == client.PlayerId || ray.LengthSquared > MaxFadeRangeSquared) {
widgetNode.Visible = false;
return;
}
}
// Put the name widget about one foot above the mob's head
if (!SetWidgetPosition(widgetNode, Vector3.Zero))
// if (!SetWidgetPosition(widgetNode, new Vector3(0, 0.3f * Client.OneMeter, 0)))
return;
if (ray.LengthSquared < MinFadeRangeSquared || IsTargeted(widgetNode.Oid))
widgetNode.Widget.Alpha = 1.0f;
else
widgetNode.Widget.Alpha = 1.0f - (ray.Length - MinFadeRange) / (MaxFadeRange - MinFadeRange);
#if OLD_CODE
ZOrderedStaticText textWidget = (ZOrderedStaticText)widgetNode.Widget;
if (IsTargeted(widgetNode.Oid)) {
const int Period = 500;
// Blink the name with a 500ms period.
float tmp = now % Period;
tmp /= Period;
int i = (int)Math.Min(3, 4 * Math.Sin(Math.PI * tmp));
textWidget.SetTextColor(SelectedColors[i]);
} else
textWidget.SetTextColor(StandardColor);
#endif
if (this.Visible)
widgetNode.Visible = true;
}
/// <summary>
/// Inform the name manager about an object node for which the name
/// should be displayed.
/// </summary>
/// <param name="oid">the object id of the node (used as the key for lookups)</param>
/// <param name="objNode">the object node whose name should be displayed</param>
public void AddNode(long oid, ObjectNode objNode) {
NameNode widgetNode = new NameNode(oid);
Node attachNode = null;
WidgetSceneObject attachObj = new WidgetSceneObject();
attachObj.WidgetNode = widgetNode;
AttachmentPoint ap = objNode.GetAttachmentPoint("name-disabled");
if (ap == null) {
// Default to a bit larger than the height of the bounding box
float objectHeight = objNode.Entity.BoundingBox.Size.y * 1.02f;
ap = new AttachmentPoint("name-disabled", null, Quaternion.Identity, Vector3.UnitY * objectHeight);
}
attachNode = objNode.AttachLocalObject(ap, attachObj);
if (attachNode == null) {
widgetNode.NodeVisible = true;
widgetNode.Node = objNode.SceneNode;
} else {
// The node visible will be set by the attachObj
widgetNode.Node = attachNode;
}
// FIXME
//widgetNode.Widget.Text = objNode.Name;
//widgetNode.Widget.Font = font;
window.AddChild(widgetNode.Widget);
widgetNode.Widget.Initialize();
widgetNode.SetFont(font);
widgetNode.SetText(objNode.Name);
lock (nameDictionary) {
nameDictionary[oid] = widgetNode;
}
}
public void RemoveNode(long oid) {
lock (nameDictionary) {
if (!nameDictionary.ContainsKey(oid))
return;
NameNode node = nameDictionary[oid];
window.RemoveChild(node.Widget);
node.Dispose();
nameDictionary.Remove(oid);
}
}
public void ClearNodes() {
lock (nameDictionary) {
foreach (long oid in nameDictionary.Keys) {
NameNode node = nameDictionary[oid];
window.RemoveChild(node.Widget);
node.Dispose();
}
nameDictionary.Clear();
}
}
#if DISABLED
public void AddNode(int oid, ObjectNode objNode) {
// Create a namebar scene node and entity to handle names
Axiom.MathLib.Vector3 offset = new Axiom.MathLib.Vector3(0, 2 * Client.OneMeter, 0);
SceneNode sceneNode = objNode.SceneNode.CreateChildSceneNode("namebar." + oid, offset);
TexturedBillboardSet widget = new TexturedBillboardSet("billboard." + oid);
widget.MaterialName = "font-material";
widget.BillboardType = BillboardType.Point;
widget.CommonDirection = Axiom.MathLib.Vector3.NegativeUnitZ;
sceneNode.AttachObject(widget);
// Set the target mesh for methods like Font.DrawText
meshRenderer.BeginRender(widget);
Rect dummyRect = new Rect();
dummyRect.left = 0;
dummyRect.top = 0;
dummyRect.Height = 150;
dummyRect.Width = 600;
font.DrawText("This is a test", dummyRect, 0);
meshRenderer.EndRender();
}
public void AddNode(int oid, ObjectNode objNode) {
NameNode nameNode = new NameNode();
// nameNode.nameBar = (StaticText)WindowManager.Instance.CreateWindow(
// "WindowsLook.WLStaticText", "Window/LabelText-" + oid);
// nameNode.nameBar.Font = font;
// nameNode.nameBar.Text = "Name: " + objNode.Name;
// nameNode.nameBar.HorizontalFormat = HorizontalTextFormat.Center;
// nameNode.nameBar.VerticalFormat = VerticalTextFormat.Top;
// nameNode.nameBar.SetTextColor(new Color(1, 0, 0, 0));
// nameNode.nameBar.MetricsMode = MetricsMode.Absolute;
// float chromeHeight =
// nameNode.nameBar.UnclippedPixelRect.Height - nameNode.nameBar.UnclippedInnerRect.Height;
// Logger.Log(0, "chromeHeight: {0} Line Spacing: {1}", chromeHeight, font.LineSpacing);
// nameNode.nameBar.Size = new Size(60, chromeHeight + font.LineSpacing + 5); // FIXME (why do i need +5)
nameDictionary[oid] = nameNode;
// window.AddChild(nameNode.nameBar);
// nameNode.nameBar.MetricsMode = MetricsMode.Relative;
// Console.WriteLine("Adding node for: " + objNode.Name);
NameWidget widget = new NameWidget(objNode.SceneNode, objNode.Name);
widget.Initialize();
// Object will be clipped to this size
widget.MetricsMode = MetricsMode.Relative;
widget.Size = new Size(1.0f, 1.0f);
widget.Position = new Point(0.0f, 0.0f);
widget.Text = objNode.Name;
widget.HorizontalFormat = HorizontalTextFormat.Center;
widget.VerticalFormat = VerticalTextFormat.Centered;
widget.Visible = true;
window.AddChild(widget);
}
#endif
}
public class BubbleTextManager : WidgetManager
{
// protected const int VertexBufferCapacity = 4096;
// private MultiverseFont font;
// private Material fontMaterial;
private Font font;
// private MultiverseRenderer meshRenderer;
private Dictionary<long, BubbleTextNode> bubbleDictionary;
public BubbleTextManager(Window rootWindow, Client client,
WorldManager worldManager) :
base(rootWindow, client, worldManager)
{
// Renderer that can be used to render stuff to a mesh
// meshRenderer = new MultiverseRenderer(rootWindow);
// font = new MultiverseFont("MV-Tahoma-30", "Tahoma", 30, meshRenderer,
// FontFlags.None, (char)32, (char)127);
// fontMaterial = (Material)MaterialManager.Instance.Create("font-material");
// SetupFontMaterial();
bubbleDictionary = new Dictionary<long, BubbleTextNode>();
if (FontManager.Instance.ContainsKey("BubbleTextFont"))
font = FontManager.Instance.GetFont("BubbleTextFont");
else
font = FontManager.Instance.CreateFont2("BubbleTextFont", "Verdana", 10);
}
#if DISABLED
private void SetupFontMaterial() {
Technique technique = fontMaterial.CreateTechnique();
Pass pass = technique.CreatePass();
TextureUnitState texUnitState = pass.CreateTextureUnitState();
texUnitState.SetTextureName(font.TextureName);
// texUnitState.SetAlphaOperation(LayerBlendOperation.AlphaBlend);
// texUnitState.SetTextureFiltering(FilterOptions.Linear);
texUnitState.TextureAddressing = TextureAddressing.Clamp;
texUnitState.TextureMatrix = Matrix4.Identity;
texUnitState.TextureCoordSet = 0;
// renderSystem.SetTextureCoordCalculation( 0, TexCoordCalcMethod.None );
// renderSystem.SetTextureUnitFiltering(0, FilterOptions.Linear, FilterOptions.Linear, FilterOptions.Point);
// renderSystem.SetAlphaRejectSettings(0, CompareFunction.AlwaysPass, 0);
// renderSystem.SetTextureBlendMode( 0, unitState.ColorBlendMode );
// renderSystem.SetTextureBlendMode( 0, unitState.AlphaBlendMode );
//
// // enable alpha blending
// renderSystem.SetSceneBlending(SceneBlendFactor.SourceAlpha, SceneBlendFactor.OneMinusSourceAlpha);
}
#endif
/// <summary>
/// Called periodically to update the attached gui widgets to match
/// the position of the underlying object.
/// </summary>
/// <param name="timeSinceLastFrame"></param>
/// <param name="now"></param>
public void Tick(float timeSinceLastFrame, long now) {
// Draw the name elements
lock (bubbleDictionary) {
foreach (AttachedWidget node in bubbleDictionary.Values)
UpdateNode(node, now);
}
}
/// <summary>
/// Lock on the bubble dictionary is held already
/// </summary>
/// <param name="widgetNode"></param>
/// <param name="now"></param>
private void UpdateNode(AttachedWidget widgetNode, long now) {
const float MaxFadeRange = 40 * Client.OneMeter;
const float MinFadeRange = 20 * Client.OneMeter;
const float MaxFadeRangeSquared = MaxFadeRange * MaxFadeRange;
const float MinFadeRangeSquared = MinFadeRange * MinFadeRange;
Axiom.MathLib.Vector3 ray =
widgetNode.Node.DerivedPosition - client.Camera.DerivedPosition;
// Don't show if they are too far away
if (ray.LengthSquared > MaxFadeRangeSquared) {
widgetNode.Visible = false;
return;
}
BubbleTextNode bubbleNode = (BubbleTextNode)widgetNode;
if (bubbleNode.IsExpired(now)) {
widgetNode.Visible = false;
return;
}
Vector3 widgetOffset = new Vector3(0, 0.3f * Client.OneMeter, 0);
Point pixelOffset = new Point(0, -50);
// if (!SetWidgetPosition(widgetNode, widgetOffset, pixelOffset))
if (!SetWidgetPosition(widgetNode, Vector3.Zero, pixelOffset))
return;
if (ray.LengthSquared < MinFadeRangeSquared)
widgetNode.Widget.Alpha = 1.0f;
else
widgetNode.Widget.Alpha = 1.0f - (ray.Length - MinFadeRange) / (MaxFadeRange - MinFadeRange);
if (this.Visible)
widgetNode.Visible = true;
}
public void SetBubbleText(long oid, string text, long now) {
lock (bubbleDictionary) {
if (bubbleDictionary.ContainsKey(oid)) {
BubbleTextNode node = bubbleDictionary[oid];
// expire in 5 seconds, plus one second for each 5 chars
long expire = now + 5000 + (1000 * text.Length) / 5;
node.SetText(text, expire);
UpdateNode(node, now);
}
}
}
// FIXME: Thread safety
public void AddNode(long oid, ObjectNode objNode) {
BubbleTextNode widgetNode = new BubbleTextNode(oid);
Node attachNode = null;
WidgetSceneObject attachObj = new WidgetSceneObject();
attachObj.WidgetNode = widgetNode;
AttachmentPoint ap = objNode.GetAttachmentPoint("bubble-disabled");
if (ap == null) {
// Default to a bit larger than the height of the bounding box
float objectHeight = objNode.Entity.BoundingBox.Size.y * 1.02f;
ap = new AttachmentPoint("bubble-disabled", null, Quaternion.Identity, Vector3.UnitY * objectHeight);
}
attachNode = objNode.AttachLocalObject(ap, attachObj);
if (attachNode == null) {
widgetNode.NodeVisible = true;
widgetNode.Node = objNode.SceneNode;
} else {
// The node visible will be set by the attachObj
widgetNode.Node = attachNode;
}
// FIXME
// widgetNode.Widget.Font = font;
window.AddChild(widgetNode.Widget);
widgetNode.Widget.Initialize();
widgetNode.SetFont(font);
lock (bubbleDictionary) {
bubbleDictionary[oid] = widgetNode;
}
}
public void RemoveNode(long oid) {
lock (bubbleDictionary) {
if (!bubbleDictionary.ContainsKey(oid))
return;
BubbleTextNode node = bubbleDictionary[oid];
window.RemoveChild(node.Widget);
bubbleDictionary.Remove(oid);
node.Dispose();
}
}
public void ClearNodes() {
lock (bubbleDictionary) {
foreach (long oid in bubbleDictionary.Keys) {
BubbleTextNode node = bubbleDictionary[oid];
window.RemoveChild(node.Widget);
node.Dispose();
}
bubbleDictionary.Clear();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
using Interlocked = System.Threading.Interlocked;
namespace Internal.IL.Stubs
{
/// <summary>
/// Thunk to dynamically invoke a method using reflection. The method accepts an object[] of parameters
/// to target method, lays them out on the stack, and calls the target method. This thunk has heavy
/// dependencies on the general dynamic invocation infrastructure in System.InvokeUtils and gets called from there
/// at runtime. See comments in System.InvokeUtils for a more thorough explanation.
/// </summary>
internal partial class DynamicInvokeMethodThunk : ILStubMethod
{
private TypeDesc _owningType;
private DynamicInvokeMethodSignature _targetSignature;
private TypeDesc[] _instantiation;
private MethodSignature _signature;
public DynamicInvokeMethodThunk(TypeDesc owningType, DynamicInvokeMethodSignature signature)
{
_owningType = owningType;
_targetSignature = signature;
}
public override TypeSystemContext Context
{
get
{
return _owningType.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _owningType;
}
}
private MetadataType InvokeUtilsType
{
get
{
return Context.SystemModule.GetKnownType("System", "InvokeUtils");
}
}
private MetadataType ArgSetupStateType
{
get
{
return InvokeUtilsType.GetNestedType("ArgSetupState");
}
}
public override MethodSignature Signature
{
get
{
if (_signature == null)
{
_signature = new MethodSignature(
MethodSignatureFlags.Static,
Instantiation.Length,
Context.GetWellKnownType(WellKnownType.Object),
new TypeDesc[]
{
Context.GetWellKnownType(WellKnownType.Object), // thisPtr
Context.GetWellKnownType(WellKnownType.IntPtr), // methodToCall
ArgSetupStateType.MakeByRefType(), // argSetupState
Context.GetWellKnownType(WellKnownType.Boolean), // targetIsThisCall
});
}
return _signature;
}
}
public override Instantiation Instantiation
{
get
{
if (_instantiation == null)
{
TypeDesc[] instantiation =
new TypeDesc[_targetSignature.HasReturnValue ? _targetSignature.Length + 1 : _targetSignature.Length];
for (int i = 0; i < _targetSignature.Length; i++)
instantiation[i] = new DynamicInvokeThunkGenericParameter(this, i);
if (_targetSignature.HasReturnValue)
instantiation[_targetSignature.Length] =
new DynamicInvokeThunkGenericParameter(this, _targetSignature.Length);
Interlocked.CompareExchange(ref _instantiation, instantiation, null);
}
return new Instantiation(_instantiation);
}
}
public override string Name
{
get
{
StringBuilder sb = new StringBuilder("InvokeRet");
if (_targetSignature.HasReturnValue)
sb.Append('O');
else
sb.Append('V');
for (int i = 0; i < _targetSignature.Length; i++)
sb.Append(_targetSignature[i] == DynamicInvokeMethodParameterKind.Value ? 'I' : 'R');
return sb.ToString();
}
}
public override MethodIL EmitIL()
{
ILEmitter emitter = new ILEmitter();
ILCodeStream argSetupStream = emitter.NewCodeStream();
ILCodeStream thisCallSiteSetupStream = emitter.NewCodeStream();
ILCodeStream staticCallSiteSetupStream = emitter.NewCodeStream();
// This function will look like
//
// !For each parameter to the method
// !if (parameter is In Parameter)
// localX is TypeOfParameterX&
// ldtoken TypeOfParameterX
// call DynamicInvokeParamHelperIn(RuntimeTypeHandle)
// stloc localX
// !else
// localX is TypeOfParameter
// ldtoken TypeOfParameterX
// call DynamicInvokeParamHelperRef(RuntimeTypeHandle)
// stloc localX
// ldarg.2
// call DynamicInvokeArgSetupComplete(ref ArgSetupState)
// *** Thiscall instruction stream starts here ***
// ldarg.3 // Load targetIsThisCall
// brfalse Not_this_call
// ldarg.0 // Load this pointer
// !For each parameter
// !if (parameter is In Parameter)
// ldloc localX
// ldobj TypeOfParameterX
// !else
// ldloc localX
// ldarg.1
// calli ReturnType thiscall(TypeOfParameter1, ...)
// !if ((ReturnType == void)
// ldnull
// !else
// box ReturnType
// ret
// *** Static call instruction stream starts here ***
// Not_this_call:
// !For each parameter
// !if (parameter is In Parameter)
// ldloc localX
// ldobj TypeOfParameterX
// !else
// ldloc localX
// ldarg.1
// calli ReturnType (TypeOfParameter1, ...)
// !if ((ReturnType == void)
// ldnull
// !else
// box ReturnType
// ret
ILCodeLabel lStaticCall = emitter.NewCodeLabel();
thisCallSiteSetupStream.EmitLdArg(3); // targetIsThisCall
thisCallSiteSetupStream.Emit(ILOpcode.brfalse, lStaticCall);
staticCallSiteSetupStream.EmitLabel(lStaticCall);
thisCallSiteSetupStream.EmitLdArg(0); // thisPtr
ILToken tokDynamicInvokeParamHelperRef =
emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperRef", null));
ILToken tokDynamicInvokeParamHelperIn =
emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeParamHelperIn", null));
TypeDesc[] targetMethodSignature = new TypeDesc[_targetSignature.Length];
for (int paramIndex = 0; paramIndex < _targetSignature.Length; paramIndex++)
{
TypeDesc paramType = Context.GetSignatureVariable(paramIndex, true);
ILToken tokParamType = emitter.NewToken(paramType);
ILLocalVariable local = emitter.NewLocal(paramType.MakeByRefType());
thisCallSiteSetupStream.EmitLdLoc(local);
staticCallSiteSetupStream.EmitLdLoc(local);
argSetupStream.Emit(ILOpcode.ldtoken, tokParamType);
if (_targetSignature[paramIndex] == DynamicInvokeMethodParameterKind.Reference)
{
argSetupStream.Emit(ILOpcode.call, tokDynamicInvokeParamHelperRef);
targetMethodSignature[paramIndex] = paramType.MakeByRefType();
}
else
{
argSetupStream.Emit(ILOpcode.call, tokDynamicInvokeParamHelperIn);
thisCallSiteSetupStream.Emit(ILOpcode.ldobj, tokParamType);
staticCallSiteSetupStream.Emit(ILOpcode.ldobj, tokParamType);
targetMethodSignature[paramIndex] = paramType;
}
argSetupStream.EmitStLoc(local);
}
argSetupStream.EmitLdArg(2); // argSetupState
argSetupStream.Emit(ILOpcode.call, emitter.NewToken(InvokeUtilsType.GetKnownMethod("DynamicInvokeArgSetupComplete", null)));
thisCallSiteSetupStream.EmitLdArg(1); // methodToCall
staticCallSiteSetupStream.EmitLdArg(1); // methodToCall
TypeDesc returnType = _targetSignature.HasReturnValue ?
Context.GetSignatureVariable(_targetSignature.Length, true) :
Context.GetWellKnownType(WellKnownType.Void);
MethodSignature thisCallMethodSig = new MethodSignature(0, 0, returnType, targetMethodSignature);
thisCallSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(thisCallMethodSig));
MethodSignature staticCallMethodSig = new MethodSignature(MethodSignatureFlags.Static, 0, returnType, targetMethodSignature);
staticCallSiteSetupStream.Emit(ILOpcode.calli, emitter.NewToken(staticCallMethodSig));
if (_targetSignature.HasReturnValue)
{
ILToken tokReturnType = emitter.NewToken(returnType);
thisCallSiteSetupStream.Emit(ILOpcode.box, tokReturnType);
staticCallSiteSetupStream.Emit(ILOpcode.box, tokReturnType);
}
else
{
thisCallSiteSetupStream.Emit(ILOpcode.ldnull);
staticCallSiteSetupStream.Emit(ILOpcode.ldnull);
}
thisCallSiteSetupStream.Emit(ILOpcode.ret);
staticCallSiteSetupStream.Emit(ILOpcode.ret);
return emitter.Link(this);
}
private partial class DynamicInvokeThunkGenericParameter : GenericParameterDesc
{
private DynamicInvokeMethodThunk _owningMethod;
public DynamicInvokeThunkGenericParameter(DynamicInvokeMethodThunk owningMethod, int index)
{
_owningMethod = owningMethod;
Index = index;
}
public override TypeSystemContext Context
{
get
{
return _owningMethod.Context;
}
}
public override int Index
{
get;
}
public override GenericParameterKind Kind
{
get
{
return GenericParameterKind.Method;
}
}
}
}
internal enum DynamicInvokeMethodParameterKind
{
None,
Value,
Reference,
}
/// <summary>
/// Wraps a <see cref="MethodSignature"/> to reduce it's fidelity.
/// </summary>
internal struct DynamicInvokeMethodSignature : IEquatable<DynamicInvokeMethodSignature>
{
private MethodSignature _signature;
public bool HasReturnValue
{
get
{
return !_signature.ReturnType.IsVoid;
}
}
public int Length
{
get
{
return _signature.Length;
}
}
public DynamicInvokeMethodParameterKind this[int index]
{
get
{
return _signature[index].IsByRef ?
DynamicInvokeMethodParameterKind.Reference :
DynamicInvokeMethodParameterKind.Value;
}
}
public DynamicInvokeMethodSignature(MethodSignature concreteSignature)
{
// ByRef returns should have been filtered out elsewhere. We don't handle them
// because reflection can't invoke such methods.
Debug.Assert(!concreteSignature.ReturnType.IsByRef);
_signature = concreteSignature;
}
public override bool Equals(object obj)
{
return obj is DynamicInvokeMethodSignature && Equals((DynamicInvokeMethodSignature)obj);
}
public override int GetHashCode()
{
int hashCode = HasReturnValue ? 17 : 23;
for (int i = 0; i < Length; i++)
{
int value = (int)this[i] * 0x5498341 + 0x832424;
hashCode = hashCode * 31 + value;
}
return hashCode;
}
public bool Equals(DynamicInvokeMethodSignature other)
{
if (HasReturnValue != other.HasReturnValue)
return false;
if (Length != other.Length)
return false;
for (int i = 0; i < Length; i++)
{
if (this[i] != other[i])
return false;
}
return true;
}
}
}
| |
//------------------------------------------------------------------------------
// Copyright (c) 2014-2016 the original author or authors. All Rights Reserved.
//
// NOTICE: You are permitted to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Robotlegs.Bender.Extensions.ViewManagement.API;
namespace Robotlegs.Bender.Extensions.ViewManagement.Impl
{
/// <summary>
/// View manager, will be made by each context.
/// It can add containers which will be passed into the Container Registry.
/// But if you add a second container view with it, it will clone all it's view handlers added to itself for you
/// </summary>
public class ViewManager : IViewManager
{
/*============================================================================*/
/* Public Properties */
/*============================================================================*/
public event Action<object> ContainerAdded
{
add
{
_containerAdded += value;
}
remove
{
_containerAdded -= value;
}
}
public event Action<object> ContainerRemoved
{
add
{
_containerRemoved += value;
}
remove
{
_containerRemoved -= value;
}
}
public event Action<IViewHandler> HandlerAdd
{
add
{
_handlerAdd += value;
}
remove
{
_handlerAdd -= value;
}
}
public event Action<IViewHandler> HandlerRemove
{
add
{
_handlerRemove += value;
}
remove
{
_handlerRemove -= value;
}
}
public List<object> Containers
{
get
{
return _containers;
}
}
/*============================================================================*/
/* Private Properties */
/*============================================================================*/
private Action<object> _containerAdded;
private Action<object> _containerRemoved;
private Action<IViewHandler> _handlerAdd;
private Action<IViewHandler> _handlerRemove;
private List<IViewHandler> _handlers = new List<IViewHandler>();
private List<object> _containers = new List<object>();
private object _fallbackContainer;
private ContainerRegistry _registry;
/*============================================================================*/
/* Constructor */
/*============================================================================*/
public ViewManager(ContainerRegistry containerRegistry)
{
_registry = containerRegistry;
}
/*============================================================================*/
/* Public Functions */
/*============================================================================*/
public void AddContainer(object container)
{
if (!ValidContainer(container))
return;
_containers.Add(container);
ContainerBinding containerBinding = _registry.AddContainer(container);
AddHandlers (containerBinding);
if (_containerAdded != null)
{
_containerAdded (container);
}
}
public void RemoveContainer(object container)
{
if (!_containers.Remove (container))
return;
ContainerBinding binding = _registry.GetBinding (container);
if (binding != null)
{
RemoveHandlers (binding);
}
if (_containerRemoved != null)
{
_containerRemoved (container);
}
}
public void SetFallbackContainer(object container)
{
_fallbackContainer = container;
ContainerBinding containerBinding = _registry.SetFallbackContainer (container);
RemoveAllHandlers (false);
AddHandlers (containerBinding);
_registry.FallbackContainerRemove += FallbackContainerBindingRemoved;
}
public void RemoveFallbackContainer()
{
if (_fallbackContainer == null)
return;
_registry.RemoveFallbackContainer ();
}
public void AddViewHandler(IViewHandler handler)
{
if (_handlers.Contains(handler))
return;
_handlers.Add(handler);
// Add new handler to our containers
if (_fallbackContainer != null)
{
_registry.GetBinding (_fallbackContainer).AddHandler (handler);
}
else
{
foreach (object container in _containers)
{
_registry.AddContainer (container).AddHandler (handler);
}
}
if (_handlerAdd != null)
{
_handlerAdd (handler);
}
}
public void RemoveViewHandler(IViewHandler handler)
{
_handlers.Remove(handler);
foreach(object container in _containers)
{
_registry.GetBinding(container).RemoveHandler(handler);
}
if (_handlerRemove != null)
{
_handlerRemove (handler);
}
}
public void RemoveAllHandlers()
{
RemoveAllHandlers (true);
}
/*============================================================================*/
/* Private Functions */
/*============================================================================*/
private void RemoveAllHandlers(bool includeFallback)
{
if (includeFallback && _fallbackContainer != null)
{
_registry.RemoveContainer (_fallbackContainer);
}
foreach (object container in _containers)
{
ContainerBinding binding = _registry.GetBinding (container);
RemoveHandlers (binding);
}
}
private void AddAllHandlers()
{
foreach (object container in _containers)
{
ContainerBinding binding = _registry.AddContainer (container);
AddHandlers (binding);
}
}
private void FallbackContainerBindingRemoved(object container)
{
_registry.FallbackContainerRemove -= FallbackContainerBindingRemoved;
_fallbackContainer = null;
AddAllHandlers ();
}
private void AddHandlers(ContainerBinding binding)
{
foreach (IViewHandler handler in _handlers)
{
binding.AddHandler(handler);
}
}
private void RemoveHandlers(ContainerBinding binding)
{
foreach (IViewHandler handler in _handlers)
{
binding.RemoveHandler (handler);
}
}
private bool ValidContainer(object container)
{
//TODO: Check for nested containers and already existing containers with this ViewManager
if (_registry.FallbackBinding != null && _registry.FallbackBinding.Container == container)
return true;
foreach (object registeredContainer in _containers)
{
if (container == registeredContainer)
return false;
if (_registry.FallbackBinding != null && _registry.FallbackBinding.Container == registeredContainer)
return false;
if (_registry.Contains (registeredContainer, container) || _registry.Contains (container, registeredContainer))
throw new Exception ("Containers can not be nested");
}
return true;
}
}
}
| |
using Bridge.Contract;
using Bridge.Contract.Constants;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Bridge.Translator.TypeScript
{
public class EmitBlock : TypeScriptBlock
{
private class OutputKey
{
public OutputKey(string key, Module module, string ns)
{
this.Key = key;
this.Module = module;
this.Namespace = ns;
}
public string Key
{
get;
set;
}
public Module Module
{
get;
set;
}
public string Namespace
{
get;
set;
}
public override int GetHashCode()
{
unchecked
{
return ((this.Key != null ? this.Key.GetHashCode() : 0) * 397) ^ (this.Module != null ? this.Module.GetHashCode() : 0);
}
}
public override bool Equals(object obj)
{
var other = obj as OutputKey;
return other == null ? false : this.Key == other.Key && (this.Module == null && other.Module == null || this.Module != null && this.Module.Equals(other.Module));
}
}
// This ensures a constant line separator throughout the application
private const char newLine = Bridge.Contract.XmlToJSConstants.DEFAULT_LINE_SEPARATOR;
private Dictionary<OutputKey, StringBuilder> Outputs
{
get;
set;
}
private string ns = null;
private OutputKey outputKey = null;
public EmitBlock(IEmitter emitter)
: base(emitter, null)
{
this.Emitter = emitter;
}
protected virtual StringBuilder GetOutputForType(ITypeInfo typeInfo)
{
var info = BridgeTypes.GetNamespaceFilename(typeInfo, this.Emitter);
var ns = info.Item1;
var fileName = info.Item2;
var module = info.Item3;
StringBuilder output = null;
OutputKey key = new OutputKey(fileName, module, ns);
if (this.ns != null && (this.ns != ns || this.outputKey != null && !this.outputKey.Equals(key)))
{
this.EndBlock();
this.WriteNewLine();
}
this.ns = ns;
this.outputKey = key;
if (this.Outputs.ContainsKey(key))
{
output = this.Outputs[key];
}
else
{
if (this.Emitter.Output != null)
{
this.InsertDependencies(this.Emitter.Output);
}
output = new StringBuilder();
this.Emitter.Output = output;
if (ns != null)
{
if (module == null || module.Type == ModuleType.UMD)
{
output.Append("declare ");
}
output.Append("namespace " + ns + " ");
this.BeginBlock();
}
this.Outputs.Add(key, output);
this.Emitter.CurrentDependencies = new List<IPluginDependency>();
}
return output;
}
protected virtual void InsertDependencies(StringBuilder sb)
{
if (this.Emitter.CurrentDependencies != null && this.Emitter.CurrentDependencies.Count > 0)
{
StringBuilder depSb = new StringBuilder();
foreach (var d in this.Emitter.CurrentDependencies)
{
depSb.Append(@"/// <reference path=""./" + d.DependencyName + @".d.ts"" />");
depSb.Append(newLine);
}
sb.Insert(0, depSb.ToString() + newLine);
this.Emitter.CurrentDependencies.Clear();
}
}
private void TransformOutputs()
{
if (this.Emitter.Outputs.Count == 0)
{
return;
}
var withoutModuleOutputs = this.Outputs.Where(o => o.Key.Module == null).ToList();
var withModuleOutputs = this.Outputs.Where(o => o.Key.Module != null).ToList();
var nonModuleOutputs = withoutModuleOutputs.GroupBy(o => o.Key.Key).ToDictionary(t => t.Key, t => string.Join(newLine.ToString(), t.Select(r => r.Value.ToString()).ToList()));
var outputs = withModuleOutputs.GroupBy(o => o.Key.Module).ToDictionary(t => t.Key, t => string.Join(newLine.ToString(), t.Select(r => r.Value.ToString()).ToList()));
if (this.Emitter.AssemblyInfo.OutputBy == OutputBy.Project)
{
var fileName = Path.GetFileNameWithoutExtension(this.Emitter.Outputs.First().Key) + Files.Extensions.DTS;
var e = new EmitterOutput(fileName);
foreach (var item in nonModuleOutputs)
{
e.NonModuletOutput.Append(item.Value.ToString() + newLine);
}
foreach (var item in outputs)
{
e.NonModuletOutput.Append(WrapModule(item) + newLine);
}
this.Emitter.Outputs.Add(fileName, e);
}
else
{
foreach (var item in nonModuleOutputs)
{
var fileName = item.Key + Files.Extensions.DTS;
var e = new EmitterOutput(fileName);
e.NonModuletOutput.Append(item.Value.ToString());
this.Emitter.Outputs.Add(fileName, e);
}
foreach (var item in outputs)
{
var fileName = item.Key.ExportAsNamespace + Files.Extensions.DTS;
var e = new EmitterOutput(fileName);
e.NonModuletOutput.Append(WrapModule(item));
this.Emitter.Outputs.Add(fileName, e);
}
}
}
private string WrapModule(KeyValuePair<Module, string> item)
{
StringBuilder sb = new StringBuilder();
if (item.Key.Type == ModuleType.AMD || item.Key.Type == ModuleType.CommonJS)
{
sb.Append("declare module \"" + item.Key.ExportAsNamespace + "\" {");
sb.Append(Bridge.Translator.Emitter.NEW_LINE);
sb.Append(" " + AbstractEmitterBlock.WriteIndentToString(item.Value, 1));
sb.Append(Bridge.Translator.Emitter.NEW_LINE);
sb.Append("}");
}
else if (item.Key.Type == ModuleType.UMD)
{
sb.Append(item.Value);
sb.Append(Bridge.Translator.Emitter.NEW_LINE);
sb.Append("declare module \"" + item.Key.ExportAsNamespace + "\" {");
sb.Append(Bridge.Translator.Emitter.NEW_LINE);
sb.Append(" export = " + item.Key.ExportAsNamespace + ";");
sb.Append(Bridge.Translator.Emitter.NEW_LINE);
sb.Append("}");
}
else
{
sb.Append(item.Value);
}
sb.Append(Bridge.Translator.Emitter.NEW_LINE);
return sb.ToString();
}
protected override void DoEmit()
{
this.Emitter.Tag = "TS";
this.Emitter.Writers = new Stack<IWriter>();
this.Outputs = new Dictionary<OutputKey, StringBuilder>();
var types = this.Emitter.Types.ToArray();
Array.Sort(types, (t1, t2) =>
{
var t1ns = BridgeTypes.GetNamespaceFilename(t1, this.Emitter);
var t2ns = BridgeTypes.GetNamespaceFilename(t2, this.Emitter);
if (t1ns.Item1 == null && t2ns.Item1 == null)
{
return 0;
}
if (t1ns.Item1 == null)
{
return -1;
}
if (t2ns.Item1 == null)
{
return 1;
}
var key1 = t1ns.Item1 + (t1ns.Item3 != null ? t1ns.Item3.ExportAsNamespace : "");
var key2 = t2ns.Item1 + (t2ns.Item3 != null ? t2ns.Item3.ExportAsNamespace : "");
return t1ns.Item1.CompareTo(t2ns.Item1);
});
this.Emitter.InitEmitter();
bool nsExists = false;
var last = types.LastOrDefault();
foreach (var type in types)
{
if (!nsExists)
{
var tns = BridgeTypes.GetNamespaceFilename(type, this.Emitter);
if (tns.Item1 != null)
{
nsExists = true;
}
}
if (type.ParentType != null)
{
continue;
}
this.Emitter.Translator.EmitNode = type.TypeDeclaration;
if (type.IsObjectLiteral)
{
continue;
}
ITypeInfo typeInfo;
if (this.Emitter.TypeInfoDefinitions.ContainsKey(type.Key))
{
typeInfo = this.Emitter.TypeInfoDefinitions[type.Key];
type.Module = typeInfo.Module;
type.FileName = typeInfo.FileName;
type.Dependencies = typeInfo.Dependencies;
typeInfo = type;
}
else
{
typeInfo = type;
}
this.Emitter.TypeInfo = type;
type.JsName = BridgeTypes.ToJsName(type.Type, this.Emitter, true);
this.Emitter.Output = this.GetOutputForType(typeInfo);
var nestedTypes = types.Where(t => t.ParentType == type);
new ClassBlock(this.Emitter, this.Emitter.TypeInfo, nestedTypes, types, this.ns).Emit();
this.WriteNewLine();
if (type != last)
{
this.WriteNewLine();
}
}
this.InsertDependencies(this.Emitter.Output);
if (this.outputKey != null && nsExists)
{
this.EndBlock();
}
this.TransformOutputs();
}
}
}
| |
using System;
using System.Management.Automation;
using EnvDTE;
using NuGet.VisualStudio;
namespace NuGet.PowerShell.Commands
{
/// <summary>
/// This project updates the specified package to the specified project.
/// </summary>
[Cmdlet(VerbsData.Update, "Package", DefaultParameterSetName = "All")]
public class UpdatePackageCommand : ProcessPackageBaseCommand, IPackageOperationEventListener
{
private readonly IVsPackageSourceProvider _packageSourceProvider;
private readonly IPackageRepositoryFactory _repositoryFactory;
private readonly IProductUpdateService _productUpdateService;
private bool _hasConnectedToHttpSource;
public UpdatePackageCommand()
: this(ServiceLocator.GetInstance<ISolutionManager>(),
ServiceLocator.GetInstance<IVsPackageManagerFactory>(),
ServiceLocator.GetInstance<IPackageRepositoryFactory>(),
ServiceLocator.GetInstance<IVsPackageSourceProvider>(),
ServiceLocator.GetInstance<IHttpClientEvents>(),
ServiceLocator.GetInstance<IProductUpdateService>(),
ServiceLocator.GetInstance<IVsCommonOperations>(),
ServiceLocator.GetInstance<IDeleteOnRestartManager>())
{
}
public UpdatePackageCommand(ISolutionManager solutionManager,
IVsPackageManagerFactory packageManagerFactory,
IPackageRepositoryFactory repositoryFactory,
IVsPackageSourceProvider packageSourceProvider,
IHttpClientEvents httpClientEvents,
IProductUpdateService productUpdateService,
IVsCommonOperations vsCommonOperations,
IDeleteOnRestartManager deleteOnRestartManager)
: base(solutionManager, packageManagerFactory, httpClientEvents, vsCommonOperations, deleteOnRestartManager)
{
_repositoryFactory = repositoryFactory;
_packageSourceProvider = packageSourceProvider;
_productUpdateService = productUpdateService;
}
// We need to override id since it's mandatory in the base class. We don't
// want it to be mandatory here.
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0, ParameterSetName = "Project")]
[Parameter(ValueFromPipelineByPropertyName = true, Position = 0, ParameterSetName = "All")]
[Parameter(ValueFromPipelineByPropertyName = true, Position = 0, ParameterSetName = "Reinstall")]
public override string Id
{
get
{
return base.Id;
}
set
{
base.Id = value;
}
}
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "All")]
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "Project")]
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "Reinstall")]
public override string ProjectName
{
get
{
return base.ProjectName;
}
set
{
base.ProjectName = value;
}
}
[Parameter(Position = 2, ParameterSetName = "Project")]
[ValidateNotNull]
public SemanticVersion Version { get; set; }
[Parameter(Position = 3)]
[ValidateNotNullOrEmpty]
public string Source { get; set; }
[Parameter]
public SwitchParameter IgnoreDependencies { get; set; }
[Parameter]
public SwitchParameter Safe { get; set; }
[Parameter(Mandatory = true, ParameterSetName = "Reinstall")]
[Parameter(ParameterSetName = "All")]
public SwitchParameter Reinstall { get; set; }
[Parameter, Alias("Prerelease")]
public SwitchParameter IncludePrerelease { get; set; }
[Parameter]
public FileConflictAction FileConflictAction { get; set; }
[Parameter]
public SwitchParameter WhatIf { get; set; }
protected override IVsPackageManager CreatePackageManager()
{
if (!String.IsNullOrEmpty(Source))
{
IPackageRepository repository = CreateRepositoryFromSource(_repositoryFactory, _packageSourceProvider, Source);
return repository == null ? null : PackageManagerFactory.CreatePackageManager(repository, useFallbackForDependencies: true);
}
return base.CreatePackageManager();
}
protected override void ProcessRecordCore()
{
if (!SolutionManager.IsSolutionOpen)
{
// terminating
ErrorHandler.ThrowSolutionNotOpenTerminatingError();
}
if (WhatIf && Reinstall)
{
Log(MessageLevel.Error, Resources.Cmdlet_WhatIfReinstallUnsupported);
return;
}
try
{
SubscribeToProgressEvents();
if (PackageManager != null)
{
PackageManager.WhatIf = WhatIf;
if (ProjectManager != null)
{
ProjectManager.WhatIf = WhatIf;
}
if (Reinstall)
{
PerformReinstalls(ProjectManager);
}
else
{
PerformUpdates(ProjectManager);
}
_hasConnectedToHttpSource |= UriHelper.IsHttpSource(Source, _packageSourceProvider);
}
}
finally
{
UnsubscribeFromProgressEvents();
}
}
private void PerformReinstalls(IProjectManager projectManager)
{
if (!String.IsNullOrEmpty(Id))
{
// If a package id was specified, but no project was specified, then update this package in all projects
if (String.IsNullOrEmpty(ProjectName))
{
PackageManager.ReinstallPackage(Id, !IgnoreDependencies, IncludePrerelease, this, this);
}
else if (projectManager != null)
{
PackageManager.ReinstallPackage(projectManager, Id, !IgnoreDependencies, IncludePrerelease, this);
}
}
else
{
if (String.IsNullOrEmpty(ProjectName))
{
PackageManager.ReinstallPackages(!IgnoreDependencies, IncludePrerelease, this, this);
}
else if (projectManager != null)
{
PackageManager.ReinstallPackages(projectManager, !IgnoreDependencies, IncludePrerelease, this);
}
}
}
private void PerformUpdates(IProjectManager projectManager)
{
if (!String.IsNullOrEmpty(Id))
{
// If a package id was specified, but no project was specified, then update this package in all projects
if (String.IsNullOrEmpty(ProjectName))
{
if (Safe.IsPresent)
{
PackageManager.SafeUpdatePackage(Id, !IgnoreDependencies.IsPresent, IncludePrerelease, this, this);
}
else
{
PackageManager.UpdatePackage(Id, Version, !IgnoreDependencies.IsPresent, IncludePrerelease, this, this);
}
}
else if (projectManager != null)
{
// If there was a project specified, then update the package in that project
if (Safe.IsPresent)
{
PackageManager.SafeUpdatePackage(projectManager, Id, !IgnoreDependencies, IncludePrerelease, this);
}
else
{
PackageManager.UpdatePackage(projectManager, Id, Version, !IgnoreDependencies, IncludePrerelease, this);
}
}
}
else
{
// if no id was specified then update all packages in the solution
if (Safe.IsPresent)
{
if (String.IsNullOrEmpty(ProjectName))
{
PackageManager.SafeUpdatePackages(!IgnoreDependencies.IsPresent, IncludePrerelease, this, this);
}
else if (projectManager != null)
{
PackageManager.SafeUpdatePackages(projectManager, !IgnoreDependencies.IsPresent, IncludePrerelease, this);
}
}
else
{
if (String.IsNullOrEmpty(ProjectName))
{
PackageManager.UpdatePackages(!IgnoreDependencies.IsPresent, IncludePrerelease, this, this);
}
else if (projectManager != null)
{
PackageManager.UpdatePackages(projectManager, !IgnoreDependencies.IsPresent, IncludePrerelease, this);
}
}
}
}
public override FileConflictResolution ResolveFileConflict(string message)
{
if (FileConflictAction == FileConflictAction.Overwrite)
{
return FileConflictResolution.Overwrite;
}
if (FileConflictAction == FileConflictAction.Ignore)
{
return FileConflictResolution.Ignore;
}
return base.ResolveFileConflict(message);
}
protected override void EndProcessing()
{
base.EndProcessing();
CheckForNuGetUpdate();
}
private void CheckForNuGetUpdate()
{
if (_productUpdateService != null && _hasConnectedToHttpSource)
{
_productUpdateService.CheckForAvailableUpdateAsync();
}
}
public void OnBeforeAddPackageReference(Project project)
{
RegisterProjectEvents(project);
}
public void OnAfterAddPackageReference(Project project)
{
// No-op
}
public void OnAddPackageReferenceError(Project project, Exception exception)
{
// No-op
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.NetworkInformation
{
public partial class Ping
{
private const int MaxUdpPacket = 0xFFFF + 256; // Marshal.SizeOf(typeof(Icmp6EchoReply)) * 2 + ip header info;
private static readonly SafeWaitHandle s_nullSafeWaitHandle = new SafeWaitHandle(IntPtr.Zero, true);
private static readonly object s_socketInitializationLock = new object();
private static bool s_socketInitialized;
private int _sendSize = 0; // Needed to determine what the reply size is for ipv6 in callback.
private bool _ipv6 = false;
private ManualResetEvent _pingEvent;
private RegisteredWaitHandle _registeredWait;
private SafeLocalAllocHandle _requestBuffer;
private SafeLocalAllocHandle _replyBuffer;
private Interop.IpHlpApi.SafeCloseIcmpHandle _handlePingV4;
private Interop.IpHlpApi.SafeCloseIcmpHandle _handlePingV6;
private TaskCompletionSource<PingReply> _taskCompletionSource;
private PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
// Since isAsync == false, DoSendPingCore will execute synchronously and return a completed
// Task - so no blocking here
return DoSendPingCore(address, buffer, timeout, options, isAsync: false).GetAwaiter().GetResult();
}
private Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
// Since isAsync == true, DoSendPingCore will execute asynchronously and return an active Task
return DoSendPingCore(address, buffer, timeout, options, isAsync: true);
}
// Any exceptions that escape synchronously will be caught by the caller and wrapped in a PingException.
// We do not need to or want to capture such exceptions into the returned task.
private Task<PingReply> DoSendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions options, bool isAsync)
{
TaskCompletionSource<PingReply> tcs = null;
if (isAsync)
{
_taskCompletionSource = tcs = new TaskCompletionSource<PingReply>();
}
_ipv6 = (address.AddressFamily == AddressFamily.InterNetworkV6);
_sendSize = buffer.Length;
// Cache correct handle.
InitialiseIcmpHandle();
if (_replyBuffer == null)
{
_replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket);
}
int error;
try
{
if (isAsync)
{
RegisterWaitHandle();
}
SetUnmanagedStructures(buffer);
error = SendEcho(address, buffer, timeout, options, isAsync);
}
catch
{
Cleanup(isAsync);
throw;
}
if (error == 0)
{
error = Marshal.GetLastWin32Error();
// Only skip Async IO Pending error value.
if (!isAsync || error != Interop.IpHlpApi.ERROR_IO_PENDING)
{
Cleanup(isAsync);
IPStatus status = GetStatusFromCode(error);
return Task.FromResult(new PingReply(address, default, status, default, Array.Empty<byte>()));
}
}
if (isAsync)
return tcs.Task;
Cleanup(isAsync);
return Task.FromResult(CreatePingReply());
}
private void RegisterWaitHandle()
{
if (_pingEvent == null)
{
_pingEvent = new ManualResetEvent(false);
}
else
{
_pingEvent.Reset();
}
_registeredWait = ThreadPool.RegisterWaitForSingleObject(_pingEvent, (state, _) => ((Ping)state).PingCallback(), this, -1, true);
}
private void UnregisterWaitHandle()
{
lock (_lockObject)
{
if (_registeredWait != null)
{
// If Unregister returns false, it is sufficient to nullify registeredWait
// and let its own finalizer clean up later.
_registeredWait.Unregister(null);
_registeredWait = null;
}
}
}
private SafeWaitHandle GetWaitHandle(bool async)
{
if (async)
{
return _pingEvent.GetSafeWaitHandle();
}
return s_nullSafeWaitHandle;
}
private void InitialiseIcmpHandle()
{
if (!_ipv6 && _handlePingV4 == null)
{
_handlePingV4 = Interop.IpHlpApi.IcmpCreateFile();
if (_handlePingV4.IsInvalid)
{
_handlePingV4 = null;
throw new Win32Exception(); // Gets last error.
}
}
else if (_ipv6 && _handlePingV6 == null)
{
_handlePingV6 = Interop.IpHlpApi.Icmp6CreateFile();
if (_handlePingV6.IsInvalid)
{
_handlePingV6 = null;
throw new Win32Exception(); // Gets last error.
}
}
}
private int SendEcho(IPAddress address, byte[] buffer, int timeout, PingOptions options, bool isAsync)
{
Interop.IpHlpApi.IPOptions ipOptions = new Interop.IpHlpApi.IPOptions(options);
if (!_ipv6)
{
return (int)Interop.IpHlpApi.IcmpSendEcho2(
_handlePingV4,
GetWaitHandle(isAsync),
IntPtr.Zero,
IntPtr.Zero,
#pragma warning disable CS0618 // Address is marked obsolete
(uint)address.Address,
#pragma warning restore CS0618
_requestBuffer,
(ushort)buffer.Length,
ref ipOptions,
_replyBuffer,
MaxUdpPacket,
(uint)timeout);
}
IPEndPoint ep = new IPEndPoint(address, 0);
Internals.SocketAddress remoteAddr = IPEndPointExtensions.Serialize(ep);
byte[] sourceAddr = new byte[28];
return (int)Interop.IpHlpApi.Icmp6SendEcho2(
_handlePingV6,
GetWaitHandle(isAsync),
IntPtr.Zero,
IntPtr.Zero,
sourceAddr,
remoteAddr.Buffer,
_requestBuffer,
(ushort)buffer.Length,
ref ipOptions,
_replyBuffer,
MaxUdpPacket,
(uint)timeout);
}
private PingReply CreatePingReply()
{
SafeLocalAllocHandle buffer = _replyBuffer;
// Marshals and constructs new reply.
if (_ipv6)
{
Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure<Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle());
return CreatePingReplyFromIcmp6EchoReply(icmp6Reply, buffer.DangerousGetHandle(), _sendSize);
}
Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure<Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle());
return CreatePingReplyFromIcmpEchoReply(icmpReply);
}
private void Cleanup(bool isAsync)
{
FreeUnmanagedStructures();
if (isAsync)
{
UnregisterWaitHandle();
}
}
partial void InternalDisposeCore()
{
if (_handlePingV4 != null)
{
_handlePingV4.Dispose();
_handlePingV4 = null;
}
if (_handlePingV6 != null)
{
_handlePingV6.Dispose();
_handlePingV6 = null;
}
UnregisterWaitHandle();
if (_pingEvent != null)
{
_pingEvent.Dispose();
_pingEvent = null;
}
if (_replyBuffer != null)
{
_replyBuffer.Dispose();
_replyBuffer = null;
}
}
// Private callback invoked when icmpsendecho APIs succeed.
private void PingCallback()
{
TaskCompletionSource<PingReply> tcs = _taskCompletionSource;
_taskCompletionSource = null;
PingReply reply = null;
Exception error = null;
bool canceled = false;
try
{
lock (_lockObject)
{
canceled = _canceled;
reply = CreatePingReply();
}
}
catch (Exception e)
{
// In case of failure, create a failed event arg.
error = new PingException(SR.net_ping, e);
}
finally
{
Cleanup(isAsync: true);
}
// Once we've called Finish, complete the task
if (canceled)
{
tcs.SetCanceled();
}
else if (reply != null)
{
tcs.SetResult(reply);
}
else
{
Debug.Assert(error != null);
tcs.SetException(error);
}
}
// Copies _requestBuffer into unmanaged memory for async icmpsendecho APIs.
private unsafe void SetUnmanagedStructures(byte[] buffer)
{
_requestBuffer = SafeLocalAllocHandle.LocalAlloc(buffer.Length);
byte* dst = (byte*)_requestBuffer.DangerousGetHandle();
for (int i = 0; i < buffer.Length; ++i)
{
dst[i] = buffer[i];
}
}
// Releases the unmanaged memory after ping completion.
private void FreeUnmanagedStructures()
{
if (_requestBuffer != null)
{
_requestBuffer.Dispose();
_requestBuffer = null;
}
}
private static IPStatus GetStatusFromCode(int statusCode)
{
// Caveat lector: IcmpSendEcho2 doesn't allow us to know for sure if an error code
// is an IP Status code or a general win32 error code. This assumes everything under
// the base is a win32 error, and everything beyond is an IPStatus.
if (statusCode != 0 && statusCode < Interop.IpHlpApi.IP_STATUS_BASE)
{
throw new Win32Exception(statusCode);
}
return (IPStatus)statusCode;
}
private static PingReply CreatePingReplyFromIcmpEchoReply(Interop.IpHlpApi.IcmpEchoReply reply)
{
const int DontFragmentFlag = 2;
IPAddress address = new IPAddress(reply.address);
IPStatus ipStatus = GetStatusFromCode((int)reply.status);
long rtt;
PingOptions options;
byte[] buffer;
if (ipStatus == IPStatus.Success)
{
// Only copy the data if we succeed w/ the ping operation.
rtt = reply.roundTripTime;
options = new PingOptions(reply.options.ttl, (reply.options.flags & DontFragmentFlag) > 0);
buffer = new byte[reply.dataSize];
Marshal.Copy(reply.data, buffer, 0, reply.dataSize);
}
else
{
rtt = default(long);
options = default(PingOptions);
buffer = Array.Empty<byte>();
}
return new PingReply(address, options, ipStatus, rtt, buffer);
}
private static PingReply CreatePingReplyFromIcmp6EchoReply(Interop.IpHlpApi.Icmp6EchoReply reply, IntPtr dataPtr, int sendSize)
{
IPAddress address = new IPAddress(reply.Address.Address, reply.Address.ScopeID);
IPStatus ipStatus = GetStatusFromCode((int)reply.Status);
long rtt;
byte[] buffer;
if (ipStatus == IPStatus.Success)
{
// Only copy the data if we succeed w/ the ping operation.
rtt = reply.RoundTripTime;
buffer = new byte[sendSize];
Marshal.Copy(dataPtr + 36, buffer, 0, sendSize);
}
else
{
rtt = default(long);
buffer = Array.Empty<byte>();
}
return new PingReply(address, default(PingOptions), ipStatus, rtt, buffer);
}
static partial void InitializeSockets()
{
if (!Volatile.Read(ref s_socketInitialized))
{
lock (s_socketInitializationLock)
{
if (!s_socketInitialized)
{
// Ensure that WSAStartup has been called once per process.
// The System.Net.NameResolution contract is responsible with the initialization.
Dns.GetHostName();
// Cache some settings locally.
s_socketInitialized = true;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using Interlocked = System.Threading.Interlocked;
using Internal.Cryptography;
namespace System.Security.Cryptography.X509Certificates
{
public partial class X509CertificateCollection : ICollection, IEnumerable, IList
{
public X509CertificateCollection()
{
_list = new LowLevelListWithIList<Object>();
}
public X509CertificateCollection(X509Certificate[] value)
: this()
{
AddRange(value);
}
public X509CertificateCollection(X509CertificateCollection value)
: this()
{
AddRange(value);
}
public int Count
{
get { return _list.Count; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
Object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
bool IList.IsFixedSize
{
get { return false; }
}
bool IList.IsReadOnly
{
get { return false; }
}
Object IList.this[int index]
{
get
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
return _list[index];
}
set
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
if (value == null)
throw new ArgumentNullException("value");
_list[index] = value;
}
}
public X509Certificate this[int index]
{
get
{
// Note: If a non-X509Certificate was inserted at this position, the result InvalidCastException is the defined behavior.
return (X509Certificate)(List[index]);
}
set
{
List[index] = value;
}
}
public int Add(X509Certificate value)
{
return List.Add(value);
}
public void AddRange(X509Certificate[] value)
{
if (value == null)
throw new ArgumentNullException("value");
for (int i = 0; i < value.Length; i++)
{
Add(value[i]);
}
}
public void AddRange(X509CertificateCollection value)
{
if (value == null)
throw new ArgumentNullException("value");
for (int i = 0; i < value.Count; i++)
{
Add(value[i]);
}
}
public void Clear()
{
_list.Clear();
}
public bool Contains(X509Certificate value)
{
foreach (X509Certificate cert in List)
{
if (cert.Equals(value))
{
return true;
}
}
return false;
}
public void CopyTo(X509Certificate[] array, int index)
{
List.CopyTo(array, index);
}
public X509CertificateEnumerator GetEnumerator()
{
return new X509CertificateEnumerator(((IList<Object>)_list).GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return new X509CertificateEnumerator(((IList<Object>)_list).GetEnumerator());
}
public override int GetHashCode()
{
int hashCode = 0;
foreach (X509Certificate cert in this)
{
hashCode += cert.GetHashCode();
}
return hashCode;
}
public int IndexOf(X509Certificate value)
{
return List.IndexOf(value);
}
public void Insert(int index, X509Certificate value)
{
List.Insert(index, value);
}
public void Remove(X509Certificate value)
{
List.Remove(value);
}
public void RemoveAt(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
_list.RemoveAt(index);
}
void ICollection.CopyTo(Array array, int index)
{
List.CopyTo(array, index);
}
int IList.Add(Object value)
{
if (value == null)
throw new ArgumentNullException("value");
int index = _list.Count;
_list.Add(value);
return index;
}
bool IList.Contains(Object value)
{
return _list.Contains(value);
}
int IList.IndexOf(Object value)
{
return _list.IndexOf(value);
}
void IList.Insert(int index, Object value)
{
_list.Insert(index, value);
}
void IList.Remove(Object value)
{
_list.Remove(value);
}
internal IList List
{
get { return this; }
}
private LowLevelListWithIList<Object> _list;
private Object _syncRoot;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//#define ENABLE
//#define MINBUFFERS
using System.Collections.Generic;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
namespace System.Threading
{
// Reduced copy of System.Collections.Concurrent.ConcurrentStack<T>
internal class ConcurrentStack<T>
{
private class Node
{
internal readonly T _value; // Value of the node.
internal Node _next; // Next pointer.
internal Node(T value)
{
_value = value;
_next = null;
}
}
private volatile Node _head; // The stack is a singly linked list, and only remembers the head.
private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff.
public int Count
{
get
{
int count = 0;
for (Node curr = _head; curr != null; curr = curr._next)
{
count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR
}
return count;
}
}
public void Push(T item)
{
Node newNode = new Node(item);
newNode._next = _head;
if (Interlocked.CompareExchange(ref _head, newNode, newNode._next) == newNode._next)
{
return;
}
// If we failed, go to the slow path and loop around until we succeed.
PushCore(newNode, newNode);
}
private void PushCore(Node head, Node tail)
{
SpinWait spin = new SpinWait();
// Keep trying to CAS the existing head with the new node until we succeed.
do
{
spin.SpinOnce();
// Reread the head and link our new node.
tail._next = _head;
}
while (Interlocked.CompareExchange(
ref _head, head, tail._next) != tail._next);
}
public bool TryPop(out T result)
{
Node head = _head;
//stack is empty
if (head == null)
{
result = default(T);
return false;
}
if (Interlocked.CompareExchange(ref _head, head._next, head) == head)
{
result = head._value;
return true;
}
// Fall through to the slow path.
return TryPopCore(out result);
}
private bool TryPopCore(out T result)
{
Node poppedNode;
if (TryPopCore(1, out poppedNode) == 1)
{
result = poppedNode._value;
return true;
}
result = default(T);
return false;
}
private int TryPopCore(int count, out Node poppedHead)
{
SpinWait spin = new SpinWait();
// Try to CAS the head with its current next. We stop when we succeed or
// when we notice that the stack is empty, whichever comes first.
Node head;
Node next;
int backoff = 1;
Random r = null;
while (true)
{
head = _head;
// Is the stack empty?
if (head == null)
{
poppedHead = null;
return 0;
}
next = head;
int nodesCount = 1;
for (; nodesCount < count && next._next != null; nodesCount++)
{
next = next._next;
}
// Try to swap the new head. If we succeed, break out of the loop.
if (Interlocked.CompareExchange(ref _head, next._next, head) == head)
{
// Return the popped Node.
poppedHead = head;
return nodesCount;
}
// We failed to CAS the new head. Spin briefly and retry.
for (int i = 0; i < backoff; i++)
{
spin.SpinOnce();
}
if (spin.NextSpinWillYield)
{
if (r == null)
{
r = new Random();
}
backoff = r.Next(1, BACKOFF_MAX_YIELDS);
}
else
{
backoff *= 2;
}
}
}
}
internal sealed class PinnableBufferCache
{
/// <summary>
/// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData)
/// This is only used in mscorlib.
/// </summary>
internal PinnableBufferCache(string cacheName, Func<object> factory)
{
m_NotGen2 = new List<object>(DefaultNumberOfBuffers);
m_factory = factory;
#if ENABLE
// Check to see if we should disable the cache.
string envVarName = "PinnableBufferCache_" + cacheName + "_Disabled";
try
{
string envVar = Environment.GetEnvironmentVariable(envVarName);
if (envVar != null)
{
PinnableBufferCacheEventSource.Log.DebugMessage("Creating " + cacheName + " PinnableBufferCacheDisabled=" + envVar);
int index = envVar.IndexOf(cacheName, StringComparison.OrdinalIgnoreCase);
if (0 <= index)
{
// The cache is disabled because we haven't set the cache name.
PinnableBufferCacheEventSource.Log.DebugMessage("Disabling " + cacheName);
return;
}
}
}
catch
{
// Ignore failures when reading the environment variable.
}
#endif
#if MINBUFFERS
// Allow the environment to specify a minimum buffer count.
string minEnvVarName = "PinnableBufferCache_" + cacheName + "_MinCount";
try
{
string minEnvVar = Environment.GetEnvironmentVariable(minEnvVarName);
if (minEnvVar != null)
{
if (int.TryParse(minEnvVar, out m_minBufferCount))
CreateNewBuffers();
}
}
catch
{
// Ignore failures when reading the environment variable.
}
#endif
PinnableBufferCacheEventSource.Log.Create(cacheName);
m_CacheName = cacheName;
}
/// <summary>
/// Get a object from the buffer manager. If no buffers exist, allocate a new one.
/// </summary>
internal object Allocate()
{
#if ENABLE
// Check to see whether or not the cache is disabled.
if (m_CacheName == null)
return m_factory();
#endif
// Fast path, get it from our Gen2 aged m_FreeList.
object returnBuffer;
if (!m_FreeList.TryPop(out returnBuffer))
Restock(out returnBuffer);
#if LOGGING
// Computing free count is expensive enough that we don't want to compute it unless logging is on.
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
int numAllocCalls = Interlocked.Increment(ref m_numAllocCalls);
if (numAllocCalls >= 1024)
{
lock (this)
{
int previousNumAllocCalls = Interlocked.Exchange(ref m_numAllocCalls, 0);
if (previousNumAllocCalls >= 1024)
{
int nonGen2Count = 0;
foreach (object o in m_FreeList)
{
if (GC.GetGeneration(o) < GC.MaxGeneration)
{
nonGen2Count++;
}
}
PinnableBufferCacheEventSource.Log.WalkFreeListResult(m_CacheName, m_FreeList.Count, nonGen2Count);
}
}
}
PinnableBufferCacheEventSource.Log.AllocateBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(returnBuffer), returnBuffer.GetHashCode(), GC.GetGeneration(returnBuffer), m_FreeList.Count);
}
#endif
return returnBuffer;
}
/// <summary>
/// Return a buffer back to the buffer manager.
/// </summary>
internal void Free(object buffer)
{
#if ENABLE
// Check to see whether or not the cache is disabled.
if (m_CacheName == null)
return;
#endif
if (PinnableBufferCacheEventSource.Log.IsEnabled())
PinnableBufferCacheEventSource.Log.FreeBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(buffer), buffer.GetHashCode(), m_FreeList.Count);
// After we've done 3 gen1 GCs, assume that all buffers have aged into gen2 on the free path.
if ((m_gen1CountAtLastRestock + 3) > GC.CollectionCount(GC.MaxGeneration - 1))
{
lock (this)
{
if (GC.GetGeneration(buffer) < GC.MaxGeneration)
{
// The buffer is not aged, so put it in the non-aged free list.
m_moreThanFreeListNeeded = true;
PinnableBufferCacheEventSource.Log.FreeBufferStillTooYoung(m_CacheName, m_NotGen2.Count);
m_NotGen2.Add(buffer);
m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1);
return;
}
}
}
// If we discovered that it is indeed Gen2, great, put it in the Gen2 list.
m_FreeList.Push(buffer);
}
#region Private
/// <summary>
/// Called when we don't have any buffers in our free list to give out.
/// </summary>
/// <returns></returns>
private void Restock(out object returnBuffer)
{
lock (this)
{
// Try again after getting the lock as another thread could have just filled the free list. If we don't check
// then we unnecessarily grab a new set of buffers because we think we are out.
if (m_FreeList.TryPop(out returnBuffer))
return;
// Lazy init, Ask that TrimFreeListIfNeeded be called on every Gen 2 GC.
if (m_restockSize == 0)
Gen2GcCallback.Register(Gen2GcCallbackFunc, this);
// Indicate to the trimming policy that the free list is insufficent.
m_moreThanFreeListNeeded = true;
PinnableBufferCacheEventSource.Log.AllocateBufferFreeListEmpty(m_CacheName, m_NotGen2.Count);
// Get more buffers if needed.
if (m_NotGen2.Count == 0)
CreateNewBuffers();
// We have no buffers in the aged freelist, so get one from the newer list. Try to pick the best one.
// Debug.Assert(m_NotGen2.Count != 0);
int idx = m_NotGen2.Count - 1;
if (GC.GetGeneration(m_NotGen2[idx]) < GC.MaxGeneration && GC.GetGeneration(m_NotGen2[0]) == GC.MaxGeneration)
idx = 0;
returnBuffer = m_NotGen2[idx];
m_NotGen2.RemoveAt(idx);
// Remember any sub-optimial buffer so we don't put it on the free list when it gets freed.
if (PinnableBufferCacheEventSource.Log.IsEnabled() && GC.GetGeneration(returnBuffer) < GC.MaxGeneration)
{
PinnableBufferCacheEventSource.Log.AllocateBufferFromNotGen2(m_CacheName, m_NotGen2.Count);
}
// If we have a Gen1 collection, then everything on m_NotGen2 should have aged. Move them to the m_Free list.
if (!AgePendingBuffers())
{
// Before we could age at set of buffers, we have handed out half of them.
// This implies we should be proactive about allocating more (since we will trim them if we over-allocate).
if (m_NotGen2.Count == m_restockSize / 2)
{
PinnableBufferCacheEventSource.Log.DebugMessage("Proactively adding more buffers to aging pool");
CreateNewBuffers();
}
}
}
}
/// <summary>
/// See if we can promote the buffers to the free list. Returns true if sucessful.
/// </summary>
private bool AgePendingBuffers()
{
if (m_gen1CountAtLastRestock < GC.CollectionCount(GC.MaxGeneration - 1))
{
// Allocate a temp list of buffers that are not actually in gen2, and swap it in once
// we're done scanning all buffers.
int promotedCount = 0;
List<object> notInGen2 = new List<object>();
PinnableBufferCacheEventSource.Log.AllocateBufferAged(m_CacheName, m_NotGen2.Count);
for (int i = 0; i < m_NotGen2.Count; i++)
{
// We actually check every object to ensure that we aren't putting non-aged buffers into the free list.
object currentBuffer = m_NotGen2[i];
if (GC.GetGeneration(currentBuffer) >= GC.MaxGeneration)
{
m_FreeList.Push(currentBuffer);
promotedCount++;
}
else
{
notInGen2.Add(currentBuffer);
}
}
PinnableBufferCacheEventSource.Log.AgePendingBuffersResults(m_CacheName, promotedCount, notInGen2.Count);
m_NotGen2 = notInGen2;
return true;
}
return false;
}
/// <summary>
/// Generates some buffers to age into Gen2.
/// </summary>
private void CreateNewBuffers()
{
// We choose a very modest number of buffers initially because for the client case. This is often enough.
if (m_restockSize == 0)
m_restockSize = 4;
else if (m_restockSize < DefaultNumberOfBuffers)
m_restockSize = DefaultNumberOfBuffers;
else if (m_restockSize < 256)
m_restockSize = m_restockSize * 2; // Grow quickly at small sizes
else if (m_restockSize < 4096)
m_restockSize = m_restockSize * 3 / 2; // Less agressively at large ones
else
m_restockSize = 4096; // Cap how agressive we are
// Ensure we hit our minimums
if (m_minBufferCount > m_buffersUnderManagement)
m_restockSize = Math.Max(m_restockSize, m_minBufferCount - m_buffersUnderManagement);
PinnableBufferCacheEventSource.Log.AllocateBufferCreatingNewBuffers(m_CacheName, m_buffersUnderManagement, m_restockSize);
for (int i = 0; i < m_restockSize; i++)
{
// Make a new buffer.
object newBuffer = m_factory();
// Create space between the objects. We do this because otherwise it forms a single plug (group of objects)
// and the GC pins the entire plug making them NOT move to Gen1 and Gen2. by putting space between them
// we ensure that object get a chance to move independently (even if some are pinned).
var dummyObject = new object();
m_NotGen2.Add(newBuffer);
}
m_buffersUnderManagement += m_restockSize;
m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1);
}
/// <summary>
/// This is the static function that is called from the gen2 GC callback.
/// The input object is the cache itself.
/// NOTE: The reason that we make this functionstatic and take the cache as a parameter is that
/// otherwise, we root the cache to the Gen2GcCallback object, and leak the cache even when
/// the application no longer needs it.
/// </summary>
private static bool Gen2GcCallbackFunc(object targetObj)
{
return ((PinnableBufferCache)(targetObj)).TrimFreeListIfNeeded();
}
/// <summary>
/// This is called on every gen2 GC to see if we need to trim the free list.
/// NOTE: DO NOT CALL THIS DIRECTLY FROM THE GEN2GCCALLBACK. INSTEAD CALL IT VIA A STATIC FUNCTION (SEE ABOVE).
/// If you register a non-static function as a callback, then this object will be leaked.
/// </summary>
private bool TrimFreeListIfNeeded()
{
int curMSec = Environment.TickCount;
int deltaMSec = curMSec - m_msecNoUseBeyondFreeListSinceThisTime;
PinnableBufferCacheEventSource.Log.TrimCheck(m_CacheName, m_buffersUnderManagement, m_moreThanFreeListNeeded, deltaMSec);
// If we needed more than just the set of aged buffers since the last time we were called,
// we obviously should not be trimming any memory, so do nothing except reset the flag
if (m_moreThanFreeListNeeded)
{
m_moreThanFreeListNeeded = false;
m_trimmingExperimentInProgress = false;
m_msecNoUseBeyondFreeListSinceThisTime = curMSec;
return true;
}
// We require a minimum amount of clock time to pass (10 seconds) before we trim. Ideally this time
// is larger than the typical buffer hold time.
if (0 <= deltaMSec && deltaMSec < 10000)
return true;
// If we got here we have spend the last few second without needing to lengthen the free list. Thus
// we have 'enough' buffers, but maybe we have too many.
// See if we can trim
lock (this)
{
// Hit a race, try again later.
if (m_moreThanFreeListNeeded)
{
m_moreThanFreeListNeeded = false;
m_trimmingExperimentInProgress = false;
m_msecNoUseBeyondFreeListSinceThisTime = curMSec;
return true;
}
var freeCount = m_FreeList.Count; // This is expensive to fetch, do it once.
// If there is something in m_NotGen2 it was not used for the last few seconds, it is trimable.
if (m_NotGen2.Count > 0)
{
// If we are not performing an experiment and we have stuff that is waiting to go into the
// free list but has not made it there, it could be becasue the 'slow path' of restocking
// has not happened, so force this (which should flush the list) and start over.
if (!m_trimmingExperimentInProgress)
{
PinnableBufferCacheEventSource.Log.TrimFlush(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count);
AgePendingBuffers();
m_trimmingExperimentInProgress = true;
return true;
}
PinnableBufferCacheEventSource.Log.TrimFree(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count);
m_buffersUnderManagement -= m_NotGen2.Count;
// Possibly revise the restocking down. We don't want to grow agressively if we are trimming.
var newRestockSize = m_buffersUnderManagement / 4;
if (newRestockSize < m_restockSize)
m_restockSize = Math.Max(newRestockSize, DefaultNumberOfBuffers);
m_NotGen2.Clear();
m_trimmingExperimentInProgress = false;
return true;
}
// Set up an experiment where we use 25% less buffers in our free list. We put them in
// m_NotGen2, and if they are needed they will be put back in the free list again.
var trimSize = freeCount / 4 + 1;
// We are OK with a 15% overhead, do nothing in that case.
if (freeCount * 15 <= m_buffersUnderManagement || m_buffersUnderManagement - trimSize <= m_minBufferCount)
{
PinnableBufferCacheEventSource.Log.TrimFreeSizeOK(m_CacheName, m_buffersUnderManagement, freeCount);
return true;
}
// Move buffers from the free list back to the non-aged list. If we don't use them by next time, then we'll consider trimming them.
PinnableBufferCacheEventSource.Log.TrimExperiment(m_CacheName, m_buffersUnderManagement, freeCount, trimSize);
object buffer;
for (int i = 0; i < trimSize; i++)
{
if (m_FreeList.TryPop(out buffer))
m_NotGen2.Add(buffer);
}
m_msecNoUseBeyondFreeListSinceThisTime = curMSec;
m_trimmingExperimentInProgress = true;
}
// Indicate that we want to be called back on the next Gen 2 GC.
return true;
}
private const int DefaultNumberOfBuffers = 16;
private string m_CacheName;
private Func<object> m_factory;
/// <summary>
/// Contains 'good' buffers to reuse. They are guarenteed to be Gen 2 ENFORCED!
/// </summary>
private ConcurrentStack<object> m_FreeList = new ConcurrentStack<object>();
/// <summary>
/// Contains buffers that are not gen 2 and thus we do not wish to give out unless we have to.
/// To implement trimming we sometimes put aged buffers in here as a place to 'park' them
/// before true deletion.
/// </summary>
private List<object> m_NotGen2;
/// <summary>
/// What whas the gen 1 count the last time re restocked? If it is now greater, then
/// we know that all objects are in Gen 2 so we don't have to check. Should be updated
/// every time something gets added to the m_NotGen2 list.
/// </summary>
private int m_gen1CountAtLastRestock;
/// <summary>
/// Used to ensure we have a minimum time between trimmings.
/// </summary>
private int m_msecNoUseBeyondFreeListSinceThisTime;
/// <summary>
/// To trim, we remove things from the free list (which is Gen 2) and see if we 'hit bottom'
/// This flag indicates that we hit bottom (we really needed a bigger free list).
/// </summary>
private bool m_moreThanFreeListNeeded;
/// <summary>
/// The total number of buffers that this cache has ever allocated.
/// Used in trimming heuristics.
/// </summary>
private int m_buffersUnderManagement;
/// <summary>
/// The number of buffers we added the last time we restocked.
/// </summary>
private int m_restockSize;
/// <summary>
/// Did we put some buffers into m_NotGen2 to see if we can trim?
/// </summary>
private bool m_trimmingExperimentInProgress;
#pragma warning disable 0649
/// <summary>
/// A forced minimum number of buffers.
/// </summary>
private int m_minBufferCount;
#pragma warning restore 0649
#if LOGGING
/// <summary>
/// The number of calls to Allocate.
/// </summary>
private int m_numAllocCalls;
#endif
#endregion
}
/// <summary>
/// Schedules a callback roughly every gen 2 GC (you may see a Gen 0 an Gen 1 but only once)
/// (We can fix this by capturing the Gen 2 count at startup and testing, but I mostly don't care)
/// </summary>
internal sealed class Gen2GcCallback : CriticalFinalizerObject
{
public Gen2GcCallback()
: base()
{
}
/// <summary>
/// Schedule 'callback' to be called in the next GC. If the callback returns true it is
/// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop.
///
/// NOTE: This callback will be kept alive until either the callback function returns false,
/// or the target object dies.
/// </summary>
public static void Register(Func<object, bool> callback, object targetObj)
{
// Create a unreachable object that remembers the callback function and target object.
Gen2GcCallback gcCallback = new Gen2GcCallback();
gcCallback.Setup(callback, targetObj);
}
#region Private
private Func<object, bool> m_callback;
private GCHandle m_weakTargetObj;
private void Setup(Func<object, bool> callback, object targetObj)
{
m_callback = callback;
m_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak);
}
~Gen2GcCallback()
{
// Check to see if the target object is still alive.
object targetObj = m_weakTargetObj.Target;
if (targetObj == null)
{
// The target object is dead, so this callback object is no longer needed.
m_weakTargetObj.Free();
return;
}
// Execute the callback method.
try
{
if (!m_callback(targetObj))
{
// If the callback returns false, this callback object is no longer needed.
return;
}
}
catch
{
// Ensure that we still get a chance to resurrect this object, even if the callback throws an exception.
}
// Resurrect ourselves by re-registering for finalization.
if (!Environment.HasShutdownStarted /*&& !AppDomain.CurrentDomain.IsFinalizingForUnload()*/)
{
GC.ReRegisterForFinalize(this);
}
}
#endregion
}
internal sealed class PinnableBufferCacheEventSource
{
public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource();
public bool IsEnabled() { return false; }
public void DebugMessage(string message) { }
public void Create(string cacheName) { }
public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { }
public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { }
public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { }
public void AllocateBufferAged(string cacheName, int agedCount) { }
public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { }
public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { }
public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { }
public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { }
public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { }
public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { }
public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { }
public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { }
public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { }
public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { }
static internal ulong AddressOf(object obj)
{
return 0;
}
}
}
| |
using System;
using System.Drawing;
using GuruComponents.Netrix;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.WebEditing.Behaviors;
namespace GuruComponents.Netrix.HelpLine
{
/// <summary>
/// Edit designer for HelpLine support.
/// </summary>
/// <remarks>
/// Checks for mouse over cross, moves and draws the
/// helpline. This designer may work if it is attached as behavior to body and as edit designer
/// to mshtml site. The host application may switch on/off the behavior but never removes the designer.
/// <para>
/// Additional features available for helplines:
/// <list type="bullet">
/// <item>
/// <term>Snap helpline to grid (default: On)</term>
/// <description>You can define a (invisible) grid which the helpline snaps into. The grids default distance is 16 pixels.</description>
/// <term>Snap Elements to helpline (Default: On)</term>
/// <description>If the control is in 2D (absolute) position mode the elements can be snapped to the line. The magnetic zone is 4 pixels.</description>
/// <term>Change the Color and Width of the Pen (Default: Blue, width 1 pixel)</term>
/// <description>You can use a <see cref="System.Drawing.Pen">Pen</see> object to change the style of the lines.</description>
/// </item>
/// </list>
/// The helpline can be moved using the mouse either on the cross (changes x and y coordinates the same time) or on each
/// line (moves only x or y, respectively). During the move with the cross the mouse pointer becomes a hand and the Ctrl-Key
/// can be used to modify the behavior.
/// </para>
/// <para>
/// <b>Usage instructions:</b>
/// </para>
/// <para>
/// To use the helpline you must retrieve an instance of that class using the property
/// <see cref="GuruComponents.Netrix.HelpLine.HelpLine">HelpLine</see>. The returned object can be changed
/// in any way. After changing you must use the
/// <see cref="GuruComponents.Netrix.HelpLine.HelplineCommands.Activate">Activate</see> command to make the lines visible.
/// The behavior can changed at any time. The object returned from <see cref="GuruComponents.Netrix.HelpLine.HelpLine">HelpLine</see>
/// is always the same (singleton).
/// </para>
/// </remarks>
public class HelpLineBehavior : BaseBehavior, Interop.IHTMLEditDesigner
{
const int CATCHZONE = 2; // Zone to catch the mouse pointer on the lines
private static int instanceCounter = 0;
private int instance;
private int x, y; // Position of Helpline
private bool _lineVisible; // makes the lines visible
private bool _lineXEnabled;
private bool _lineYEnabled;
private bool _crossEnabled;
private bool _snapHelpLineX; // true during helpline x move
private bool _snapHelpLineY; // true during helpline y move
private bool _snapToGrid; // snaps help line to grid
private bool _snapelements; // snaps elements to the help line
private int _snapgrid; // snaps helpline to grid measure
private int snapZone = 12;
private bool snapOnResize = true;
private IHtmlEditor _host;
private System.Windows.Forms.Cursor _oldCursor;
private Pen _style;
private Interop.IHTMLElement2 body2;
private HelpLine extender;
/// <summary>
/// This constructor builds a new helpline object with given coordinates.
/// </summary>
/// <param name="host">The related control</param>
/// <param name="helpLine">Properties</param>
/// <param name="extender">Reference to editor component.</param>
internal HelpLineBehavior(IHtmlEditor host, HelpLineProperties helpLine, HelpLine extender) : base(host)
{
_host = host;
_host.ReadyStateComplete += new EventHandler(_host_ReadyStateComplete);
// store the instances to help the behavior to work on multiple extenders
instance = instanceCounter++;
this.extender = extender;
_snapToGrid = helpLine.SnapToGrid;
_snapgrid = helpLine.SnapGrid;
// assure a valid value, avoid Div by zero
if (_snapToGrid && _snapgrid == 0) _snapgrid = 16;
snapZone = helpLine.SnapZone;
base.HtmlPaintFlag = HtmlPainter.Transparent;
base.HtmlZOrderFlag = HtmlZOrder.AboveContent;
_style = new Pen(helpLine.LineColor, (float)helpLine.LineWidth);
_lineVisible = helpLine.LineVisible;
_snapelements = helpLine.SnapElements;
_lineXEnabled = helpLine.LineXEnabled;
_lineYEnabled = helpLine.LineYEnabled;
_crossEnabled = helpLine.CrossEnabled;
this.x = helpLine.X;
this.y = helpLine.Y;
}
void _host_ReadyStateComplete(object sender, EventArgs e)
{
if (_host.DesignModeEnabled)
{
body2 = ((Interop.IHTMLElement2)_host.GetBodyElement().GetBaseElement());
}
}
/// <summary>
/// The name of the behavior. This value is used to distinguesh between behaviors and to remove
/// a behavior later without touching other ones.
/// </summary>
public override string Name
{
get
{
return "HelpLine#" + instance.ToString();
}
}
/// <summary>
/// Pen used to draw both lines.
/// </summary>
public Pen PenStyle
{
get { return _style; }
set { _style = value; }
}
/// <summary>
/// Gets or sets the snap zone in which the helpline is magnetic. Defaults to 12 pixel.
/// </summary>
public int SnapZone
{
get
{
return snapZone;
}
set
{
snapZone = value;
}
}
/// <summary>
/// Gets or sets the snap on resize feature. If on the helpline will be magnetic during element resizing.
/// </summary>
public bool SnapOnResize
{
get
{
return snapOnResize;
}
set
{
snapOnResize = value;
}
}
/// <summary>
/// Enables the X line. Default is On.
/// </summary>
public bool LineXEnabled
{
set
{
_lineXEnabled = value;
}
}
/// <summary>
/// Enables the Y line. Default is On.
/// </summary>
public bool LineYEnabled
{
set
{
_lineYEnabled = value;
}
}
/// <summary>
/// Enables the cross sign. Default is On.
/// </summary>
public bool CrossEnabled
{
set
{
_crossEnabled = value;
}
}
/// <summary>
/// The draw method used to draw to helpline.
/// </summary>
/// <remarks>
/// This method supports the NetRix infrastructure and cannot be called from user code.
/// </remarks>
/// <param name="leftBounds"></param>
/// <param name="topBounds"></param>
/// <param name="rightBounds"></param>
/// <param name="bottomBounds"></param>
/// <param name="gr">The graphics object the line is drawn into.</param>
protected override void Draw(int leftBounds, int topBounds, int rightBounds, int bottomBounds, Graphics gr)
{
if (!_lineVisible) return;
//if (!_lineVisible)
//{
// try
// {
// base.Invalidate();
// }
// catch
// {
// }
// return;
//}
gr.PageUnit = GraphicsUnit.Pixel;
if (_lineXEnabled)
{
gr.DrawLine(_style, leftBounds + this.X, topBounds, leftBounds + this.X, bottomBounds);
}
if (_lineYEnabled)
{
gr.DrawLine(_style, leftBounds, topBounds + this.Y, rightBounds, topBounds + this.Y);
}
if (_crossEnabled)
{
gr.FillRectangle(new SolidBrush(Color.White), leftBounds + this.X - 2, topBounds + this.Y - 2, 5, 5);
gr.DrawRectangle(_style, leftBounds + this.X - 3, topBounds + this.Y - 3, 6, 6);
}
}
# region Public Properties
/// <summary>
/// Sets the style used to draw the helpline and the border of the cross.
/// </summary>
public Pen LineStyle
{
set
{
_style = value;
}
get
{
return _style;
}
}
/// <summary>
/// Make the helpline temporarily invisble.
/// </summary>
public bool LineVisible
{
set
{
_lineVisible = value;
}
}
/// <summary>
/// Sets an existing helpline to specific point.
/// </summary>
/// <param name="origin"></param>
public void SetXY(Point origin)
{
X = origin.X;
Y = origin.Y;
}
/// <summary>
/// Gets or sets the current X coordinate.
/// </summary>
/// <remarks>
/// Setting the point outside the area make the helpline invisible. The user cannot
/// move the helpline anymore. The host application should provide a technique to
/// replace the helpline to a visible point.
/// </remarks>
public int X
{
get
{
return x;
}
set
{
x = value;
base.Invalidate();
}
}
/// <summary>
/// Gets or sets the current Y coordinate.
/// </summary>
/// <remarks>
/// Setting the point outside the area make the helpline invisible. The user cannot
/// move the helpline anymore. The host application should provide a technique to
/// replace the helpline to a visible point.
/// </remarks>
public int Y
{
get
{
return y;
}
set
{
y = value;
base.Invalidate();
}
}
internal void SetY(int y)
{
this.y = y;
}
internal void SetX(int x)
{
this.x = x;
}
/// <summary>
/// Gets or sets the snap function.
/// </summary>
/// <remarks>
/// If the Helpline snap feature is turned on the helpline jumps
/// from point to point within a grid. The grid is defined with the
/// <see cref="SnapGrid">SnapGrid</see> property.
/// </remarks>
public bool SnapEnabled
{
get
{
return _snapToGrid;
}
set
{
_snapToGrid = value;
}
}
/// <summary>
/// Let elements snap to the current helpline during move or resize.
/// </summary>
public bool SnapElements
{
get
{
return _snapelements;
}
set
{
_snapelements = value;
}
}
/// <summary>
/// Gets or sets the distance in pixels between a virtual grid.
/// </summary>
/// <remarks>
/// The grid is used to snap the helpline to fixed points. It should match
/// the visible grid, but can be set independently if required.
/// </remarks>
public int SnapGrid
{
get
{
return _snapgrid;
}
set
{
_snapgrid = value;
}
}
# endregion
private bool IsInCross(int x, int y)
{
if (x > this.X - 4
&&
x < this.X + 4
&&
y > this.Y - 4
&&
y < this.Y + 4)
return true;
else
return false;
}
private void ResetCurrentHelpPointer()
{
System.Windows.Forms.Cursor.Current = this._oldCursor;
this._host.SetMousePointer(false);
this._snapHelpLineX = _snapHelpLineY = false;
this._oldCursor = null;
extender.OnHelpLineMoved(this._host, new Point(this.x, this.y));
}
private void SnapToGrid()
{
if (!_snapToGrid)
{
return;
}
else
{
if (_snapHelpLineX)
x = Convert.ToInt32(Math.Ceiling((double)x / _snapgrid)) * _snapgrid - (_snapgrid / 2);
if (_snapHelpLineY)
y = Convert.ToInt32(Math.Ceiling((double)y / _snapgrid)) * _snapgrid - (_snapgrid / 2);
}
}
/// <summary>
/// Checks id a value is between to boundaries (including the boundary value).
/// </summary>
/// <param name="check">Value to check</param>
/// <param name="min">Lower boundary</param>
/// <param name="max">Upper boundary</param>
/// <returns></returns>
private bool IsBetween(int check, int min, int max)
{
if (check <= max && check >= min)
return true;
else
return false;
}
#region IHTMLEditDesigner Member
int Interop.IHTMLEditDesigner.PreHandleEvent(int dispId, GuruComponents.Netrix.ComInterop.Interop.IHTMLEventObj eventObj)
{
int result = Interop.S_FALSE;
// Not ready end immediately
if (!this._host.IsReady || eventObj.srcElement == null) return result;
// If not active drop any handling completely
if (!this.extender.GetHelpLine(_host).Active) return result;
//
if (body2 == null) return result;
int RealX = eventObj.clientX + body2.GetScrollLeft();
int RealY = eventObj.clientY + body2.GetScrollTop();
switch (dispId)
{
case DispId.MOUSEUP:
// release moving and restore cursor
if (this._snapHelpLineX || _snapHelpLineY)
{
ResetCurrentHelpPointer();
result = Interop.S_OK;
}
break;
case DispId.MOUSEMOVE:
// move helpline with left button down
// 1 == left click, 2 == right click
if (this._lineVisible && (this._snapHelpLineX || _snapHelpLineY) && eventObj.button == 1)
{
// check for overlaying scrollbar areas
// body has vertical scrollbar; this reduces the active width
if (body2.GetClientWidth() > 0 && eventObj.clientX > body2.GetClientWidth() || eventObj.clientX <= 0)
{
ResetCurrentHelpPointer();
}
// body has horizontal scrollbar; this reduces the active height
if (body2.GetClientHeight() > 0 && eventObj.clientY > body2.GetClientHeight() || eventObj.clientY <= 0)
{
ResetCurrentHelpPointer();
}
bool fixX = false, fixY = false;
if (eventObj.ctrlKey)
{
// control key fixes the movement to only one direction, to determine the
// direction check the last move and fix this one
if ((this.x - RealX) < (this.y - RealY))
{
fixY = true;
}
else
{
fixX = true;
}
}
if (!fixX && _snapHelpLineX)
this.x = RealX;
if (!fixY && _snapHelpLineY)
this.y = RealY;
// Snap to grid if enabled and no ALT key pressed
if (!eventObj.altKey)
{
SnapToGrid();
}
// refresh mouse pointer
if (_snapHelpLineX && _snapHelpLineY)
{
this._host.SetMousePointer(true);
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Hand;
}
else
{
if (_snapHelpLineX)
{
this._host.SetMousePointer(true);
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.SizeWE;
}
if (_snapHelpLineY)
{
this._host.SetMousePointer(true);
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.SizeNS;
}
}
// fire event to inform host app that new coordinates reached
extender.OnHelpLineMoving(this._host, new Point(this.x, this.y));
base.Invalidate();
result = Interop.S_OK;
}
if (this._lineVisible && !this._snapHelpLineX && !_snapHelpLineY && eventObj.button == 0)
{
// check for mouse over cross to inform user that snap is possible
if (IsInCross(RealX, RealY))
{
_oldCursor = System.Windows.Forms.Cursor.Current;
this._host.SetMousePointer(true);
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Hand;
result = Interop.S_OK;
break;
}
// check for mouse over line to inform user that snap is possible
if (IsBetween(RealX, x-CATCHZONE, x+CATCHZONE))
{
_oldCursor = System.Windows.Forms.Cursor.Current;
this._host.SetMousePointer(true);
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.SizeWE;
result = Interop.S_OK;
break;
}
if (IsBetween(RealY, y-CATCHZONE, y+CATCHZONE))
{
_oldCursor = System.Windows.Forms.Cursor.Current;
this._host.SetMousePointer(true);
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.SizeNS;
result = Interop.S_OK;
break;
}
if (this._oldCursor != null)
{
System.Windows.Forms.Cursor.Current = this._oldCursor;
this._host.SetMousePointer(false);
this._oldCursor = null;
result = Interop.S_FALSE;
}
}
break;
case DispId.MOUSEDOWN:
// mouse goes down, check if it is on helpline cross, then start moving
if (IsInCross(RealX, RealY) && !this._snapHelpLineX && !_snapHelpLineY && eventObj.button == 1)
{
this._snapHelpLineX = _snapHelpLineY = true;
result = Interop.S_OK;
break;
}
if (IsBetween(RealX, x-CATCHZONE, x+CATCHZONE))
{
this._snapHelpLineX = true;
result = Interop.S_OK;
break;
}
if (IsBetween(RealY, y-CATCHZONE, y+CATCHZONE))
{
this._snapHelpLineY = true;
result = Interop.S_OK;
break;
}
break;
}
return result;
}
int Interop.IHTMLEditDesigner.PostHandleEvent(int dispId, GuruComponents.Netrix.ComInterop.Interop.IHTMLEventObj eventObj)
{
return Interop.S_FALSE;
}
int Interop.IHTMLEditDesigner.TranslateAccelerator(int dispId, GuruComponents.Netrix.ComInterop.Interop.IHTMLEventObj eventObj)
{
return Interop.S_FALSE;
}
int Interop.IHTMLEditDesigner.PostEditorEventNotify(int dispId, GuruComponents.Netrix.ComInterop.Interop.IHTMLEventObj eventObj)
{
return Interop.S_FALSE;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayer
{
public class UniverseSyncCache
{
public string cacheDirectory
{
get
{
return Path.Combine(Path.Combine(Client.dmpClient.gameDataDir, "DarkMultiPlayer"), "Cache");
}
}
private AutoResetEvent incomingEvent = new AutoResetEvent(false);
private Queue<ByteArray> incomingQueue = new Queue<ByteArray>();
private Dictionary<string, long> fileLengths = new Dictionary<string, long>();
private Dictionary<string, DateTime> fileCreationTimes = new Dictionary<string, DateTime>();
//Services
private Settings dmpSettings;
public long currentCacheSize
{
get;
private set;
}
public UniverseSyncCache(Settings dmpSettings)
{
this.dmpSettings = dmpSettings;
Thread processingThread = new Thread(new ThreadStart(ProcessingThreadMain));
processingThread.IsBackground = true;
processingThread.Start();
}
private void ProcessingThreadMain()
{
while (true)
{
if (incomingQueue.Count == 0)
{
incomingEvent.WaitOne(500);
}
else
{
ByteArray incomingBytes;
lock (incomingQueue)
{
incomingBytes = incomingQueue.Dequeue();
}
SaveToCache(incomingBytes);
ByteRecycler.ReleaseObject(incomingBytes);
}
}
}
private string[] GetCachedFiles()
{
return Directory.GetFiles(cacheDirectory);
}
public string[] GetCachedObjects()
{
string[] cacheFiles = GetCachedFiles();
string[] cacheObjects = new string[cacheFiles.Length];
for (int i = 0; i < cacheFiles.Length; i++)
{
cacheObjects[i] = Path.GetFileNameWithoutExtension(cacheFiles[i]);
}
return cacheObjects;
}
public void ExpireCache()
{
DarkLog.Debug("Expiring cache!");
//No folder, no delete.
if (!Directory.Exists(Path.Combine(cacheDirectory, "Incoming")))
{
DarkLog.Debug("No sync cache folder, skipping expire.");
return;
}
//Delete partial incoming files
string[] incomingFiles = Directory.GetFiles(Path.Combine(cacheDirectory, "Incoming"));
foreach (string incomingFile in incomingFiles)
{
DarkLog.Debug("Deleting partially cached object " + incomingFile);
File.Delete(incomingFile);
}
//Delete old files
string[] cacheObjects = GetCachedObjects();
currentCacheSize = 0;
foreach (string cacheObject in cacheObjects)
{
if (!string.IsNullOrEmpty(cacheObject))
{
string cacheFile = Path.Combine(cacheDirectory, cacheObject + ".txt");
//If the file is older than a week, delete it.
if (File.GetCreationTime(cacheFile).AddDays(7d) < DateTime.Now)
{
DarkLog.Debug("Deleting cached object " + cacheObject + ", reason: Expired!");
File.Delete(cacheFile);
}
else
{
FileInfo fi = new FileInfo(cacheFile);
fileCreationTimes[cacheObject] = fi.CreationTime;
fileLengths[cacheObject] = fi.Length;
currentCacheSize += fi.Length;
}
}
}
//While the directory is over (cacheSize) MB
while (currentCacheSize > (dmpSettings.cacheSize * 1024 * 1024))
{
string deleteObject = null;
//Find oldest file
foreach (KeyValuePair<string, DateTime> testFile in fileCreationTimes)
{
if (deleteObject == null)
{
deleteObject = testFile.Key;
}
if (testFile.Value < fileCreationTimes[deleteObject])
{
deleteObject = testFile.Key;
}
}
if (deleteObject == null)
{
return;
}
DarkLog.Debug("Deleting cached object " + deleteObject + ", reason: Cache full!");
string deleteFile = Path.Combine(cacheDirectory, deleteObject + ".txt");
File.Delete(deleteFile);
currentCacheSize -= fileLengths[deleteObject];
if (fileCreationTimes.ContainsKey(deleteObject))
{
fileCreationTimes.Remove(deleteObject);
}
if (fileLengths.ContainsKey(deleteObject))
{
fileLengths.Remove(deleteObject);
}
}
}
/// <summary>
/// Queues to cache. This method is non-blocking, using SaveToCache for a blocking method.
/// </summary>
/// <param name="fileData">File data.</param>
public void QueueToCache(ByteArray fileData)
{
lock (incomingQueue)
{
ByteArray incomingBytes = ByteRecycler.GetObject(fileData.Length);
Array.Copy(fileData.data, 0, incomingBytes.data, 0, fileData.Length);
incomingQueue.Enqueue(incomingBytes);
}
incomingEvent.Set();
}
/// <summary>
/// Saves to cache. This method is blocking, use QueueToCache for a non-blocking method.
/// </summary>
/// <param name="fileData">File data.</param>
public void SaveToCache(ByteArray fileData)
{
if (fileData == null || fileData.Length == 0)
{
//Don't save 0 byte data.
return;
}
string objectName = Common.CalculateSHA256Hash(fileData);
string objectFile = Path.Combine(cacheDirectory, objectName + ".txt");
string incomingFile = Path.Combine(Path.Combine(cacheDirectory, "Incoming"), objectName + ".txt");
if (!File.Exists(objectFile))
{
using (FileStream fs = new FileStream(incomingFile, FileMode.OpenOrCreate))
{
fs.Write(fileData.data, 0, fileData.Length);
}
File.Move(incomingFile, objectFile);
currentCacheSize += fileData.Length;
fileLengths[objectName] = fileData.Length;
fileCreationTimes[objectName] = new FileInfo(objectFile).CreationTime;
}
else
{
File.SetCreationTime(objectFile, DateTime.Now);
fileCreationTimes[objectName] = new FileInfo(objectFile).CreationTime;
}
}
public byte[] GetFromCache(string objectName)
{
string objectFile = Path.Combine(cacheDirectory, objectName + ".txt");
if (File.Exists(objectFile))
{
return File.ReadAllBytes(objectFile);
}
else
{
throw new IOException("Cached object " + objectName + " does not exist");
}
}
public void DeleteCache()
{
DarkLog.Debug("Deleting cache!");
foreach (string cacheFile in GetCachedFiles())
{
File.Delete(cacheFile);
}
fileLengths = new Dictionary<string, long>();
fileCreationTimes = new Dictionary<string, DateTime>();
currentCacheSize = 0;
}
}
}
| |
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NodaTime.TimeZones;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NodaTime.TimeZones.IO;
using NodaTime.TimeZones.Cldr;
namespace NodaTime.TzdbCompiler.Tzdb
{
/// <summary>
/// Writes time zone data to a stream in nzd format.
/// </summary>
/// <remarks>
/// <para>The file format consists of four bytes indicating the file format version/type (mostly for
/// future expansion), followed by a number of fields. Each field is identified by a <see cref="TzdbStreamFieldId"/>.
/// The fields are always written in order, and the format of a field consists of its field ID, a 7-bit-encoded
/// integer with the size of the data, and then the data itself.
/// </para>
/// <para>
/// The version number does not need to be increased if new fields are added, as the reader will simply ignore
/// unknown fields. It only needs to be increased for incompatible changes such as a different time zone format,
/// or if old fields are removed.
/// </para>
/// </remarks>
internal sealed class TzdbStreamWriter
{
private const int Version = 0;
private readonly Stream stream;
internal TzdbStreamWriter(Stream stream)
{
this.stream = stream;
}
public void Write(TzdbDatabase database, WindowsZones cldrWindowsZones)
{
FieldCollection fields = new FieldCollection();
var zones = database.GenerateDateTimeZones().ToList();
var stringPool = CreateOptimizedStringPool(zones, database.ZoneLocations, database.Zone1970Locations, cldrWindowsZones);
// First assemble the fields (writing to the string pool as we go)
foreach (var zone in zones)
{
var zoneField = fields.AddField(TzdbStreamFieldId.TimeZone, stringPool);
WriteZone(zone, zoneField.Writer);
}
fields.AddField(TzdbStreamFieldId.TzdbVersion, null).Writer.WriteString(database.Version);
// Normalize the aliases
var timeZoneMap = new Dictionary<string, string>();
foreach (var key in database.Aliases.Keys)
{
var value = database.Aliases[key];
while (database.Aliases.ContainsKey(value))
{
value = database.Aliases[value];
}
timeZoneMap.Add(key, value);
}
fields.AddField(TzdbStreamFieldId.TzdbIdMap, stringPool).Writer.WriteDictionary(timeZoneMap);
// Windows mappings
cldrWindowsZones.Write(fields.AddField(TzdbStreamFieldId.CldrSupplementalWindowsZones, stringPool).Writer);
fields.AddField(TzdbStreamFieldId.WindowsAdditionalStandardNameToIdMapping, stringPool).Writer.WriteDictionary
(PclSupport.StandardNameToIdMap.ToDictionary(pair => pair.Key, pair => cldrWindowsZones.PrimaryMapping[pair.Value]));
// Zone locations, if any.
var zoneLocations = database.ZoneLocations;
if (zoneLocations != null)
{
var field = fields.AddField(TzdbStreamFieldId.ZoneLocations, stringPool);
field.Writer.WriteCount(zoneLocations.Count);
foreach (var zoneLocation in zoneLocations)
{
zoneLocation.Write(field.Writer);
}
}
// Zone 1970 locations, if any.
var zone1970Locations = database.Zone1970Locations;
if (zone1970Locations != null)
{
var field = fields.AddField(TzdbStreamFieldId.Zone1970Locations, stringPool);
field.Writer.WriteCount(zone1970Locations.Count);
foreach (var zoneLocation in zone1970Locations)
{
zoneLocation.Write(field.Writer);
}
}
var stringPoolField = fields.AddField(TzdbStreamFieldId.StringPool, null);
stringPoolField.Writer.WriteCount(stringPool.Count);
foreach (string value in stringPool)
{
stringPoolField.Writer.WriteString(value);
}
// Now write all the fields out, in the right order.
new BinaryWriter(stream).Write(Version);
fields.WriteTo(stream);
stream.Close();
}
private static void WriteZone(DateTimeZone zone, IDateTimeZoneWriter writer)
{
writer.WriteString(zone.Id);
// For cached zones, simply uncache first.
var cachedZone = zone as CachedDateTimeZone;
if (cachedZone != null)
{
zone = cachedZone.TimeZone;
}
var fixedZone = zone as FixedDateTimeZone;
if (fixedZone != null)
{
writer.WriteByte((byte) DateTimeZoneWriter.DateTimeZoneType.Fixed);
fixedZone.Write(writer);
}
else
{
var precalculatedZone = zone as PrecalculatedDateTimeZone;
if (precalculatedZone != null)
{
writer.WriteByte((byte) DateTimeZoneWriter.DateTimeZoneType.Precalculated);
precalculatedZone.Write(writer);
}
else
{
throw new ArgumentException("Unserializable DateTimeZone type " + zone.GetType());
}
}
}
/// <summary>
/// Creates a string pool which contains the most commonly-used strings within the given set
/// of zones first. This will allow them to be more efficiently represented when we write them out for real.
/// </summary>
private static List<string> CreateOptimizedStringPool(
IEnumerable<DateTimeZone> zones,
IEnumerable<TzdbZoneLocation> zoneLocations,
IEnumerable<TzdbZone1970Location> zone1970Locations,
WindowsZones cldrWindowsZones)
{
var optimizingWriter = new StringPoolOptimizingFakeWriter();
foreach (var zone in zones)
{
optimizingWriter.WriteString(zone.Id);
WriteZone(zone, optimizingWriter);
}
if (zoneLocations != null)
{
foreach (var location in zoneLocations)
{
location.Write(optimizingWriter);
}
}
if (zone1970Locations != null)
{
foreach (var location in zone1970Locations)
{
location.Write(optimizingWriter);
}
}
cldrWindowsZones.Write(optimizingWriter);
return optimizingWriter.CreatePool();
}
/// <summary>
/// Writer which only cares about strings. It builds a complete list of all strings written for the given
/// zones, then creates a distinct list in most-prevalent-first order. This allows the most frequently-written
/// strings to be the ones which are cheapest to write.
/// </summary>
private class StringPoolOptimizingFakeWriter : IDateTimeZoneWriter
{
private readonly List<string> allStrings = new List<string>();
public List<string> CreatePool()
{
return allStrings.GroupBy(x => x)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.ToList();
}
public void WriteString(string value)
{
allStrings.Add(value);
}
public void WriteMilliseconds(int millis) { }
public void WriteOffset(Offset offset) {}
public void WriteCount(int count) { }
public void WriteByte(byte value) { }
public void WriteSignedCount(int count) { }
public void WriteZoneIntervalTransition(Instant? previous, Instant value) {}
public void WriteDictionary(IDictionary<string, string> dictionary)
{
foreach (var entry in dictionary)
{
WriteString(entry.Key);
WriteString(entry.Value);
}
}
}
/// <summary>
/// The data for a field, including the field number itself.
/// </summary>
private class FieldData
{
private readonly MemoryStream stream;
internal FieldData(TzdbStreamFieldId fieldId, IList<string> stringPool)
{
this.FieldId = fieldId;
this.stream = new MemoryStream();
this.Writer = new DateTimeZoneWriter(stream, stringPool);
}
internal IDateTimeZoneWriter Writer { get; }
internal TzdbStreamFieldId FieldId { get; }
internal void WriteTo(Stream output)
{
output.WriteByte((byte)FieldId);
int length = (int) stream.Length;
// We've got a 7-bit-encoding routine... might as well use it.
new DateTimeZoneWriter(output, null).WriteCount(length);
stream.WriteTo(output);
}
}
private class FieldCollection
{
private readonly List<FieldData> fields = new List<FieldData>();
internal FieldData AddField(TzdbStreamFieldId fieldNumber, IList<string> stringPool)
{
FieldData ret = new FieldData(fieldNumber, stringPool);
fields.Add(ret);
return ret;
}
internal void WriteTo(Stream stream)
{
foreach (var field in fields.OrderBy(field => field.FieldId))
{
field.WriteTo(stream);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Gui;
using FlatRedBall.Input;
using FlatRedBall.Math;
using FlatRedBall.Math.Geometry;
using PolygonEditor.Gui;
using EditorObjects;
using FlatRedBall.IO;
using FlatRedBall.Graphics;
using FlatRedBall.Content;
using EditorObjects.EditorSettings;
namespace PolygonEditor
{
public static class EditorData
{
#region Fields
public const string ContentManagerName = "PolygonEditor Content Manager";
static ShapeCollection mShapeCollection = new ShapeCollection();
static LineGrid mLineGrid = new LineGrid();
static Scene mScene;
static EditingLogic mEditingLogic;
public static EditorProperties EditorProperties = new EditorProperties();
#if FRB_XNA
static FormMethods mFormMethods = new FormMethods();
#endif
static Camera mSceneCamera;
static Text mDebugText;
#endregion
#region Properties
public static PositionedObjectList<AxisAlignedCube> AxisAlignedCubes
{
get { return ShapeCollection.AxisAlignedCubes; }
}
public static PositionedObjectList<Capsule2D> Capsule2Ds
{
get { return ShapeCollection.Capsule2Ds; }
}
public static PositionedObjectList<AxisAlignedRectangle> AxisAlignedRectangles
{
get { return ShapeCollection.AxisAlignedRectangles;}
}
public static PositionedObjectList<Circle> Circles
{
get {return ShapeCollection.Circles;}
}
public static PositionedObjectList<Sphere> Spheres
{
get { return ShapeCollection.Spheres;}
}
public static PositionedObjectList<Polygon> Polygons
{
get { return ShapeCollection.Polygons; }
}
public static LineGrid LineGrid
{
get { return mLineGrid; }
}
public static string LastLoadedShapeCollection
{
get;
set;
}
public static string LastLoadedPolygonList
{
get;
set;
}
public static EditingLogic EditingLogic
{
get { return mEditingLogic; }
}
public static Scene Scene
{
get { return mScene; }
set
{
mScene = value;
mScene.AddToManagers();
}
}
public static ShapeCollection ShapeCollection
{
get { return mShapeCollection; }
//set { mShapeCollection = value; }
}
public static Camera BoundsCamera
{
get { return mSceneCamera; }
}
#endregion
#region Methods
#region Initialize
public static void Initialize(ShapeCollection shapeCollectionEditing)
{
//ColorDisplay colorDisplay = new ColorDisplay(GuiManager.Cursor);
//GuiManager.AddWindow(colorDisplay);
ShapeManager.ShapeDrawingOrder = ShapeDrawingOrder.OverEverything;
ShapeManager.UseZTestingWhenDrawing = false;
//Increase the number of particles available
SpriteManager.AutoIncrementParticleCountValue = 500;
SpriteManager.MaxParticleCount = 5000;
if (shapeCollectionEditing == null)
{
mShapeCollection = new ShapeCollection();
}
mSceneCamera = new Camera(FlatRedBallServices.GlobalContentManager);
mEditingLogic = new EditingLogic();
mDebugText = TextManager.AddText("Hello");
mDebugText.Visible = false;
}
#endregion
#region Public Methods
public static void LoadPolygonList(string fileName)
{
FlatRedBall.Content.Polygon.PolygonSaveList psl = FlatRedBall.Content.Polygon.PolygonSaveList.FromFile(fileName);
PositionedObjectList<Polygon> polygonList = psl.ToPolygonList();
// At a later time may want to support Insert and Replace. For now, do Replace
while (Polygons.Count != 0)
{
ShapeManager.Remove(Polygons[0]);
}
foreach (Polygon polygon in polygonList)
{
ShapeManager.AddPolygon(polygon);
ShapeCollection.Polygons.Add(polygon);
polygon.Color = EditorProperties.PolygonColor;
}
#if FRB_MDX
GameForm.TitleText = "PolygonEditor - Editing " + fileName;
#else
FlatRedBallServices.Game.Window.Title = "PolygonEditor Editing - " + fileName;
#endif
LastLoadedShapeCollection = null;
LastLoadedPolygonList = fileName;
#region Load the SavedInformation if available
fileName = FileManager.RemoveExtension(fileName) + ".pesix";
if (System.IO.File.Exists(fileName))
{
try
{
PolygonEditorSettings savedInformation = PolygonEditorSettings.FromFile(fileName);
if (savedInformation.LineGridSave != null)
{
savedInformation.LineGridSave.ToLineGrid(EditorData.LineGrid);
}
if (savedInformation.UsePixelCoordinates)
{
SpriteManager.Camera.UsePixelCoordinates(false);
}
}
catch
{
GuiManager.ShowMessageBox(
"Could not load the settings file " + fileName + ". \nThe data file was loaded with no problems",
"Error");
}
}
#endregion
}
public static void LoadScene(string fileName)
{
if (mScene != null)
{
FlatRedBallServices.Unload(ContentManagerName);
mScene.RemoveFromManagers();
}
FlatRedBall.Content.SpriteEditorScene ses = FlatRedBall.Content.SpriteEditorScene.FromFile(fileName);
EditorData.Scene = ses.ToScene(EditorData.ContentManagerName);
}
public static void DeleteForNew()
{
#region Delete the referenced Polygons
while (Polygons.Count != 0)
{
ShapeManager.Remove(Polygons[0]);
}
#endregion
#region Delete the referenced AxisAlignedRectangles
while (AxisAlignedRectangles.Count != 0)
{
ShapeManager.Remove(AxisAlignedRectangles[0]);
}
#endregion
#region Delete the referenced AxisAlignedCubes
while (AxisAlignedCubes.Count != 0)
{
ShapeManager.Remove(AxisAlignedCubes[0]);
}
#endregion
#region Delete the referenced Circles
while (Circles.Count != 0)
{
ShapeManager.Remove(Circles[Circles.Count - 1]);
}
#endregion
#region Delete the referenced Spheres
while (Spheres.Count != 0)
{
ShapeManager.Remove(Spheres[Spheres.Count - 1]);
}
#endregion
#region Hide the Property Grids
EditingLogic.DeselectAll();
#endregion
UnloadScene();
LastLoadedPolygonList = null;
LastLoadedShapeCollection = null;
#if FRB_MDX
GameForm.TitleText = "PolygonEditor - untitled file";
#else
FlatRedBallServices.Game.Window.Title = "PolygonEditor Editing - untitled file";
#endif
}
public static void SaveScene(string fileName)
{
if (mScene == null)
{
GuiManager.ShowMessageBox("There's no scene to save.", "Error Saving");
}
else
{
SpriteEditorScene spriteEditorScene = SpriteEditorScene.FromScene(mScene);
spriteEditorScene.Save(fileName);
}
}
public static void UnloadScene()
{
#region Delete the Scene
if (Scene != null)
{
Scene.RemoveFromManagers();
}
SpriteManager.Camera.X = 0f;
SpriteManager.Camera.Y = 0f;
SpriteManager.Camera.Z = -40f;
#endregion
#region Remove ContentManager
FlatRedBallServices.Unload(EditorData.ContentManagerName);
#endregion
}
public static void Update()
{
mEditingLogic.Update();
PerformMouseCameraControl();
UpdateUI();
mDebugText.DisplayText = UndoManager.ToString();
}
#endregion
#region Private Methods
private static void PerformMouseCameraControl()
{
EditorObjects.CameraMethods.MouseCameraControl(SpriteManager.Camera);
}
private static void UpdateUI()
{
GuiData.Update();
}
#endregion
#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.IO;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.Text;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Security
{
//
// The class maintains the state of the authentication process and the security context.
// It encapsulates security context and does the real work in authentication and
// user data encryption with NEGO SSPI package.
//
internal static partial class NegotiateStreamPal
{
// value should match the Windows sspicli NTE_FAIL value
// defined in winerror.h
private const int NTE_FAIL = unchecked((int)0x80090020);
internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext)
{
throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
}
internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext)
{
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
return negoContext.IsNtlmUsed ? NegotiationInfoClass.NTLM : NegotiationInfoClass.Kerberos;
}
private static byte[] GssWrap(
SafeGssContextHandle context,
bool encrypt,
byte[] buffer,
int offset,
int count)
{
Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Encrypt");
Debug.Assert((offset >= 0) && (offset < buffer.Length), "Invalid input offset passed to Encrypt");
Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Encrypt");
Interop.NetSecurityNative.GssBuffer encryptedBuffer = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.WrapBuffer(out minorStatus, context, encrypt, buffer, offset, count, ref encryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return encryptedBuffer.ToByteArray();
}
finally
{
encryptedBuffer.Dispose();
}
}
private static int GssUnwrap(
SafeGssContextHandle context,
byte[] buffer,
int offset,
int count)
{
Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Decrypt");
Debug.Assert((offset >= 0) && (offset <= buffer.Length), "Invalid input offset passed to Decrypt");
Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Decrypt");
Interop.NetSecurityNative.GssBuffer decryptedBuffer = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.UnwrapBuffer(out minorStatus, context, buffer, offset, count, ref decryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return decryptedBuffer.Copy(buffer, offset);
}
finally
{
decryptedBuffer.Dispose();
}
}
private static bool GssInitSecurityContext(
ref SafeGssContextHandle context,
SafeGssCredHandle credential,
bool isNtlm,
ChannelBinding channelBinding,
SafeGssNameHandle targetName,
Interop.NetSecurityNative.GssFlags inFlags,
byte[] buffer,
out byte[] outputBuffer,
out uint outFlags,
out bool isNtlmUsed)
{
outputBuffer = null;
outFlags = 0;
// EstablishSecurityContext is called multiple times in a session.
// In each call, we need to pass the context handle from the previous call.
// For the first call, the context handle will be null.
bool newContext = false;
if (context == null)
{
newContext = true;
context = new SafeGssContextHandle();
}
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
Interop.NetSecurityNative.Status status;
try
{
Interop.NetSecurityNative.Status minorStatus;
if (channelBinding != null)
{
// If a TLS channel binding token (cbt) is available then get the pointer
// to the application specific data.
int appDataOffset = Marshal.SizeOf<SecChannelBindings>();
Debug.Assert(appDataOffset < channelBinding.Size);
IntPtr cbtAppData = channelBinding.DangerousGetHandle() + appDataOffset;
int cbtAppDataSize = channelBinding.Size - appDataOffset;
status = Interop.NetSecurityNative.InitSecContext(out minorStatus,
credential,
ref context,
isNtlm,
cbtAppData,
cbtAppDataSize,
targetName,
(uint)inFlags,
buffer,
(buffer == null) ? 0 : buffer.Length,
ref token,
out outFlags,
out isNtlmUsed);
}
else
{
status = Interop.NetSecurityNative.InitSecContext(out minorStatus,
credential,
ref context,
isNtlm,
targetName,
(uint)inFlags,
buffer,
(buffer == null) ? 0 : buffer.Length,
ref token,
out outFlags,
out isNtlmUsed);
}
if ((status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) &&
(status != Interop.NetSecurityNative.Status.GSS_S_CONTINUE_NEEDED))
{
if (newContext)
{
context.Dispose();
context = null;
}
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
outputBuffer = token.ToByteArray();
}
finally
{
token.Dispose();
}
return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE;
}
private static bool GssAcceptSecurityContext(
ref SafeGssContextHandle context,
byte[] buffer,
out byte[] outputBuffer,
out uint outFlags)
{
bool newContext = false;
if (context == null)
{
newContext = true;
context = new SafeGssContextHandle();
}
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
Interop.NetSecurityNative.Status status;
try
{
Interop.NetSecurityNative.Status minorStatus;
status = Interop.NetSecurityNative.AcceptSecContext(out minorStatus,
ref context,
buffer,
buffer?.Length ?? 0,
ref token,
out outFlags);
if ((status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) &&
(status != Interop.NetSecurityNative.Status.GSS_S_CONTINUE_NEEDED))
{
if (newContext)
{
context.Dispose();
context = null;
}
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
outputBuffer = token.ToByteArray();
}
finally
{
token.Dispose();
}
return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE;
}
private static string GssGetUser(
ref SafeGssContextHandle context)
{
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status status
= Interop.NetSecurityNative.GetUser(out var minorStatus,
context,
ref token);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return Encoding.UTF8.GetString(token.ToByteArray());
}
finally
{
token.Dispose();
}
}
private static SecurityStatusPal EstablishSecurityContext(
SafeFreeNegoCredentials credential,
ref SafeDeleteContext context,
ChannelBinding channelBinding,
string targetName,
ContextFlagsPal inFlags,
byte[] incomingBlob,
ref byte[] resultBuffer,
ref ContextFlagsPal outFlags)
{
bool isNtlmOnly = credential.IsNtlmOnly;
if (context == null)
{
if (NetEventSource.IsEnabled)
{
string protocol = isNtlmOnly ? "NTLM" : "SPNEGO";
NetEventSource.Info(null, $"requested protocol = {protocol}, target = {targetName}");
}
context = new SafeDeleteNegoContext(credential, targetName);
}
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)context;
try
{
Interop.NetSecurityNative.GssFlags inputFlags =
ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(inFlags, isServer: false);
uint outputFlags;
bool isNtlmUsed;
SafeGssContextHandle contextHandle = negoContext.GssContext;
bool done = GssInitSecurityContext(
ref contextHandle,
credential.GssCredential,
isNtlmOnly,
channelBinding,
negoContext.TargetName,
inputFlags,
incomingBlob,
out resultBuffer,
out outputFlags,
out isNtlmUsed);
if (done)
{
if (NetEventSource.IsEnabled)
{
string protocol = isNtlmOnly ? "NTLM" : isNtlmUsed ? "SPNEGO-NTLM" : "SPNEGO-Kerberos";
NetEventSource.Info(null, $"actual protocol = {protocol}");
}
// Populate protocol used for authentication
negoContext.SetAuthenticationPackage(isNtlmUsed);
}
Debug.Assert(resultBuffer != null, "Unexpected null buffer returned by GssApi");
outFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(
(Interop.NetSecurityNative.GssFlags)outputFlags, isServer: false);
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
// Save the inner context handle for further calls to NetSecurity
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
if (null == negoContext.GssContext)
{
negoContext.SetGssContext(contextHandle);
}
SecurityStatusPalErrorCode errorCode = done ?
(negoContext.IsNtlmUsed && resultBuffer.Length > 0 ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.CompleteNeeded) :
SecurityStatusPalErrorCode.ContinueNeeded;
return new SecurityStatusPal(errorCode);
}
catch (Exception ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
internal static SecurityStatusPal InitializeSecurityContext(
ref SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext securityContext,
string spn,
ContextFlagsPal requestedContextFlags,
byte[] incomingBlob,
ChannelBinding channelBinding,
ref byte[] resultBlob,
ref ContextFlagsPal contextFlags)
{
SafeFreeNegoCredentials negoCredentialsHandle = (SafeFreeNegoCredentials)credentialsHandle;
if (negoCredentialsHandle.IsDefault && string.IsNullOrEmpty(spn))
{
throw new PlatformNotSupportedException(SR.net_nego_not_supported_empty_target_with_defaultcreds);
}
SecurityStatusPal status = EstablishSecurityContext(
negoCredentialsHandle,
ref securityContext,
channelBinding,
spn,
requestedContextFlags,
incomingBlob,
ref resultBlob,
ref contextFlags);
// Confidentiality flag should not be set if not requested
if (status.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded)
{
ContextFlagsPal mask = ContextFlagsPal.Confidentiality;
if ((requestedContextFlags & mask) != (contextFlags & mask))
{
throw new PlatformNotSupportedException(SR.net_nego_protection_level_not_supported);
}
}
return status;
}
internal static SecurityStatusPal AcceptSecurityContext(
SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext securityContext,
ContextFlagsPal requestedContextFlags,
byte[] incomingBlob,
ChannelBinding channelBinding,
ref byte[] resultBlob,
ref ContextFlagsPal contextFlags)
{
if (securityContext == null)
{
securityContext = new SafeDeleteNegoContext((SafeFreeNegoCredentials)credentialsHandle);
}
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
try
{
SafeGssContextHandle contextHandle = negoContext.GssContext;
bool done = GssAcceptSecurityContext(
ref contextHandle,
incomingBlob,
out resultBlob,
out uint outputFlags);
Debug.Assert(resultBlob != null, "Unexpected null buffer returned by GssApi");
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
// Save the inner context handle for further calls to NetSecurity
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
if (null == negoContext.GssContext)
{
negoContext.SetGssContext(contextHandle);
}
contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(
(Interop.NetSecurityNative.GssFlags)outputFlags, isServer: true);
SecurityStatusPalErrorCode errorCode = done ?
(negoContext.IsNtlmUsed && resultBlob.Length > 0 ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.CompleteNeeded) :
SecurityStatusPalErrorCode.ContinueNeeded;
return new SecurityStatusPal(errorCode);
}
catch (Interop.NetSecurityNative.GssApiException gex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, gex);
return new SecurityStatusPal(GetErrorCode(gex), gex);
}
catch (Exception ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
// https://www.gnu.org/software/gss/reference/gss.pdf (page 25)
private static SecurityStatusPalErrorCode GetErrorCode(Interop.NetSecurityNative.GssApiException exception)
{
switch (exception.MajorStatus)
{
case Interop.NetSecurityNative.Status.GSS_S_NO_CRED:
return SecurityStatusPalErrorCode.UnknownCredentials;
case Interop.NetSecurityNative.Status.GSS_S_BAD_BINDINGS:
return SecurityStatusPalErrorCode.BadBinding;
case Interop.NetSecurityNative.Status.GSS_S_CREDENTIALS_EXPIRED:
return SecurityStatusPalErrorCode.CertExpired;
case Interop.NetSecurityNative.Status.GSS_S_DEFECTIVE_TOKEN:
return SecurityStatusPalErrorCode.InvalidToken;
case Interop.NetSecurityNative.Status.GSS_S_DEFECTIVE_CREDENTIAL:
return SecurityStatusPalErrorCode.IncompleteCredentials;
case Interop.NetSecurityNative.Status.GSS_S_BAD_SIG:
return SecurityStatusPalErrorCode.MessageAltered;
case Interop.NetSecurityNative.Status.GSS_S_BAD_MECH:
return SecurityStatusPalErrorCode.Unsupported;
case Interop.NetSecurityNative.Status.GSS_S_NO_CONTEXT:
default:
return SecurityStatusPalErrorCode.InternalError;
}
}
private static string GetUser(
ref SafeDeleteContext securityContext)
{
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
try
{
SafeGssContextHandle contextHandle = negoContext.GssContext;
return GssGetUser(ref contextHandle);
}
catch (Exception ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
throw;
}
}
internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode)
{
return new Win32Exception(NTE_FAIL, (statusCode.Exception != null) ? statusCode.Exception.Message : statusCode.ErrorCode.ToString());
}
internal static int QueryMaxTokenSize(string package)
{
// This value is not used on Unix
return 0;
}
internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer)
{
return AcquireCredentialsHandle(package, isServer, new NetworkCredential(string.Empty, string.Empty, string.Empty));
}
internal static SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential)
{
bool isEmptyCredential = string.IsNullOrWhiteSpace(credential.UserName) ||
string.IsNullOrWhiteSpace(credential.Password);
bool ntlmOnly = string.Equals(package, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase);
if (ntlmOnly && isEmptyCredential)
{
// NTLM authentication is not possible with default credentials which are no-op
throw new PlatformNotSupportedException(SR.net_ntlm_not_possible_default_cred);
}
try
{
return isEmptyCredential ?
new SafeFreeNegoCredentials(false, string.Empty, string.Empty, string.Empty) :
new SafeFreeNegoCredentials(ntlmOnly, credential.UserName, credential.Password, credential.Domain);
}
catch (Exception ex)
{
throw new Win32Exception(NTE_FAIL, ex.Message);
}
}
internal static SecurityStatusPal CompleteAuthToken(
ref SafeDeleteContext securityContext,
byte[] incomingBlob)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
internal static int Encrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
ref byte[] output,
uint sequenceNumber)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext) securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, isConfidential, buffer, offset, count);
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
internal static int Decrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
out int newOffset,
uint sequenceNumber)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
NetEventSource.Fail(securityContext, "Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
NetEventSource.Fail(securityContext, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
newOffset = offset;
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count);
}
internal static int VerifySignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
NetEventSource.Fail(securityContext, "Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
NetEventSource.Fail(securityContext, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count);
}
internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext)securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, false, buffer, offset, count);
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
}
}
| |
// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace math {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Math {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_math_DivArgs__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::math.DivArgs, global::math.DivArgs.Builder> internal__static_math_DivArgs__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_math_DivReply__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::math.DivReply, global::math.DivReply.Builder> internal__static_math_DivReply__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_math_FibArgs__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::math.FibArgs, global::math.FibArgs.Builder> internal__static_math_FibArgs__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_math_Num__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::math.Num, global::math.Num.Builder> internal__static_math_Num__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_math_FibReply__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::math.FibReply, global::math.FibReply.Builder> internal__static_math_FibReply__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static Math() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgptYXRoLnByb3RvEgRtYXRoIiwKB0RpdkFyZ3MSEAoIZGl2aWRlbmQYASAB",
"KAMSDwoHZGl2aXNvchgCIAEoAyIvCghEaXZSZXBseRIQCghxdW90aWVudBgB",
"IAEoAxIRCglyZW1haW5kZXIYAiABKAMiGAoHRmliQXJncxINCgVsaW1pdBgB",
"IAEoAyISCgNOdW0SCwoDbnVtGAEgASgDIhkKCEZpYlJlcGx5Eg0KBWNvdW50",
"GAEgASgDMqQBCgRNYXRoEiYKA0RpdhINLm1hdGguRGl2QXJncxoOLm1hdGgu",
"RGl2UmVwbHkiABIuCgdEaXZNYW55Eg0ubWF0aC5EaXZBcmdzGg4ubWF0aC5E",
"aXZSZXBseSIAKAEwARIjCgNGaWISDS5tYXRoLkZpYkFyZ3MaCS5tYXRoLk51",
"bSIAMAESHwoDU3VtEgkubWF0aC5OdW0aCS5tYXRoLk51bSIAKAE="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_math_DivArgs__Descriptor = Descriptor.MessageTypes[0];
internal__static_math_DivArgs__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::math.DivArgs, global::math.DivArgs.Builder>(internal__static_math_DivArgs__Descriptor,
new string[] { "Dividend", "Divisor", });
internal__static_math_DivReply__Descriptor = Descriptor.MessageTypes[1];
internal__static_math_DivReply__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::math.DivReply, global::math.DivReply.Builder>(internal__static_math_DivReply__Descriptor,
new string[] { "Quotient", "Remainder", });
internal__static_math_FibArgs__Descriptor = Descriptor.MessageTypes[2];
internal__static_math_FibArgs__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::math.FibArgs, global::math.FibArgs.Builder>(internal__static_math_FibArgs__Descriptor,
new string[] { "Limit", });
internal__static_math_Num__Descriptor = Descriptor.MessageTypes[3];
internal__static_math_Num__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::math.Num, global::math.Num.Builder>(internal__static_math_Num__Descriptor,
new string[] { "Num_", });
internal__static_math_FibReply__Descriptor = Descriptor.MessageTypes[4];
internal__static_math_FibReply__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::math.FibReply, global::math.FibReply.Builder>(internal__static_math_FibReply__Descriptor,
new string[] { "Count", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DivArgs : pb::GeneratedMessage<DivArgs, DivArgs.Builder> {
private DivArgs() { }
private static readonly DivArgs defaultInstance = new DivArgs().MakeReadOnly();
private static readonly string[] _divArgsFieldNames = new string[] { "dividend", "divisor" };
private static readonly uint[] _divArgsFieldTags = new uint[] { 8, 16 };
public static DivArgs DefaultInstance {
get { return defaultInstance; }
}
public override DivArgs DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override DivArgs ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::math.Proto.Math.internal__static_math_DivArgs__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<DivArgs, DivArgs.Builder> InternalFieldAccessors {
get { return global::math.Proto.Math.internal__static_math_DivArgs__FieldAccessorTable; }
}
public const int DividendFieldNumber = 1;
private bool hasDividend;
private long dividend_;
public bool HasDividend {
get { return hasDividend; }
}
public long Dividend {
get { return dividend_; }
}
public const int DivisorFieldNumber = 2;
private bool hasDivisor;
private long divisor_;
public bool HasDivisor {
get { return hasDivisor; }
}
public long Divisor {
get { return divisor_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _divArgsFieldNames;
if (hasDividend) {
output.WriteInt64(1, field_names[0], Dividend);
}
if (hasDivisor) {
output.WriteInt64(2, field_names[1], Divisor);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasDividend) {
size += pb::CodedOutputStream.ComputeInt64Size(1, Dividend);
}
if (hasDivisor) {
size += pb::CodedOutputStream.ComputeInt64Size(2, Divisor);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static DivArgs ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DivArgs ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DivArgs ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DivArgs ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DivArgs ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DivArgs ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static DivArgs ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static DivArgs ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static DivArgs ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DivArgs ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private DivArgs MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(DivArgs prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<DivArgs, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(DivArgs cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private DivArgs result;
private DivArgs PrepareBuilder() {
if (resultIsReadOnly) {
DivArgs original = result;
result = new DivArgs();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override DivArgs MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::math.DivArgs.Descriptor; }
}
public override DivArgs DefaultInstanceForType {
get { return global::math.DivArgs.DefaultInstance; }
}
public override DivArgs BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is DivArgs) {
return MergeFrom((DivArgs) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(DivArgs other) {
if (other == global::math.DivArgs.DefaultInstance) return this;
PrepareBuilder();
if (other.HasDividend) {
Dividend = other.Dividend;
}
if (other.HasDivisor) {
Divisor = other.Divisor;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_divArgsFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _divArgsFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasDividend = input.ReadInt64(ref result.dividend_);
break;
}
case 16: {
result.hasDivisor = input.ReadInt64(ref result.divisor_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasDividend {
get { return result.hasDividend; }
}
public long Dividend {
get { return result.Dividend; }
set { SetDividend(value); }
}
public Builder SetDividend(long value) {
PrepareBuilder();
result.hasDividend = true;
result.dividend_ = value;
return this;
}
public Builder ClearDividend() {
PrepareBuilder();
result.hasDividend = false;
result.dividend_ = 0L;
return this;
}
public bool HasDivisor {
get { return result.hasDivisor; }
}
public long Divisor {
get { return result.Divisor; }
set { SetDivisor(value); }
}
public Builder SetDivisor(long value) {
PrepareBuilder();
result.hasDivisor = true;
result.divisor_ = value;
return this;
}
public Builder ClearDivisor() {
PrepareBuilder();
result.hasDivisor = false;
result.divisor_ = 0L;
return this;
}
}
static DivArgs() {
object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DivReply : pb::GeneratedMessage<DivReply, DivReply.Builder> {
private DivReply() { }
private static readonly DivReply defaultInstance = new DivReply().MakeReadOnly();
private static readonly string[] _divReplyFieldNames = new string[] { "quotient", "remainder" };
private static readonly uint[] _divReplyFieldTags = new uint[] { 8, 16 };
public static DivReply DefaultInstance {
get { return defaultInstance; }
}
public override DivReply DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override DivReply ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::math.Proto.Math.internal__static_math_DivReply__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<DivReply, DivReply.Builder> InternalFieldAccessors {
get { return global::math.Proto.Math.internal__static_math_DivReply__FieldAccessorTable; }
}
public const int QuotientFieldNumber = 1;
private bool hasQuotient;
private long quotient_;
public bool HasQuotient {
get { return hasQuotient; }
}
public long Quotient {
get { return quotient_; }
}
public const int RemainderFieldNumber = 2;
private bool hasRemainder;
private long remainder_;
public bool HasRemainder {
get { return hasRemainder; }
}
public long Remainder {
get { return remainder_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _divReplyFieldNames;
if (hasQuotient) {
output.WriteInt64(1, field_names[0], Quotient);
}
if (hasRemainder) {
output.WriteInt64(2, field_names[1], Remainder);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasQuotient) {
size += pb::CodedOutputStream.ComputeInt64Size(1, Quotient);
}
if (hasRemainder) {
size += pb::CodedOutputStream.ComputeInt64Size(2, Remainder);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static DivReply ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DivReply ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DivReply ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DivReply ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DivReply ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DivReply ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static DivReply ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static DivReply ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static DivReply ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DivReply ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private DivReply MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(DivReply prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<DivReply, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(DivReply cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private DivReply result;
private DivReply PrepareBuilder() {
if (resultIsReadOnly) {
DivReply original = result;
result = new DivReply();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override DivReply MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::math.DivReply.Descriptor; }
}
public override DivReply DefaultInstanceForType {
get { return global::math.DivReply.DefaultInstance; }
}
public override DivReply BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is DivReply) {
return MergeFrom((DivReply) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(DivReply other) {
if (other == global::math.DivReply.DefaultInstance) return this;
PrepareBuilder();
if (other.HasQuotient) {
Quotient = other.Quotient;
}
if (other.HasRemainder) {
Remainder = other.Remainder;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_divReplyFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _divReplyFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasQuotient = input.ReadInt64(ref result.quotient_);
break;
}
case 16: {
result.hasRemainder = input.ReadInt64(ref result.remainder_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasQuotient {
get { return result.hasQuotient; }
}
public long Quotient {
get { return result.Quotient; }
set { SetQuotient(value); }
}
public Builder SetQuotient(long value) {
PrepareBuilder();
result.hasQuotient = true;
result.quotient_ = value;
return this;
}
public Builder ClearQuotient() {
PrepareBuilder();
result.hasQuotient = false;
result.quotient_ = 0L;
return this;
}
public bool HasRemainder {
get { return result.hasRemainder; }
}
public long Remainder {
get { return result.Remainder; }
set { SetRemainder(value); }
}
public Builder SetRemainder(long value) {
PrepareBuilder();
result.hasRemainder = true;
result.remainder_ = value;
return this;
}
public Builder ClearRemainder() {
PrepareBuilder();
result.hasRemainder = false;
result.remainder_ = 0L;
return this;
}
}
static DivReply() {
object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FibArgs : pb::GeneratedMessage<FibArgs, FibArgs.Builder> {
private FibArgs() { }
private static readonly FibArgs defaultInstance = new FibArgs().MakeReadOnly();
private static readonly string[] _fibArgsFieldNames = new string[] { "limit" };
private static readonly uint[] _fibArgsFieldTags = new uint[] { 8 };
public static FibArgs DefaultInstance {
get { return defaultInstance; }
}
public override FibArgs DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override FibArgs ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::math.Proto.Math.internal__static_math_FibArgs__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<FibArgs, FibArgs.Builder> InternalFieldAccessors {
get { return global::math.Proto.Math.internal__static_math_FibArgs__FieldAccessorTable; }
}
public const int LimitFieldNumber = 1;
private bool hasLimit;
private long limit_;
public bool HasLimit {
get { return hasLimit; }
}
public long Limit {
get { return limit_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _fibArgsFieldNames;
if (hasLimit) {
output.WriteInt64(1, field_names[0], Limit);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasLimit) {
size += pb::CodedOutputStream.ComputeInt64Size(1, Limit);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static FibArgs ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static FibArgs ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static FibArgs ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static FibArgs ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static FibArgs ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static FibArgs ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static FibArgs ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static FibArgs ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static FibArgs ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static FibArgs ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private FibArgs MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(FibArgs prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<FibArgs, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(FibArgs cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private FibArgs result;
private FibArgs PrepareBuilder() {
if (resultIsReadOnly) {
FibArgs original = result;
result = new FibArgs();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override FibArgs MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::math.FibArgs.Descriptor; }
}
public override FibArgs DefaultInstanceForType {
get { return global::math.FibArgs.DefaultInstance; }
}
public override FibArgs BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is FibArgs) {
return MergeFrom((FibArgs) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(FibArgs other) {
if (other == global::math.FibArgs.DefaultInstance) return this;
PrepareBuilder();
if (other.HasLimit) {
Limit = other.Limit;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_fibArgsFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _fibArgsFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasLimit = input.ReadInt64(ref result.limit_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasLimit {
get { return result.hasLimit; }
}
public long Limit {
get { return result.Limit; }
set { SetLimit(value); }
}
public Builder SetLimit(long value) {
PrepareBuilder();
result.hasLimit = true;
result.limit_ = value;
return this;
}
public Builder ClearLimit() {
PrepareBuilder();
result.hasLimit = false;
result.limit_ = 0L;
return this;
}
}
static FibArgs() {
object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Num : pb::GeneratedMessage<Num, Num.Builder> {
private Num() { }
private static readonly Num defaultInstance = new Num().MakeReadOnly();
private static readonly string[] _numFieldNames = new string[] { "num" };
private static readonly uint[] _numFieldTags = new uint[] { 8 };
public static Num DefaultInstance {
get { return defaultInstance; }
}
public override Num DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override Num ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::math.Proto.Math.internal__static_math_Num__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<Num, Num.Builder> InternalFieldAccessors {
get { return global::math.Proto.Math.internal__static_math_Num__FieldAccessorTable; }
}
public const int Num_FieldNumber = 1;
private bool hasNum_;
private long num_;
public bool HasNum_ {
get { return hasNum_; }
}
public long Num_ {
get { return num_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _numFieldNames;
if (hasNum_) {
output.WriteInt64(1, field_names[0], Num_);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasNum_) {
size += pb::CodedOutputStream.ComputeInt64Size(1, Num_);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static Num ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Num ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Num ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Num ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Num ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Num ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Num ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static Num ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static Num ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Num ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private Num MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(Num prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<Num, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(Num cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private Num result;
private Num PrepareBuilder() {
if (resultIsReadOnly) {
Num original = result;
result = new Num();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override Num MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::math.Num.Descriptor; }
}
public override Num DefaultInstanceForType {
get { return global::math.Num.DefaultInstance; }
}
public override Num BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is Num) {
return MergeFrom((Num) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(Num other) {
if (other == global::math.Num.DefaultInstance) return this;
PrepareBuilder();
if (other.HasNum_) {
Num_ = other.Num_;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_numFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _numFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasNum_ = input.ReadInt64(ref result.num_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasNum_ {
get { return result.hasNum_; }
}
public long Num_ {
get { return result.Num_; }
set { SetNum_(value); }
}
public Builder SetNum_(long value) {
PrepareBuilder();
result.hasNum_ = true;
result.num_ = value;
return this;
}
public Builder ClearNum_() {
PrepareBuilder();
result.hasNum_ = false;
result.num_ = 0L;
return this;
}
}
static Num() {
object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FibReply : pb::GeneratedMessage<FibReply, FibReply.Builder> {
private FibReply() { }
private static readonly FibReply defaultInstance = new FibReply().MakeReadOnly();
private static readonly string[] _fibReplyFieldNames = new string[] { "count" };
private static readonly uint[] _fibReplyFieldTags = new uint[] { 8 };
public static FibReply DefaultInstance {
get { return defaultInstance; }
}
public override FibReply DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override FibReply ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::math.Proto.Math.internal__static_math_FibReply__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<FibReply, FibReply.Builder> InternalFieldAccessors {
get { return global::math.Proto.Math.internal__static_math_FibReply__FieldAccessorTable; }
}
public const int CountFieldNumber = 1;
private bool hasCount;
private long count_;
public bool HasCount {
get { return hasCount; }
}
public long Count {
get { return count_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _fibReplyFieldNames;
if (hasCount) {
output.WriteInt64(1, field_names[0], Count);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasCount) {
size += pb::CodedOutputStream.ComputeInt64Size(1, Count);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static FibReply ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static FibReply ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static FibReply ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static FibReply ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static FibReply ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static FibReply ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static FibReply ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static FibReply ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static FibReply ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static FibReply ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private FibReply MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(FibReply prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<FibReply, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(FibReply cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private FibReply result;
private FibReply PrepareBuilder() {
if (resultIsReadOnly) {
FibReply original = result;
result = new FibReply();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override FibReply MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::math.FibReply.Descriptor; }
}
public override FibReply DefaultInstanceForType {
get { return global::math.FibReply.DefaultInstance; }
}
public override FibReply BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is FibReply) {
return MergeFrom((FibReply) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(FibReply other) {
if (other == global::math.FibReply.DefaultInstance) return this;
PrepareBuilder();
if (other.HasCount) {
Count = other.Count;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_fibReplyFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _fibReplyFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasCount = input.ReadInt64(ref result.count_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasCount {
get { return result.hasCount; }
}
public long Count {
get { return result.Count; }
set { SetCount(value); }
}
public Builder SetCount(long value) {
PrepareBuilder();
result.hasCount = true;
result.count_ = value;
return this;
}
public Builder ClearCount() {
PrepareBuilder();
result.hasCount = false;
result.count_ = 0L;
return this;
}
}
static FibReply() {
object.ReferenceEquals(global::math.Proto.Math.Descriptor, null);
}
}
#endregion
#region Services
/*
* Service generation is now disabled by default, use the following option to enable:
* option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;
*/
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Media;
using Nop.Services.Localization;
using Nop.Services.Media;
using Nop.Services.Seo;
using Nop.Services.Stores;
namespace Nop.Services.Catalog
{
/// <summary>
/// Copy Product service
/// </summary>
public partial class CopyProductService : ICopyProductService
{
#region Fields
private readonly IProductService _productService;
private readonly IProductAttributeService _productAttributeService;
private readonly ILanguageService _languageService;
private readonly ILocalizedEntityService _localizedEntityService;
private readonly ILocalizationService _localizationService;
private readonly IPictureService _pictureService;
private readonly ICategoryService _categoryService;
private readonly IManufacturerService _manufacturerService;
private readonly ISpecificationAttributeService _specificationAttributeService;
private readonly IDownloadService _downloadService;
private readonly IProductAttributeParser _productAttributeParser;
private readonly IUrlRecordService _urlRecordService;
private readonly IStoreMappingService _storeMappingService;
#endregion
#region Ctor
public CopyProductService(IProductService productService,
IProductAttributeService productAttributeService,
ILanguageService languageService,
ILocalizedEntityService localizedEntityService,
ILocalizationService localizationService,
IPictureService pictureService,
ICategoryService categoryService,
IManufacturerService manufacturerService,
ISpecificationAttributeService specificationAttributeService,
IDownloadService downloadService,
IProductAttributeParser productAttributeParser,
IUrlRecordService urlRecordService,
IStoreMappingService storeMappingService)
{
this._productService = productService;
this._productAttributeService = productAttributeService;
this._languageService = languageService;
this._localizedEntityService = localizedEntityService;
this._localizationService = localizationService;
this._pictureService = pictureService;
this._categoryService = categoryService;
this._manufacturerService = manufacturerService;
this._specificationAttributeService = specificationAttributeService;
this._downloadService = downloadService;
this._productAttributeParser = productAttributeParser;
this._urlRecordService = urlRecordService;
this._storeMappingService = storeMappingService;
}
#endregion
#region Methods
/// <summary>
/// Create a copy of product with all depended data
/// </summary>
/// <param name="product">The product to copy</param>
/// <param name="newName">The name of product duplicate</param>
/// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
/// <param name="copyImages">A value indicating whether the product images should be copied</param>
/// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
/// <returns>Product copy</returns>
public virtual Product CopyProduct(Product product, string newName,
bool isPublished = true, bool copyImages = true, bool copyAssociatedProducts = true)
{
if (product == null)
throw new ArgumentNullException("product");
if (String.IsNullOrEmpty(newName))
throw new ArgumentException("Product name is required");
//product download & sample download
int downloadId = product.DownloadId;
int sampleDownloadId = product.SampleDownloadId;
if (product.IsDownload)
{
var download = _downloadService.GetDownloadById(product.DownloadId);
if (download != null)
{
var downloadCopy = new Download
{
DownloadGuid = Guid.NewGuid(),
UseDownloadUrl = download.UseDownloadUrl,
DownloadUrl = download.DownloadUrl,
DownloadBinary = download.DownloadBinary,
ContentType = download.ContentType,
Filename = download.Filename,
Extension = download.Extension,
IsNew = download.IsNew,
};
_downloadService.InsertDownload(downloadCopy);
downloadId = downloadCopy.Id;
}
if (product.HasSampleDownload)
{
var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId);
if (sampleDownload != null)
{
var sampleDownloadCopy = new Download
{
DownloadGuid = Guid.NewGuid(),
UseDownloadUrl = sampleDownload.UseDownloadUrl,
DownloadUrl = sampleDownload.DownloadUrl,
DownloadBinary = sampleDownload.DownloadBinary,
ContentType = sampleDownload.ContentType,
Filename = sampleDownload.Filename,
Extension = sampleDownload.Extension,
IsNew = sampleDownload.IsNew
};
_downloadService.InsertDownload(sampleDownloadCopy);
sampleDownloadId = sampleDownloadCopy.Id;
}
}
}
var newSku = !String.IsNullOrWhiteSpace(product.Sku)
? string.Format(_localizationService.GetResource("Admin.Catalog.Products.Copy.SKU.New"), product.Sku) :
product.Sku;
// product
var productCopy = new Product
{
ProductTypeId = product.ProductTypeId,
ParentGroupedProductId = product.ParentGroupedProductId,
VisibleIndividually = product.VisibleIndividually,
Name = newName,
ShortDescription = product.ShortDescription,
FullDescription = product.FullDescription,
VendorId = product.VendorId,
ProductTemplateId = product.ProductTemplateId,
AdminComment = product.AdminComment,
ShowOnHomePage = product.ShowOnHomePage,
MetaKeywords = product.MetaKeywords,
MetaDescription = product.MetaDescription,
MetaTitle = product.MetaTitle,
AllowCustomerReviews = product.AllowCustomerReviews,
LimitedToStores = product.LimitedToStores,
Sku = newSku,
ManufacturerPartNumber = product.ManufacturerPartNumber,
Gtin = product.Gtin,
IsGiftCard = product.IsGiftCard,
GiftCardType = product.GiftCardType,
OverriddenGiftCardAmount = product.OverriddenGiftCardAmount,
RequireOtherProducts = product.RequireOtherProducts,
RequiredProductIds = product.RequiredProductIds,
AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts,
IsDownload = product.IsDownload,
DownloadId = downloadId,
UnlimitedDownloads = product.UnlimitedDownloads,
MaxNumberOfDownloads = product.MaxNumberOfDownloads,
DownloadExpirationDays = product.DownloadExpirationDays,
DownloadActivationType = product.DownloadActivationType,
HasSampleDownload = product.HasSampleDownload,
SampleDownloadId = sampleDownloadId,
HasUserAgreement = product.HasUserAgreement,
UserAgreementText = product.UserAgreementText,
IsRecurring = product.IsRecurring,
RecurringCycleLength = product.RecurringCycleLength,
RecurringCyclePeriod = product.RecurringCyclePeriod,
RecurringTotalCycles = product.RecurringTotalCycles,
IsRental = product.IsRental,
RentalPriceLength = product.RentalPriceLength,
RentalPricePeriod = product.RentalPricePeriod,
IsShipEnabled = product.IsShipEnabled,
IsFreeShipping = product.IsFreeShipping,
ShipSeparately = product.ShipSeparately,
AdditionalShippingCharge = product.AdditionalShippingCharge,
DeliveryDateId = product.DeliveryDateId,
IsTaxExempt = product.IsTaxExempt,
TaxCategoryId = product.TaxCategoryId,
IsTelecommunicationsOrBroadcastingOrElectronicServices = product.IsTelecommunicationsOrBroadcastingOrElectronicServices,
ManageInventoryMethod = product.ManageInventoryMethod,
ProductAvailabilityRangeId = product.ProductAvailabilityRangeId,
UseMultipleWarehouses = product.UseMultipleWarehouses,
WarehouseId = product.WarehouseId,
StockQuantity = product.StockQuantity,
DisplayStockAvailability = product.DisplayStockAvailability,
DisplayStockQuantity = product.DisplayStockQuantity,
MinStockQuantity = product.MinStockQuantity,
LowStockActivityId = product.LowStockActivityId,
NotifyAdminForQuantityBelow = product.NotifyAdminForQuantityBelow,
BackorderMode = product.BackorderMode,
AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions,
OrderMinimumQuantity = product.OrderMinimumQuantity,
OrderMaximumQuantity = product.OrderMaximumQuantity,
AllowedQuantities = product.AllowedQuantities,
AllowAddingOnlyExistingAttributeCombinations = product.AllowAddingOnlyExistingAttributeCombinations,
NotReturnable = product.NotReturnable,
DisableBuyButton = product.DisableBuyButton,
DisableWishlistButton = product.DisableWishlistButton,
AvailableForPreOrder = product.AvailableForPreOrder,
PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc,
CallForPrice = product.CallForPrice,
Price = product.Price,
OldPrice = product.OldPrice,
ProductCost = product.ProductCost,
CustomerEntersPrice = product.CustomerEntersPrice,
MinimumCustomerEnteredPrice = product.MinimumCustomerEnteredPrice,
MaximumCustomerEnteredPrice = product.MaximumCustomerEnteredPrice,
BasepriceEnabled = product.BasepriceEnabled,
BasepriceAmount = product.BasepriceAmount,
BasepriceUnitId = product.BasepriceUnitId,
BasepriceBaseAmount = product.BasepriceBaseAmount,
BasepriceBaseUnitId = product.BasepriceBaseUnitId,
MarkAsNew = product.MarkAsNew,
MarkAsNewStartDateTimeUtc = product.MarkAsNewStartDateTimeUtc,
MarkAsNewEndDateTimeUtc = product.MarkAsNewEndDateTimeUtc,
Weight = product.Weight,
Length = product.Length,
Width = product.Width,
Height = product.Height,
AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc,
AvailableEndDateTimeUtc = product.AvailableEndDateTimeUtc,
DisplayOrder = product.DisplayOrder,
Published = isPublished,
Deleted = product.Deleted,
CreatedOnUtc = DateTime.UtcNow,
UpdatedOnUtc = DateTime.UtcNow
};
//validate search engine name
_productService.InsertProduct(productCopy);
//search engine name
_urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);
var languages = _languageService.GetAllLanguages(true);
//localization
foreach (var lang in languages)
{
var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
if (!String.IsNullOrEmpty(name))
_localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);
var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
if (!String.IsNullOrEmpty(shortDescription))
_localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);
var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
if (!String.IsNullOrEmpty(fullDescription))
_localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);
var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
if (!String.IsNullOrEmpty(metaKeywords))
_localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);
var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
if (!String.IsNullOrEmpty(metaDescription))
_localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);
var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
if (!String.IsNullOrEmpty(metaTitle))
_localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);
//search engine name
_urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);
}
//product tags
foreach (var productTag in product.ProductTags)
{
productCopy.ProductTags.Add(productTag);
}
_productService.UpdateProduct(productCopy);
//product pictures
//variable to store original and new picture identifiers
var originalNewPictureIdentifiers = new Dictionary<int, int>();
if (copyImages)
{
foreach (var productPicture in product.ProductPictures)
{
var picture = productPicture.Picture;
var pictureCopy = _pictureService.InsertPicture(
_pictureService.LoadPictureBinary(picture),
picture.MimeType,
_pictureService.GetPictureSeName(newName),
picture.AltAttribute,
picture.TitleAttribute);
_productService.InsertProductPicture(new ProductPicture
{
ProductId = productCopy.Id,
PictureId = pictureCopy.Id,
DisplayOrder = productPicture.DisplayOrder
});
originalNewPictureIdentifiers.Add(picture.Id, pictureCopy.Id);
}
}
//quantity change history
_productService.AddStockQuantityHistoryEntry(productCopy, product.StockQuantity, product.StockQuantity, product.WarehouseId,
string.Format(_localizationService.GetResource("Admin.StockQuantityHistory.Messages.CopyProduct"), product.Id));
// product <-> warehouses mappings
foreach (var pwi in product.ProductWarehouseInventory)
{
var pwiCopy = new ProductWarehouseInventory
{
ProductId = productCopy.Id,
WarehouseId = pwi.WarehouseId,
StockQuantity = pwi.StockQuantity,
ReservedQuantity = 0,
};
productCopy.ProductWarehouseInventory.Add(pwiCopy);
//quantity change history
var message = string.Format("{0} {1}", _localizationService.GetResource("Admin.StockQuantityHistory.Messages.MultipleWarehouses"),
string.Format(_localizationService.GetResource("Admin.StockQuantityHistory.Messages.CopyProduct"), product.Id));
_productService.AddStockQuantityHistoryEntry(productCopy, pwi.StockQuantity, pwi.StockQuantity, pwi.WarehouseId, message);
}
_productService.UpdateProduct(productCopy);
// product <-> categories mappings
foreach (var productCategory in product.ProductCategories)
{
var productCategoryCopy = new ProductCategory
{
ProductId = productCopy.Id,
CategoryId = productCategory.CategoryId,
IsFeaturedProduct = productCategory.IsFeaturedProduct,
DisplayOrder = productCategory.DisplayOrder
};
_categoryService.InsertProductCategory(productCategoryCopy);
}
// product <-> manufacturers mappings
foreach (var productManufacturers in product.ProductManufacturers)
{
var productManufacturerCopy = new ProductManufacturer
{
ProductId = productCopy.Id,
ManufacturerId = productManufacturers.ManufacturerId,
IsFeaturedProduct = productManufacturers.IsFeaturedProduct,
DisplayOrder = productManufacturers.DisplayOrder
};
_manufacturerService.InsertProductManufacturer(productManufacturerCopy);
}
// product <-> releated products mappings
foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true))
{
_productService.InsertRelatedProduct(
new RelatedProduct
{
ProductId1 = productCopy.Id,
ProductId2 = relatedProduct.ProductId2,
DisplayOrder = relatedProduct.DisplayOrder
});
}
// product <-> cross sells mappings
foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true))
{
_productService.InsertCrossSellProduct(
new CrossSellProduct
{
ProductId1 = productCopy.Id,
ProductId2 = csProduct.ProductId2,
});
}
// product specifications
foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
{
var psaCopy = new ProductSpecificationAttribute
{
ProductId = productCopy.Id,
AttributeTypeId = productSpecificationAttribute.AttributeTypeId,
SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
CustomValue = productSpecificationAttribute.CustomValue,
AllowFiltering = productSpecificationAttribute.AllowFiltering,
ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
DisplayOrder = productSpecificationAttribute.DisplayOrder
};
_specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
}
//store mapping
var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);
foreach (var id in selectedStoreIds)
{
_storeMappingService.InsertStoreMapping(productCopy, id);
}
//product <-> attributes mappings
var associatedAttributes = new Dictionary<int, int>();
var associatedAttributeValues = new Dictionary<int, int>();
//attribute mapping with condition attributes
var oldCopyWithConditionAttributes = new List<ProductAttributeMapping>();
//all product attribute mapping copies
var productAttributeMappingCopies = new Dictionary<int, ProductAttributeMapping>();
foreach (var productAttributeMapping in _productAttributeService.GetProductAttributeMappingsByProductId(product.Id))
{
var productAttributeMappingCopy = new ProductAttributeMapping
{
ProductId = productCopy.Id,
ProductAttributeId = productAttributeMapping.ProductAttributeId,
TextPrompt = productAttributeMapping.TextPrompt,
IsRequired = productAttributeMapping.IsRequired,
AttributeControlTypeId = productAttributeMapping.AttributeControlTypeId,
DisplayOrder = productAttributeMapping.DisplayOrder,
ValidationMinLength = productAttributeMapping.ValidationMinLength,
ValidationMaxLength = productAttributeMapping.ValidationMaxLength,
ValidationFileAllowedExtensions = productAttributeMapping.ValidationFileAllowedExtensions,
ValidationFileMaximumSize = productAttributeMapping.ValidationFileMaximumSize,
DefaultValue = productAttributeMapping.DefaultValue
};
_productAttributeService.InsertProductAttributeMapping(productAttributeMappingCopy);
productAttributeMappingCopies.Add(productAttributeMappingCopy.Id, productAttributeMappingCopy);
if (!string.IsNullOrEmpty(productAttributeMapping.ConditionAttributeXml))
{
oldCopyWithConditionAttributes.Add(productAttributeMapping);
}
//save associated value (used for combinations copying)
associatedAttributes.Add(productAttributeMapping.Id, productAttributeMappingCopy.Id);
// product attribute values
var productAttributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id);
foreach (var productAttributeValue in productAttributeValues)
{
int attributeValuePictureId = 0;
if (originalNewPictureIdentifiers.ContainsKey(productAttributeValue.PictureId))
{
attributeValuePictureId = originalNewPictureIdentifiers[productAttributeValue.PictureId];
}
var attributeValueCopy = new ProductAttributeValue
{
ProductAttributeMappingId = productAttributeMappingCopy.Id,
AttributeValueTypeId = productAttributeValue.AttributeValueTypeId,
AssociatedProductId = productAttributeValue.AssociatedProductId,
Name = productAttributeValue.Name,
ColorSquaresRgb = productAttributeValue.ColorSquaresRgb,
PriceAdjustment = productAttributeValue.PriceAdjustment,
WeightAdjustment = productAttributeValue.WeightAdjustment,
Cost = productAttributeValue.Cost,
CustomerEntersQty = productAttributeValue.CustomerEntersQty,
Quantity = productAttributeValue.Quantity,
IsPreSelected = productAttributeValue.IsPreSelected,
DisplayOrder = productAttributeValue.DisplayOrder,
PictureId = attributeValuePictureId,
};
//picture associated to "iamge square" attribute type (if exists)
if (productAttributeValue.ImageSquaresPictureId > 0)
{
var origImageSquaresPicture = _pictureService.GetPictureById(productAttributeValue.ImageSquaresPictureId);
if (origImageSquaresPicture != null)
{
//copy the picture
var imageSquaresPictureCopy = _pictureService.InsertPicture(
_pictureService.LoadPictureBinary(origImageSquaresPicture),
origImageSquaresPicture.MimeType,
origImageSquaresPicture.SeoFilename,
origImageSquaresPicture.AltAttribute,
origImageSquaresPicture.TitleAttribute);
attributeValueCopy.ImageSquaresPictureId = imageSquaresPictureCopy.Id;
}
}
_productAttributeService.InsertProductAttributeValue(attributeValueCopy);
//save associated value (used for combinations copying)
associatedAttributeValues.Add(productAttributeValue.Id, attributeValueCopy.Id);
//localization
foreach (var lang in languages)
{
var name = productAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
if (!String.IsNullOrEmpty(name))
_localizedEntityService.SaveLocalizedValue(attributeValueCopy, x => x.Name, name, lang.Id);
}
}
}
//copy attribute conditions
foreach (var productAttributeMapping in oldCopyWithConditionAttributes)
{
var oldConditionAttributeMapping = _productAttributeParser.ParseProductAttributeMappings(productAttributeMapping.ConditionAttributeXml).FirstOrDefault();
if (oldConditionAttributeMapping == null)
continue;
var oldConditionValues = _productAttributeParser.ParseProductAttributeValues(productAttributeMapping.ConditionAttributeXml, oldConditionAttributeMapping.Id);
if (!oldConditionValues.Any())
continue;
var newAttributeMappingId = associatedAttributes[oldConditionAttributeMapping.Id];
var newConditionAttributeMapping = productAttributeMappingCopies[newAttributeMappingId];
var newConditionAttributeXml = string.Empty;
foreach (var oldConditionValue in oldConditionValues)
{
newConditionAttributeXml = _productAttributeParser.AddProductAttribute(newConditionAttributeXml, newConditionAttributeMapping, associatedAttributeValues[oldConditionValue.Id].ToString());
}
var attributeMappingId = associatedAttributes[productAttributeMapping.Id];
var conditionAttribute = productAttributeMappingCopies[attributeMappingId];
conditionAttribute.ConditionAttributeXml = newConditionAttributeXml;
_productAttributeService.UpdateProductAttributeMapping(conditionAttribute);
}
//attribute combinations
foreach (var combination in _productAttributeService.GetAllProductAttributeCombinations(product.Id))
{
//generate new AttributesXml according to new value IDs
string newAttributesXml = "";
var parsedProductAttributes = _productAttributeParser.ParseProductAttributeMappings(combination.AttributesXml);
foreach (var oldAttribute in parsedProductAttributes)
{
if (associatedAttributes.ContainsKey(oldAttribute.Id))
{
var newAttribute = _productAttributeService.GetProductAttributeMappingById(associatedAttributes[oldAttribute.Id]);
if (newAttribute != null)
{
var oldAttributeValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldAttribute.Id);
foreach (var oldAttributeValueStr in oldAttributeValuesStr)
{
if (newAttribute.ShouldHaveValues())
{
//attribute values
int oldAttributeValue = int.Parse(oldAttributeValueStr);
if (associatedAttributeValues.ContainsKey(oldAttributeValue))
{
var newAttributeValue = _productAttributeService.GetProductAttributeValueById(associatedAttributeValues[oldAttributeValue]);
if (newAttributeValue != null)
{
newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
newAttribute, newAttributeValue.Id.ToString());
}
}
}
else
{
//just a text
newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
newAttribute, oldAttributeValueStr);
}
}
}
}
}
var combinationCopy = new ProductAttributeCombination
{
ProductId = productCopy.Id,
AttributesXml = newAttributesXml,
StockQuantity = combination.StockQuantity,
AllowOutOfStockOrders = combination.AllowOutOfStockOrders,
Sku = combination.Sku,
ManufacturerPartNumber = combination.ManufacturerPartNumber,
Gtin = combination.Gtin,
OverriddenPrice = combination.OverriddenPrice,
NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow
};
_productAttributeService.InsertProductAttributeCombination(combinationCopy);
//quantity change history
_productService.AddStockQuantityHistoryEntry(productCopy, combination.StockQuantity, combination.StockQuantity,
message: string.Format(_localizationService.GetResource("Admin.StockQuantityHistory.Messages.CopyProduct"), product.Id), combinationId: combination.Id);
}
//tier prices
foreach (var tierPrice in product.TierPrices)
{
_productService.InsertTierPrice(
new TierPrice
{
ProductId = productCopy.Id,
StoreId = tierPrice.StoreId,
CustomerRoleId = tierPrice.CustomerRoleId,
Quantity = tierPrice.Quantity,
Price = tierPrice.Price,
StartDateTimeUtc = tierPrice.StartDateTimeUtc,
EndDateTimeUtc = tierPrice.EndDateTimeUtc
});
}
// product <-> discounts mapping
foreach (var discount in product.AppliedDiscounts)
{
productCopy.AppliedDiscounts.Add(discount);
_productService.UpdateProduct(productCopy);
}
//update "HasTierPrices" and "HasDiscountsApplied" properties
_productService.UpdateHasTierPricesProperty(productCopy);
_productService.UpdateHasDiscountsApplied(productCopy);
//associated products
if (copyAssociatedProducts)
{
var associatedProducts = _productService.GetAssociatedProducts(product.Id, showHidden: true);
foreach (var associatedProduct in associatedProducts)
{
var associatedProductCopy = CopyProduct(associatedProduct, string.Format("Copy of {0}", associatedProduct.Name),
isPublished, copyImages, false);
associatedProductCopy.ParentGroupedProductId = productCopy.Id;
_productService.UpdateProduct(productCopy);
}
}
return productCopy;
}
#endregion
}
}
| |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
namespace NPOI.XSSF.UserModel
{
/**
* @author Yegor Kozlov
*/
public class XSSFFontFormatting : IFontFormatting
{
CT_Font _font;
/*package*/
internal XSSFFontFormatting(CT_Font font)
{
_font = font;
}
/**
* Get the type of super or subscript for the font
*
* @return super or subscript option
* @see #SS_NONE
* @see #SS_SUPER
* @see #SS_SUB
*/
public FontSuperScript EscapementType
{
get
{
if (_font.sizeOfVertAlignArray() == 0) return FontSuperScript.None;
CT_VerticalAlignFontProperty prop = _font.GetVertAlignArray(0);
return (FontSuperScript)(prop.val - 1);
}
set
{
_font.SetVertAlignArray(null);
if (value != FontSuperScript.None)
{
_font.AddNewVertAlign().val = (ST_VerticalAlignRun)(value + 1);
}
}
}
/**
* @return font color index
*/
public short FontColorIndex
{
get
{
if (_font.sizeOfColorArray() == 0) return -1;
int idx = 0;
CT_Color color = _font.GetColorArray(0);
if (color.IsSetIndexed()) idx = (int)color.indexed;
return (short)idx;
}
set
{
_font.SetColorArray(null);
if (value != -1)
{
var clr=_font.AddNewColor();
clr.indexed = (uint)(value);
clr.indexedSpecified = true;
}
}
}
/**
*
* @return xssf color wrapper or null if color info is missing
*/
public XSSFColor GetXSSFColor()
{
if (_font.sizeOfColorArray() == 0) return null;
return new XSSFColor(_font.GetColorArray(0));
}
/**
* Gets the height of the font in 1/20th point units
*
* @return fontheight (in points/20); or -1 if not modified
*/
public int FontHeight
{
get
{
if (_font.sizeOfSzArray() == 0) return -1;
CT_FontSize sz = _font.GetSzArray(0);
return (short)(20 * sz.val);
}
set
{
_font.SetSzArray(null);
if (value != -1)
{
_font.AddNewSz().val = (double)value / 20;
}
}
}
/**
* Get the type of underlining for the font
*
* @return font underlining type
*
* @see #U_NONE
* @see #U_SINGLE
* @see #U_DOUBLE
* @see #U_SINGLE_ACCOUNTING
* @see #U_DOUBLE_ACCOUNTING
*/
public FontUnderlineType UnderlineType
{
get
{
if (_font.sizeOfUArray() == 0) return FontUnderlineType.None;
CT_UnderlineProperty u = _font.GetUArray(0);
switch (u.val)
{
case ST_UnderlineValues.single: return FontUnderlineType.Single;
case ST_UnderlineValues.@double: return FontUnderlineType.Double;
case ST_UnderlineValues.singleAccounting: return FontUnderlineType.SingleAccounting;
case ST_UnderlineValues.doubleAccounting: return FontUnderlineType.DoubleAccounting;
default: return FontUnderlineType.None;
}
}
set
{
_font.SetUArray(null);
if (value != FontUnderlineType.None)
{
FontUnderline fenum = FontUnderline.ValueOf(value);
ST_UnderlineValues val = (ST_UnderlineValues)(fenum.Value);
_font.AddNewU().val = val;
}
}
}
/**
* Get whether the font weight is Set to bold or not
*
* @return bold - whether the font is bold or not
*/
public bool IsBold
{
get
{
return _font.SizeOfBArray() == 1 && _font.GetBArray(0).val;
}
}
/**
* @return true if font style was Set to <i>italic</i>
*/
public bool IsItalic
{
get
{
return _font.sizeOfIArray() == 1 && _font.GetIArray(0).val;
}
}
/**
* Set font style options.
*
* @param italic - if true, Set posture style to italic, otherwise to normal
* @param bold if true, Set font weight to bold, otherwise to normal
*/
public void SetFontStyle(bool italic, bool bold)
{
_font.SetIArray(null);
_font.SetBArray(null);
if (italic) _font.AddNewI().val = true;
if (bold) _font.AddNewB().val = true;
}
/**
* Set font style options to default values (non-italic, non-bold)
*/
public void ResetFontStyle()
{
_font = new CT_Font();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for ServiceRunnersOperations.
/// </summary>
public static partial class ServiceRunnersOperationsExtensions
{
/// <summary>
/// List service runners in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<ServiceRunner> List(this IServiceRunnersOperations operations, string labName, ODataQuery<ServiceRunner> odataQuery = default(ODataQuery<ServiceRunner>))
{
return Task.Factory.StartNew(s => ((IServiceRunnersOperations)s).ListAsync(labName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List service runners in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ServiceRunner>> ListAsync(this IServiceRunnersOperations operations, string labName, ODataQuery<ServiceRunner> odataQuery = default(ODataQuery<ServiceRunner>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(labName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get service runner.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the service runner.
/// </param>
public static ServiceRunner Get(this IServiceRunnersOperations operations, string labName, string name)
{
return Task.Factory.StartNew(s => ((IServiceRunnersOperations)s).GetAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get service runner.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the service runner.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServiceRunner> GetAsync(this IServiceRunnersOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing Service runner.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the service runner.
/// </param>
/// <param name='serviceRunner'>
/// A container for a managed identity to execute DevTest lab services.
/// </param>
public static ServiceRunner CreateOrUpdate(this IServiceRunnersOperations operations, string labName, string name, ServiceRunner serviceRunner)
{
return Task.Factory.StartNew(s => ((IServiceRunnersOperations)s).CreateOrUpdateAsync(labName, name, serviceRunner), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing Service runner.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the service runner.
/// </param>
/// <param name='serviceRunner'>
/// A container for a managed identity to execute DevTest lab services.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServiceRunner> CreateOrUpdateAsync(this IServiceRunnersOperations operations, string labName, string name, ServiceRunner serviceRunner, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(labName, name, serviceRunner, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete service runner.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the service runner.
/// </param>
public static void Delete(this IServiceRunnersOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IServiceRunnersOperations)s).DeleteAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete service runner.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the service runner.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IServiceRunnersOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// List service runners in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ServiceRunner> ListNext(this IServiceRunnersOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IServiceRunnersOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List service runners in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ServiceRunner>> ListNextAsync(this IServiceRunnersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Default way to read streams of resources on
** demand.
**
** Version 2 support on October 6, 2003
**
===========================================================*/
namespace System.Resources
{
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Globalization;
using System.Configuration.Assemblies;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
// Provides the default implementation of IResourceReader, reading
// .resources file from the system default binary format. This class
// can be treated as an enumerator once.
//
// See the RuntimeResourceSet overview for details on the system
// default file format.
//
internal struct ResourceLocator
{
internal object _value; // Can be null. Consider WeakReference instead?
internal int _dataPos;
internal ResourceLocator(int dataPos, object value)
{
_dataPos = dataPos;
_value = value;
}
internal int DataPosition
{
get { return _dataPos; }
//set { _dataPos = value; }
}
// Allows adding in profiling data in a future version, or a special
// resource profiling build. We could also use WeakReference.
internal object Value
{
get { return _value; }
set { _value = value; }
}
internal static bool CanCache(ResourceTypeCode value)
{
Debug.Assert(value >= 0, "negative ResourceTypeCode. What?");
return value <= ResourceTypeCode.LastPrimitive;
}
}
public sealed class ResourceReader : IResourceReader
{
// A reasonable default buffer size for reading from files, especially
// when we will likely be seeking frequently. Could be smaller, but does
// it make sense to use anything less than one page?
private const int DefaultFileStreamBufferSize = 4096;
private BinaryReader _store; // backing store we're reading from.
// Used by RuntimeResourceSet and this class's enumerator. Maps
// resource name to a value, a ResourceLocator, or a
// LooselyLinkedManifestResource.
internal Dictionary<string, ResourceLocator> _resCache;
private long _nameSectionOffset; // Offset to name section of file.
private long _dataSectionOffset; // Offset to Data section of file.
// Note this class is tightly coupled with UnmanagedMemoryStream.
// At runtime when getting an embedded resource from an assembly,
// we're given an UnmanagedMemoryStream referring to the mmap'ed portion
// of the assembly. The pointers here are pointers into that block of
// memory controlled by the OS's loader.
private int[] _nameHashes; // hash values for all names.
private unsafe int* _nameHashesPtr; // In case we're using UnmanagedMemoryStream
private int[] _namePositions; // relative locations of names
private unsafe int* _namePositionsPtr; // If we're using UnmanagedMemoryStream
private Type[] _typeTable; // Lazy array of Types for resource values.
private int[] _typeNamePositions; // To delay initialize type table
private int _numResources; // Num of resources files, in case arrays aren't allocated.
// We'll include a separate code path that uses UnmanagedMemoryStream to
// avoid allocating String objects and the like.
private UnmanagedMemoryStream _ums;
// Version number of .resources file, for compatibility
private int _version;
public ResourceReader(string fileName)
{
_resCache = new Dictionary<string, ResourceLocator>(FastResourceComparer.Default);
_store = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.RandomAccess), Encoding.UTF8);
try
{
ReadResources();
}
catch
{
_store.Close(); // If we threw an exception, close the file.
throw;
}
}
public ResourceReader(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable);
_resCache = new Dictionary<string, ResourceLocator>(FastResourceComparer.Default);
_store = new BinaryReader(stream, Encoding.UTF8);
// We have a faster code path for reading resource files from an assembly.
_ums = stream as UnmanagedMemoryStream;
ReadResources();
}
// This is the constructor the RuntimeResourceSet calls,
// passing in the stream to read from and the RuntimeResourceSet's
// internal hash table (hash table of names with file offsets
// and values, coupled to this ResourceReader).
internal ResourceReader(Stream stream, Dictionary<string, ResourceLocator> resCache)
{
Debug.Assert(stream != null, "Need a stream!");
Debug.Assert(stream.CanRead, "Stream should be readable!");
Debug.Assert(resCache != null, "Need a Dictionary!");
_resCache = resCache;
_store = new BinaryReader(stream, Encoding.UTF8);
_ums = stream as UnmanagedMemoryStream;
ReadResources();
}
public void Close()
{
Dispose(true);
}
public void Dispose()
{
Close();
}
private unsafe void Dispose(bool disposing)
{
if (_store != null)
{
_resCache = null;
if (disposing)
{
// Close the stream in a thread-safe way. This fix means
// that we may call Close n times, but that's safe.
BinaryReader copyOfStore = _store;
_store = null;
if (copyOfStore != null)
copyOfStore.Close();
}
_store = null;
_namePositions = null;
_nameHashes = null;
_ums = null;
_namePositionsPtr = null;
_nameHashesPtr = null;
}
}
internal static unsafe int ReadUnalignedI4(int* p)
{
byte* buffer = (byte*)p;
// Unaligned, little endian format
return buffer[0] | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24);
}
private void SkipString()
{
int stringLength = _store.Read7BitEncodedInt();
if (stringLength < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
_store.BaseStream.Seek(stringLength, SeekOrigin.Current);
}
private unsafe int GetNameHash(int index)
{
Debug.Assert(index >= 0 && index < _numResources, "Bad index into hash array. index: " + index);
Debug.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) ||
(_ums != null && _nameHashes == null && _nameHashesPtr != null), "Internal state mangled.");
if (_ums == null)
return _nameHashes[index];
else
return ReadUnalignedI4(&_nameHashesPtr[index]);
}
private unsafe int GetNamePosition(int index)
{
Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index);
Debug.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) ||
(_ums != null && _namePositions == null && _namePositionsPtr != null), "Internal state mangled.");
int r;
if (_ums == null)
r = _namePositions[index];
else
r = ReadUnalignedI4(&_namePositionsPtr[index]);
if (r < 0 || r > _dataSectionOffset - _nameSectionOffset)
{
throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, r));
}
return r;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IDictionaryEnumerator GetEnumerator()
{
if (_resCache == null)
throw new InvalidOperationException(SR.ResourceReaderIsClosed);
return new ResourceEnumerator(this);
}
internal ResourceEnumerator GetEnumeratorInternal()
{
return new ResourceEnumerator(this);
}
// From a name, finds the associated virtual offset for the data.
// To read the data, seek to _dataSectionOffset + dataPos, then
// read the resource type & data.
// This does a binary search through the names.
internal int FindPosForResource(string name)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
int hash = FastResourceComparer.HashFunction(name);
// Binary search over the hashes. Use the _namePositions array to
// determine where they exist in the underlying stream.
int lo = 0;
int hi = _numResources - 1;
int index = -1;
bool success = false;
while (lo <= hi)
{
index = (lo + hi) >> 1;
// Do NOT use subtraction here, since it will wrap for large
// negative numbers.
int currentHash = GetNameHash(index);
int c;
if (currentHash == hash)
c = 0;
else if (currentHash < hash)
c = -1;
else
c = 1;
if (c == 0)
{
success = true;
break;
}
if (c < 0)
lo = index + 1;
else
hi = index - 1;
}
if (!success)
{
return -1;
}
// index is the location in our hash array that corresponds with a
// value in the namePositions array.
// There could be collisions in our hash function. Check on both sides
// of index to find the range of hash values that are equal to the
// target hash value.
if (lo != index)
{
lo = index;
while (lo > 0 && GetNameHash(lo - 1) == hash)
lo--;
}
if (hi != index)
{
hi = index;
while (hi < _numResources - 1 && GetNameHash(hi + 1) == hash)
hi++;
}
lock (this)
{
for (int i = lo; i <= hi; i++)
{
_store.BaseStream.Seek(_nameSectionOffset + GetNamePosition(i), SeekOrigin.Begin);
if (CompareStringEqualsName(name))
{
int dataPos = _store.ReadInt32();
if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset)
{
throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataPos));
}
return dataPos;
}
}
}
return -1;
}
// This compares the String in the .resources file at the current position
// with the string you pass in.
// Whoever calls this method should make sure that they take a lock
// so no one else can cause us to seek in the stream.
private unsafe bool CompareStringEqualsName(string name)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
int byteLen = _store.Read7BitEncodedInt();
if (byteLen < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
if (_ums != null)
{
byte* bytes = _ums.PositionPointer;
// Skip over the data in the Stream, positioning ourselves right after it.
_ums.Seek(byteLen, SeekOrigin.Current);
if (_ums.Position > _ums.Length)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesNameTooLong);
}
// On 64-bit machines, these char*'s may be misaligned. Use a
// byte-by-byte comparison instead.
//return FastResourceComparer.CompareOrdinal((char*)bytes, byteLen/2, name) == 0;
return FastResourceComparer.CompareOrdinal(bytes, byteLen, name) == 0;
}
else
{
// This code needs to be fast
byte[] bytes = new byte[byteLen];
int numBytesToRead = byteLen;
while (numBytesToRead > 0)
{
int n = _store.Read(bytes, byteLen - numBytesToRead, numBytesToRead);
if (n == 0)
throw new BadImageFormatException(SR.BadImageFormat_ResourceNameCorrupted);
numBytesToRead -= n;
}
return FastResourceComparer.CompareOrdinal(bytes, byteLen / 2, name) == 0;
}
}
// This is used in the enumerator. The enumerator iterates from 0 to n
// of our resources and this returns the resource name for a particular
// index. The parameter is NOT a virtual offset.
private unsafe string AllocateStringForNameIndex(int index, out int dataOffset)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
byte[] bytes;
int byteLen;
long nameVA = GetNamePosition(index);
lock (this)
{
_store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
// Can't use _store.ReadString, since it's using UTF-8!
byteLen = _store.Read7BitEncodedInt();
if (byteLen < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
if (_ums != null)
{
if (_ums.Position > _ums.Length - byteLen)
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourcesIndexTooLong, index));
string s = null;
char* charPtr = (char*)_ums.PositionPointer;
s = new string(charPtr, 0, byteLen / 2);
_ums.Position += byteLen;
dataOffset = _store.ReadInt32();
if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset)
{
throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataOffset));
}
return s;
}
bytes = new byte[byteLen];
// We must read byteLen bytes, or we have a corrupted file.
// Use a blocking read in case the stream doesn't give us back
// everything immediately.
int count = byteLen;
while (count > 0)
{
int n = _store.Read(bytes, byteLen - count, count);
if (n == 0)
throw new EndOfStreamException(SR.Format(SR.BadImageFormat_ResourceNameCorrupted_NameIndex, index));
count -= n;
}
dataOffset = _store.ReadInt32();
if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset)
{
throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataOffset));
}
}
return Encoding.Unicode.GetString(bytes, 0, byteLen);
}
// This is used in the enumerator. The enumerator iterates from 0 to n
// of our resources and this returns the resource value for a particular
// index. The parameter is NOT a virtual offset.
private object GetValueForNameIndex(int index)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock (this)
{
_store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
SkipString();
int dataPos = _store.ReadInt32();
if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset)
{
throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataPos));
}
ResourceTypeCode junk;
if (_version == 1)
return LoadObjectV1(dataPos);
else
return LoadObjectV2(dataPos, out junk);
}
}
// This takes a virtual offset into the data section and reads a String
// from that location.
// Anyone who calls LoadObject should make sure they take a lock so
// no one can cause us to do a seek in here.
internal string LoadString(int pos)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
_store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
string s = null;
int typeIndex = _store.Read7BitEncodedInt();
if (_version == 1)
{
if (typeIndex == -1)
return null;
if (FindType(typeIndex) != typeof(string))
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Type, FindType(typeIndex).FullName));
s = _store.ReadString();
}
else
{
ResourceTypeCode typeCode = (ResourceTypeCode)typeIndex;
if (typeCode != ResourceTypeCode.String && typeCode != ResourceTypeCode.Null)
{
string typeString;
if (typeCode < ResourceTypeCode.StartOfUserTypes)
typeString = typeCode.ToString();
else
typeString = FindType(typeCode - ResourceTypeCode.StartOfUserTypes).FullName;
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Type, typeString));
}
if (typeCode == ResourceTypeCode.String) // ignore Null
s = _store.ReadString();
}
return s;
}
// Called from RuntimeResourceSet
internal object LoadObject(int pos)
{
if (_version == 1)
return LoadObjectV1(pos);
ResourceTypeCode typeCode;
return LoadObjectV2(pos, out typeCode);
}
internal object LoadObject(int pos, out ResourceTypeCode typeCode)
{
if (_version == 1)
{
object o = LoadObjectV1(pos);
typeCode = (o is string) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes;
return o;
}
return LoadObjectV2(pos, out typeCode);
}
// This takes a virtual offset into the data section and reads an Object
// from that location.
// Anyone who calls LoadObject should make sure they take a lock so
// no one can cause us to do a seek in here.
internal object LoadObjectV1(int pos)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!");
try
{
// mega try-catch performs exceptionally bad on x64; factored out body into
// _LoadObjectV1 and wrap here.
return _LoadObjectV1(pos);
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof);
}
catch (ArgumentOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e);
}
}
private object _LoadObjectV1(int pos)
{
_store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
int typeIndex = _store.Read7BitEncodedInt();
if (typeIndex == -1)
return null;
Type type = FindType(typeIndex);
// Consider putting in logic to see if this type is a
// primitive or a value type first, so we can reach the
// deserialization code faster for arbitrary objects.
if (type == typeof(string))
return _store.ReadString();
else if (type == typeof(int))
return _store.ReadInt32();
else if (type == typeof(byte))
return _store.ReadByte();
else if (type == typeof(sbyte))
return _store.ReadSByte();
else if (type == typeof(short))
return _store.ReadInt16();
else if (type == typeof(long))
return _store.ReadInt64();
else if (type == typeof(ushort))
return _store.ReadUInt16();
else if (type == typeof(uint))
return _store.ReadUInt32();
else if (type == typeof(ulong))
return _store.ReadUInt64();
else if (type == typeof(float))
return _store.ReadSingle();
else if (type == typeof(double))
return _store.ReadDouble();
else if (type == typeof(DateTime))
{
// Ideally we should use DateTime's ToBinary & FromBinary,
// but we can't for compatibility reasons.
return new DateTime(_store.ReadInt64());
}
else if (type == typeof(TimeSpan))
return new TimeSpan(_store.ReadInt64());
else if (type == typeof(decimal))
{
int[] bits = new int[4];
for (int i = 0; i < bits.Length; i++)
bits[i] = _store.ReadInt32();
return new decimal(bits);
}
else
{
throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization);
}
}
internal object LoadObjectV2(int pos, out ResourceTypeCode typeCode)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!");
try
{
// mega try-catch performs exceptionally bad on x64; factored out body into
// _LoadObjectV2 and wrap here.
return _LoadObjectV2(pos, out typeCode);
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof);
}
catch (ArgumentOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e);
}
}
private object _LoadObjectV2(int pos, out ResourceTypeCode typeCode)
{
_store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt();
switch (typeCode)
{
case ResourceTypeCode.Null:
return null;
case ResourceTypeCode.String:
return _store.ReadString();
case ResourceTypeCode.Boolean:
return _store.ReadBoolean();
case ResourceTypeCode.Char:
return (char)_store.ReadUInt16();
case ResourceTypeCode.Byte:
return _store.ReadByte();
case ResourceTypeCode.SByte:
return _store.ReadSByte();
case ResourceTypeCode.Int16:
return _store.ReadInt16();
case ResourceTypeCode.UInt16:
return _store.ReadUInt16();
case ResourceTypeCode.Int32:
return _store.ReadInt32();
case ResourceTypeCode.UInt32:
return _store.ReadUInt32();
case ResourceTypeCode.Int64:
return _store.ReadInt64();
case ResourceTypeCode.UInt64:
return _store.ReadUInt64();
case ResourceTypeCode.Single:
return _store.ReadSingle();
case ResourceTypeCode.Double:
return _store.ReadDouble();
case ResourceTypeCode.Decimal:
return _store.ReadDecimal();
case ResourceTypeCode.DateTime:
// Use DateTime's ToBinary & FromBinary.
long data = _store.ReadInt64();
return DateTime.FromBinary(data);
case ResourceTypeCode.TimeSpan:
long ticks = _store.ReadInt64();
return new TimeSpan(ticks);
// Special types
case ResourceTypeCode.ByteArray:
{
int len = _store.ReadInt32();
if (len < 0)
{
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
}
if (_ums == null)
{
if (len > _store.BaseStream.Length)
{
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
}
return _store.ReadBytes(len);
}
if (len > _ums.Length - _ums.Position)
{
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
}
byte[] bytes = new byte[len];
int r = _ums.Read(bytes, 0, len);
Debug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)");
return bytes;
}
case ResourceTypeCode.Stream:
{
int len = _store.ReadInt32();
if (len < 0)
{
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
}
if (_ums == null)
{
byte[] bytes = _store.ReadBytes(len);
// Lifetime of memory == lifetime of this stream.
return new PinnedBufferMemoryStream(bytes);
}
// make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream.
if (len > _ums.Length - _ums.Position)
{
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
}
// For the case that we've memory mapped in the .resources
// file, just return a Stream pointing to that block of memory.
unsafe
{
return new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read);
}
}
default:
if (typeCode < ResourceTypeCode.StartOfUserTypes)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch);
}
break;
}
// Normal serialized objects
throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization);
}
// Reads in the header information for a .resources file. Verifies some
// of the assumptions about this resource set, and builds the class table
// for the default resource file format.
private void ReadResources()
{
Debug.Assert(_store != null, "ResourceReader is closed!");
try
{
// mega try-catch performs exceptionally bad on x64; factored out body into
// _ReadResources and wrap here.
_ReadResources();
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, eof);
}
catch (IndexOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, e);
}
}
private void _ReadResources()
{
// Read ResourceManager header
// Check for magic number
int magicNum = _store.ReadInt32();
if (magicNum != ResourceManager.MagicNumber)
throw new ArgumentException(SR.Resources_StreamNotValid);
// Assuming this is ResourceManager header V1 or greater, hopefully
// after the version number there is a number of bytes to skip
// to bypass the rest of the ResMgr header. For V2 or greater, we
// use this to skip to the end of the header
int resMgrHeaderVersion = _store.ReadInt32();
int numBytesToSkip = _store.ReadInt32();
if (numBytesToSkip < 0 || resMgrHeaderVersion < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
if (resMgrHeaderVersion > 1)
{
_store.BaseStream.Seek(numBytesToSkip, SeekOrigin.Current);
}
else
{
// We don't care about numBytesToSkip; read the rest of the header
// Read in type name for a suitable ResourceReader
// Note ResourceWriter & InternalResGen use different Strings.
string readerType = _store.ReadString();
readerType = System.CoreLib.FixupCoreLibName(readerType);
AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName);
if (!ResourceManager.CompareNames(readerType, ResourceManager.ResReaderTypeName, mscorlib))
throw new NotSupportedException(SR.Format(SR.NotSupported_WrongResourceReader_Type, readerType));
// Skip over type name for a suitable ResourceSet
SkipString();
}
// Read RuntimeResourceSet header
// Do file version check
int version = _store.ReadInt32();
if (version != RuntimeResourceSet.Version && version != 1)
throw new ArgumentException(SR.Format(SR.Arg_ResourceFileUnsupportedVersion, RuntimeResourceSet.Version, version));
_version = version;
_numResources = _store.ReadInt32();
if (_numResources < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
// Read type positions into type positions array.
// But delay initialize the type table.
int numTypes = _store.ReadInt32();
if (numTypes < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_typeTable = new Type[numTypes];
_typeNamePositions = new int[numTypes];
for (int i = 0; i < numTypes; i++)
{
_typeNamePositions[i] = (int)_store.BaseStream.Position;
// Skip over the Strings in the file. Don't create types.
SkipString();
}
// Prepare to read in the array of name hashes
// Note that the name hashes array is aligned to 8 bytes so
// we can use pointers into it on 64 bit machines. (4 bytes
// may be sufficient, but let's plan for the future)
// Skip over alignment stuff. All public .resources files
// should be aligned No need to verify the byte values.
long pos = _store.BaseStream.Position;
int alignBytes = ((int)pos) & 7;
if (alignBytes != 0)
{
for (int i = 0; i < 8 - alignBytes; i++)
{
_store.ReadByte();
}
}
// Read in the array of name hashes
if (_ums == null)
{
_nameHashes = new int[_numResources];
for (int i = 0; i < _numResources; i++)
{
_nameHashes[i] = _store.ReadInt32();
}
}
else
{
int seekPos = unchecked(4 * _numResources);
if (seekPos < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
unsafe
{
_nameHashesPtr = (int*)_ums.PositionPointer;
// Skip over the array of nameHashes.
_ums.Seek(seekPos, SeekOrigin.Current);
// get the position pointer once more to check that the whole table is within the stream
byte* junk = _ums.PositionPointer;
}
}
// Read in the array of relative positions for all the names.
if (_ums == null)
{
_namePositions = new int[_numResources];
for (int i = 0; i < _numResources; i++)
{
int namePosition = _store.ReadInt32();
if (namePosition < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_namePositions[i] = namePosition;
}
}
else
{
int seekPos = unchecked(4 * _numResources);
if (seekPos < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
unsafe
{
_namePositionsPtr = (int*)_ums.PositionPointer;
// Skip over the array of namePositions.
_ums.Seek(seekPos, SeekOrigin.Current);
// get the position pointer once more to check that the whole table is within the stream
byte* junk = _ums.PositionPointer;
}
}
// Read location of data section.
_dataSectionOffset = _store.ReadInt32();
if (_dataSectionOffset < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
// Store current location as start of name section
_nameSectionOffset = _store.BaseStream.Position;
// _nameSectionOffset should be <= _dataSectionOffset; if not, it's corrupt
if (_dataSectionOffset < _nameSectionOffset)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
}
// This allows us to delay-initialize the Type[]. This might be a
// good startup time savings, since we might have to load assemblies
// and initialize Reflection.
private Type FindType(int typeIndex)
{
if (typeIndex < 0 || typeIndex >= _typeTable.Length)
{
throw new BadImageFormatException(SR.BadImageFormat_InvalidType);
}
if (_typeTable[typeIndex] == null)
{
long oldPos = _store.BaseStream.Position;
try
{
_store.BaseStream.Position = _typeNamePositions[typeIndex];
string typeName = _store.ReadString();
_typeTable[typeIndex] = Type.GetType(typeName, true);
}
// If serialization isn't supported, we convert FileNotFoundException to
// NotSupportedException for consistency with v2. This is a corner-case, but the
// idea is that we want to give the user a more accurate error message. Even if
// the dependency were found, we know it will require serialization since it
// can't be one of the types we special case. So if the dependency were found,
// it would go down the serialization code path, resulting in NotSupported for
// SKUs without serialization.
//
// We don't want to regress the expected case by checking the type info before
// getting to Type.GetType -- this is costly with v1 resource formats.
catch (FileNotFoundException)
{
throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization);
}
finally
{
_store.BaseStream.Position = oldPos;
}
}
Debug.Assert(_typeTable[typeIndex] != null, "Should have found a type!");
return _typeTable[typeIndex];
}
public void GetResourceData(string resourceName, out string resourceType, out byte[] resourceData)
{
if (resourceName == null)
throw new ArgumentNullException(nameof(resourceName));
if (_resCache == null)
throw new InvalidOperationException(SR.ResourceReaderIsClosed);
// Get the type information from the data section. Also,
// sort all of the data section's indexes to compute length of
// the serialized data for this type (making sure to subtract
// off the length of the type code).
int[] sortedDataPositions = new int[_numResources];
int dataPos = FindPosForResource(resourceName);
if (dataPos == -1)
{
throw new ArgumentException(SR.Format(SR.Arg_ResourceNameNotExist, resourceName));
}
lock (this)
{
// Read all the positions of data within the data section.
for (int i = 0; i < _numResources; i++)
{
_store.BaseStream.Position = _nameSectionOffset + GetNamePosition(i);
// Skip over name of resource
int numBytesToSkip = _store.Read7BitEncodedInt();
if (numBytesToSkip < 0)
{
throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, numBytesToSkip));
}
_store.BaseStream.Position += numBytesToSkip;
int dPos = _store.ReadInt32();
if (dPos < 0 || dPos >= _store.BaseStream.Length - _dataSectionOffset)
{
throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dPos));
}
sortedDataPositions[i] = dPos;
}
Array.Sort(sortedDataPositions);
int index = Array.BinarySearch(sortedDataPositions, dataPos);
Debug.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!");
long nextData = (index < _numResources - 1) ? sortedDataPositions[index + 1] + _dataSectionOffset : _store.BaseStream.Length;
int len = (int)(nextData - (dataPos + _dataSectionOffset));
Debug.Assert(len >= 0 && len <= (int)_store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!");
// Read type code then byte[]
_store.BaseStream.Position = _dataSectionOffset + dataPos;
ResourceTypeCode typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt();
if (typeCode < 0 || typeCode >= ResourceTypeCode.StartOfUserTypes + _typeTable.Length)
{
throw new BadImageFormatException(SR.BadImageFormat_InvalidType);
}
resourceType = TypeNameFromTypeCode(typeCode);
// The length must be adjusted to subtract off the number
// of bytes in the 7 bit encoded type code.
len -= (int)(_store.BaseStream.Position - (_dataSectionOffset + dataPos));
byte[] bytes = _store.ReadBytes(len);
if (bytes.Length != len)
throw new FormatException(SR.BadImageFormat_ResourceNameCorrupted);
resourceData = bytes;
}
}
private string TypeNameFromTypeCode(ResourceTypeCode typeCode)
{
Debug.Assert(typeCode >= 0, "can't be negative");
if (typeCode < ResourceTypeCode.StartOfUserTypes)
{
Debug.Assert(!string.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers.");
return "ResourceTypeCode." + typeCode.ToString();
}
else
{
int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes;
Debug.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!");
long oldPos = _store.BaseStream.Position;
try
{
_store.BaseStream.Position = _typeNamePositions[typeIndex];
return _store.ReadString();
}
finally
{
_store.BaseStream.Position = oldPos;
}
}
}
internal sealed class ResourceEnumerator : IDictionaryEnumerator
{
private const int ENUM_DONE = int.MinValue;
private const int ENUM_NOT_STARTED = -1;
private ResourceReader _reader;
private bool _currentIsValid;
private int _currentName;
private int _dataPosition; // cached for case-insensitive table
internal ResourceEnumerator(ResourceReader reader)
{
_currentName = ENUM_NOT_STARTED;
_reader = reader;
_dataPosition = -2;
}
public bool MoveNext()
{
if (_currentName == _reader._numResources - 1 || _currentName == ENUM_DONE)
{
_currentIsValid = false;
_currentName = ENUM_DONE;
return false;
}
_currentIsValid = true;
_currentName++;
return true;
}
public object Key
{
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
return _reader.AllocateStringForNameIndex(_currentName, out _dataPosition);
}
}
public object Current
{
get
{
return Entry;
}
}
// Warning: This requires that you call the Key or Entry property FIRST before calling it!
internal int DataPosition
{
get
{
return _dataPosition;
}
}
public DictionaryEntry Entry
{
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
string key;
object value = null;
lock (_reader)
{ // locks should be taken in the same order as in RuntimeResourceSet.GetObject to avoid deadlock
lock (_reader._resCache)
{
key = _reader.AllocateStringForNameIndex(_currentName, out _dataPosition); // AllocateStringForNameIndex could lock on _reader
ResourceLocator locator;
if (_reader._resCache.TryGetValue(key, out locator))
{
value = locator.Value;
}
if (value == null)
{
if (_dataPosition == -1)
value = _reader.GetValueForNameIndex(_currentName);
else
value = _reader.LoadObject(_dataPosition);
// If enumeration and subsequent lookups happen very
// frequently in the same process, add a ResourceLocator
// to _resCache here. But WinForms enumerates and
// just about everyone else does lookups. So caching
// here may bloat working set.
}
}
}
return new DictionaryEntry(key, value);
}
}
public object Value
{
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
// Consider using _resCache here, eventually, if
// this proves to be an interesting perf scenario.
// But mixing lookups and enumerators shouldn't be
// particularly compelling.
return _reader.GetValueForNameIndex(_currentName);
}
}
public void Reset()
{
if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
_currentIsValid = false;
_currentName = ENUM_NOT_STARTED;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using GoCardless.Internals;
using GoCardless.Resources;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace GoCardless.Services
{
/// <summary>
/// Service class for working with mandate import resources.
///
/// Mandate Imports allow you to migrate existing mandates from other
/// providers into the
/// GoCardless platform.
///
/// The process is as follows:
///
/// 1. [Create a mandate
/// import](#mandate-imports-create-a-new-mandate-import)
/// 2. [Add entries](#mandate-import-entries-add-a-mandate-import-entry)
/// to the import
/// 3. [Submit](#mandate-imports-submit-a-mandate-import) the import
/// 4. Wait until a member of the GoCardless team approves the import, at
/// which point the mandates will be created
/// 5. [Link up the
/// mandates](#mandate-import-entries-list-all-mandate-import-entries) in
/// your system
///
/// When you add entries to your mandate import, they are not turned into
/// actual mandates
/// until the mandate import is submitted by you via the API, and then
/// processed by a member
/// of the GoCardless team. When that happens, a mandate will be created for
/// each entry in the import.
///
/// We will issue a `mandate_created` webhook for each entry, which will be
/// the same as the webhooks
/// triggered when [ creating a mandate ](#mandates-create-a-mandate) using
/// the mandates API. Once these
/// webhooks start arriving, any reconciliation can now be accomplished by
/// [checking the current status](#mandate-imports-get-a-mandate-import) of
/// the mandate import and
/// [linking up the mandates to your
/// system](#mandate-import-entries-list-all-mandate-import-entries).
///
/// <p class="notice">Note that all Mandate Imports have an upper limit of
/// 30,000 entries, so we recommend you split your import into several
/// smaller imports if you're planning to exceed this threshold.</p>
///
/// <p class="restricted-notice"><strong>Restricted</strong>: This API is
/// currently only available for approved integrators - please <a
/// href="mailto:help@gocardless.com">get in touch</a> if you would like to
/// use this API.</p>
/// </summary>
public class MandateImportService
{
private readonly GoCardlessClient _goCardlessClient;
/// <summary>
/// Constructor. Users of this library should not call this. An instance of this
/// class can be accessed through an initialised GoCardlessClient.
/// </summary>
public MandateImportService(GoCardlessClient goCardlessClient)
{
_goCardlessClient = goCardlessClient;
}
/// <summary>
/// Mandate imports are first created, before mandates are added
/// one-at-a-time, so
/// this endpoint merely signals the start of the import process. Once
/// you've finished
/// adding entries to an import, you should
/// [submit](#mandate-imports-submit-a-mandate-import) it.
/// </summary>
/// <param name="request">An optional `MandateImportCreateRequest` representing the body for this create request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single mandate import resource</returns>
public Task<MandateImportResponse> CreateAsync(MandateImportCreateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateImportCreateRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<MandateImportResponse>("POST", "/mandate_imports", urlParams, request, id => GetAsync(id, null, customiseRequestMessage), "mandate_imports", customiseRequestMessage);
}
/// <summary>
/// Returns a single mandate import.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "IM".</param>
/// <param name="request">An optional `MandateImportGetRequest` representing the query parameters for this get request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single mandate import resource</returns>
public Task<MandateImportResponse> GetAsync(string identity, MandateImportGetRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateImportGetRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<MandateImportResponse>("GET", "/mandate_imports/:identity", urlParams, request, null, null, customiseRequestMessage);
}
/// <summary>
/// Submits the mandate import, which allows it to be processed by a
/// member of the
/// GoCardless team. Once the import has been submitted, it can no
/// longer have entries
/// added to it.
///
/// In our sandbox environment, to aid development, we automatically
/// process mandate
/// imports approximately 10 seconds after they are submitted. This will
/// allow you to
/// test both the "submitted" response and wait for the webhook to
/// confirm the
/// processing has begun.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "IM".</param>
/// <param name="request">An optional `MandateImportSubmitRequest` representing the body for this submit request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single mandate import resource</returns>
public Task<MandateImportResponse> SubmitAsync(string identity, MandateImportSubmitRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateImportSubmitRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<MandateImportResponse>("POST", "/mandate_imports/:identity/actions/submit", urlParams, request, null, "data", customiseRequestMessage);
}
/// <summary>
/// Cancels the mandate import, which aborts the import process and
/// stops the mandates
/// being set up in GoCardless. Once the import has been cancelled, it
/// can no longer have
/// entries added to it. Mandate imports which have already been
/// submitted or processed
/// cannot be cancelled.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "IM".</param>
/// <param name="request">An optional `MandateImportCancelRequest` representing the body for this cancel request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single mandate import resource</returns>
public Task<MandateImportResponse> CancelAsync(string identity, MandateImportCancelRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateImportCancelRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<MandateImportResponse>("POST", "/mandate_imports/:identity/actions/cancel", urlParams, request, null, "data", customiseRequestMessage);
}
}
/// <summary>
/// Mandate imports are first created, before mandates are added
/// one-at-a-time, so
/// this endpoint merely signals the start of the import process. Once
/// you've finished
/// adding entries to an import, you should
/// [submit](#mandate-imports-submit-a-mandate-import) it.
/// </summary>
public class MandateImportCreateRequest : IHasIdempotencyKey
{
/// <summary>
/// A Direct Debit scheme. Currently "ach", "autogiro", "bacs", "becs",
/// "becs_nz", "betalingsservice", "pad" and "sepa_core" are supported.
/// </summary>
[JsonProperty("scheme")]
public MandateImportScheme? Scheme { get; set; }
/// <summary>
/// A Direct Debit scheme. Currently "ach", "autogiro", "bacs", "becs",
/// "becs_nz", "betalingsservice", "pad" and "sepa_core" are supported.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum MandateImportScheme
{
/// <summary>`scheme` with a value of "ach"</summary>
[EnumMember(Value = "ach")]
Ach,
/// <summary>`scheme` with a value of "autogiro"</summary>
[EnumMember(Value = "autogiro")]
Autogiro,
/// <summary>`scheme` with a value of "bacs"</summary>
[EnumMember(Value = "bacs")]
Bacs,
/// <summary>`scheme` with a value of "becs"</summary>
[EnumMember(Value = "becs")]
Becs,
/// <summary>`scheme` with a value of "becs_nz"</summary>
[EnumMember(Value = "becs_nz")]
BecsNz,
/// <summary>`scheme` with a value of "betalingsservice"</summary>
[EnumMember(Value = "betalingsservice")]
Betalingsservice,
/// <summary>`scheme` with a value of "pad"</summary>
[EnumMember(Value = "pad")]
Pad,
/// <summary>`scheme` with a value of "sepa_core"</summary>
[EnumMember(Value = "sepa_core")]
SepaCore,
}
/// <summary>
/// A unique key to ensure that this request only succeeds once, allowing you to safely retry request errors such as network failures.
/// Any requests, where supported, to create a resource with a key that has previously been used will not succeed.
/// See: https://developer.gocardless.com/api-reference/#making-requests-idempotency-keys
/// </summary>
[JsonIgnore]
public string IdempotencyKey { get; set; }
}
/// <summary>
/// Returns a single mandate import.
/// </summary>
public class MandateImportGetRequest
{
}
/// <summary>
/// Submits the mandate import, which allows it to be processed by a member
/// of the
/// GoCardless team. Once the import has been submitted, it can no longer
/// have entries
/// added to it.
///
/// In our sandbox environment, to aid development, we automatically process
/// mandate
/// imports approximately 10 seconds after they are submitted. This will
/// allow you to
/// test both the "submitted" response and wait for the webhook to confirm
/// the
/// processing has begun.
/// </summary>
public class MandateImportSubmitRequest
{
}
/// <summary>
/// Cancels the mandate import, which aborts the import process and stops
/// the mandates
/// being set up in GoCardless. Once the import has been cancelled, it can
/// no longer have
/// entries added to it. Mandate imports which have already been submitted
/// or processed
/// cannot be cancelled.
/// </summary>
public class MandateImportCancelRequest
{
}
/// <summary>
/// An API response for a request returning a single mandate import.
/// </summary>
public class MandateImportResponse : ApiResponse
{
/// <summary>
/// The mandate import from the response.
/// </summary>
[JsonProperty("mandate_imports")]
public MandateImport MandateImport { get; private set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using FlatRedBall.Utilities;
using System.Globalization;
using FlatRedBall.IO;
#if !FRB_RAW
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
#endif
namespace FlatRedBall.Instructions.Reflection
{
public struct PropertyValuePair
{
static Type stringType = typeof(string);
public string Property;
public object Value;
static Dictionary<string, Type> mUnqualifiedTypeDictionary = new Dictionary<string, Type>();
#if UWP
/// <summary>
/// Stores a reference to the current assembly. This is the
/// assembly of your game. This must be explicitly set.
/// </summary>
public static Assembly TopLevelAssembly
{
get;
set;
}
#endif
public static List<Assembly> AdditionalAssemblies
{
get;
private set;
}
static PropertyValuePair()
{
AdditionalAssemblies = new List<Assembly>();
}
public PropertyValuePair(string property, object value)
{
Property = property;
Value = value;
}
public static string ConvertTypeToString(object value)
{
if (value == null) return string.Empty;
// Get the type
Type typeToConvertTo = value.GetType();
// Do the conversion
#region Convert To String
if (typeToConvertTo == typeof(bool))
{
return ((bool)value).ToString();
}
if (typeToConvertTo == typeof(int) || typeToConvertTo == typeof(Int32) || typeToConvertTo == typeof(Int16))
{
return ((int)value).ToString();
}
if (typeToConvertTo == typeof(float) || typeToConvertTo == typeof(Single))
{
return ((float)value).ToString(CultureInfo.InvariantCulture);
}
if (typeToConvertTo == typeof(double))
{
return ((double)value).ToString(CultureInfo.InvariantCulture);
}
if(typeToConvertTo == typeof(decimal))
{
return ((decimal)value).ToString(CultureInfo.InvariantCulture);
}
if (typeToConvertTo == typeof(string))
{
return (string)value;
}
#if !FRB_RAW
if (typeToConvertTo == typeof(Texture2D))
{
return ((Texture2D)value).Name;
}
if (typeToConvertTo == typeof(Matrix))
{
Matrix m = (Matrix)value;
float[] values = new float[16];
values[0] = m.M11;
values[1] = m.M12;
values[2] = m.M13;
values[3] = m.M14;
values[4] = m.M21;
values[5] = m.M22;
values[6] = m.M23;
values[7] = m.M24;
values[8] = m.M31;
values[9] = m.M32;
values[10] = m.M33;
values[11] = m.M34;
values[12] = m.M41;
values[13] = m.M42;
values[14] = m.M43;
values[15] = m.M44;
string outputString = string.Empty;
// output values in comma-delimited form
for (int i = 0; i < values.Length; i++)
{
outputString += ((i == 0) ? string.Empty : ",") +
ConvertTypeToString(values[i]);
}
return outputString;
}
if (typeToConvertTo == typeof(Vector2))
{
Vector2 v = (Vector2)value;
return ConvertTypeToString(v.X) + "," +
ConvertTypeToString(v.Y);
}
if (typeToConvertTo == typeof(Vector3))
{
Vector3 v = (Vector3)value;
return ConvertTypeToString(v.X) + "," +
ConvertTypeToString(v.Y) + "," +
ConvertTypeToString(v.Z);
}
if (typeToConvertTo == typeof(Vector4))
{
Vector4 v = (Vector4)value;
return ConvertTypeToString(v.X) + "," +
ConvertTypeToString(v.Y) + "," +
ConvertTypeToString(v.Z) + "," +
ConvertTypeToString(v.W);
}
#endif
#if UWP
if (typeToConvertTo.IsEnum())
#else
if (typeToConvertTo.IsEnum)
#endif
{
return value.ToString();
}
#endregion
// No cases matched, return empty string
return String.Empty;
}
public static T ConvertStringToType<T>(string value)
{
return (T)ConvertStringToType(value, typeof(T));
}
public static object ConvertStringToType(string value, string qualifiedTypeName)
{
// use "Global" so this file can be used outside of FRB proper
return ConvertStringValueToValueOfType(value, qualifiedTypeName, null, "Global", trimQuotes:false);
}
public static object ConvertStringToType(string value, Type typeToConvertTo)
{
#if FRB_RAW
return ConvertStringToType(value, typeToConvertTo, "Global");
#else
return ConvertStringToType(value, typeToConvertTo, FlatRedBallServices.GlobalContentManager);
#endif
}
public static object ConvertStringToType(string value, Type typeToConvertTo, string contentManagerName)
{
return ConvertStringToType(value, typeToConvertTo, contentManagerName, false);
}
public static object ConvertStringToType(string value, Type typeToConvertTo, string contentManagerName, bool trimQuotes)
{
if (IsGenericList(typeToConvertTo))
{
return CreateGenericListFrom(value, typeToConvertTo, contentManagerName);
}
else
{
return ConvertStringValueToValueOfType(value, typeToConvertTo.FullName, typeToConvertTo, contentManagerName, trimQuotes);
}
}
public static object ConvertStringValueToValueOfType(string value, string desiredType, Type alreadyKnownType, string contentManagerName, bool trimQuotes)
{
value = value.Trim(); // this is in case there is a space in front - I don't think we need it.
//Fix any exported CSV bugs (such as quotes around a boolean)
if (trimQuotes ||
(value != null && (desiredType != typeof(string).FullName && desiredType != typeof(char).FullName)
&& value.Contains("\"") == false) // If it has a quote, then we don't want to trim.
)
{
if (!value.StartsWith("new ") && desiredType != typeof(string).FullName)
{
value = FlatRedBall.Utilities.StringFunctions.RemoveWhitespace(value);
}
value = value.Replace("\"", "");
}
// Do the conversion
#region Convert To Object
// String needs to be first because it could contain equals and
// we don't want to cause problems
bool handled = false;
object toReturn = null;
if (desiredType == typeof(string).FullName)
{
toReturn = value;
handled = true;
}
if (!handled)
{
TryHandleComplexType(value, desiredType, alreadyKnownType, out handled, out toReturn);
}
if (!handled)
{
#region bool
if (desiredType == typeof(bool).FullName)
{
if (string.IsNullOrEmpty(value))
{
return false;
}
// value could be upper case like "TRUE" or "True". Make it lower
value = value.ToLower();
toReturn = bool.Parse(value);
handled = true;
}
else if(desiredType == typeof(bool?).FullName)
{
if(string.IsNullOrEmpty(value))
{
toReturn = (bool?)null;
handled = true;
}
else
{
value = value.ToLower();
toReturn = bool.Parse(value);
handled = true;
}
}
#endregion
#region int, Int32, Int16, uint, long
else if (desiredType == typeof(int).FullName || desiredType == typeof(Int32).FullName || desiredType == typeof(Int16).FullName ||
desiredType == typeof(uint).FullName || desiredType == typeof(long).FullName || desiredType == typeof(byte).FullName)
{
if (string.IsNullOrEmpty(value))
{
return 0;
}
int indexOfDecimal = value.IndexOf('.');
if (value.IndexOf(",") != -1)
{
value = value.Replace(",", "");
}
#region uint
#if FRB_XNA
if (desiredType == typeof(uint).FullName)
{
if (indexOfDecimal == -1)
{
return uint.Parse(value);
}
else
{
return (uint)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endif
#endregion
#region byte
#if FRB_XNA
if (desiredType == typeof(byte).FullName)
{
if (indexOfDecimal == -1)
{
return byte.Parse(value);
}
else
{
return (byte)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endif
#endregion
#region long
if (desiredType == typeof(long).FullName)
{
if (indexOfDecimal == -1)
{
return long.Parse(value);
}
#if FRB_XNA
else
{
return (long)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
#endif
}
#endregion
#region regular int
else
{
if (indexOfDecimal == -1)
{
return int.Parse(value);
}
#if FRB_XNA
else
{
return (int)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
#endif
}
#endregion
}
else if(desiredType == typeof(int?).FullName)
{
if(string.IsNullOrWhiteSpace(value))
{
toReturn = (int?)null;
handled = true;
}
else
{
handled = true;
toReturn = int.Parse(value);
}
}
#endregion
#region float, Single
else if (desiredType == typeof(float).FullName || desiredType == typeof(Single).FullName)
{
if (string.IsNullOrEmpty(value))
{
return 0f;
}
return float.Parse(value, CultureInfo.InvariantCulture);
}
else if (desiredType == typeof(float?).FullName)
{
if (string.IsNullOrWhiteSpace(value))
{
toReturn = (float?)null;
handled = true;
}
else
{
handled = true;
toReturn = float.Parse(value, CultureInfo.InvariantCulture);
}
}
#endregion
#region double
else if (desiredType == typeof(double).FullName)
{
if (string.IsNullOrEmpty(value))
{
return 0.0;
}
return double.Parse(value, CultureInfo.InvariantCulture);
}
#endregion
else if(desiredType == typeof(double?).FullName)
{
if (string.IsNullOrWhiteSpace(value))
{
toReturn = (double?)null;
handled = true;
}
else
{
handled = true;
toReturn = double.Parse(value);
}
}
#region Decimal
else if(desiredType == typeof(decimal).FullName)
{
if (string.IsNullOrEmpty(value))
{
return 0.0m;
}
return decimal.Parse(value, CultureInfo.InvariantCulture);
}
#endregion
else if(desiredType == typeof(DateTime).FullName)
{
//return DateTime.Parse(value);
var parsedDateTime = DateTime.Parse(value, null, DateTimeStyles.RoundtripKind);
return parsedDateTime;
}
#if !FRB_RAW
#region Texture2D
else if (desiredType == typeof(Texture2D).FullName)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
#if !SILVERLIGHT && !ZUNE
if (FileManager.IsRelative(value))
{
// Vic says: This used to throw an exception on relative values. I'm not quite
// sure why this is the case...why don't we just make it relative to the relative
// directory? Maybe there's a reason to have this exception, but I can't think of
// what it is, and I'm writing a tutorial on how to load Texture2Ds from CSVs right
// now and it totally makes sense that the user would want to use a relative directory.
// In fact, the user will want to always use a relative directory so that their project is
// portable.
//throw new ArgumentException("Texture path must be absolute to load texture. Path: " + value);
value = FileManager.RelativeDirectory + value;
}
// Try to load a compiled asset first
if (FileManager.FileExists(FileManager.RemoveExtension(value) + @".xnb"))
{
Texture2D texture =
FlatRedBallServices.Load<Texture2D>(FileManager.RemoveExtension(value), contentManagerName);
// Vic asks: Why did we have to set the name? This is redundant and gets
// rid of the standardized file name which causes caching to not work properly.
// texture.Name = FileManager.RemoveExtension(value);
return texture;
}
else
{
Texture2D texture =
FlatRedBallServices.Load<Texture2D>(value, contentManagerName);
// Vic asks: Why did we have to set the name? This is redundant and gets
// rid of the standardized file name which causes caching to not work properly.
// texture.Name = value;
return texture;
}
#else
return null;
#endif
}
#endregion
#region Matrix
else if (desiredType == typeof(Matrix).FullName)
{
if (string.IsNullOrEmpty(value))
{
return Matrix.Identity;
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 16)
{
throw new ArgumentException("String to Matrix conversion requires 16 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[16];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
// Parse to matrix
Matrix m = new Matrix(
values[0], values[1], values[2], values[3],
values[4], values[5], values[6], values[7],
values[8], values[9], values[10], values[11],
values[12], values[13], values[14], values[15]
);
return m;
}
#endregion
#region Vector2
else if (desiredType == typeof(Vector2).FullName)
{
if (string.IsNullOrEmpty(value))
{
return new Vector2(0, 0);
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 2)
{
throw new ArgumentException("String to Vector2 conversion requires 2 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[2];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
return new Vector2(values[0], values[1]);
}
#endregion
#region Vector3
else if (desiredType == typeof(Vector3).FullName)
{
if (string.IsNullOrEmpty(value))
{
return new Vector3(0, 0, 0);
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 3)
{
throw new ArgumentException("String to Vector3 conversion requires 3 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[3];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
return new Vector3(values[0], values[1], values[2]);
}
#endregion
#region Vector4
else if (desiredType == typeof(Vector4).FullName)
{
if (string.IsNullOrEmpty(value))
{
return new Vector4(0, 0, 0, 0);
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 4)
{
throw new ArgumentException("String to Vector4 conversion requires 4 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[4];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
return new Vector4(values[0], values[1], values[2], values[3]);
}
#endregion
#endif
#region enum
else if (IsEnum(desiredType))
{
#if DEBUG
if (string.IsNullOrEmpty(value))
{
throw new InvalidOperationException("Error trying to create enum value for empty string. Enum type: " + desiredType);
}
#endif
bool ignoreCase = true; // 3rd arugment needed for 360
Type foundType;
if (mUnqualifiedTypeDictionary.ContainsKey(desiredType))
{
foundType = mUnqualifiedTypeDictionary[desiredType];
}
else
{
foundType = TryToGetTypeFromAssemblies(desiredType);
}
return Enum.Parse(foundType, value, ignoreCase); // built-in .NET version
//return StringEnum.Parse(typeToConvertTo, value);
}
#endregion
#region Color
#if FRB_XNA
else if (desiredType == typeof(Color).FullName)
{
#if WINDOWS_8 || UWP
PropertyInfo info = typeof(Color).GetProperty(value);
#else
PropertyInfo info = typeof(Color).GetProperty(value, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
#endif
if (info == null)
{
if (value.StartsWith("Color."))
{
throw new Exception("Could not parse the value " + value + ". Remove \"Color.\" and instead " +
"use " + value.Substring("Color.".Length));
}
else
{
throw new Exception("Could not parse " + value + " as a Color");
}
}
toReturn = info.GetValue(null, null);
handled = true;
}
#endif
#endregion
#endregion
// Why do we catch exceptions here? That seems baaaad
//catch (Exception)
//{
// //int m = 3;
//}
if (!handled)
{
throw new NotImplementedException("Cannot convert the value " + value + " to the type " +
desiredType.ToString());
}
}
return toReturn;
}
private static bool IsEnum(string typeAsString)
{
Type foundType = null;
if (mUnqualifiedTypeDictionary.ContainsKey(typeAsString))
{
foundType = mUnqualifiedTypeDictionary[typeAsString];
}
else
{
foundType = TryToGetTypeFromAssemblies(typeAsString);
}
return foundType != null &&
#if WINDOWS_8 || UWP
foundType.IsEnum();
#else
foundType.IsEnum;
#endif
}
private static void TryHandleComplexType(string value, string typeName, Type alreadyKnownType, out bool handled, out object toReturn)
{
handled = false;
toReturn = null;
if (value.StartsWith("new "))
{
string typeAfterNewString = value.Substring("new ".Length, value.IndexOf('(') - "new ".Length);
Type foundType = alreadyKnownType;
if(foundType == null)
{
if (mUnqualifiedTypeDictionary.ContainsKey(typeAfterNewString))
{
foundType = mUnqualifiedTypeDictionary[typeAfterNewString];
}
else
{
foundType = TryToGetTypeFromAssemblies(typeAfterNewString);
}
}
if (foundType != null)
{
int openingParen = value.IndexOf('(');
// Make sure to get the last parenthesis, in case one of the inner properties is a complex type
int closingParen = value.LastIndexOf(')');
// Make sure valid parenthesis were found
if (openingParen < 0 || closingParen < 0)
throw new InvalidOperationException("Type definition did not have a matching pair of opening and closing parenthesis");
if (openingParen > closingParen)
throw new InvalidOperationException("Type definition has parenthesis in the incorrect order");
string valueInsideParens = value.Substring(openingParen + 1, closingParen - (openingParen + 1));
toReturn = CreateInstanceFromNamedAssignment(foundType, valueInsideParens);
}
else
{
throw new InvalidOperationException("Could not find a type in the assemblies for " + foundType);
}
handled = true;
}
else if (value.Contains("="))
{
// They're using the "x=0,y=0,z=0" syntax
handled = true;
Type foundType = alreadyKnownType;
if(foundType == null)
{
if (mUnqualifiedTypeDictionary.ContainsKey(typeName))
{
foundType = mUnqualifiedTypeDictionary[typeName];
}
else
{
foundType = TryToGetTypeFromAssemblies(typeName);
}
}
toReturn = CreateInstanceFromNamedAssignment(foundType, value);
}
}
public static List<string> SplitProperties(string value)
{
var splitOnComma = value.Split(',');
List<string> toReturn = new List<string>();
// We may have a List declaration, or a string with commas in it, so we need to account for that
// For now I'm going to handle the list declaration because that's what I need for Baron, but will
// eventually return to this and make it more robust to handle strings with commas too.
int parenCount = 0;
int quoteCount = 0;
foreach (string entryInSplit in splitOnComma)
{
bool shouldCombine = parenCount != 0 || quoteCount != 0;
parenCount += entryInSplit.CountOf("(");
parenCount -= entryInSplit.CountOf(")");
quoteCount += entryInSplit.CountOf("\"");
quoteCount = (quoteCount % 2);
if (shouldCombine)
{
toReturn[toReturn.Count - 1] = toReturn[toReturn.Count - 1] + ',' + entryInSplit;
}
else
{
toReturn.Add(entryInSplit);
}
}
return toReturn;
}
private static object CreateGenericListFrom(string value, Type listType, string contentManagerName)
{
object newObject = Activator.CreateInstance(listType);
Type genericType = listType.GetGenericArguments()[0];
MethodInfo add = listType.GetMethod("Add");
int start = value.IndexOf("(") + 1;
int end = value.IndexOf(")");
if (end > 0)
{
string insideOfParens = value.Substring(start, end - start);
// Cheat for now, make it more robust later
var values = SplitProperties(insideOfParens);
object[] arguments = new object[1];
foreach (var itemInList in values)
{
object converted = ConvertStringToType(itemInList, genericType, contentManagerName, true);
arguments[0] = converted;
add.Invoke(newObject, arguments);
}
}
return newObject;
}
private static Type TryToGetTypeFromAssemblies(string typeAfterNewString)
{
Type foundType = null;
#if WINDOWS_8 || UWP
foundType = TryToGetTypeFromAssembly(typeAfterNewString, FlatRedBallServices.Game.GetType().GetTypeInfo().Assembly);
if (foundType == null)
{
#if DEBUG
if (TopLevelAssembly == null)
{
throw new Exception("The TopLevelAssembly member must be set before it is used. It is currently null");
}
#endif
foundType = TryToGetTypeFromAssembly(typeAfterNewString, TopLevelAssembly);
}
if (foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, typeof(Vector3).GetTypeInfo().Assembly);
}
if(foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, typeof(FlatRedBall.Sprite).GetTypeInfo().Assembly);
}
#else
// This may be run from a tool. If so
// then there is no Game class, so we shouldn't
// try to use it.
#if FRB_XNA
if (FlatRedBallServices.Game != null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, FlatRedBallServices.Game.GetType().Assembly);
}
#endif
if (foundType == null)
{
foreach (var assembly in AdditionalAssemblies)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, assembly);
if (foundType != null)
{
break;
}
}
}
if(foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, Assembly.GetExecutingAssembly());
}
if (foundType == null)
{
#if WINDOWS
foundType = TryToGetTypeFromAssembly(typeAfterNewString, Assembly.GetEntryAssembly());
#endif
}
#if FRB_XNA
if(foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, typeof(Vector3).Assembly);
}
#endif
#endif
if (foundType == null)
{
throw new ArgumentException
("Could not find the type for " + typeAfterNewString +
"\nIf this is a type in your project, you may need to add the assembly to the PropertyValuePair.AdditionalAssemblies");
}
else
{
mUnqualifiedTypeDictionary.Add(typeAfterNewString, foundType);
}
return foundType;
}
private static Type TryToGetTypeFromAssembly(string typeAfterNewString, Assembly assembly)
{
Type foundType = null;
// Make sure the type isn't null, and the type string is trimmed to make the compare valid
if (typeAfterNewString == null)
return null;
typeAfterNewString = typeAfterNewString.Trim();
// Is this slow? Do we want to cache off the Type[]?
#if WINDOWS_8
IEnumerable<Type> types = assembly.ExportedTypes;
#else
IEnumerable<Type> types = assembly.GetTypes();
#endif
foreach (Type type in types)
{
if (type.Name == typeAfterNewString || type.FullName == typeAfterNewString)
{
foundType = type;
break;
}
}
return foundType;
}
private static object CreateInstanceFromNamedAssignment(Type type, string value)
{
object returnObject = null;
value = value.Trim();
returnObject = Activator.CreateInstance(type);
if (!string.IsNullOrEmpty(value))
{
var split = SplitProperties(value);
foreach (string assignment in split)
{
int indexOfEqual = assignment.IndexOf('=');
// If the assignment is not in the proper Name=Value format, ignore it
// Update - November 6, 2015
// This can hide syntax errors
// in the CSV. It allows cells to
// do things like: new Vectore(1,2,3)
// We want an error to be thrown so the
// user knows what to do to fix the CSV:
if (indexOfEqual < 0)
{
string message =
"Invalid value " + assignment + " in " + value + $". Expected a variable assignment like \"X={assignment}\" when creating an instance of {type.Name}";
throw new Exception(message);
}
// Make sure the = sign isn't the last character in the assignment
if (indexOfEqual >= assignment.Length - 1)
continue;
string variableName = assignment.Substring(0, indexOfEqual).Trim();
string whatToassignTo = assignment.Substring(indexOfEqual + 1, assignment.Length - (indexOfEqual + 1));
FieldInfo fieldInfo = type.GetField(variableName);
if (fieldInfo != null)
{
Type fieldType = fieldInfo.FieldType;
StripQuotesIfNecessary(ref whatToassignTo);
object assignValue = ConvertStringToType(whatToassignTo, fieldType);
fieldInfo.SetValue(returnObject, assignValue);
}
else
{
PropertyInfo propertyInfo = type.GetProperty(variableName);
#if DEBUG
if (propertyInfo == null)
{
throw new ArgumentException("Could not find the field/property " + variableName + " in the type " + type.Name);
}
#endif
Type propertyType = propertyInfo.PropertyType;
StripQuotesIfNecessary(ref whatToassignTo);
object assignValue = ConvertStringToType(whatToassignTo, propertyType);
propertyInfo.SetValue(returnObject, assignValue, null);
}
}
}
return returnObject;
}
public static bool IsGenericList(Type type)
{
bool isGenericList = false;
#if WINDOWS_8 || UWP
// Not sure why we check the declaring type. I think declaring
// type is for when a class is inside of another class
//if (type.DeclaringType.IsGenericParameter && (type.GetGenericTypeDefinition() == typeof(List<>)))
if (type.GetGenericTypeDefinition() == typeof(List<>))
#else
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>)))
#endif
{
isGenericList = true;
}
return isGenericList;
}
private static void StripQuotesIfNecessary(ref string whatToassignTo)
{
if (whatToassignTo != null)
{
string trimmed = whatToassignTo.Trim();
if (trimmed.StartsWith("\"") &&
trimmed.EndsWith("\"") && trimmed.Length > 1)
{
whatToassignTo = trimmed.Substring(1, trimmed.Length - 2);
}
}
}
//Remove any parenthesis at the start and end of the string.
private static string StripParenthesis(string value)
{
string result = value;
if (result.StartsWith("("))
{
int startIndex = 1;
int endIndex = result.Length - 1;
if (result.EndsWith(")"))
endIndex -= 1;
result = result.Substring(startIndex, endIndex);
}
return result;
}
public override string ToString()
{
return Property + " = " + Value;
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Iso9660
{
using System.IO;
using DiscUtils.Vfs;
/// <summary>
/// Class for reading existing ISO images.
/// </summary>
public class CDReader : VfsFileSystemFacade, IClusterBasedFileSystem, IUnixFileSystem
{
/// <summary>
/// Initializes a new instance of the CDReader class.
/// </summary>
/// <param name="data">The stream to read the ISO image from.</param>
/// <param name="joliet">Whether to read Joliet extensions.</param>
public CDReader(Stream data, bool joliet)
: base(new VfsCDReader(data, joliet, false))
{
}
/// <summary>
/// Initializes a new instance of the CDReader class.
/// </summary>
/// <param name="data">The stream to read the ISO image from.</param>
/// <param name="joliet">Whether to read Joliet extensions.</param>
/// <param name="hideVersions">Hides version numbers (e.g. ";1") from the end of files.</param>
public CDReader(Stream data, bool joliet, bool hideVersions)
: base(new VfsCDReader(data, joliet, hideVersions))
{
}
/// <summary>
/// Gets a value indicating whether a boot image is present.
/// </summary>
public bool HasBootImage
{
get
{
return GetRealFileSystem<VfsCDReader>().HasBootImage;
}
}
/// <summary>
/// Gets the emulation requested of BIOS when the image is loaded.
/// </summary>
public BootDeviceEmulation BootEmulation
{
get
{
return GetRealFileSystem<VfsCDReader>().BootEmulation;
}
}
/// <summary>
/// Gets the memory segment the image should be loaded into (0 for default).
/// </summary>
public int BootLoadSegment
{
get
{
return GetRealFileSystem<VfsCDReader>().BootLoadSegment;
}
}
/// <summary>
/// Gets the absolute start position (in bytes) of the boot image, or zero if not found.
/// </summary>
public long BootImageStart
{
get
{
return GetRealFileSystem<VfsCDReader>().BootImageStart;
}
}
/// <summary>
/// Gets the size (in bytes) of each cluster.
/// </summary>
public long ClusterSize
{
get { return GetRealFileSystem<VfsCDReader>().ClusterSize; }
}
/// <summary>
/// Gets the total number of clusters managed by the file system.
/// </summary>
public long TotalClusters
{
get { return GetRealFileSystem<VfsCDReader>().TotalClusters; }
}
/// <summary>
/// Gets which of the Iso9660 variants is being used.
/// </summary>
public Iso9660Variant ActiveVariant
{
get { return GetRealFileSystem<VfsCDReader>().ActiveVariant; }
}
/// <summary>
/// Detects if a stream contains a valid ISO file system.
/// </summary>
/// <param name="data">The stream to inspect.</param>
/// <returns><c>true</c> if the stream contains an ISO file system, else false.</returns>
public static bool Detect(Stream data)
{
byte[] buffer = new byte[IsoUtilities.SectorSize];
if (data.Length < 0x8000 + IsoUtilities.SectorSize)
{
return false;
}
data.Position = 0x8000;
int numRead = Utilities.ReadFully(data, buffer, 0, IsoUtilities.SectorSize);
if (numRead != IsoUtilities.SectorSize)
{
return false;
}
BaseVolumeDescriptor bvd = new BaseVolumeDescriptor(buffer, 0);
return bvd.StandardIdentifier == "CD001";
}
/// <summary>
/// Opens a stream containing the boot image.
/// </summary>
/// <returns>The boot image as a stream.</returns>
public Stream OpenBootImage()
{
return GetRealFileSystem<VfsCDReader>().OpenBootImage();
}
/// <summary>
/// Converts a cluster (index) into an absolute byte position in the underlying stream.
/// </summary>
/// <param name="cluster">The cluster to convert.</param>
/// <returns>The corresponding absolute byte position.</returns>
public long ClusterToOffset(long cluster)
{
return GetRealFileSystem<VfsCDReader>().ClusterToOffset(cluster);
}
/// <summary>
/// Converts an absolute byte position in the underlying stream to a cluster (index).
/// </summary>
/// <param name="offset">The byte position to convert.</param>
/// <returns>The cluster containing the specified byte.</returns>
public long OffsetToCluster(long offset)
{
return GetRealFileSystem<VfsCDReader>().OffsetToCluster(offset);
}
/// <summary>
/// Converts a file name to the list of clusters occupied by the file's data.
/// </summary>
/// <param name="path">The path to inspect.</param>
/// <returns>The clusters.</returns>
/// <remarks>Note that in some file systems, small files may not have dedicated
/// clusters. Only dedicated clusters will be returned.</remarks>
public Range<long, long>[] PathToClusters(string path)
{
return GetRealFileSystem<VfsCDReader>().PathToClusters(path);
}
/// <summary>
/// Converts a file name to the extents containing its data.
/// </summary>
/// <param name="path">The path to inspect.</param>
/// <returns>The file extents, as absolute byte positions in the underlying stream.</returns>
/// <remarks>Use this method with caution - not all file systems will store all bytes
/// directly in extents. Files may be compressed, sparse or encrypted. This method
/// merely indicates where file data is stored, not what's stored.</remarks>
public StreamExtent[] PathToExtents(string path)
{
return GetRealFileSystem<VfsCDReader>().PathToExtents(path);
}
/// <summary>
/// Gets an object that can convert between clusters and files.
/// </summary>
/// <returns>The cluster map.</returns>
public ClusterMap BuildClusterMap()
{
return GetRealFileSystem<VfsCDReader>().BuildClusterMap();
}
/// <summary>
/// Retrieves Unix-specific information about a file or directory.
/// </summary>
/// <param name="path">Path to the file or directory.</param>
/// <returns>Information about the owner, group, permissions and type of the
/// file or directory.</returns>
public UnixFileSystemInfo GetUnixFileInfo(string path)
{
return GetRealFileSystem<VfsCDReader>().GetUnixFileInfo(path);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Dynamic.Utils;
using AstUtils = System.Linq.Expressions.Interpreter.Utils;
namespace System.Linq.Expressions.Interpreter
{
internal sealed class LightLambdaCompileEventArgs : EventArgs
{
public Delegate Compiled { get; private set; }
internal LightLambdaCompileEventArgs(Delegate compiled)
{
Compiled = compiled;
}
}
public partial class LightLambda
{
private readonly IStrongBox[] _closure;
private readonly Interpreter _interpreter;
#if NO_FEATURE_STATIC_DELEGATE
private static readonly CacheDict<Type, Func<LightLambda, Delegate>> _runCache = new CacheDict<Type, Func<LightLambda, Delegate>>(100);
#endif
// Adaptive compilation support
private readonly LightDelegateCreator _delegateCreator;
internal LightLambda(LightDelegateCreator delegateCreator, IStrongBox[] closure)
{
_delegateCreator = delegateCreator;
_closure = closure;
_interpreter = delegateCreator.Interpreter;
}
#if NO_FEATURE_STATIC_DELEGATE
private static Func<LightLambda, Delegate> GetRunDelegateCtor(Type delegateType)
{
lock (_runCache)
{
Func<LightLambda, Delegate> fastCtor;
if (_runCache.TryGetValue(delegateType, out fastCtor))
{
return fastCtor;
}
return MakeRunDelegateCtor(delegateType);
}
}
private static Func<LightLambda, Delegate> MakeRunDelegateCtor(Type delegateType)
{
var method = delegateType.GetMethod("Invoke");
var paramInfos = method.GetParameters();
Type[] paramTypes;
string name = "Run";
if (paramInfos.Length >= MaxParameters)
{
return null;
}
if (method.ReturnType == typeof(void))
{
name += "Void";
paramTypes = new Type[paramInfos.Length];
}
else
{
paramTypes = new Type[paramInfos.Length + 1];
paramTypes[paramTypes.Length - 1] = method.ReturnType;
}
MethodInfo runMethod;
if (method.ReturnType == typeof(void) && paramTypes.Length == 2 &&
paramInfos[0].ParameterType.IsByRef && paramInfos[1].ParameterType.IsByRef)
{
runMethod = typeof(LightLambda).GetMethod("RunVoidRef2", BindingFlags.NonPublic | BindingFlags.Instance);
paramTypes[0] = paramInfos[0].ParameterType.GetElementType();
paramTypes[1] = paramInfos[1].ParameterType.GetElementType();
}
else if (method.ReturnType == typeof(void) && paramTypes.Length == 0)
{
runMethod = typeof(LightLambda).GetMethod("RunVoid0", BindingFlags.NonPublic | BindingFlags.Instance);
}
else
{
for (int i = 0; i < paramInfos.Length; i++)
{
paramTypes[i] = paramInfos[i].ParameterType;
if (paramTypes[i].IsByRef)
{
return null;
}
}
#if FEATURE_MAKE_RUN_METHODS
if (DelegateHelpers.MakeDelegate(paramTypes) == delegateType)
{
name = "Make" + name + paramInfos.Length;
MethodInfo ctorMethod = typeof(LightLambda).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(paramTypes);
return _runCache[delegateType] = (Func<LightLambda, Delegate>)ctorMethod.CreateDelegate(typeof(Func<LightLambda, Delegate>));
}
#endif
runMethod = typeof(LightLambda).GetMethod(name + paramInfos.Length, BindingFlags.NonPublic | BindingFlags.Instance);
}
/*
try {
DynamicMethod dm = new DynamicMethod("FastCtor", typeof(Delegate), new[] { typeof(LightLambda) }, typeof(LightLambda), true);
var ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Ldftn, runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod);
ilgen.Emit(OpCodes.Newobj, delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
ilgen.Emit(OpCodes.Ret);
return _runCache[delegateType] = (Func<LightLambda, Delegate>)dm.CreateDelegate(typeof(Func<LightLambda, Delegate>));
} catch (SecurityException) {
}*/
// we don't have permission for restricted skip visibility dynamic methods, use the slower Delegate.CreateDelegate.
var targetMethod = runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod;
return _runCache[delegateType] = lambda => targetMethod.CreateDelegate(delegateType, lambda);
}
//TODO enable sharing of these custom delegates
private Delegate CreateCustomDelegate(Type delegateType)
{
//PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Synchronously compiling a custom delegate");
var method = delegateType.GetMethod("Invoke");
var paramInfos = method.GetParameters();
var parameters = new ParameterExpression[paramInfos.Length];
var parametersAsObject = new Expression[paramInfos.Length];
bool hasByRef = false;
for (int i = 0; i < paramInfos.Length; i++)
{
ParameterExpression parameter = Expression.Parameter(paramInfos[i].ParameterType, paramInfos[i].Name);
hasByRef = hasByRef || paramInfos[i].ParameterType.IsByRef;
parameters[i] = parameter;
parametersAsObject[i] = Expression.Convert(parameter, typeof(object));
}
var data = Expression.NewArrayInit(typeof(object), parametersAsObject);
var dlg = new Func<object[], object>(Run);
var dlgExpr = AstUtils.Constant(dlg);
var argsParam = Expression.Parameter(typeof(object[]), "$args");
Expression body;
if (method.ReturnType == typeof(void))
{
body = Expression.Block(typeof(void), Expression.Invoke(dlgExpr, argsParam));
}
else
{
body = Expression.Convert(Expression.Invoke(dlgExpr, argsParam), method.ReturnType);
}
if (hasByRef)
{
List<Expression> updates = new List<Expression>();
for (int i = 0; i < paramInfos.Length; i++)
{
if (paramInfos[i].ParameterType.IsByRef)
{
updates.Add(
Expression.Assign(
parameters[i],
Expression.Convert(
Expression.ArrayAccess(argsParam, Expression.Constant(i)),
paramInfos[i].ParameterType.GetElementType()
)
)
);
}
}
body = Expression.TryFinally(body, Expression.Block(typeof(void), updates));
}
body = Expression.Block(
method.ReturnType,
new[] { argsParam },
Expression.Assign(argsParam, data),
body
);
var lambda = Expression.Lambda(delegateType, body, parameters);
//return System.Linq.Expressions.Compiler.LambdaCompiler.Compile(lambda, null);
throw new NotImplementedException("byref delegate");
}
#endif
internal Delegate MakeDelegate(Type delegateType)
{
#if !NO_FEATURE_STATIC_DELEGATE
var method = delegateType.GetMethod("Invoke");
if (method.ReturnType == typeof(void))
{
return System.Dynamic.Utils.DelegateHelpers.CreateObjectArrayDelegate(delegateType, RunVoid);
}
else
{
return System.Dynamic.Utils.DelegateHelpers.CreateObjectArrayDelegate(delegateType, Run);
}
#else
Func<LightLambda, Delegate> fastCtor = GetRunDelegateCtor(delegateType);
if (fastCtor != null)
{
return fastCtor(this);
}
else
{
return CreateCustomDelegate(delegateType);
}
#endif
}
private InterpretedFrame MakeFrame()
{
return new InterpretedFrame(_interpreter, _closure);
}
#if NO_FEATURE_STATIC_DELEGATE
[EnableInvokeTesting]
internal void RunVoidRef2<T0, T1>(ref T0 arg0, ref T1 arg1)
{
// copy in and copy out for today...
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var currentFrame = frame.Enter();
try
{
_interpreter.Run(frame);
}
finally
{
frame.Leave(currentFrame);
arg0 = (T0)frame.Data[0];
arg1 = (T1)frame.Data[1];
}
}
#endif
public object Run(params object[] arguments)
{
var frame = MakeFrame();
for (int i = 0; i < arguments.Length; i++)
{
frame.Data[i] = arguments[i];
}
var currentFrame = frame.Enter();
try
{
_interpreter.Run(frame);
}
finally
{
for (int i = 0; i < arguments.Length; i++)
{
arguments[i] = frame.Data[i];
}
frame.Leave(currentFrame);
}
return frame.Pop();
}
public object RunVoid(params object[] arguments)
{
var frame = MakeFrame();
for (int i = 0; i < arguments.Length; i++)
{
frame.Data[i] = arguments[i];
}
var currentFrame = frame.Enter();
try
{
_interpreter.Run(frame);
}
finally
{
for (int i = 0; i < arguments.Length; i++)
{
arguments[i] = frame.Data[i];
}
frame.Leave(currentFrame);
}
return null;
}
}
}
| |
using System;
using System.Globalization;
using System.Xml;
using Orchard.Comments.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Aspects;
using Orchard.Services;
using Orchard.Localization;
using Orchard.Comments.Services;
using Orchard.UI.Notify;
namespace Orchard.Comments.Drivers {
public class CommentPartDriver : ContentPartDriver<CommentPart> {
private readonly IContentManager _contentManager;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IClock _clock;
private readonly ICommentService _commentService;
private readonly IOrchardServices _orchardServices;
protected override string Prefix { get { return "Comments"; } }
public Localizer T { get; set; }
public CommentPartDriver(
IContentManager contentManager,
IWorkContextAccessor workContextAccessor,
IClock clock,
ICommentService commentService,
IOrchardServices orchardServices) {
_contentManager = contentManager;
_workContextAccessor = workContextAccessor;
_clock = clock;
_commentService = commentService;
_orchardServices = orchardServices;
T = NullLocalizer.Instance;
}
protected override DriverResult Display(CommentPart part, string displayType, dynamic shapeHelper) {
return Combined(
ContentShape("Parts_Comment", () => shapeHelper.Parts_Comment()),
ContentShape("Parts_Comment_SummaryAdmin", () => shapeHelper.Parts_Comment_SummaryAdmin())
);
}
// GET
protected override DriverResult Editor(CommentPart part, dynamic shapeHelper) {
if (UI.Admin.AdminFilter.IsApplied(_workContextAccessor.GetContext().HttpContext.Request.RequestContext)) {
return ContentShape("Parts_Comment_AdminEdit",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment.AdminEdit", Model: part, Prefix: Prefix));
}
else {
return ContentShape("Parts_Comment_Edit",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment", Model: part, Prefix: Prefix));
}
}
// POST
protected override DriverResult Editor(CommentPart part, IUpdateModel updater, dynamic shapeHelper) {
updater.TryUpdateModel(part, Prefix, null, null);
var workContext = _workContextAccessor.GetContext();
// applying moderate/approve actions
var httpContext = workContext.HttpContext;
var name = httpContext.Request.Form["submit.Save"];
if (!string.IsNullOrEmpty(name) && String.Equals(name, "moderate", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) {
_commentService.UnapproveComment(part.Id);
_orchardServices.Notifier.Information(T("Comment successfully moderated."));
return Editor(part, shapeHelper);
}
}
if (!string.IsNullOrEmpty(name) && String.Equals(name, "approve", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) {
_commentService.ApproveComment(part.Id);
_orchardServices.Notifier.Information(T("Comment approved."));
return Editor(part, shapeHelper);
}
}
if (!string.IsNullOrEmpty(name) && String.Equals(name, "delete", StringComparison.OrdinalIgnoreCase)) {
if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) {
_commentService.DeleteComment(part.Id);
_orchardServices.Notifier.Information(T("Comment successfully deleted."));
return Editor(part, shapeHelper);
}
}
// if editing from the admin, don't update the owner or the status
if (!string.IsNullOrEmpty(name) && String.Equals(name, "save", StringComparison.OrdinalIgnoreCase)) {
_orchardServices.Notifier.Information(T("Comment saved."));
return Editor(part, shapeHelper);
}
part.CommentDateUtc = _clock.UtcNow;
if (!String.IsNullOrEmpty(part.SiteName) && !part.SiteName.StartsWith("http://") && !part.SiteName.StartsWith("https://")) {
part.SiteName = "http://" + part.SiteName;
}
var currentUser = workContext.CurrentUser;
part.UserName = (currentUser != null ? currentUser.UserName : null);
if (currentUser != null)
part.Author = currentUser.UserName;
else if (string.IsNullOrWhiteSpace(part.Author)) {
updater.AddModelError("Comments.Author", T("Name is mandatory"));
}
var moderateComments = workContext.CurrentSite.As<CommentSettingsPart>().ModerateComments;
part.Status = moderateComments ? CommentStatus.Pending : CommentStatus.Approved;
var commentedOn = _contentManager.Get<ICommonPart>(part.CommentedOn);
// prevent users from commenting on a closed thread by hijacking the commentedOn property
var commentsPart = commentedOn.As<CommentsPart>();
if (commentsPart == null || !commentsPart.CommentsActive) {
_orchardServices.TransactionManager.Cancel();
return Editor(part, shapeHelper);
}
if (commentedOn != null && commentedOn.Container != null) {
part.CommentedOnContainer = commentedOn.Container.ContentItem.Id;
}
commentsPart.Record.CommentPartRecords.Add(part.Record);
return Editor(part, shapeHelper);
}
protected override void Importing(CommentPart part, ContentManagement.Handlers.ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "Author", author =>
part.Record.Author = author
);
context.ImportAttribute(part.PartDefinition.Name, "SiteName", siteName =>
part.Record.SiteName = siteName
);
context.ImportAttribute(part.PartDefinition.Name, "UserName", userName =>
part.Record.UserName = userName
);
context.ImportAttribute(part.PartDefinition.Name, "Email", email =>
part.Record.Email = email
);
context.ImportAttribute(part.PartDefinition.Name, "Position", position =>
part.Record.Position = decimal.Parse(position, CultureInfo.InvariantCulture)
);
context.ImportAttribute(part.PartDefinition.Name, "Status", status =>
part.Record.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), status)
);
context.ImportAttribute(part.PartDefinition.Name, "CommentDateUtc", commentDate =>
part.Record.CommentDateUtc = XmlConvert.ToDateTime(commentDate, XmlDateTimeSerializationMode.Utc)
);
context.ImportAttribute(part.PartDefinition.Name, "CommentText", text =>
part.Record.CommentText = text
);
context.ImportAttribute(part.PartDefinition.Name, "CommentedOn", commentedOn => {
var contentItem = context.GetItemFromSession(commentedOn);
if (contentItem != null) {
part.Record.CommentedOn = contentItem.Id;
}
contentItem.As<CommentsPart>().Record.CommentPartRecords.Add(part.Record);
});
context.ImportAttribute(part.PartDefinition.Name, "RepliedOn", repliedOn => {
var contentItem = context.GetItemFromSession(repliedOn);
if (contentItem != null) {
part.Record.RepliedOn = contentItem.Id;
}
});
context.ImportAttribute(part.PartDefinition.Name, "CommentedOnContainer", commentedOnContainer => {
var container = context.GetItemFromSession(commentedOnContainer);
if (container != null) {
part.Record.CommentedOnContainer = container.Id;
}
});
}
protected override void Exporting(CommentPart part, ContentManagement.Handlers.ExportContentContext context) {
context.Element(part.PartDefinition.Name).SetAttributeValue("Author", part.Record.Author);
context.Element(part.PartDefinition.Name).SetAttributeValue("SiteName", part.Record.SiteName);
context.Element(part.PartDefinition.Name).SetAttributeValue("UserName", part.Record.UserName);
context.Element(part.PartDefinition.Name).SetAttributeValue("Email", part.Record.Email);
context.Element(part.PartDefinition.Name).SetAttributeValue("Position", part.Record.Position.ToString(CultureInfo.InvariantCulture));
context.Element(part.PartDefinition.Name).SetAttributeValue("Status", part.Record.Status.ToString());
if (part.Record.CommentDateUtc != null) {
context.Element(part.PartDefinition.Name)
.SetAttributeValue("CommentDateUtc", XmlConvert.ToString(part.Record.CommentDateUtc.Value, XmlDateTimeSerializationMode.Utc));
}
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentText", part.Record.CommentText);
var commentedOn = _contentManager.Get(part.Record.CommentedOn);
if (commentedOn != null) {
var commentedOnIdentity = _contentManager.GetItemMetadata(commentedOn).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOn", commentedOnIdentity.ToString());
}
var commentedOnContainer = _contentManager.Get(part.Record.CommentedOnContainer);
if (commentedOnContainer != null) {
var commentedOnContainerIdentity = _contentManager.GetItemMetadata(commentedOnContainer).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOnContainer", commentedOnContainerIdentity.ToString());
}
if (part.Record.RepliedOn.HasValue) {
var repliedOn = _contentManager.Get(part.Record.RepliedOn.Value);
if (repliedOn != null) {
var repliedOnIdentity = _contentManager.GetItemMetadata(repliedOn).Identity;
context.Element(part.PartDefinition.Name).SetAttributeValue("RepliedOn", repliedOnIdentity.ToString());
}
}
}
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// 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.Web;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Collections;
using gov.va.medora.mdo;
using gov.va.medora.mdws.dto;
using gov.va.medora.mdo.dao.hl7.rxRefill;
using gov.va.medora.mdo.dao;
using gov.va.medora.mdo.api;
namespace gov.va.medora.mdws
{
public class MedsLib
{
MySession mySession;
public MedsLib() { }
public MedsLib(MySession mySession)
{
this.mySession = mySession;
}
public TaggedMedicationArrays getOutpatientMeds()
{
TaggedMedicationArrays result = new TaggedMedicationArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getOutpatientMeds(mySession.ConnectionSet);
result = new TaggedMedicationArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedMedicationArrays getIvMeds()
{
TaggedMedicationArrays result = new TaggedMedicationArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getIvMeds(mySession.ConnectionSet);
result = new TaggedMedicationArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedMedicationArrays getImoMeds()
{
TaggedMedicationArrays result = new TaggedMedicationArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getImoMeds(mySession.ConnectionSet);
result = new TaggedMedicationArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedMedicationArrays getUnitDoseMeds()
{
TaggedMedicationArrays result = new TaggedMedicationArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getUnitDoseMeds(mySession.ConnectionSet);
result = new TaggedMedicationArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedMedicationArrays getOtherMeds()
{
TaggedMedicationArrays result = new TaggedMedicationArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getOtherMeds(mySession.ConnectionSet);
result = new TaggedMedicationArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedMedicationArrays getAllMeds()
{
TaggedMedicationArrays result = new TaggedMedicationArrays();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getAllMeds(mySession.ConnectionSet);
result = new TaggedMedicationArrays(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TextTO getMedicationDetail(string siteId, string medId)
{
TextTO result = new TextTO();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (siteId == "")
{
result.fault = new FaultTO("Missing siteId");
}
else if (medId == "")
{
result.fault = new FaultTO("Missing medId");
}
if (result.fault != null)
{
return result;
}
try
{
string s = Medication.getMedicationDetail(mySession.ConnectionSet.getConnection(siteId), medId);
result = new TextTO(s);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedTextArray getImmunizations(string fromDate, string toDate, int nrpts)
{
TaggedTextArray result = new TaggedTextArray();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (fromDate == "")
{
result.fault = new FaultTO("Missing fromDate");
}
else if (toDate == "")
{
result.fault = new FaultTO("Missing toDate");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getImmunizations(mySession.ConnectionSet, fromDate, toDate, nrpts);
result = new TaggedTextArray(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedTextArray getOutpatientRxProfile()
{
TaggedTextArray result = new TaggedTextArray();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getOutpatientRxProfile(mySession.ConnectionSet);
result = new TaggedTextArray(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedTextArray getMedsAdminHx(string fromDate, string toDate, int nrpts)
{
TaggedTextArray result = new TaggedTextArray();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (fromDate == "")
{
result.fault = new FaultTO("Missing fromDate");
}
else if (toDate == "")
{
result.fault = new FaultTO("Missing toDate");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getMedsAdminHx(mySession.ConnectionSet, fromDate, toDate, nrpts);
result = new TaggedTextArray(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public TaggedTextArray getMedsAdminLog(string fromDate, string toDate, int nrpts)
{
TaggedTextArray result = new TaggedTextArray();
if (!mySession.ConnectionSet.IsAuthorized)
{
result.fault = new FaultTO("Connections not ready for operation", "Need to login?");
}
else if (fromDate == "")
{
result.fault = new FaultTO("Missing fromDate");
}
else if (toDate == "")
{
result.fault = new FaultTO("Missing toDate");
}
if (result.fault != null)
{
return result;
}
try
{
IndexedHashtable t = Medication.getMedsAdminLog(mySession.ConnectionSet, fromDate, toDate, nrpts);
result = new TaggedTextArray(t);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public MedicationTO refillPrescription(string pwd, string sitecode, string mpiPid, string rxId)
{
MedicationTO result = new MedicationTO();
if (String.IsNullOrEmpty(pwd))
{
result.fault = new FaultTO("Missing pwd");
}
else if (String.IsNullOrEmpty(sitecode))
{
result.fault = new FaultTO("Missing site ID");
}
else if (String.IsNullOrEmpty(mpiPid))
{
result.fault = new FaultTO("Missing patient ID");
}
else if (String.IsNullOrEmpty(rxId))
{
result.fault = new FaultTO("Missing Rx ID");
}
if (result.fault != null)
{
return result;
}
try
{
Site hl7Site = mySession.SiteTable.getSite(sitecode);
DataSource hl7Src = null;
foreach (DataSource src in hl7Site.Sources)
{
if (String.Equals(src.Protocol, "HL7", StringComparison.CurrentCultureIgnoreCase))
{
hl7Src = src;
break;
}
}
if (hl7Src == null)
{
throw new gov.va.medora.mdo.exceptions.MdoException("No HL7 data source in site table for that site ID");
}
HL7Connection cxn = new HL7Connection(hl7Src);
cxn.connect();
cxn.Pid = mpiPid;
result = new MedicationTO(new MedsApi().refillPrescription(cxn, rxId));
}
catch (Exception exc)
{
result.fault = new FaultTO(exc);
}
return result;
}
public MedicationTO getRefillStatus(string sitecode, string rxId)
{
return new MedicationTO() { fault = new FaultTO(new NotImplementedException()) };
}
public TaggedMedicationArrays getPrescriptionsHL7(string pwd, string sitecode, string mpiPid)
{
TaggedMedicationArrays result = new TaggedMedicationArrays();
if (String.IsNullOrEmpty(pwd))
{
result.fault = new FaultTO("Missing pwd");
}
else if (String.IsNullOrEmpty(sitecode))
{
result.fault = new FaultTO("Missing site ID");
}
else if (String.IsNullOrEmpty(mpiPid))
{
result.fault = new FaultTO("Missing patient ID");
}
if (result.fault != null)
{
return result;
}
try
{
Site hl7Site = mySession.SiteTable.getSite(sitecode);
DataSource hl7Src = null;
foreach (DataSource src in hl7Site.Sources)
{
if (String.Equals(src.Protocol, "HL7", StringComparison.CurrentCultureIgnoreCase))
{
hl7Src = src;
break;
}
}
if (hl7Src == null)
{
throw new gov.va.medora.mdo.exceptions.MdoException("No HL7 data source in site table for that site ID");
}
HL7Connection cxn = new HL7Connection(hl7Src);
cxn.connect();
cxn.Pid = mpiPid;
result = new TaggedMedicationArrays(new MedsApi().getAllMeds(new ConnectionSet(cxn)));
}
catch (Exception exc)
{
result.fault = new FaultTO(exc);
}
return result;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MobileContainerDesigner.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.Design.MobileControls
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Web.UI.Design.MobileControls.Adapters;
using System.Web.UI.MobileControls;
using System.Web.UI.MobileControls.Adapters;
using IHTMLElement = NativeMethods.IHTMLElement;
using IHTMLElementCollection = NativeMethods.IHTMLElementCollection;
/// <summary>
/// <para>Provides a base designer class for all mobile container controls.</para>
/// </summary>
[
System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand,
Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)
]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
internal abstract class MobileContainerDesigner : ControlDesigner, IMobileDesigner
{
private MobileControl _mobileControl;
private readonly Size _defaultSize;
private bool _containmentStatusDirty = true;
private bool _hasAttributesCached = false;
private bool _shouldDirtyPage = false;
private ContainmentStatus _containmentStatus = ContainmentStatus.Unknown;
private IDictionary _behaviorAttributes;
private String _currentErrorMessage = null;
private IWebFormsDocumentService _iWebFormsDocumentService;
private IMobileWebFormServices _iMobileWebFormServices;
private EventHandler _loadComplete = null;
// cached Behavior object
private IHtmlControlDesignerBehavior _cachedBehavior = null;
/// <summary>
/// <para>
/// Initializes an instance of the <see cref='System.Web.UI.Design.MobileControls.MobileContainerDesigner'/> class.
/// </para>
/// </summary>
internal MobileContainerDesigner()
{
ReadOnly = false;
_defaultSize = new Size(300, 100);
_behaviorAttributes = new HybridDictionary();
}
/// <summary>
/// return the containment status
/// </summary>
protected ContainmentStatus ContainmentStatus
{
get
{
if (!_containmentStatusDirty)
{
return _containmentStatus;
}
_containmentStatus =
DesignerAdapterUtil.GetContainmentStatus(_mobileControl);
_containmentStatusDirty = false;
return _containmentStatus;
}
}
internal Object DesignTimeElementInternal
{
get
{
return typeof(HtmlControlDesigner).InvokeMember("DesignTimeElement",
BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic,
null, this, null, CultureInfo.InvariantCulture);
}
}
private IMobileWebFormServices IMobileWebFormServices
{
get
{
if (_iMobileWebFormServices == null)
{
_iMobileWebFormServices =
(IMobileWebFormServices)GetService(typeof(IMobileWebFormServices));
}
return _iMobileWebFormServices;
}
}
private IWebFormsDocumentService IWebFormsDocumentService
{
get
{
if (_iWebFormsDocumentService == null)
{
_iWebFormsDocumentService =
(IWebFormsDocumentService)GetService(typeof(IWebFormsDocumentService));
Debug.Assert(_iWebFormsDocumentService != null);
}
return _iWebFormsDocumentService;
}
}
/// <summary>
/// Indicates whether the initial page load is completed
/// </summary>
protected bool LoadComplete
{
get
{
return !IWebFormsDocumentService.IsLoading;
}
}
/// <summary>
/// Control's style, available only when page is MobilePage
/// </summary>
protected Style Style
{
get
{
if (!DesignerAdapterUtil.InMobilePage(_mobileControl))
{
return null;
}
Style style = ((ControlAdapter)_mobileControl.Adapter).Style;
// Each MobileControl should have its own style
Debug.Assert(style != null);
return style;
}
}
/// <summary>
/// Apply style related properties to behavior
/// </summary>
/// <param name="propName">
/// property that needs to be applied, null to apply all
/// </param>
private void ApplyPropertyToBehavior(String propName)
{
if (Style == null)
{
return;
}
if (propName == null || propName.Equals("BackColor"))
{
Color backColor = (Color)Style[Style.BackColorKey, true];
SetBehaviorStyle("backgroundColor", ColorTranslator.ToHtml(backColor));
}
if (propName == null || propName.Equals("ForeColor"))
{
Color foreColor = (Color)Style[Style.ForeColorKey, true];
SetBehaviorStyle("color", ColorTranslator.ToHtml(foreColor));
}
if (propName == null || propName.Equals("Font"))
{
bool bold =
(BooleanOption)Style[Style.BoldKey, true] == BooleanOption.True;
bool italic =
(BooleanOption)Style[Style.ItalicKey, true] == BooleanOption.True;
FontSize fontSize = (FontSize) Style[Style.FontSizeKey , true];
String fontName = (String) Style[Style.FontNameKey , true];
SetBehaviorStyle("fontWeight", bold? "bold" : "normal");
SetBehaviorStyle("fontStyle", italic? "italic" : "normal");
if (fontSize == FontSize.Large)
{
SetBehaviorStyle("fontSize", "medium");
}
else if (fontSize == FontSize.Small)
{
SetBehaviorStyle("fontSize", "x-small");
}
else
{
RemoveBehaviorStyle("fontSize");
}
SetBehaviorStyle("fontFamily", fontName);
}
if (propName == null || propName.Equals("Alignment"))
{
Alignment alignment = (Alignment)Style[Style.AlignmentKey, true];
bool alignmentNotSet = alignment == Alignment.NotSet;
SetBehaviorStyle("textAlign",
alignmentNotSet ? "" : Enum.Format(typeof(Alignment), alignment, "G"));
}
}
/// <summary>
/// Performs the cleanup of the designer class.
/// </summary>
/// <seealso cref='IDesigner'/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_loadComplete != null)
{
IWebFormsDocumentService.LoadComplete -= _loadComplete;
_loadComplete = null;
}
}
base.Dispose(disposing);
}
/// <summary>
/// The default size of Container Control.
/// </summary>
protected virtual Size GetDefaultSize()
{
return _defaultSize;
}
/// <summary>
/// non-null string will render the text as an image
/// on the top of container control.
/// </summary>
protected virtual String GetErrorMessage(out bool infoMode)
{
infoMode = false;
return null;
}
/// <summary>
/// <para>
/// Initializes the designer using
/// the specified component.
/// </para>
/// </summary>
/// <param name='component'>
/// The control element being designed.
/// </param>
/// <remarks>
/// <para>
/// This is called by the designer host to establish the component being
/// designed.
/// </para>
/// </remarks>
/// <seealso cref='System.ComponentModel.Design.IDesigner'/>
public override void Initialize(IComponent component)
{
Debug.Assert(component is MobileControl,
"MobileContainerDesigner.Initialize - Invalid Mobile Control");
_mobileControl = (MobileControl) component;
base.Initialize(component);
_loadComplete = new EventHandler(this.OnLoadComplete);
IWebFormsDocumentService.LoadComplete += _loadComplete;
}
/// <summary>
/// return true if the property is an appearance attribute that needs
/// to apply to all child controls.
/// </summary>
/// <param name="propertyName">
/// </param>
private bool IsAppearanceAttribute(String propertyName)
{
return (
propertyName.Equals("Font") ||
propertyName.Equals("ForeColor") ||
propertyName.Equals("BackColor") ||
propertyName.Equals("Wrapping") ||
propertyName.Equals("Alignment") ||
propertyName.Equals("StyleReference"));
}
internal virtual void OnBackgroundImageChange(String message, bool infoMode)
{
}
/// <summary>
/// <para>
/// Notification that is called when the designer is attached to the behavior.
/// </para>
/// </summary>
protected override void OnBehaviorAttached()
{
Debug.Assert(_cachedBehavior == null);
_cachedBehavior = Behavior;
PrefixDeviceSpecificTags();
base.OnBehaviorAttached();
// Reload the original state if an old Behavior is cached.
if (_hasAttributesCached)
{
ReloadBehaviorState();
}
}
/// <summary>
/// Notification that is called when the behavior is detached from designer
/// </summary>
protected override void OnBehaviorDetaching()
{
// dispose the cached behavior.
_cachedBehavior = null;
}
/// <summary>
/// <para>
/// Delegate to handle component changed event.
/// </para>
/// </summary>
/// <param name='sender'>
/// The object sending the event.
/// </param>
/// <param name='ce'>
/// The event object used when firing a component changed notification.
/// </param>
/// <remarks>
/// <para>
/// This is called after a property has been changed. It allows the implementor
/// to do any post-processing that may be needed after a property change.
/// </para>
/// </remarks>
public override void OnComponentChanged(Object sender, ComponentChangedEventArgs ce)
{
// Delegate to the base class implementation first!
base.OnComponentChanged(sender, ce);
MemberDescriptor member = ce.Member;
if (member != null &&
member.GetType().FullName.Equals(Constants.ReflectPropertyDescriptorTypeFullName))
{
PropertyDescriptor propDesc = (PropertyDescriptor)member;
String propName = propDesc.Name;
if (IsAppearanceAttribute(propName))
{
// Update control rendering
UpdateRenderingRecursive();
}
}
}
/// <summary>
/// Subclasses can override to modify their container appearance,
/// this method is invoked by OnLoadComplete()
/// </summary>
protected virtual void OnContainmentChanged()
{
// do nothing
}
/// <summary>
/// helper method for external UIs
/// </summary>
protected virtual void OnInternalChange()
{
ISite site = _mobileControl.Site;
if (site != null)
{
IComponentChangeService changeService =
(IComponentChangeService)site.GetService(typeof(IComponentChangeService));
if (changeService != null)
{
try
{
changeService.OnComponentChanging(_mobileControl, null);
}
catch (CheckoutException ex)
{
if (ex == CheckoutException.Canceled)
return;
throw;
}
changeService.OnComponentChanged(_mobileControl, null, null, null);
}
}
}
/// <summary>
/// <para>
/// Notification that is called when the page completes loading.
/// </para>
/// </summary>
private void OnLoadComplete(Object source, EventArgs e)
{
// Need to apply behavior attributes since none are cached
if (!_hasAttributesCached)
{
SetControlDefaultAppearance();
// Apply the style properties to Behavior
ApplyPropertyToBehavior(null);
}
bool infoMode = false;
String msg = GetErrorMessage(out infoMode);
if (msg != _currentErrorMessage || !_hasAttributesCached)
{
OnBackgroundImageChange(msg, infoMode);
_currentErrorMessage = msg;
}
// we could reload the attributes
_hasAttributesCached = true;
// Change containment related appearance
OnContainmentChanged();
// Don't forget the change children appearance,
// this call is necessary to solve multi-nested control problem.
UpdateRenderingRecursive();
// Make the page dirty by calling OnInternalChange if an subsitution occurs.
if (_shouldDirtyPage)
{
OnInternalChange();
_shouldDirtyPage = false;
}
}
/// <summary>
/// <para>
/// Notification that is called when the associated control is parented.
/// </para>
/// </summary>
public override void OnSetParent()
{
base.OnSetParent();
// The containment status is invalidated
_containmentStatusDirty = true;
// Make sure the control refreshes when it is moved around
if (LoadComplete)
{
OnLoadComplete(this, EventArgs.Empty);
}
}
protected override void PreFilterProperties(IDictionary properties)
{
base.PreFilterProperties(properties);
PropertyDescriptor property = (PropertyDescriptor) properties["Expressions"];
if (property != null) {
properties["Expressions"] = TypeDescriptor.CreateProperty(this.GetType(), property, BrowsableAttribute.No);
}
}
/// <summary>
/// dynamically transform DeviceSpecific element to a server control,
/// called from OnBehaviorAttached
/// </summary>
private void PrefixDeviceSpecificTags()
{
IHTMLElement htmlElement = (IHTMLElement) DesignTimeElementInternal;
Debug.Assert(htmlElement != null,
"Invalid HTML element in FormDesigner.OnBehaviorAttached");
IWebFormReferenceManager refMgr =
(IWebFormReferenceManager) GetService(typeof(IWebFormReferenceManager));
Debug.Assert(refMgr != null, "Did not get back IWebFormReferenceManager service.");
String tagPrefix = refMgr.GetTagPrefix(typeof(DeviceSpecific));
Debug.Assert(tagPrefix != null && tagPrefix.Length > 0, "TagPrefix is invalid");
IHTMLElementCollection allChildren = (IHTMLElementCollection) htmlElement.GetChildren();
if (null != allChildren)
{
bool substitutions = false;
int nestingLevel = 0;
String modifiedInnerHTML = String.Empty;
for (Int32 i = 0; i < allChildren.GetLength(); i++)
{
IHTMLElement htmlChild = (IHTMLElement) allChildren.Item(i, 0);
Debug.Assert(null != htmlChild, "htmlChild is null");
String childContent = htmlChild.GetOuterHTML();
String childUpperContent = childContent.ToUpper(CultureInfo.InvariantCulture);
if (childContent.StartsWith("<", StringComparison.Ordinal) &&
!(childContent.StartsWith("</", StringComparison.Ordinal) || (childContent.EndsWith("/>", StringComparison.Ordinal))))
{
if (!childUpperContent.StartsWith("<" + tagPrefix.ToUpper(CultureInfo.InvariantCulture) + ":", StringComparison.Ordinal))
{
nestingLevel++;
}
}
else if (childContent.StartsWith("</", StringComparison.Ordinal))
{
nestingLevel--;
}
if (1 == nestingLevel &&
childUpperContent.StartsWith("<DEVICESPECIFIC", StringComparison.Ordinal) &&
childUpperContent.EndsWith(">", StringComparison.Ordinal))
{
Debug.Assert(substitutions == false, "substitutions is true");
modifiedInnerHTML += "<" + tagPrefix + ":DeviceSpecific runat=\"server\">\r\n";
substitutions = true;
}
else if (1 == nestingLevel &&
childUpperContent.StartsWith("<DEVICESPECIFIC", StringComparison.Ordinal) &&
childUpperContent.EndsWith("/>", StringComparison.Ordinal))
{
modifiedInnerHTML += "<" + tagPrefix + ":DeviceSpecific runat=\"server\"></" + tagPrefix + ":DeviceSpecific>\r\n";
substitutions = true;
}
else if (0 == nestingLevel && 0 == String.Compare(childUpperContent, "</DEVICESPECIFIC>", StringComparison.Ordinal))
{
Debug.Assert(substitutions == true, "substitutions is false");
modifiedInnerHTML += "</" + tagPrefix + ":DeviceSpecific>\r\n";
}
else
{
modifiedInnerHTML += childContent + "\r\n";
}
}
if (substitutions)
{
_shouldDirtyPage = true;
htmlElement.SetInnerHTML(modifiedInnerHTML);
}
}
}
/// <summary>
/// Reload the cached Behavior states
/// </summary>
private void ReloadBehaviorState()
{
Debug.Assert(Behavior != null && _behaviorAttributes != null);
IDictionaryEnumerator enumerator = _behaviorAttributes.GetEnumerator();
while (enumerator.MoveNext())
{
String key = (String)enumerator.Key;
Object obj = _behaviorAttributes[key];
Behavior.SetStyleAttribute(key, true, obj, true);
}
}
/// <summary>
/// Remove the attribute from Behavior
/// </summary>
/// <param name="attribute">
/// attribute that need to be removed.
/// </param>
protected void RemoveBehaviorStyle(String attribute)
{
Debug.Assert (_behaviorAttributes != null);
if (Behavior != null)
{
Behavior.RemoveStyleAttribute(attribute, true, true);
}
// also remove the cached attribute
_behaviorAttributes.Remove(attribute);
}
/// <summary>
/// Apply the style attribute to Behavior
/// </summary>
/// <param name="attribute">
/// attribute that needs to be applied to Behavior
/// </param>
/// <param name="obj">
/// value to apply
/// </param>
protected void SetBehaviorStyle(String attribute, Object obj)
{
Debug.Assert (obj != null, "null object passed in!");
Debug.Assert (_behaviorAttributes != null);
// here we cache the value;
// Note that the value is cached even if Behavior is not available,
// this is because this method could be called between Behavior
// detached and attached events, we want to re-apply these lost
// attributes when Behavior is attached again.
_behaviorAttributes[attribute] = obj;
if (Behavior == null)
{
return;
}
Behavior.SetStyleAttribute(attribute, true, obj, true);
}
/// <summary>
/// This method will be called only once when the control is first created.
/// </summary>
protected virtual void SetControlDefaultAppearance()
{
// Default border appearance
SetBehaviorStyle("borderWidth", "1px");
SetBehaviorStyle("borderColor", ColorTranslator.ToHtml(SystemColors.ControlDark));
// Default margin, paddings for container controls.
SetBehaviorStyle("paddingTop", "8px");
SetBehaviorStyle("paddingBottom", "8px");
SetBehaviorStyle("paddingRight", "4px");
SetBehaviorStyle("paddingLeft", "5px");
SetBehaviorStyle("marginTop", "3px");
SetBehaviorStyle("marginBottom", "3px");
SetBehaviorStyle("marginRight", "5px");
SetBehaviorStyle("marginLeft", "5px");
// Setup background parameters
SetBehaviorStyle("backgroundRepeat", "no-repeat");
SetBehaviorStyle("backgroundAttachment", "fixed");
SetBehaviorStyle("backgroundPositionX", "left");
SetBehaviorStyle("backgroundPositionY", "top");
// Container sze info.
SetBehaviorStyle("height", GetDefaultSize().Height);
SetBehaviorStyle("width", GetDefaultSize().Width);
}
/// <summary>
/// Update the designtime rendering for the container control
/// </summary>
public void UpdateRendering()
{
_mobileControl.RefreshStyle();
ApplyPropertyToBehavior(null);
}
/// <summary>
/// Update the designtime rendering for the container control and all controls
/// inside this container control.
/// </summary>
private void UpdateRenderingRecursive()
{
UpdateRendering();
if (IMobileWebFormServices != null)
{
IMobileWebFormServices.UpdateRenderingRecursive(_mobileControl);
}
}
}
}
| |
using System;
using Server.Items;
using Server.Network;
namespace Server.Items
{
public abstract class BaseIngot : Item, ICommodity
{
private CraftResource m_Resource;
[CommandProperty( AccessLevel.GameMaster )]
public CraftResource Resource
{
get{ return m_Resource; }
set{ m_Resource = value; InvalidateProperties(); }
}
public override double DefaultWeight
{
get { return 0.1; }
}
int ICommodity.DescriptionNumber { get { return LabelNumber; } }
bool ICommodity.IsDeedable { get { return true; } }
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 ); // version
writer.Write( (int) m_Resource );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 1:
{
m_Resource = (CraftResource)reader.ReadInt();
break;
}
case 0:
{
OreInfo info;
switch ( reader.ReadInt() )
{
case 0: info = OreInfo.MIron; break;
case 1: info = OreInfo.MBronze; break;
case 2: info = OreInfo.MGold; break;
case 3: info = OreInfo.MCopper; break;
case 4: info = OreInfo.MOldcopper; break;
case 5: info = OreInfo.MDullcopper; break;
case 6: info = OreInfo.MSilver; break;
case 7: info = OreInfo.MShadow; break;
case 8: info = OreInfo.MBloodrock; break;
case 9: info = OreInfo.MBlackrock; break;
case 10: info = OreInfo.MMytheril; break;
case 11: info = OreInfo.MRose; break;
case 12: info = OreInfo.MVerite; break;
case 13: info = OreInfo.MAgapite; break;
case 14: info = OreInfo.MRusty; break;
case 15: info = OreInfo.MValorite; break;
case 16: info = OreInfo.MDragon; break;
case 17: info = OreInfo.MTitan; break;
case 18: info = OreInfo.MCrystaline; break;
case 19: info = OreInfo.MKrynite; break;
case 20: info = OreInfo.MVulcan; break;
case 21: info = OreInfo.MBloodcrest; break;
case 22: info = OreInfo.MElvin; break;
case 23: info = OreInfo.MAcid; break;
case 24: info = OreInfo.MAqua; break;
case 25: info = OreInfo.MEldar; break;
case 26: info = OreInfo.MGlowing; break;
case 27: info = OreInfo.MGorgan; break;
case 28: info = OreInfo.MSandrock; break;
case 29: info = OreInfo.MSteel; break;
default: info = null; break;
}
m_Resource = CraftResources.GetFromOreInfo( info );
break;
}
}
}
public BaseIngot( CraftResource resource ) : this( resource, 1 )
{
}
public BaseIngot( CraftResource resource, int amount ) : base( 0x1BF2 )
{
Stackable = true;
Amount = amount;
Hue = CraftResources.GetHue( resource );
m_Resource = resource;
}
public BaseIngot( Serial serial ) : base( serial )
{
}
public override void AddNameProperty( ObjectPropertyList list )
{
if ( Amount > 1 )
list.Add( 1050039, "{0}\t#{1}", Amount, 1027154 ); // ~1_NUMBER~ ~2_ITEMNAME~
else
list.Add( 1027154 ); // ingots
}
public override void GetProperties( ObjectPropertyList list )
{
base.GetProperties( list );
if ( !CraftResources.IsStandard( m_Resource ) )
{
int num = CraftResources.GetLocalizationNumber( m_Resource );
if ( num > 0 )
list.Add( num );
else
list.Add( CraftResources.GetName( m_Resource ) );
}
}
/*public override int LabelNumber
{
get
{
if (m_Resource >= CraftResource.DullCopper && m_Resource <= CraftResource.Valorite)
return 1042684 + (int)(m_Resource - CraftResource.DullCopper);
return 1042692;
}
}*/
}
[FlipableAttribute( 0x1BF2, 0x1BEF )]
public class IronIngot : BaseIngot
{
[Constructable]
public IronIngot() : this( 1 )
{
}
[Constructable]
public IronIngot( int amount ) : base( CraftResource.MIron, amount )
{
}
public IronIngot( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x1BF2, 0x1BEF )]
public class BronzeIngot : BaseIngot
{
[Constructable]
public BronzeIngot() : this( 1 )
{
}
[Constructable]
public BronzeIngot( int amount ) : base( CraftResource.MBronze, amount )
{
}
public BronzeIngot(Serial serial) : base(serial)
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x1BF2, 0x1BEF )]
public class GoldIngot : BaseIngot
{
[Constructable]
public GoldIngot() : this(1)
{
}
[Constructable]
public GoldIngot( int amount ) : base( CraftResource.MGold, amount )
{
}
public GoldIngot( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x1BF2, 0x1BEF )]
public class CopperIngot : BaseIngot
{
[Constructable]
public CopperIngot() : this( 1 )
{
}
[Constructable]
public CopperIngot( int amount ) : base( CraftResource.MCopper, amount )
{
}
public CopperIngot( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x1BF2, 0x1BEF )]
public class OldcopperIngot : BaseIngot
{
[Constructable]
public OldcopperIngot() : this( 1 )
{
}
[Constructable]
public OldcopperIngot(int amount)
: base(CraftResource.MOldcopper, amount)
{
}
public OldcopperIngot(Serial serial)
: base(serial)
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x1BF2, 0x1BEF )]
public class DullcopperIngot : BaseIngot
{
[Constructable]
public DullcopperIngot() : this( 1 )
{
}
[Constructable]
public DullcopperIngot( int amount ) : base( CraftResource.MDullcopper, amount )
{
}
public DullcopperIngot(Serial serial)
: base(serial)
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x1BF2, 0x1BEF )]
public class SilverIngot : BaseIngot
{
[Constructable]
public SilverIngot() : this( 1 )
{
}
[Constructable]
public SilverIngot( int amount ) : base( CraftResource.MSilver, amount )
{
}
public SilverIngot(Serial serial) : base(serial)
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x1BF2, 0x1BEF )]
public class ShadowIngot : BaseIngot
{
[Constructable]
public ShadowIngot() : this( 1 )
{
}
[Constructable]
public ShadowIngot( int amount ) : base( CraftResource.MShadow, amount )
{
}
public ShadowIngot(Serial serial)
: base(serial)
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x1BF2, 0x1BEF )]
public class BloodrockIngot : BaseIngot
{
[Constructable]
public BloodrockIngot() : this( 1 )
{
}
[Constructable]
public BloodrockIngot( int amount ) : base( CraftResource.MBloodrock, amount )
{
}
public BloodrockIngot(Serial serial) : base(serial)
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class BlackrockIngot : BaseIngot
{
[Constructable]
public BlackrockIngot() : this(1)
{
}
[Constructable]
public BlackrockIngot(int amount)
: base(CraftResource.MBlackrock, amount)
{
}
public BlackrockIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class MytherilIngot : BaseIngot
{
[Constructable]
public MytherilIngot()
: this(1)
{
}
[Constructable]
public MytherilIngot(int amount)
: base(CraftResource.MMytheril, amount)
{
}
public MytherilIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class RoseIngot : BaseIngot
{
[Constructable]
public RoseIngot()
: this(1)
{
}
[Constructable]
public RoseIngot(int amount)
: base(CraftResource.MRose, amount)
{
}
public RoseIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class VeriteIngot : BaseIngot
{
[Constructable]
public VeriteIngot()
: this(1)
{
}
[Constructable]
public VeriteIngot(int amount)
: base(CraftResource.MVerite, amount)
{
}
public VeriteIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class AgapiteIngot : BaseIngot
{
[Constructable]
public AgapiteIngot()
: this(1)
{
}
[Constructable]
public AgapiteIngot(int amount)
: base(CraftResource.MAgapite, amount)
{
}
public AgapiteIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class RustyIngot : BaseIngot
{
[Constructable]
public RustyIngot()
: this(1)
{
}
[Constructable]
public RustyIngot(int amount)
: base(CraftResource.MRusty, amount)
{
}
public RustyIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class ValoriteIngot : BaseIngot
{
[Constructable]
public ValoriteIngot()
: this(1)
{
}
[Constructable]
public ValoriteIngot(int amount)
: base(CraftResource.MValorite, amount)
{
}
public ValoriteIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class DragonIngot : BaseIngot
{
[Constructable]
public DragonIngot()
: this(1)
{
}
[Constructable]
public DragonIngot(int amount)
: base(CraftResource.MDragon, amount)
{
}
public DragonIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class TitanIngot : BaseIngot
{
[Constructable]
public TitanIngot()
: this(1)
{
}
[Constructable]
public TitanIngot(int amount)
: base(CraftResource.MTitan, amount)
{
}
public TitanIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class CrystalineIngot : BaseIngot
{
[Constructable]
public CrystalineIngot()
: this(1)
{
}
[Constructable]
public CrystalineIngot(int amount)
: base(CraftResource.MCrystaline, amount)
{
}
public CrystalineIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class KryniteIngot : BaseIngot
{
[Constructable]
public KryniteIngot()
: this(1)
{
}
[Constructable]
public KryniteIngot(int amount)
: base(CraftResource.MKrynite, amount)
{
}
public KryniteIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class VulcanIngot : BaseIngot
{
[Constructable]
public VulcanIngot()
: this(1)
{
}
[Constructable]
public VulcanIngot(int amount)
: base(CraftResource.MVulcan, amount)
{
}
public VulcanIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class BloodcrestIngot : BaseIngot
{
[Constructable]
public BloodcrestIngot()
: this(1)
{
}
[Constructable]
public BloodcrestIngot(int amount)
: base(CraftResource.MBloodcrest, amount)
{
}
public BloodcrestIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class ElvinIngot : BaseIngot
{
[Constructable]
public ElvinIngot()
: this(1)
{
}
[Constructable]
public ElvinIngot(int amount)
: base(CraftResource.MElvin, amount)
{
}
public ElvinIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class AcidIngot : BaseIngot
{
[Constructable]
public AcidIngot()
: this(1)
{
}
[Constructable]
public AcidIngot(int amount)
: base(CraftResource.MAcid, amount)
{
}
public AcidIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class AquaIngot : BaseIngot
{
[Constructable]
public AquaIngot()
: this(1)
{
}
[Constructable]
public AquaIngot(int amount)
: base(CraftResource.MAqua, amount)
{
}
public AquaIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class EldarIngot : BaseIngot
{
[Constructable]
public EldarIngot()
: this(1)
{
}
[Constructable]
public EldarIngot(int amount)
: base(CraftResource.MEldar, amount)
{
}
public EldarIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class GlowingIngot : BaseIngot
{
[Constructable]
public GlowingIngot()
: this(1)
{
}
[Constructable]
public GlowingIngot(int amount)
: base(CraftResource.MGlowing, amount)
{
}
public GlowingIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class GorganIngot : BaseIngot
{
[Constructable]
public GorganIngot()
: this(1)
{
}
[Constructable]
public GorganIngot(int amount)
: base(CraftResource.MGorgan, amount)
{
}
public GorganIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class SandrockIngot : BaseIngot
{
[Constructable]
public SandrockIngot()
: this(1)
{
}
[Constructable]
public SandrockIngot(int amount)
: base(CraftResource.MSandrock, amount)
{
}
public SandrockIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1BF2, 0x1BEF)]
public class SteelIngot : BaseIngot
{
[Constructable]
public SteelIngot()
: this(1)
{
}
[Constructable]
public SteelIngot(int amount)
: base(CraftResource.MSteel, amount)
{
}
public SteelIngot(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.