context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
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.
*/
namespace TAUpdateControlSample
{
partial class TAUpdateControlForm
{
/// <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()
{
this.checkManualUpdate = new System.Windows.Forms.CheckBox();
this.checkAutoRefresh = new System.Windows.Forms.CheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtUpdateRate = new System.Windows.Forms.TextBox();
this.txtRefreshRate = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.btnStats = new System.Windows.Forms.Button();
this.txtStatistics = new System.Windows.Forms.TextBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.cbRefreshType = new System.Windows.Forms.ComboBox();
this.btnRefresh = new System.Windows.Forms.Button();
this.cbUpdateMethod = new System.Windows.Forms.ComboBox();
this.txtUpdateValue = new System.Windows.Forms.TextBox();
this.btnApply = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.btnHelp = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
this.SuspendLayout();
//
// checkManualUpdate
//
this.checkManualUpdate.AutoSize = true;
this.checkManualUpdate.Location = new System.Drawing.Point(10, 19);
this.checkManualUpdate.Name = "checkManualUpdate";
this.checkManualUpdate.Size = new System.Drawing.Size(61, 17);
this.checkManualUpdate.TabIndex = 0;
this.checkManualUpdate.Text = "Manual";
this.checkManualUpdate.UseVisualStyleBackColor = true;
this.checkManualUpdate.CheckedChanged += new System.EventHandler(this.checkManualUpdate_CheckedChanged);
//
// checkAutoRefresh
//
this.checkAutoRefresh.AutoSize = true;
this.checkAutoRefresh.Location = new System.Drawing.Point(10, 22);
this.checkAutoRefresh.Name = "checkAutoRefresh";
this.checkAutoRefresh.Size = new System.Drawing.Size(73, 17);
this.checkAutoRefresh.TabIndex = 1;
this.checkAutoRefresh.Text = "Automatic";
this.checkAutoRefresh.UseVisualStyleBackColor = true;
this.checkAutoRefresh.CheckedChanged += new System.EventHandler(this.checkAutoRefresh_CheckedChanged);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.txtUpdateValue);
this.groupBox1.Controls.Add(this.cbUpdateMethod);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.txtUpdateRate);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.checkManualUpdate);
this.groupBox1.Location = new System.Drawing.Point(13, 13);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(308, 80);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Update Settings";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.txtRefreshRate);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.checkAutoRefresh);
this.groupBox2.Location = new System.Drawing.Point(13, 106);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(151, 80);
this.groupBox2.TabIndex = 3;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Refresh Settings";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(7, 48);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(33, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Rate:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(7, 52);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(33, 13);
this.label2.TabIndex = 2;
this.label2.Text = "Rate:";
//
// txtUpdateRate
//
this.txtUpdateRate.Location = new System.Drawing.Point(46, 44);
this.txtUpdateRate.Name = "txtUpdateRate";
this.txtUpdateRate.Size = new System.Drawing.Size(68, 20);
this.txtUpdateRate.TabIndex = 2;
this.txtUpdateRate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// txtRefreshRate
//
this.txtRefreshRate.Location = new System.Drawing.Point(46, 48);
this.txtRefreshRate.Name = "txtRefreshRate";
this.txtRefreshRate.Size = new System.Drawing.Size(68, 20);
this.txtRefreshRate.TabIndex = 3;
this.txtRefreshRate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(120, 48);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(24, 13);
this.label3.TabIndex = 3;
this.label3.Text = "sec";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(120, 52);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(24, 13);
this.label4.TabIndex = 4;
this.label4.Text = "sec";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.txtStatistics);
this.groupBox3.Controls.Add(this.btnStats);
this.groupBox3.Location = new System.Drawing.Point(13, 192);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(308, 199);
this.groupBox3.TabIndex = 4;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Statistics";
//
// btnStats
//
this.btnStats.Location = new System.Drawing.Point(10, 20);
this.btnStats.Name = "btnStats";
this.btnStats.Size = new System.Drawing.Size(75, 23);
this.btnStats.TabIndex = 0;
this.btnStats.Text = "Retrieve";
this.btnStats.UseVisualStyleBackColor = true;
this.btnStats.Click += new System.EventHandler(this.btnStats_Click);
//
// txtStatistics
//
this.txtStatistics.Location = new System.Drawing.Point(10, 49);
this.txtStatistics.Multiline = true;
this.txtStatistics.Name = "txtStatistics";
this.txtStatistics.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtStatistics.Size = new System.Drawing.Size(288, 144);
this.txtStatistics.TabIndex = 1;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.label7);
this.groupBox4.Controls.Add(this.btnRefresh);
this.groupBox4.Controls.Add(this.cbRefreshType);
this.groupBox4.Location = new System.Drawing.Point(170, 106);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(151, 80);
this.groupBox4.TabIndex = 5;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Display Refresh";
//
// cbRefreshType
//
this.cbRefreshType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbRefreshType.FormattingEnabled = true;
this.cbRefreshType.Items.AddRange(new object[] {
"Short Update",
"Quick Update",
"Full Update",
"Asynchronous Update",
"Full Screen Redraw"});
this.cbRefreshType.Location = new System.Drawing.Point(58, 20);
this.cbRefreshType.Name = "cbRefreshType";
this.cbRefreshType.Size = new System.Drawing.Size(83, 21);
this.cbRefreshType.TabIndex = 0;
//
// btnRefresh
//
this.btnRefresh.Location = new System.Drawing.Point(66, 46);
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(75, 23);
this.btnRefresh.TabIndex = 1;
this.btnRefresh.Text = "Refresh";
this.btnRefresh.UseVisualStyleBackColor = true;
this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
//
// cbUpdateMethod
//
this.cbUpdateMethod.FormattingEnabled = true;
this.cbUpdateMethod.Items.AddRange(new object[] {
"Event-based",
"CPU Usage-based"});
this.cbUpdateMethod.Location = new System.Drawing.Point(202, 17);
this.cbUpdateMethod.Name = "cbUpdateMethod";
this.cbUpdateMethod.Size = new System.Drawing.Size(96, 21);
this.cbUpdateMethod.TabIndex = 4;
//
// txtUpdateValue
//
this.txtUpdateValue.Location = new System.Drawing.Point(202, 44);
this.txtUpdateValue.Name = "txtUpdateValue";
this.txtUpdateValue.Size = new System.Drawing.Size(96, 20);
this.txtUpdateValue.TabIndex = 5;
//
// btnApply
//
this.btnApply.Location = new System.Drawing.Point(243, 397);
this.btnApply.Name = "btnApply";
this.btnApply.Size = new System.Drawing.Size(75, 23);
this.btnApply.TabIndex = 6;
this.btnApply.Text = "Apply";
this.btnApply.UseVisualStyleBackColor = true;
this.btnApply.Click += new System.EventHandler(this.btnApply_Click);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(150, 20);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(46, 13);
this.label5.TabIndex = 6;
this.label5.Text = "Method:";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(150, 48);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(37, 13);
this.label6.TabIndex = 7;
this.label6.Text = "Value:";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(6, 22);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(46, 13);
this.label7.TabIndex = 8;
this.label7.Text = "Method:";
//
// btnHelp
//
this.btnHelp.Location = new System.Drawing.Point(162, 397);
this.btnHelp.Name = "btnHelp";
this.btnHelp.Size = new System.Drawing.Size(75, 23);
this.btnHelp.TabIndex = 7;
this.btnHelp.Text = "Help";
this.btnHelp.UseVisualStyleBackColor = true;
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// TAUpdateControlForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(330, 428);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnApply);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "TAUpdateControlForm";
this.ShowInTaskbar = false;
this.Text = "TAUpdateControl Settings";
this.TopMost = true;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.TAUpdateControlForm_FormClosing);
this.Load += new System.EventHandler(this.TAUpdateControlForm_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.CheckBox checkManualUpdate;
private System.Windows.Forms.CheckBox checkAutoRefresh;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtUpdateRate;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtRefreshRate;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.TextBox txtStatistics;
private System.Windows.Forms.Button btnStats;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.ComboBox cbRefreshType;
private System.Windows.Forms.Button btnRefresh;
private System.Windows.Forms.ComboBox cbUpdateMethod;
private System.Windows.Forms.TextBox txtUpdateValue;
private System.Windows.Forms.Button btnApply;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Button btnHelp;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable UnassignedField.Global
// ReSharper disable CollectionNeverUpdated.Global
namespace Apache.Ignite.Core.Tests.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using NUnit.Framework;
/// <summary>
/// Binary builder self test.
/// </summary>
public class BinaryBuilderSelfTest
{
/** Undefined type: Empty. */
private const string TypeEmpty = "EmptyUndefined";
/** Grid. */
private Ignite _grid;
/** Marshaller. */
private Marshaller _marsh;
/// <summary>
/// Set up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
TestUtils.KillProcesses();
var cfg = new IgniteConfiguration
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof (Empty)),
new BinaryTypeConfiguration(typeof (Primitives)),
new BinaryTypeConfiguration(typeof (PrimitiveArrays)),
new BinaryTypeConfiguration(typeof (StringDateGuidEnum)),
new BinaryTypeConfiguration(typeof (WithRaw)),
new BinaryTypeConfiguration(typeof (MetaOverwrite)),
new BinaryTypeConfiguration(typeof (NestedOuter)),
new BinaryTypeConfiguration(typeof (NestedInner)),
new BinaryTypeConfiguration(typeof (MigrationOuter)),
new BinaryTypeConfiguration(typeof (MigrationInner)),
new BinaryTypeConfiguration(typeof (InversionOuter)),
new BinaryTypeConfiguration(typeof (InversionInner)),
new BinaryTypeConfiguration(typeof (CompositeOuter)),
new BinaryTypeConfiguration(typeof (CompositeInner)),
new BinaryTypeConfiguration(typeof (CompositeArray)),
new BinaryTypeConfiguration(typeof (CompositeContainer)),
new BinaryTypeConfiguration(typeof (ToBinary)),
new BinaryTypeConfiguration(typeof (Remove)),
new BinaryTypeConfiguration(typeof (RemoveInner)),
new BinaryTypeConfiguration(typeof (BuilderInBuilderOuter)),
new BinaryTypeConfiguration(typeof (BuilderInBuilderInner)),
new BinaryTypeConfiguration(typeof (BuilderCollection)),
new BinaryTypeConfiguration(typeof (BuilderCollectionItem)),
new BinaryTypeConfiguration(typeof (DecimalHolder)),
new BinaryTypeConfiguration(TypeEmpty),
new BinaryTypeConfiguration(typeof(TestEnumRegistered))
},
DefaultIdMapper = new IdMapper()
},
JvmClasspath = TestUtils.CreateTestClasspath(),
JvmOptions = TestUtils.TestJavaOptions(),
SpringConfigUrl = "config\\binary.xml"
};
_grid = (Ignite) Ignition.Start(cfg);
_marsh = _grid.Marshaller;
}
/// <summary>
/// Tear down routine.
/// </summary>
[TestFixtureTearDown]
public virtual void TearDown()
{
if (_grid != null)
Ignition.Stop(_grid.Name, true);
_grid = null;
}
/// <summary>
/// Ensure that binary engine is able to work with type names, which are not configured.
/// </summary>
[Test]
public void TestNonConfigured()
{
string typeName1 = "Type1";
string typeName2 = "Type2";
string field1 = "field1";
string field2 = "field2";
// 1. Ensure that builder works fine.
IBinaryObject binObj1 = _grid.GetBinary().GetBuilder(typeName1).SetField(field1, 1).Build();
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 2. Ensure that object can be unmarshalled without deserialization.
byte[] data = ((BinaryObject) binObj1).Data;
binObj1 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 3. Ensure that we can nest one anonymous object inside another
IBinaryObject binObj2 =
_grid.GetBinary().GetBuilder(typeName2).SetField(field2, binObj1).Build();
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 4. Ensure that we can unmarshal object with other nested object.
data = ((BinaryObject) binObj2).Data;
binObj2 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
}
/// <summary>
/// Test "ToBinary()" method.
/// </summary>
[Test]
public void TestToBinary()
{
DateTime date = DateTime.Now.ToUniversalTime();
Guid guid = Guid.NewGuid();
IBinary api = _grid.GetBinary();
// 1. Primitives.
Assert.AreEqual(1, api.ToBinary<byte>((byte)1));
Assert.AreEqual(1, api.ToBinary<short>((short)1));
Assert.AreEqual(1, api.ToBinary<int>(1));
Assert.AreEqual(1, api.ToBinary<long>((long)1));
Assert.AreEqual((float)1, api.ToBinary<float>((float)1));
Assert.AreEqual((double)1, api.ToBinary<double>((double)1));
Assert.AreEqual(true, api.ToBinary<bool>(true));
Assert.AreEqual('a', api.ToBinary<char>('a'));
// 2. Special types.
Assert.AreEqual("a", api.ToBinary<string>("a"));
Assert.AreEqual(date, api.ToBinary<DateTime>(date));
Assert.AreEqual(guid, api.ToBinary<Guid>(guid));
Assert.AreEqual(TestEnumRegistered.One, api.ToBinary<IBinaryObject>(TestEnumRegistered.One)
.Deserialize<TestEnumRegistered>());
// 3. Arrays.
Assert.AreEqual(new byte[] { 1 }, api.ToBinary<byte[]>(new byte[] { 1 }));
Assert.AreEqual(new short[] { 1 }, api.ToBinary<short[]>(new short[] { 1 }));
Assert.AreEqual(new[] { 1 }, api.ToBinary<int[]>(new[] { 1 }));
Assert.AreEqual(new long[] { 1 }, api.ToBinary<long[]>(new long[] { 1 }));
Assert.AreEqual(new float[] { 1 }, api.ToBinary<float[]>(new float[] { 1 }));
Assert.AreEqual(new double[] { 1 }, api.ToBinary<double[]>(new double[] { 1 }));
Assert.AreEqual(new[] { true }, api.ToBinary<bool[]>(new[] { true }));
Assert.AreEqual(new[] { 'a' }, api.ToBinary<char[]>(new[] { 'a' }));
Assert.AreEqual(new[] { "a" }, api.ToBinary<string[]>(new[] { "a" }));
Assert.AreEqual(new[] { date }, api.ToBinary<DateTime[]>(new[] { date }));
Assert.AreEqual(new[] { guid }, api.ToBinary<Guid[]>(new[] { guid }));
Assert.AreEqual(new[] { TestEnumRegistered.One},
api.ToBinary<IBinaryObject[]>(new[] { TestEnumRegistered.One})
.Select(x => x.Deserialize<TestEnumRegistered>()).ToArray());
// 4. Objects.
IBinaryObject binObj = api.ToBinary<IBinaryObject>(new ToBinary(1));
Assert.AreEqual(typeof(ToBinary).Name, binObj.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj.GetBinaryType().Fields.Count);
Assert.AreEqual("Val", binObj.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj.GetBinaryType().GetFieldTypeName("Val"));
Assert.AreEqual(1, binObj.GetField<int>("val"));
Assert.AreEqual(1, binObj.Deserialize<ToBinary>().Val);
// 5. Object array.
var binObjArr = api.ToBinary<object[]>(new object[] {new ToBinary(1)})
.OfType<IBinaryObject>().ToArray();
Assert.AreEqual(1, binObjArr.Length);
Assert.AreEqual(1, binObjArr[0].GetField<int>("Val"));
Assert.AreEqual(1, binObjArr[0].Deserialize<ToBinary>().Val);
}
/// <summary>
/// Test builder field remove logic.
/// </summary>
[Test]
public void TestRemove()
{
// Create empty object.
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Remove)).Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Remove).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
// Populate it with field.
IBinaryObjectBuilder builder = binObj.ToBuilder();
Assert.IsNull(builder.GetField<object>("val"));
object val = 1;
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
binObj = builder.Build();
Assert.AreEqual(val, binObj.GetField<object>("val"));
Assert.AreEqual(val, binObj.Deserialize<Remove>().Val);
meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Remove).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("val"));
// Perform field remove.
builder = binObj.ToBuilder();
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
binObj = builder.Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
// Test correct removal of field being referenced by handle somewhere else.
RemoveInner inner = new RemoveInner(2);
binObj = _grid.GetBinary().GetBuilder(typeof(Remove))
.SetField("val", inner)
.SetField("val2", inner)
.Build();
binObj = binObj.ToBuilder().RemoveField("val").Build();
Remove obj = binObj.Deserialize<Remove>();
Assert.IsNull(obj.Val);
Assert.AreEqual(2, obj.Val2.Val);
}
/// <summary>
/// Test builder-in-builder scenario.
/// </summary>
[Test]
public void TestBuilderInBuilder()
{
// Test different builders assembly.
IBinaryObjectBuilder builderOuter = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter));
IBinaryObjectBuilder builderInner = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner));
builderOuter.SetField<object>("inner", builderInner);
builderInner.SetField<object>("outer", builderOuter);
IBinaryObject outerbinObj = builderOuter.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderOuter).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("inner", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
IBinaryObject innerbinObj = outerbinObj.GetField<IBinaryObject>("inner");
meta = innerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderInner).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("outer", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("outer"));
BuilderInBuilderOuter outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
// Test same builders assembly.
innerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner)).Build();
outerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter))
.SetField("inner", innerbinObj)
.SetField("inner2", innerbinObj)
.Build();
meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderOuter).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("inner"));
Assert.IsTrue(meta.Fields.Contains("inner2"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner2"));
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer.Inner, outer.Inner2);
builderOuter = _grid.GetBinary().GetBuilder(outerbinObj);
IBinaryObjectBuilder builderInner2 = builderOuter.GetField<IBinaryObjectBuilder>("inner2");
builderInner2.SetField("outer", builderOuter);
outerbinObj = builderOuter.Build();
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
Assert.AreSame(outer.Inner, outer.Inner2);
}
/// <summary>
/// Test for decimals building.
/// </summary>
[Test]
public void TestDecimals()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(DecimalHolder))
.SetField("val", decimal.One)
.SetField("valArr", new decimal?[] { decimal.MinusOne })
.Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(DecimalHolder).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("val"));
Assert.IsTrue(meta.Fields.Contains("valArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("val"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("valArr"));
Assert.AreEqual(decimal.One, binObj.GetField<decimal>("val"));
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, binObj.GetField<decimal?[]>("valArr"));
DecimalHolder obj = binObj.Deserialize<DecimalHolder>();
Assert.AreEqual(decimal.One, obj.Val);
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, obj.ValArr);
}
/// <summary>
/// Test for an object returning collection of builders.
/// </summary>
[Test]
public void TestBuilderCollection()
{
// Test collection with single element.
IBinaryObjectBuilder builderCol = _grid.GetBinary().GetBuilder(typeof(BuilderCollection));
IBinaryObjectBuilder builderItem =
_grid.GetBinary().GetBuilder(typeof(BuilderCollectionItem)).SetField("val", 1);
builderCol.SetCollectionField("col", new ArrayList { builderItem });
IBinaryObject binCol = builderCol.Build();
IBinaryType meta = binCol.GetBinaryType();
Assert.AreEqual(typeof(BuilderCollection).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("col", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
var binColItems = binCol.GetField<ArrayList>("col");
Assert.AreEqual(1, binColItems.Count);
var binItem = (IBinaryObject) binColItems[0];
meta = binItem.GetBinaryType();
Assert.AreEqual(typeof(BuilderCollectionItem).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("val"));
BuilderCollection col = binCol.Deserialize<BuilderCollection>();
Assert.IsNotNull(col.Col);
Assert.AreEqual(1, col.Col.Count);
Assert.AreEqual(1, ((BuilderCollectionItem) col.Col[0]).Val);
// Add more binary objects to collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
IList builderColItems = builderCol.GetField<IList>("col");
Assert.AreEqual(1, builderColItems.Count);
BinaryObjectBuilder builderColItem = (BinaryObjectBuilder) builderColItems[0];
builderColItem.SetField("val", 2); // Change nested value.
builderColItems.Add(builderColItem); // Add the same object to check handles.
builderColItems.Add(builderItem); // Add item from another builder.
builderColItems.Add(binItem); // Add item in binary form.
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
Assert.AreEqual(4, col.Col.Count);
var item0 = (BuilderCollectionItem) col.Col[0];
var item1 = (BuilderCollectionItem) col.Col[1];
var item2 = (BuilderCollectionItem) col.Col[2];
var item3 = (BuilderCollectionItem) col.Col[3];
Assert.AreEqual(2, item0.Val);
Assert.AreSame(item0, item1);
Assert.AreNotSame(item0, item2);
Assert.AreNotSame(item0, item3);
Assert.AreEqual(1, item2.Val);
Assert.AreEqual(1, item3.Val);
Assert.AreNotSame(item2, item3);
// Test handle update inside collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
builderColItems = builderCol.GetField<IList>("col");
((BinaryObjectBuilder) builderColItems[1]).SetField("val", 3);
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
item0 = (BuilderCollectionItem) col.Col[0];
item1 = (BuilderCollectionItem) col.Col[1];
Assert.AreEqual(3, item0.Val);
Assert.AreSame(item0, item1);
}
/// <summary>
/// Test build of an empty object.
/// </summary>
[Test]
public void TestEmptyDefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(0, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(typeof(Empty).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
Empty obj = binObj.Deserialize<Empty>();
Assert.IsNotNull(obj);
}
/// <summary>
/// Test build of an empty undefined object.
/// </summary>
[Test]
public void TestEmptyUndefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(TypeEmpty).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(0, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(TypeEmpty, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test object rebuild with no changes.
/// </summary>
[Test]
public void TestEmptyRebuild()
{
var binObj = (BinaryObject) _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
BinaryObject newbinObj = (BinaryObject) _grid.GetBinary().GetBuilder(binObj).Build();
Assert.AreEqual(binObj.Data, newbinObj.Data);
}
/// <summary>
/// Test hash code alteration.
/// </summary>
[Test]
public void TestHashCodeChange()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).SetHashCode(100).Build();
Assert.AreEqual(100, binObj.GetHashCode());
}
/// <summary>
/// Test primitive fields setting.
/// </summary>
[Test]
public void TestPrimitiveFields()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetField<byte>("fByte", 1)
.SetField("fBool", true)
.SetField<short>("fShort", 2)
.SetField("fChar", 'a')
.SetField("fInt", 3)
.SetField<long>("fLong", 4)
.SetField<float>("fFloat", 5)
.SetField<double>("fDouble", 6)
.SetHashCode(100)
.Build();
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Primitives).Name, meta.TypeName);
Assert.AreEqual(8, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(1, binObj.GetField<byte>("fByte"));
Assert.AreEqual(true, binObj.GetField<bool>("fBool"));
Assert.AreEqual(2, binObj.GetField<short>("fShort"));
Assert.AreEqual('a', binObj.GetField<char>("fChar"));
Assert.AreEqual(3, binObj.GetField<int>("fInt"));
Assert.AreEqual(4, binObj.GetField<long>("fLong"));
Assert.AreEqual(5, binObj.GetField<float>("fFloat"));
Assert.AreEqual(6, binObj.GetField<double>("fDouble"));
Primitives obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(1, obj.FByte);
Assert.AreEqual(true, obj.FBool);
Assert.AreEqual(2, obj.FShort);
Assert.AreEqual('a', obj.FChar);
Assert.AreEqual(3, obj.FInt);
Assert.AreEqual(4, obj.FLong);
Assert.AreEqual(5, obj.FFloat);
Assert.AreEqual(6, obj.FDouble);
// Overwrite.
binObj = binObj.ToBuilder()
.SetField<byte>("fByte", 7)
.SetField("fBool", false)
.SetField<short>("fShort", 8)
.SetField("fChar", 'b')
.SetField("fInt", 9)
.SetField<long>("fLong", 10)
.SetField<float>("fFloat", 11)
.SetField<double>("fDouble", 12)
.SetHashCode(200)
.Build();
Assert.AreEqual(200, binObj.GetHashCode());
Assert.AreEqual(7, binObj.GetField<byte>("fByte"));
Assert.AreEqual(false, binObj.GetField<bool>("fBool"));
Assert.AreEqual(8, binObj.GetField<short>("fShort"));
Assert.AreEqual('b', binObj.GetField<char>("fChar"));
Assert.AreEqual(9, binObj.GetField<int>("fInt"));
Assert.AreEqual(10, binObj.GetField<long>("fLong"));
Assert.AreEqual(11, binObj.GetField<float>("fFloat"));
Assert.AreEqual(12, binObj.GetField<double>("fDouble"));
obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(7, obj.FByte);
Assert.AreEqual(false, obj.FBool);
Assert.AreEqual(8, obj.FShort);
Assert.AreEqual('b', obj.FChar);
Assert.AreEqual(9, obj.FInt);
Assert.AreEqual(10, obj.FLong);
Assert.AreEqual(11, obj.FFloat);
Assert.AreEqual(12, obj.FDouble);
}
/// <summary>
/// Test primitive array fields setting.
/// </summary>
[Test]
public void TestPrimitiveArrayFields()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetField("fByte", new byte[] { 1 })
.SetField("fBool", new[] { true })
.SetField("fShort", new short[] { 2 })
.SetField("fChar", new[] { 'a' })
.SetField("fInt", new[] { 3 })
.SetField("fLong", new long[] { 4 })
.SetField("fFloat", new float[] { 5 })
.SetField("fDouble", new double[] { 6 })
.SetHashCode(100)
.Build();
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(PrimitiveArrays).Name, meta.TypeName);
Assert.AreEqual(8, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(new byte[] { 1 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { true }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 2 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'a' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 3 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 4 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 5 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 6 }, binObj.GetField<double[]>("fDouble"));
PrimitiveArrays obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 1 }, obj.FByte);
Assert.AreEqual(new[] { true }, obj.FBool);
Assert.AreEqual(new short[] { 2 }, obj.FShort);
Assert.AreEqual(new[] { 'a' }, obj.FChar);
Assert.AreEqual(new[] { 3 }, obj.FInt);
Assert.AreEqual(new long[] { 4 }, obj.FLong);
Assert.AreEqual(new float[] { 5 }, obj.FFloat);
Assert.AreEqual(new double[] { 6 }, obj.FDouble);
// Overwrite.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("fByte", new byte[] { 7 })
.SetField("fBool", new[] { false })
.SetField("fShort", new short[] { 8 })
.SetField("fChar", new[] { 'b' })
.SetField("fInt", new[] { 9 })
.SetField("fLong", new long[] { 10 })
.SetField("fFloat", new float[] { 11 })
.SetField("fDouble", new double[] { 12 })
.SetHashCode(200)
.Build();
Assert.AreEqual(200, binObj.GetHashCode());
Assert.AreEqual(new byte[] { 7 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { false }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 8 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'b' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 9 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 10 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 11 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 12 }, binObj.GetField<double[]>("fDouble"));
obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 7 }, obj.FByte);
Assert.AreEqual(new[] { false }, obj.FBool);
Assert.AreEqual(new short[] { 8 }, obj.FShort);
Assert.AreEqual(new[] { 'b' }, obj.FChar);
Assert.AreEqual(new[] { 9 }, obj.FInt);
Assert.AreEqual(new long[] { 10 }, obj.FLong);
Assert.AreEqual(new float[] { 11 }, obj.FFloat);
Assert.AreEqual(new double[] { 12 }, obj.FDouble);
}
/// <summary>
/// Test non-primitive fields and their array counterparts.
/// </summary>
[Test]
public void TestStringDateGuidEnum()
{
DateTime? nDate = DateTime.Now;
Guid? nGuid = Guid.NewGuid();
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str")
.SetField("fNDate", nDate)
.SetGuidField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.One)
.SetField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetField("fEnumArr", new[] { TestEnum.One })
.SetHashCode(100)
.Build();
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(StringDateGuidEnum).Name, meta.TypeName);
Assert.AreEqual(8, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameString, meta.GetFieldTypeName("fStr"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("fNDate"));
Assert.AreEqual(BinaryTypeNames.TypeNameGuid, meta.GetFieldTypeName("fNGuid"));
Assert.AreEqual(BinaryTypeNames.TypeNameEnum, meta.GetFieldTypeName("fEnum"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayString, meta.GetFieldTypeName("fStrArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("fDateArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayGuid, meta.GetFieldTypeName("fGuidArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayEnum, meta.GetFieldTypeName("fEnumArr"));
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, binObj.GetField<TestEnum[]>("fEnumArr"));
StringDateGuidEnum obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] { "str" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.One }, obj.FEnumArr);
// Check builder field caching.
var builder = _grid.GetBinary().GetBuilder(binObj);
Assert.AreEqual("str", builder.GetField<string>("fStr"));
Assert.AreEqual(nDate, builder.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nGuid, builder.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, builder.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str" }, builder.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, builder.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nGuid }, builder.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, builder.GetField<TestEnum[]>("fEnumArr"));
// Check reassemble.
binObj = builder.Build();
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, binObj.GetField<TestEnum[]>("fEnumArr"));
obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] { "str" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.One }, obj.FEnumArr);
// Overwrite.
nDate = DateTime.Now.ToUniversalTime();
nGuid = Guid.NewGuid();
binObj = builder
.SetField("fStr", "str2")
.SetTimestampField("fNDate", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.Two)
.SetField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetField("fGuidArr", new[] { nGuid })
.SetField("fEnumArr", new[] { TestEnum.Two })
.SetHashCode(200)
.Build();
Assert.AreEqual(200, binObj.GetHashCode());
Assert.AreEqual("str2", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.Two, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str2" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.Two}, binObj.GetField<TestEnum[]>("fEnumArr"));
obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str2", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.Two, obj.FEnum);
Assert.AreEqual(new[] { "str2" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.Two }, obj.FEnumArr);
}
[Test]
public void TestEnumMeta()
{
var bin = _grid.GetBinary();
// Put to cache to populate metas
var binEnum = bin.ToBinary<IBinaryObject>(TestEnumRegistered.One);
Assert.AreEqual(_marsh.GetDescriptor(typeof (TestEnumRegistered)).TypeId, binEnum.GetBinaryType().TypeId);
Assert.AreEqual(0, binEnum.EnumValue);
var meta = binEnum.GetBinaryType();
Assert.IsTrue(meta.IsEnum);
Assert.AreEqual(typeof (TestEnumRegistered).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test arrays.
/// </summary>
[Test]
public void TestCompositeArray()
{
// 1. Test simple array.
object[] inArr = { new CompositeInner(1) };
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("inArr", inArr).Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeArray).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(100, binObj.GetHashCode());
var binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(1, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
CompositeArray arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(1, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
// 2. Test addition to array.
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("inArr", new[] { binInArr[0], null }).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.IsNull(binInArr[1]);
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
Assert.IsNull(arr.InArr[1]);
binInArr[1] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(300)
.SetField("inArr", binInArr.OfType<object>().ToArray()).Build();
Assert.AreEqual(300, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(2, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[1]).Val);
// 3. Test top-level handle inversion.
CompositeInner inner = new CompositeInner(1);
inArr = new object[] { inner, inner };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("inArr", inArr).Build();
Assert.AreEqual(100, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
binInArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("inArr", binInArr.ToArray<object>()).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
// 4. Test nested object handle inversion.
CompositeOuter[] outArr = { new CompositeOuter(inner), new CompositeOuter(inner) };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("outArr", outArr.ToArray<object>()).Build();
meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeArray).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("outArr"));
Assert.AreEqual(100, binObj.GetHashCode());
var binOutArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binOutArr.Length);
Assert.AreEqual(1, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
binOutArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeOuter))
.SetField("inner", new CompositeInner(2)).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("outArr", binOutArr.ToArray<object>()).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(2, ((CompositeOuter)arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter)arr.OutArr[1]).Inner.Val);
}
/// <summary>
/// Test container types other than array.
/// </summary>
[Test]
public void TestCompositeContainer()
{
ArrayList col = new ArrayList();
IDictionary dict = new Hashtable();
col.Add(new CompositeInner(1));
dict[3] = new CompositeInner(3);
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeContainer)).SetHashCode(100)
.SetCollectionField("col", col)
.SetDictionaryField("dict", dict).Build();
// 1. Check meta.
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeContainer).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
Assert.AreEqual(BinaryTypeNames.TypeNameMap, meta.GetFieldTypeName("dict"));
// 2. Check in binary form.
Assert.AreEqual(1, binObj.GetField<ICollection>("col").Count);
Assert.AreEqual(1, binObj.GetField<ICollection>("col").OfType<IBinaryObject>().First()
.GetField<int>("val"));
Assert.AreEqual(1, binObj.GetField<IDictionary>("dict").Count);
Assert.AreEqual(3, ((IBinaryObject) binObj.GetField<IDictionary>("dict")[3]).GetField<int>("val"));
// 3. Check in deserialized form.
CompositeContainer obj = binObj.Deserialize<CompositeContainer>();
Assert.AreEqual(1, obj.Col.Count);
Assert.AreEqual(1, obj.Col.OfType<CompositeInner>().First().Val);
Assert.AreEqual(1, obj.Dict.Count);
Assert.AreEqual(3, ((CompositeInner) obj.Dict[3]).Val);
}
/// <summary>
/// Ensure that raw data is not lost during build.
/// </summary>
[Test]
public void TestRawData()
{
var raw = new WithRaw
{
A = 1,
B = 2
};
var binObj = _marsh.Unmarshal<IBinaryObject>(_marsh.Marshal(raw), BinaryMode.ForceBinary);
raw = binObj.Deserialize<WithRaw>();
Assert.AreEqual(1, raw.A);
Assert.AreEqual(2, raw.B);
IBinaryObject newbinObj = _grid.GetBinary().GetBuilder(binObj).SetField("a", 3).Build();
raw = newbinObj.Deserialize<WithRaw>();
Assert.AreEqual(3, raw.A);
Assert.AreEqual(2, raw.B);
}
/// <summary>
/// Test nested objects.
/// </summary>
[Test]
public void TestNested()
{
// 1. Create from scratch.
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(NestedOuter));
NestedInner inner1 = new NestedInner {Val = 1};
builder.SetField("inner1", inner1);
IBinaryObject outerbinObj = builder.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(NestedOuter).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner1"));
IBinaryObject innerbinObj1 = outerbinObj.GetField<IBinaryObject>("inner1");
IBinaryType innerMeta = innerbinObj1.GetBinaryType();
Assert.AreEqual(typeof(NestedInner).Name, innerMeta.TypeName);
Assert.AreEqual(1, innerMeta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameInt, innerMeta.GetFieldTypeName("Val"));
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(1, inner1.Val);
NestedOuter outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(outer.Inner1.Val, 1);
Assert.IsNull(outer.Inner2);
// 2. Add another field over existing binary object.
builder = _grid.GetBinary().GetBuilder(outerbinObj);
NestedInner inner2 = new NestedInner {Val = 2};
builder.SetField("inner2", inner2);
outerbinObj = builder.Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(1, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
// 3. Try setting inner object in binary form.
innerbinObj1 = _grid.GetBinary().GetBuilder(innerbinObj1).SetField("val", 3).Build();
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(3, inner1.Val);
outerbinObj = _grid.GetBinary().GetBuilder(outerbinObj).SetField<object>("inner1", innerbinObj1).Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(3, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
}
/// <summary>
/// Test handle migration.
/// </summary>
[Test]
public void TestHandleMigration()
{
// 1. Simple comparison of results.
MigrationInner inner = new MigrationInner {Val = 1};
MigrationOuter outer = new MigrationOuter
{
Inner1 = inner,
Inner2 = inner
};
byte[] outerBytes = _marsh.Marshal(outer);
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(MigrationOuter));
builder.SetHashCode(outer.GetHashCode());
builder.SetField<object>("inner1", inner);
builder.SetField<object>("inner2", inner);
BinaryObject portOuter = (BinaryObject) builder.Build();
byte[] portOuterBytes = new byte[outerBytes.Length];
Buffer.BlockCopy(portOuter.Data, 0, portOuterBytes, 0, portOuterBytes.Length);
Assert.AreEqual(outerBytes, portOuterBytes);
// 2. Change the first inner object so that the handle must migrate.
MigrationInner inner1 = new MigrationInner {Val = 2};
IBinaryObject portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1).Build();
MigrationOuter outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
// 3. Change the first value using serialized form.
IBinaryObject inner1Port =
_grid.GetBinary().GetBuilder(typeof(MigrationInner)).SetField("val", 2).Build();
portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1Port).Build();
outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
}
/// <summary>
/// Test handle inversion.
/// </summary>
[Test]
public void TestHandleInversion()
{
InversionInner inner = new InversionInner();
InversionOuter outer = new InversionOuter();
inner.Outer = outer;
outer.Inner = inner;
byte[] rawOuter = _marsh.Marshal(outer);
IBinaryObject portOuter = _marsh.Unmarshal<IBinaryObject>(rawOuter, BinaryMode.ForceBinary);
IBinaryObject portInner = portOuter.GetField<IBinaryObject>("inner");
// 1. Ensure that inner object can be deserialized after build.
IBinaryObject portInnerNew = _grid.GetBinary().GetBuilder(portInner).Build();
InversionInner innerNew = portInnerNew.Deserialize<InversionInner>();
Assert.AreSame(innerNew, innerNew.Outer.Inner);
// 2. Ensure that binary object with external dependencies could be added to builder.
IBinaryObject portOuterNew =
_grid.GetBinary().GetBuilder(typeof(InversionOuter)).SetField<object>("inner", portInner).Build();
InversionOuter outerNew = portOuterNew.Deserialize<InversionOuter>();
Assert.AreNotSame(outerNew, outerNew.Inner.Outer);
Assert.AreSame(outerNew.Inner, outerNew.Inner.Outer.Inner);
}
/// <summary>
/// Test build multiple objects.
/// </summary>
[Test]
public void TestBuildMultiple()
{
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(Primitives));
builder.SetField<byte>("fByte", 1).SetField("fBool", true);
IBinaryObject po1 = builder.Build();
IBinaryObject po2 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder.SetField<byte>("fByte", 2);
IBinaryObject po3 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(2, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder = _grid.GetBinary().GetBuilder(po1);
builder.SetField<byte>("fByte", 10);
po1 = builder.Build();
po2 = builder.Build();
builder.SetField<byte>("fByte", 20);
po3 = builder.Build();
Assert.AreEqual(10, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(10, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(20, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po3.GetField<bool>("fBool"));
}
/// <summary>
/// Tests type id method.
/// </summary>
[Test]
public void TestTypeId()
{
Assert.Throws<ArgumentException>(() => _grid.GetBinary().GetTypeId(null));
Assert.AreEqual(IdMapper.TestTypeId, _grid.GetBinary().GetTypeId(IdMapper.TestTypeName));
Assert.AreEqual(BinaryUtils.GetStringHashCode("someTypeName"), _grid.GetBinary().GetTypeId("someTypeName"));
}
/// <summary>
/// Tests metadata methods.
/// </summary>
[Test]
public void TestMetadata()
{
// Populate metadata
var binary = _grid.GetBinary();
binary.ToBinary<IBinaryObject>(new DecimalHolder());
// All meta
var allMetas = binary.GetBinaryTypes();
var decimalMeta = allMetas.Single(x => x.TypeName == "DecimalHolder");
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type
decimalMeta = binary.GetBinaryType(typeof (DecimalHolder));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type id
decimalMeta = binary.GetBinaryType(binary.GetTypeId("DecimalHolder"));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type name
decimalMeta = binary.GetBinaryType("DecimalHolder");
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
}
[Test]
public void TestBuildEnum()
{
var binary = _grid.GetBinary();
int val = (int) TestEnumRegistered.Two;
var binEnums = new[]
{
binary.BuildEnum(typeof (TestEnumRegistered), val),
binary.BuildEnum(typeof (TestEnumRegistered).Name, val)
};
foreach (var binEnum in binEnums)
{
Assert.IsTrue(binEnum.GetBinaryType().IsEnum);
Assert.AreEqual(val, binEnum.EnumValue);
Assert.AreEqual((TestEnumRegistered)val, binEnum.Deserialize<TestEnumRegistered>());
}
}
}
/// <summary>
/// Empty binary class.
/// </summary>
public class Empty
{
// No-op.
}
/// <summary>
/// binary with primitive fields.
/// </summary>
public class Primitives
{
public byte FByte;
public bool FBool;
public short FShort;
public char FChar;
public int FInt;
public long FLong;
public float FFloat;
public double FDouble;
}
/// <summary>
/// binary with primitive array fields.
/// </summary>
public class PrimitiveArrays
{
public byte[] FByte;
public bool[] FBool;
public short[] FShort;
public char[] FChar;
public int[] FInt;
public long[] FLong;
public float[] FFloat;
public double[] FDouble;
}
/// <summary>
/// binary having strings, dates, Guids and enums.
/// </summary>
public class StringDateGuidEnum
{
public string FStr;
public DateTime? FnDate;
public Guid? FnGuid;
public TestEnum FEnum;
public string[] FStrArr;
public DateTime?[] FDateArr;
public Guid?[] FGuidArr;
public TestEnum[] FEnumArr;
}
/// <summary>
/// Enumeration.
/// </summary>
public enum TestEnum
{
One, Two
}
/// <summary>
/// Registered enumeration.
/// </summary>
public enum TestEnumRegistered
{
One, Two
}
/// <summary>
/// binary with raw data.
/// </summary>
public class WithRaw : IBinarizable
{
public int A;
public int B;
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.WriteInt("a", A);
writer.GetRawWriter().WriteInt(B);
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
A = reader.ReadInt("a");
B = reader.GetRawReader().ReadInt();
}
}
/// <summary>
/// Empty class for metadata overwrite test.
/// </summary>
public class MetaOverwrite
{
// No-op.
}
/// <summary>
/// Nested outer object.
/// </summary>
public class NestedOuter
{
public NestedInner Inner1;
public NestedInner Inner2;
}
/// <summary>
/// Nested inner object.
/// </summary>
public class NestedInner
{
public int Val;
}
/// <summary>
/// Outer object for handle migration test.
/// </summary>
public class MigrationOuter
{
public MigrationInner Inner1;
public MigrationInner Inner2;
}
/// <summary>
/// Inner object for handle migration test.
/// </summary>
public class MigrationInner
{
public int Val;
}
/// <summary>
/// Outer object for handle inversion test.
/// </summary>
public class InversionOuter
{
public InversionInner Inner;
}
/// <summary>
/// Inner object for handle inversion test.
/// </summary>
public class InversionInner
{
public InversionOuter Outer;
}
/// <summary>
/// Object for composite array tests.
/// </summary>
public class CompositeArray
{
public object[] InArr;
public object[] OutArr;
}
/// <summary>
/// Object for composite collection/dictionary tests.
/// </summary>
public class CompositeContainer
{
public ICollection Col;
public IDictionary Dict;
}
/// <summary>
/// OUter object for composite structures test.
/// </summary>
public class CompositeOuter
{
public CompositeInner Inner;
public CompositeOuter()
{
// No-op.
}
public CompositeOuter(CompositeInner inner)
{
Inner = inner;
}
}
/// <summary>
/// Inner object for composite structures test.
/// </summary>
public class CompositeInner
{
public int Val;
public CompositeInner()
{
// No-op.
}
public CompositeInner(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test "ToBinary()" logic.
/// </summary>
public class ToBinary
{
public int Val;
public ToBinary(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test removal.
/// </summary>
public class Remove
{
public object Val;
public RemoveInner Val2;
}
/// <summary>
/// Inner type to test removal.
/// </summary>
public class RemoveInner
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public RemoveInner(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderOuter
{
/** */
public BuilderInBuilderInner Inner;
/** */
public BuilderInBuilderInner Inner2;
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderInner
{
/** */
public BuilderInBuilderOuter Outer;
}
/// <summary>
///
/// </summary>
public class BuilderCollection
{
/** */
public readonly ArrayList Col;
/// <summary>
///
/// </summary>
/// <param name="col"></param>
public BuilderCollection(ArrayList col)
{
Col = col;
}
}
/// <summary>
///
/// </summary>
public class BuilderCollectionItem
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public BuilderCollectionItem(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class DecimalHolder
{
/** */
public decimal Val;
/** */
public decimal?[] ValArr;
}
/// <summary>
/// Test id mapper.
/// </summary>
public class IdMapper : IBinaryIdMapper
{
/** */
public const string TestTypeName = "IdMapperTestType";
/** */
public const int TestTypeId = -65537;
/** <inheritdoc /> */
public int GetTypeId(string typeName)
{
return typeName == TestTypeName ? TestTypeId : 0;
}
/** <inheritdoc /> */
public int GetFieldId(int typeId, string fieldName)
{
return 0;
}
}
}
| |
// 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.
//
// Exposes features of the Garbage Collector to managed code.
//
// This is an extremely simple initial version that only exposes a small fraction of the API that the CLR
// version does.
//
using System;
using System.Threading;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
namespace System
{
// !!!!!!!!!!!!!!!!!!!!!!!
// Make sure you change the def in rtu\gc.h if you change this!
public enum GCCollectionMode
{
Default = 0,
Forced = 1,
Optimized = 2
}
internal enum InternalGCCollectionMode
{
NonBlocking = 0x00000001,
Blocking = 0x00000002,
Optimized = 0x00000004,
}
public static class GC
{
public static int GetGeneration(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
return RuntimeImports.RhGetGeneration(obj);
}
// Forces a collection of all generations from 0 through Generation.
public static void Collect(int generation)
{
Collect(generation, GCCollectionMode.Default);
}
// Garbage collect all generations.
public static void Collect()
{
//-1 says to GC all generations.
RuntimeImports.RhCollect(-1, InternalGCCollectionMode.Blocking);
}
public static void Collect(int generation, GCCollectionMode mode)
{
Collect(generation, mode, true);
}
public static void Collect(int generation, GCCollectionMode mode, bool blocking)
{
if (generation < 0)
{
throw new ArgumentOutOfRangeException("generation", SR.ArgumentOutOfRange_GenericPositive);
}
if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized))
{
throw new ArgumentOutOfRangeException("mode", SR.ArgumentOutOfRange_Enum);
}
int iInternalModes = 0;
if (mode == GCCollectionMode.Optimized)
{
iInternalModes |= (int)InternalGCCollectionMode.Optimized;
}
if (blocking)
{
iInternalModes |= (int)InternalGCCollectionMode.Blocking;
}
else
{
iInternalModes |= (int)InternalGCCollectionMode.NonBlocking;
}
RuntimeImports.RhCollect(generation, (InternalGCCollectionMode)iInternalModes);
}
// Block until the next finalization pass is complete.
public static void WaitForPendingFinalizers()
{
RuntimeImports.RhWaitForPendingFinalizers(LowLevelThread.ReentrantWaitsEnabled);
}
public static void SuppressFinalize(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
RuntimeImports.RhSuppressFinalize(obj);
}
public static void ReRegisterForFinalize(Object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
RuntimeImports.RhReRegisterForFinalize(obj);
}
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
public static void KeepAlive(Object obj)
{
}
// Returns the maximum GC generation. Currently assumes only 1 heap.
//
public static int MaxGeneration
{
get { return RuntimeImports.RhGetMaxGcGeneration(); }
}
public static int CollectionCount(int generation)
{
if (generation < 0)
throw new ArgumentOutOfRangeException("generation", SR.ArgumentOutOfRange_GenericPositive);
return RuntimeImports.RhGetGcCollectionCount(generation, false);
}
// Support for AddMemoryPressure and RemoveMemoryPressure below.
private const uint PressureCount = 4;
#if BIT64
private const uint MinGCMemoryPressureBudget = 4 * 1024 * 1024;
#else
private const uint MinGCMemoryPressureBudget = 3 * 1024 * 1024;
#endif
private const uint MaxGCMemoryPressureRatio = 10;
private static int[] s_gcCounts = new int[] { 0, 0, 0 };
private static long[] s_addPressure = new long[] { 0, 0, 0, 0 };
private static long[] s_removePressure = new long[] { 0, 0, 0, 0 };
private static uint s_iteration = 0;
/// <summary>
/// Resets the pressure accounting after a gen2 GC has occured.
/// </summary>
private static void CheckCollectionCount()
{
if (s_gcCounts[2] != CollectionCount(2))
{
for (int i = 0; i < 3; i++)
{
s_gcCounts[i] = CollectionCount(i);
}
s_iteration++;
uint p = s_iteration % PressureCount;
s_addPressure[p] = 0;
s_removePressure[p] = 0;
}
}
private static long InterlockedAddMemoryPressure(ref long pAugend, long addend)
{
long oldMemValue;
long newMemValue;
do
{
oldMemValue = pAugend;
newMemValue = oldMemValue + addend;
// check for overflow
if (newMemValue < oldMemValue)
{
newMemValue = long.MaxValue;
}
} while (Interlocked.CompareExchange(ref pAugend, newMemValue, oldMemValue) != oldMemValue);
return newMemValue;
}
/// <summary>
/// New AddMemoryPressure implementation (used by RCW and the CLRServicesImpl class)
/// 1. Less sensitive than the original implementation (start budget 3 MB)
/// 2. Focuses more on newly added memory pressure
/// 3. Budget adjusted by effectiveness of last 3 triggered GC (add / remove ratio, max 10x)
/// 4. Budget maxed with 30% of current managed GC size
/// 5. If Gen2 GC is happening naturally, ignore past pressure
///
/// Here's a brief description of the ideal algorithm for Add/Remove memory pressure:
/// Do a GC when (HeapStart is less than X * MemPressureGrowth) where
/// - HeapStart is GC Heap size after doing the last GC
/// - MemPressureGrowth is the net of Add and Remove since the last GC
/// - X is proportional to our guess of the ummanaged memory death rate per GC interval,
/// and would be calculated based on historic data using standard exponential approximation:
/// Xnew = UMDeath/UMTotal * 0.5 + Xprev
/// </summary>
/// <param name="bytesAllocated"></param>
[SecurityCritical] // required to match contract
public static void AddMemoryPressure(long bytesAllocated)
{
if (bytesAllocated <= 0)
{
throw new ArgumentOutOfRangeException("bytesAllocated",
SR.ArgumentOutOfRange_NeedPosNum);
}
#if !BIT64
if (bytesAllocated > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException("bytesAllocated",
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
#endif
CheckCollectionCount();
uint p = s_iteration % PressureCount;
long newMemValue = InterlockedAddMemoryPressure(ref s_addPressure[p], bytesAllocated);
Debug.Assert(PressureCount == 4, "GC.AddMemoryPressure contains unrolled loops which depend on the PressureCount");
if (newMemValue >= MinGCMemoryPressureBudget)
{
long add = s_addPressure[0] + s_addPressure[1] + s_addPressure[2] + s_addPressure[3] - s_addPressure[p];
long rem = s_removePressure[0] + s_removePressure[1] + s_removePressure[2] + s_removePressure[3] - s_removePressure[p];
long budget = MinGCMemoryPressureBudget;
if (s_iteration >= PressureCount) // wait until we have enough data points
{
// Adjust according to effectiveness of GC
// Scale budget according to past m_addPressure / m_remPressure ratio
if (add >= rem * MaxGCMemoryPressureRatio)
{
budget = MinGCMemoryPressureBudget * MaxGCMemoryPressureRatio;
}
else if (add > rem)
{
Debug.Assert(rem != 0);
// Avoid overflow by calculating addPressure / remPressure as fixed point (1 = 1024)
budget = (add * 1024 / rem) * budget / 1024;
}
}
// If still over budget, check current managed heap size
if (newMemValue >= budget)
{
long heapOver3 = RuntimeImports.RhGetCurrentObjSize() / 3;
if (budget < heapOver3) //Max
{
budget = heapOver3;
}
if (newMemValue >= budget)
{
// last check - if we would exceed 20% of GC "duty cycle", do not trigger GC at this time
if ((RuntimeImports.RhGetGCNow() - RuntimeImports.RhGetLastGCStartTime(2)) > (RuntimeImports.RhGetLastGCDuration(2) * 5))
{
RuntimeImports.RhCollect(2, InternalGCCollectionMode.NonBlocking);
CheckCollectionCount();
}
}
}
}
}
[SecurityCritical] // required to match contract
public static void RemoveMemoryPressure(long bytesAllocated)
{
if (bytesAllocated <= 0)
{
throw new ArgumentOutOfRangeException("bytesAllocated",
SR.ArgumentOutOfRange_NeedPosNum);
}
#if !BIT64
if (bytesAllocated > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException("bytesAllocated",
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
#endif
CheckCollectionCount();
uint p = s_iteration % PressureCount;
InterlockedAddMemoryPressure(ref s_removePressure[p], bytesAllocated);
}
public static long GetTotalMemory(bool forceFullCollection)
{
long size = RuntimeImports.RhGetGcTotalMemory();
if (forceFullCollection)
{
// If we force a full collection, we will run the finalizers on all
// existing objects and do a collection until the value stabilizes.
// The value is "stable" when either the value is within 5% of the
// previous call to GetTotalMemory, or if we have been sitting
// here for more than x times (we don't want to loop forever here).
int reps = 20; // Number of iterations
long diff;
do
{
GC.WaitForPendingFinalizers();
GC.Collect();
long newSize = RuntimeImports.RhGetGcTotalMemory();
diff = (newSize - size) * 100 / size;
size = newSize;
}
while (reps-- > 0 && !(-5 < diff && diff < 5));
}
return size;
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.IO;
using System.Xml;
using System.Text;
using System.Linq;
using System.Collections.Generic;
namespace Soomla
{
public class SoomlaManifestTools
{
#if UNITY_EDITOR
public static void GenerateManifest()
{
var outputFile = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml");
// only copy over a fresh copy of the AndroidManifest if one does not exist
if (!File.Exists(outputFile))
{
#if UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1
var inputFile = Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines/androidplayer/AndroidManifest.xml");
#else
var inputFile = Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines/androidplayer/Apk/AndroidManifest.xml");
#endif
File.Copy(inputFile, outputFile);
}
UpdateManifest(outputFile);
}
private static string _namespace = "";
private static XmlDocument _document = null;
private static XmlNode _manifestNode = null;
private static XmlNode _applicationNode = null;
public static List<ISoomlaManifestTools> ManTools = new List<ISoomlaManifestTools>();
public static void UpdateManifest(string fullPath) {
_document = new XmlDocument();
_document.Load(fullPath);
if (_document == null)
{
Debug.LogError("Couldn't load " + fullPath);
return;
}
_manifestNode = FindChildNode(_document, "manifest");
_namespace = _manifestNode.GetNamespaceOfPrefix("android");
_applicationNode = FindChildNode(_manifestNode, "application");
if (_applicationNode == null) {
Debug.LogError("Error parsing " + fullPath);
return;
}
SetPermission("android.permission.INTERNET");
XmlElement applicationElement = FindChildElement(_manifestNode, "application");
applicationElement.SetAttribute("name", _namespace, "com.soomla.SoomlaApp");
foreach(ISoomlaManifestTools manifestTool in ManTools) {
manifestTool.UpdateManifest();
}
_document.Save(fullPath);
}
public static void AddActivity(string activityName, Dictionary<string, string> attributes) {
AppendApplicationElement("activity", activityName, attributes);
}
public static void RemoveActivity(string activityName) {
RemoveApplicationElement("activity", activityName);
}
public static void SetPermission(string permissionName) {
PrependManifestElement("uses-permission", permissionName);
}
public static void RemovePermission(string permissionName) {
RemoveManifestElement("uses-permission", permissionName);
}
public static XmlElement AppendApplicationElement(string tagName, string name, Dictionary<string, string> attributes) {
return AppendElementIfMissing(tagName, name, attributes, _applicationNode);
}
public static void RemoveApplicationElement(string tagName, string name) {
RemoveElement(tagName, name, _applicationNode);
}
public static XmlElement PrependManifestElement(string tagName, string name) {
return PrependElementIfMissing(tagName, name, null, _manifestNode);
}
public static void RemoveManifestElement(string tagName, string name) {
RemoveElement(tagName, name, _manifestNode);
}
public static XmlElement AddMetaDataTag(string mdName, string mdValue) {
return AppendApplicationElement("meta-data", mdName, new Dictionary<string, string>() {
{ "value", mdValue }
});
}
public static XmlElement AppendElementIfMissing(string tagName, string name, Dictionary<string, string> otherAttributes, XmlNode parent) {
XmlElement e = null;
if (!string.IsNullOrEmpty(name)) {
e = FindElementWithTagAndName(tagName, name, parent);
}
if (e == null)
{
e = _document.CreateElement(tagName);
if (!string.IsNullOrEmpty(name)) {
e.SetAttribute("name", _namespace, name);
}
parent.AppendChild(e);
}
if (otherAttributes != null) {
foreach(string key in otherAttributes.Keys) {
e.SetAttribute(key, _namespace, otherAttributes[key]);
}
}
return e;
}
public static XmlElement PrependElementIfMissing(string tagName, string name, Dictionary<string, string> otherAttributes, XmlNode parent) {
XmlElement e = null;
if (!string.IsNullOrEmpty(name)) {
e = FindElementWithTagAndName(tagName, name, parent);
}
if (e == null)
{
e = _document.CreateElement(tagName);
if (!string.IsNullOrEmpty(name)) {
e.SetAttribute("name", _namespace, name);
}
parent.PrependChild(e);
}
if (otherAttributes != null) {
foreach(string key in otherAttributes.Keys) {
e.SetAttribute(key, _namespace, otherAttributes[key]);
}
}
return e;
}
public static void RemoveElement(string tagName, string name, XmlNode parent) {
XmlElement e = FindElementWithTagAndName(tagName, name, parent);
if (e != null)
{
parent.RemoveChild(e);
}
}
public static XmlNode FindChildNode(XmlNode parent, string tagName)
{
XmlNode curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(tagName))
{
return curr;
}
curr = curr.NextSibling;
}
return null;
}
public static XmlElement FindChildElement(XmlNode parent, string tagName)
{
XmlNode curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(tagName))
{
return curr as XmlElement;
}
curr = curr.NextSibling;
}
return null;
}
public static XmlElement FindElementWithTagAndName(string tagName, string name, XmlNode parent)
{
var curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(tagName) && curr is XmlElement && ((XmlElement)curr).GetAttribute("name", _namespace) == name)
{
return curr as XmlElement;
}
curr = curr.NextSibling;
}
return null;
}
#endif
}
}
| |
//WordSlide
//Copyright (C) 2008-2012 Jonathan Ray <[email protected]>
//WordSlide is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//A copy of the GNU General Public License should be in the
//Installer directory of this source tree. If not, see
//<http://www.gnu.org/licenses/>.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace WordSlideEngine
{
public struct Font
{
public string family;
public int size;
}
public class Options
{
private string filePath;
public int BackgroundColor { get; set; }
public int TextColor { get; set; }
public string SongEnd { get; set; }
public string ShowEnd { get; set; }
public bool AutoUpdate { get; set; }
public Font TitleFont { get; set; }
public Font TextFont { get; set; }
public Font BylineFont { get; set; }
public Font DotFont { get; set; }
public int TextStart { get; set; }
public int TitleStart { get; set; }
public int TitleTextSpace { get; set; }
public string ExitKey { get; set; }
public string ForwardKey { get; set; }
public string BackwardKey { get; set; }
public string BlankKey { get; set; }
public string ChorusKey { get; set; }
public string SongForwardKey { get; set; }
public string SongBackwardKey { get; set; }
public string VerseForwardKey { get; set; }
public string VerseBackwardKey { get; set; }
public string HelpKey { get; set; }
public string TestKey { get; set; }
public Version SkippedVersion { get; set; }
public bool AutoBackup { get; set; }
public int BackupInterval { get; set; }
public bool ReportErrors { get; set; }
public static int BackgroundColorDefault { get { return -16777216; } }
public static int TextColorDefault { get { return -1; } }
public static string SongEndDefault { get { return ".."; } }
public static string ShowEndDefault { get { return "..."; } }
public static bool AutoUpdateDefault { get { return true; } }
public static Font TitleFontDefault { get { return new Font { family = "Microsoft Sans Serif", size = 42 }; } }
public static Font TextFontDefault { get { return new Font { family = "Microsoft Sans Serif", size = 36 }; } }
public static Font BylineFontDefault { get { return new Font { family = "Microsoft Sans Serif", size = 16 }; } }
public static Font DotFontDefault { get { return new Font { family = "Microsoft Sans Serif", size = 14 }; } }
public static int TextStartDefault { get { return 200; } }
public static int TitleStartDefault { get { return 100; } }
public static int TitleTextSpaceDefault { get { return 50; } }
public static int TextStartTop { get { return 50; } }
public static int TitleStartTop { get { return 0; } }
public static int TitleTextSpaceTop { get { return 100; } }
public static string ExitKeyDefault { get { return "Escape"; } }
public static string ForwardKeyDefault { get { return "Right"; } }
public static string BackwardKeyDefault { get { return "Left"; } }
public static string BlankKeyDefault { get { return "B"; } }
public static string ChorusKeyDefault { get { return "C"; } }
public static string SongForwardKeyDefault { get { return "S"; } }
public static string SongBackwardKeyDefault { get { return "A"; } }
public static string VerseForwardKeyDefault { get { return "X"; } }
public static string VerseBackwardKeyDefault { get { return "Z"; } }
public static string HelpKeyDefault { get { return "F1"; } }
public static string TestKeyDefault { get { return "F12"; } }
public static Version SkippedVersionDefault { get { return new Version(0, 0, 0, 0); } }
public static bool AutoBackupDefault { get { return false; } }
public static int BackupIntervalDefault { get { return 0; } }
public static bool ReportErrorsDefault { get { return true; } }
public Options(string fileName)
{
filePath = fileName;
}
public void loadFile()
{
try
{
setDefaults();
using (StreamReader reader = new StreamReader(new FileStream(filePath, FileMode.Open)))
{
while (!reader.EndOfStream)
{
string[] line = reader.ReadLine().Split(new char[] { '=' }, 2);
if (line.Length != 2) continue;
switch (line[0].ToLower())
{
case "backgroundcolor":
this.BackgroundColor = int.Parse(line[1]);
break;
case "textcolor":
this.TextColor = int.Parse(line[1]);
break;
case "titlefontfamily":
this.TitleFont = new Font { family = line[1], size = this.TitleFont.size };
break;
case "titlefontsize":
this.TitleFont = new Font { family = this.TitleFont.family, size = int.Parse(line[1]) };
break;
case "textfontfamily":
this.TextFont = new Font { family = line[1], size = this.TextFont.size };
break;
case "textfontsize":
this.TextFont = new Font { family = this.TextFont.family, size = int.Parse(line[1]) };
break;
case "bylinefontfamily":
this.BylineFont = new Font { family = line[1], size = this.BylineFont.size };
break;
case "bylinefontsize":
this.BylineFont = new Font { family = this.BylineFont.family, size = int.Parse(line[1]) };
break;
case "dotfontfamily":
this.DotFont = new Font { family = line[1], size = this.DotFont.size };
break;
case "dotfontsize":
this.DotFont = new Font { family = this.DotFont.family, size = int.Parse(line[1]) };
break;
case "songend":
this.SongEnd = line[1];
break;
case "showend":
this.ShowEnd = line[1];
break;
case "autoupdate":
this.AutoUpdate = bool.Parse(line[1]);
break;
case "textstart":
this.TextStart = int.Parse(line[1]);
break;
case "titlestart":
this.TitleStart = int.Parse(line[1]);
break;
case "titletextspace":
this.TitleTextSpace = int.Parse(line[1]);
break;
case "exitkey":
this.ExitKey = line[1];
break;
case "forwardkey":
this.ForwardKey = line[1];
break;
case "backwardkey":
this.BackwardKey = line[1];
break;
case "blankkey":
this.BlankKey = line[1];
break;
case "choruskey":
this.ChorusKey = line[1];
break;
case "songforwardkey":
this.SongForwardKey = line[1];
break;
case "songbackwardkey":
this.SongBackwardKey = line[1];
break;
case "verseforwardkey":
this.VerseForwardKey = line[1];
break;
case "versebackwardkey":
this.VerseBackwardKey = line[1];
break;
case "helpkey":
this.HelpKey = line[1];
break;
case "testkey":
this.TestKey = line[1];
break;
case "skippedversion":
this.SkippedVersion = new Version(line[1]);
break;
case "autobackup":
this.AutoBackup = bool.Parse(line[1]);
break;
case "backupinterval":
this.BackupInterval = int.Parse(line[1]);
break;
case "reporterrors":
this.ReportErrors = bool.Parse(line[1]);
break;
}
}
}
}
catch
{
setDefaults();
}
}
private void setDefaults()
{
this.BackgroundColor = BackgroundColorDefault;
this.TextColor = TextColorDefault;
this.TitleFont = TitleFontDefault;
this.TextFont = TextFontDefault;
this.BylineFont = BylineFontDefault;
this.DotFont = DotFontDefault;
this.SongEnd = SongEndDefault;
this.ShowEnd = ShowEndDefault;
this.AutoUpdate = AutoUpdateDefault;
this.TextStart = TextStartDefault;
this.TitleStart = TitleStartDefault;
this.TitleTextSpace = TitleTextSpaceDefault;
this.ExitKey = ExitKeyDefault;
this.ForwardKey = ForwardKeyDefault;
this.BackwardKey = BackwardKeyDefault;
this.BlankKey = BlankKeyDefault;
this.ChorusKey = ChorusKeyDefault;
this.SongForwardKey = SongForwardKeyDefault;
this.SongBackwardKey = SongBackwardKeyDefault;
this.VerseForwardKey = VerseForwardKeyDefault;
this.VerseBackwardKey = VerseBackwardKeyDefault;
this.HelpKey = HelpKeyDefault;
this.TestKey = TestKeyDefault;
this.SkippedVersion = SkippedVersionDefault;
this.AutoBackup = AutoBackupDefault;
this.BackupInterval = BackupIntervalDefault;
this.ReportErrors = ReportErrorsDefault;
}
public void saveFile()
{
using (StreamWriter writer = new StreamWriter(new FileStream(filePath, FileMode.Create)))
{
writer.WriteLine(string.Join("=", "BackgroundColor", this.BackgroundColor));
writer.WriteLine(string.Join("=", "TextColor", this.TextColor));
writer.WriteLine(string.Join("=", "TitleFontFamily", this.TitleFont.family));
writer.WriteLine(string.Join("=", "TitleFontSize", (int)this.TitleFont.size));
writer.WriteLine(string.Join("=", "TextFontFamily", this.TextFont.family));
writer.WriteLine(string.Join("=", "TextFontSize", (int)this.TextFont.size));
writer.WriteLine(string.Join("=", "BylineFontFamily", this.BylineFont.family));
writer.WriteLine(string.Join("=", "BylineFontSize", (int)this.BylineFont.size));
writer.WriteLine(string.Join("=", "DotFontFamily", this.DotFont.family));
writer.WriteLine(string.Join("=", "DotFontSize", (int)this.DotFont.size));
writer.WriteLine(string.Join("=", "SongEnd", this.SongEnd));
writer.WriteLine(string.Join("=", "ShowEnd", this.ShowEnd));
writer.WriteLine(string.Join("=", "AutoUpdate", this.AutoUpdate));
writer.WriteLine(string.Join("=", "TextStart", this.TextStart));
writer.WriteLine(string.Join("=", "TitleStart", this.TitleStart));
writer.WriteLine(string.Join("=", "TitleTextSpace", this.TitleTextSpace));
writer.WriteLine(string.Join("=", "ExitKey", this.ExitKey));
writer.WriteLine(string.Join("=", "ForwardKey", this.ForwardKey));
writer.WriteLine(string.Join("=", "BackwardKey", this.BackwardKey));
writer.WriteLine(string.Join("=", "BlankKey", this.BlankKey));
writer.WriteLine(string.Join("=", "ChorusKey", this.ChorusKey));
writer.WriteLine(string.Join("=", "SongForwardKey", this.SongForwardKey));
writer.WriteLine(string.Join("=", "SongBackwardKey", this.SongBackwardKey));
writer.WriteLine(string.Join("=", "VerseForwardKey", this.VerseForwardKey));
writer.WriteLine(string.Join("=", "VerseBackwardKey", this.VerseBackwardKey));
writer.WriteLine(string.Join("=", "HelpKey", this.HelpKey));
writer.WriteLine(string.Join("=", "TestKey", this.TestKey));
writer.WriteLine(string.Join("=", "SkippedVersion", this.SkippedVersion.ToString()));
writer.WriteLine(string.Join("=", "AutoBackup", this.AutoBackup));
writer.WriteLine(string.Join("=", "BackupInterval", this.BackupInterval));
writer.WriteLine(string.Join("=", "ReportErrors", this.ReportErrors));
writer.WriteLine(string.Join("=", "Path", Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)));
writer.WriteLine(string.Join("=", "Version", Engine.Version.ToString()));
}
}
}
}
| |
// General image manipulation program.
//
// Current functions:
// 1. Generate Thumbnails by specified size and/or quality;
// 2. Add text and/or watermaker to images.
//
// Started at: 27/2/2004
// Author: Ray Wang
// Copyright 2013 Dragonfish Pty Ltd
// Licensed under the Apache License v2.0
// http://www.apache.org/licenses/LICENSE-2.0
//
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace Dragonfish.Library.Image
{
/// <summary>
/// Generate thumbnail by specifying scale percentage or fixed width & hight.
/// </summary>
public class ImageHelper : IDisposable
{
public enum WatermarkPosition
{
/// <summary>
/// Centered
/// </summary>
Centre = 0,
/// <summary>
/// Upper left corner
/// </summary>
UpperLeft = 1,
/// <summary>
/// Upper right corner
/// </summary>
UpperRight = 2,
/// <summary>
/// Lower left corner
/// </summary>
LowerLeft = 3,
/// <summary>
/// Lower right corner
/// </summary>
LowerRight = 4
};
#region Member variables
private System.Drawing.Image _srcImage;
private const long DEFAULT_JPG_QUALITY = 85L;
private const string DEFAULT_ENCODER_INFO = "image/jpeg";
#endregion Member variables
#region Constructors
public ImageHelper(System.Drawing.Image srcImage)
{
_srcImage = srcImage;
}
/// <summary>
/// Constructors
/// </summary>
/// <param name="inputFileName">Full path & file name</param>
/// <param name="outputWidth">Thumbnail width</param>
/// <param name="outputHeight">Thumbnail hight</param>
/// <param name="outputFileName">Output path & file name</param>
public ImageHelper(string inputFileName)
{
try
{
_srcImage = System.Drawing.Image.FromFile(inputFileName);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion Constructors
#region Methods
#region thumbnail
/// <summary>
/// Save resized image to a give path in specified format.
/// </summary>
/// <param name="outputFileName">output file name</param>
/// <param name="outputWidth">output width</param>
/// <param name="outputHeight">output height</param>
/// <param name="lockRatio">lock scacle</param>
/// <param name="jpegQuality">jpeg quality. (1-100)</param>
/// <param name="encoderInfo">encoder info i.e. jpeg or png</param>
public void SaveResizedImage(string outputFileName, int outputWidth, int outputHeight, bool lockRatio, long jpegQuality, string encoderInfo)
{
try
{
GetResizedImage(outputWidth, outputHeight, lockRatio).Save(outputFileName, GetEncoderInfo(encoderInfo), GetEncoderParameters(jpegQuality));
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Save resized image to a give path in jpeg format.
/// </summary>
/// <param name="outputFileName">output file name</param>
/// <param name="outputWidth">output width</param>
/// <param name="outputHeight">output height</param>
/// <param name="lockRatio">lock scacle</param>
/// <param name="jpegQuality">jpeg quality. (1-100)</param>
public void SaveResizedImage(string outputFileName, int outputWidth, int outputHeight, bool lockRatio, long jpegQuality)
{
SaveResizedImage(outputFileName, outputWidth, outputHeight, lockRatio, jpegQuality, DEFAULT_ENCODER_INFO);
}
/// <summary>
/// Save resized image to a give path in specified format with default quality 85%.
/// </summary>
/// <param name="outputFileName">output file name</param>
/// <param name="outputWidth">output width</param>
/// <param name="outputHeight">output height</param>
/// <param name="lockRatio">lock scale</param>
/// <param name="encoderInfo">encoder info either jpeg or png</param>
public void SaveResizedImage(string outputFileName, int outputWidth, int outputHeight, bool lockRatio, string encoderInfo)
{
SaveResizedImage(outputFileName, outputWidth, outputHeight, lockRatio, DEFAULT_JPG_QUALITY, encoderInfo);
}
/// <summary>
/// Save resized image to a give path in jpeg format with default quality 85%.
/// </summary>
/// <param name="outputFileName">output file name</param>
/// <param name="outputWidth">output width</param>
/// <param name="outputHeight">output height</param>
/// <param name="lockRatio">lock scale</param>
public void SaveResizedImage(string outputFileName, int outputWidth, int outputHeight, bool lockRatio)
{
SaveResizedImage(outputFileName, outputWidth, outputHeight, lockRatio, DEFAULT_JPG_QUALITY, DEFAULT_ENCODER_INFO);
}
public void SaveCroppedImage(string outputFileName, int size)
{
SaveCroppedImage(outputFileName, size, 80);
}
public void SaveCroppedImage(string outputFileName, int size, long jpegQuality)
{
ImageAttributes attributes = null;
Bitmap bmPhoto = null;
Graphics grPhoto = null;
try
{
int squareSize = _srcImage.Width > _srcImage.Height ? _srcImage.Height : _srcImage.Width;
int x = _srcImage.Width > _srcImage.Height ? (int)((_srcImage.Width - _srcImage.Height) / 2) : 0;
int y = _srcImage.Width > _srcImage.Height ? 0 : (int)((_srcImage.Height - _srcImage.Width) / 2);
bmPhoto = new Bitmap(size, size, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(72, 72);
attributes = new ImageAttributes();
attributes.SetWrapMode(WrapMode.TileFlipXY);
grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(_srcImage,
new Rectangle(0, 0, size, size),
x, y, squareSize, squareSize, GraphicsUnit.Pixel, attributes);
bmPhoto.Save(outputFileName, GetEncoderInfo("image/jpeg"), GetEncoderParameters(jpegQuality));
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (attributes != null)
attributes.Dispose();
if (grPhoto != null)
grPhoto.Dispose();
GC.Collect();
}
}
/// <summary>
/// get resized image.
/// </summary>
/// <param name="outputFileName">output file name</param>
/// <param name="outputWidth">output width</param>
/// <param name="outputHeight">output height</param>
/// <param name="lockScale">lock scacle</param>
/// <param name="jpegQuality">jpeg quality. (1-100)</param>
/// <returns>resized image</returns>
public System.Drawing.Image GetResizedImage(int outputWidth, int outputHeight, bool lockRatio)
{
ImageAttributes attributes = null;
Bitmap bmPhoto = null;
Graphics grPhoto = null;
try
{
if (_srcImage.Width < outputWidth && _srcImage.Height < outputHeight)
return _srcImage;
if (lockRatio == true)
{
if ((_srcImage.Width / _srcImage.Height) >= (outputWidth / outputHeight))
outputHeight = outputWidth * _srcImage.Height / _srcImage.Width;
else if ((_srcImage.Width / _srcImage.Height) < (outputWidth / outputHeight))
outputWidth = outputHeight * _srcImage.Width / _srcImage.Height;
else
return _srcImage;
}
// do not set pixel format then it can detect automatically 24bit for jpeg or 32bit for png for example
bmPhoto = new Bitmap(outputWidth, outputHeight);
bmPhoto.SetResolution(72, 72);
attributes = new ImageAttributes();
attributes.SetWrapMode(WrapMode.TileFlipXY);
grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(_srcImage,
new Rectangle(0, 0, outputWidth, outputHeight),
0, 0, _srcImage.Width, _srcImage.Height, GraphicsUnit.Pixel, attributes);
return bmPhoto;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (attributes != null)
attributes.Dispose();
if (grPhoto != null)
grPhoto.Dispose();
GC.Collect();
}
}
#endregion thumbnail
#region watermark
public System.Drawing.Image GetWatermarkedImage(string watermarkFileName, string outputFileName, WatermarkPosition wmPosition, int pixToHorizontalEdge, int pixToVerticalEdge)
{
Bitmap bmPhoto = null;
System.Drawing.Image imgWatermark = null;
Bitmap bmWatermark = null;
Graphics grPhoto = null;
Graphics grWatermark = null;
ImageAttributes imageAttributes = null;
try
{
imgWatermark = new Bitmap(watermarkFileName);
bmPhoto = new Bitmap(_srcImage.Width, _srcImage.Height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(_srcImage.HorizontalResolution, _srcImage.VerticalResolution);
grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
grPhoto.DrawImage(_srcImage, new Rectangle(0, 0, _srcImage.Width, _srcImage.Height), 0, 0, _srcImage.Width, _srcImage.Height, GraphicsUnit.Pixel);
bmWatermark = new Bitmap(bmPhoto);
bmWatermark.SetResolution(_srcImage.HorizontalResolution, _srcImage.VerticalResolution);
grWatermark = Graphics.FromImage(bmWatermark);
imageAttributes = new ImageAttributes();
ColorMap colorMap = new ColorMap();
colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
ColorMap[] remapTable = { colorMap };
imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
float[][] colorMatrixElements = {
new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
};
ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
int xPosOfWatermark = 0;
int yPosOfWatermark = 0;
switch (wmPosition)
{
case WatermarkPosition.Centre:
xPosOfWatermark = (_srcImage.Width - imgWatermark.Width) / 2;
yPosOfWatermark = (_srcImage.Height - imgWatermark.Height) / 2;
break;
case WatermarkPosition.UpperLeft:
xPosOfWatermark = pixToVerticalEdge;
yPosOfWatermark = pixToHorizontalEdge;
break;
case WatermarkPosition.UpperRight:
xPosOfWatermark = _srcImage.Width - imgWatermark.Width - pixToVerticalEdge;
yPosOfWatermark = pixToHorizontalEdge;
break;
case WatermarkPosition.LowerLeft:
xPosOfWatermark = pixToVerticalEdge;
yPosOfWatermark = _srcImage.Height - imgWatermark.Height - pixToHorizontalEdge;
break;
case WatermarkPosition.LowerRight:
xPosOfWatermark = _srcImage.Width - imgWatermark.Width - pixToVerticalEdge;
yPosOfWatermark = _srcImage.Height - imgWatermark.Height - pixToHorizontalEdge;
break;
}
grWatermark.DrawImage(imgWatermark, new Rectangle(xPosOfWatermark, yPosOfWatermark, imgWatermark.Width, imgWatermark.Height), 0, 0, imgWatermark.Width, imgWatermark.Height, GraphicsUnit.Pixel, imageAttributes);
return bmWatermark;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
if (bmPhoto != null)
bmPhoto.Dispose();
if (grPhoto != null)
grPhoto.Dispose();
if (grWatermark != null)
grWatermark.Dispose();
if (imgWatermark != null)
imgWatermark.Dispose();
if (imageAttributes != null)
imageAttributes.Dispose();
GC.Collect();
}
}
public void SaveWatermarkedImage(string watermarkFileName, string outputFileName, WatermarkPosition wmPosition, int pixToHorizontalEdge, int pixToVerticalEdge, long jpegQuality)
{
try
{
GetWatermarkedImage(watermarkFileName, outputFileName, wmPosition, pixToHorizontalEdge, pixToVerticalEdge).Save(outputFileName, GetEncoderInfo("image/jpeg"), GetEncoderParameters(jpegQuality));
}
catch (Exception ex)
{
throw (ex);
}
}
/// <summary>
/// Save watermarked image to specified path. Image quality set to default which is 85%.
/// </summary>
/// <param name="watermarkFileName"></param>
/// <param name="outputFileName"></param>
/// <param name="wmPosition"></param>
/// <param name="pixToHorizontalEdge"></param>
/// <param name="pixToVerticalEdge"></param>
public void SaveWatermarkedImage(string watermarkFileName, string outputFileName, WatermarkPosition wmPosition, int pixToHorizontalEdge, int pixToVerticalEdge)
{
SaveWatermarkedImage(watermarkFileName, outputFileName, wmPosition, pixToHorizontalEdge, pixToVerticalEdge, DEFAULT_JPG_QUALITY);
}
public void GetTextedPicture(string outputFileName, string text, string fontName, Brush brush, float size, Rectangle rec, long jpegQuality)
{
try
{
Bitmap bmPhoto = new Bitmap(_srcImage);
// bmPhoto.SetResolution(_srcImage.HorizontalResolution, _srcImage.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(_srcImage);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
grPhoto.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
Font font = new Font(fontName, size);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Near;
grPhoto.DrawString(text,
font,
brush,
rec,
format);
_srcImage.Save(outputFileName, GetEncoderInfo("image/jpeg"), GetEncoderParameters(jpegQuality));
bmPhoto.Dispose();
grPhoto.Dispose();
GC.Collect();
}
catch (Exception ex)
{
throw (ex);
}
}
#endregion watermark
#region Merge two
/// <summary>
///
/// </summary>
/// <param name="ImageBack"></param>
/// <param name="ImageFore"></param>
/// <param name="output"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="height"></param>
public void MergeImages(string ImageBack, string ImageFore, string output, int x, int y, int width, int height)
{
System.Drawing.Graphics myGraphic = null;
System.Drawing.Image imgB;// =new Image.FromFile(ImageBack);
imgB = System.Drawing.Image.FromFile(ImageBack);
System.Drawing.Image imgF;// =new Image.FromFile(ImageBack);
imgF = System.Drawing.Image.FromFile(ImageFore);
System.Drawing.Image m;
m = System.Drawing.Image.FromFile(ImageFore);
myGraphic = Graphics.FromImage(m);
myGraphic.DrawImageUnscaled(imgB, x, y, width, height);
myGraphic.DrawImageUnscaled(imgF, 0, 0);
myGraphic.Save();
m.Save(output, System.Drawing.Imaging.ImageFormat.Jpeg);
}
#endregion Merge two
private EncoderParameters GetEncoderParameters(long jpegQuality)
{
Encoder qualityEncoder = Encoder.Quality;
EncoderParameter ratio = new EncoderParameter(qualityEncoder, jpegQuality);
EncoderParameters codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
return codecParams;
}
/// <summary>
///
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
private ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
public void Dispose()
{
if (_srcImage != null)
_srcImage.Dispose();
GC.SuppressFinalize(this);
}
/// <summary>
///
/// </summary>
///
~ImageHelper()
{
this.Dispose();
}
#endregion Methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class SizeFConverterTests : StringTypeConverterTestBase<SizeF>
{
protected override TypeConverter Converter { get; } = new SizeFConverter();
protected override bool StandardValuesSupported { get; } = false;
protected override bool StandardValuesExclusive { get; } = false;
protected override SizeF Default => new SizeF(1, 1);
protected override bool CreateInstanceSupported { get; } = true;
protected override bool IsGetPropertiesSupported { get; } = true;
protected override IEnumerable<Tuple<SizeF, Dictionary<string, object>>> CreateInstancePairs
{
get
{
yield return Tuple.Create(new SizeF(10, 20), new Dictionary<string, object>
{
["Width"] = 10f,
["Height"] = 20f,
});
yield return Tuple.Create(new SizeF(-2, 3), new Dictionary<string, object>
{
["Width"] = -2f,
["Height"] = 3f,
});
}
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertFromTrue(Type type)
{
CanConvertFrom(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertFromFalse(Type type)
{
CannotConvertFrom(type);
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertToTrue(Type type)
{
CanConvertTo(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertToFalse(Type type)
{
CannotConvertTo(type);
}
public static IEnumerable<object[]> SizeFData =>
new[]
{
new object[] {0, 0},
new object[] {1, 1},
new object[] {-1, 1},
new object[] {1, -1},
new object[] {-1, -1},
new object[] {float.MaxValue, float.MaxValue},
new object[] {float.MinValue, float.MaxValue},
new object[] {float.MaxValue, float.MinValue},
new object[] {float.MinValue, float.MinValue},
};
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertFrom(float width, float height)
{
TestConvertFromString(new SizeF(width, height), FormattableString.Invariant($"{width:G9}, {height:G9}"));
}
[Theory]
[InlineData("1")]
[InlineData("1, 1, 1")]
public void ConvertFrom_ArgumentException(string value)
{
ConvertFromThrowsArgumentExceptionForString(value);
}
[Fact]
public void ConvertFrom_Invalid()
{
ConvertFromThrowsFormatInnerExceptionForString("*1, 1");
}
public static IEnumerable<object[]> ConvertFrom_NotSupportedData =>
new[]
{
new object[] {new Point(1, 1)},
new object[] {new PointF(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {0x10},
};
[Theory]
[MemberData(nameof(ConvertFrom_NotSupportedData))]
public void ConvertFrom_NotSupported(object value)
{
ConvertFromThrowsNotSupportedFor(value);
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertTo(float width, float height)
{
TestConvertToString(new SizeF(width, height), FormattableString.Invariant($"{width:G9}, {height:G9}"));
}
[Theory]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(int))]
public void ConvertTo_NotSupportedException(Type type)
{
ConvertToThrowsNotSupportedForType(type);
}
[Fact]
public void ConvertTo_NullCulture()
{
string listSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
Assert.Equal($"1{listSep} 1", Converter.ConvertTo(null, null, new SizeF(1, 1), typeof(string)));
}
[Fact]
public void CreateInstance_CaseSensitive()
{
Assert.Throws<ArgumentException>(() =>
{
Converter.CreateInstance(null, new Dictionary<string, object>
{
["width"] = 1,
["Height"] = 1,
});
});
}
[Fact]
public void GetProperties()
{
var pt = new SizeF(1, 1);
var props = Converter.GetProperties(new SizeF(1, 1));
Assert.Equal(3, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new SizeF(1, 1));
Assert.Equal(3, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new SizeF(1, 1), null);
Assert.Equal(3, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new SizeF(1, 1),
typeof(SizeF).GetCustomAttributes(true).OfType<Attribute>().ToArray());
Assert.Equal(3, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertFromInvariantString(float width, float height)
{
var point = (SizeF)Converter.ConvertFromInvariantString(FormattableString.Invariant($"{width:G9}, {height:G9}"));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromInvariantString_ArgumentException()
{
ConvertFromInvariantStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromInvariantString_FormatException()
{
ConvertFromInvariantStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertFromString(float width, float height)
{
var point =
(SizeF)Converter.ConvertFromString(string.Format(CultureInfo.CurrentCulture, "{0:g9}{2} {1:g9}", width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromString_ArgumentException()
{
ConvertFromStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromString_FormatException()
{
ConvertFromStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertToInvariantString(float width, float height)
{
var str = Converter.ConvertToInvariantString(new SizeF(width, height));
Assert.Equal(FormattableString.Invariant($"{width:G9}, {height:G9}"), str);
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertToString(float width, float height)
{
var str = Converter.ConvertToString(new SizeF(width, height));
Assert.Equal(string.Format(CultureInfo.CurrentCulture, "{0:G9}{2} {1:G9}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public partial class CodeGenerationTests
{
public class Shared
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task TestSorting()
{
var initial = "namespace [|N|] { }";
var generationSource = @"
using System;
namespace N
{
public class [|C|]
{
private delegate void DAccessA();
internal delegate void DAccessB();
protected internal delegate void DAccessC();
protected delegate void DAccessD();
public delegate void DAccessE();
public delegate void DGeneric<T1, T2>(T1 a, T2 b);
public delegate void DGeneric<T>(T t, int i);
public class CNotStatic { }
public static class CStatic { }
private class CAccessA { }
internal class CAccessB { }
protected internal class CAccessC { }
protected class CAccessD { }
public class CAccessE { }
public class CGeneric<T1, T2> { }
public class CGeneric<T> { }
private struct SAccessA { }
internal struct SAccessB { }
protected internal struct SAccessC { }
protected struct SAccessD { }
public struct SAccessE { }
public struct SGeneric<T1, T2> { }
public struct SGeneric<T> { }
public struct SNameB { }
public struct SNameA { }
private enum EAccessA { }
internal enum EAccessB { }
protected internal enum EAccessC { }
protected enum EAccessD { }
public enum EAccessE { }
public enum ENameB { }
public enum ENameA { }
private interface IAccessA { }
internal interface IAccessB { }
protected internal interface IAccessC { }
protected interface IAccessD { }
public interface IAccessE { }
public interface IGeneric<T1, T2> { }
public interface IGeneric<T> { }
public static C operator !(C c) { return c; }
public static C operator +(C c) { return c; }
public void MNotStatic() { }
public static void MStatic() { }
private void MAccessA() { }
internal void MAccessB() { }
protected internal void MAccessC() { }
protected void MAccessD() { }
public void MAccessE() { }
public void MGeneric<T1, T2>() { }
public void MGeneric<T>(int param) { }
public void MGeneric<T>() { }
public int M2NotStatic() { return 0; }
public static int M2Static() { return 0; }
private int M2AccessA() { return 0; }
internal int M2AccessB() { return 0; }
protected internal int M2AccessC() { return 0; }
protected int M2AccessD() { return 0; }
public int M2AccessE() { return 0; }
public int M2Generic<T1, T2>() { return 0; }
public int M2Generic<T>(int param) { return 0; }
public int M2Generic<T>() { return 0; }
public int PNotStatic { get { return 0; } }
public static int PStatic { get { return 0; } }
private int PAccessA { get { return 0; } }
internal int PAccessB { get { return 0; } }
protected internal int PAccessC { get { return 0; } }
protected int PAccessD { get { return 0; } }
public int PAccessE { get { return 0; } }
public int this[int index1, int index2] { get { return 0; } }
public int this[int index] { get { return 0; } }
public event Action EFNotStatic;
public static event Action EFStatic;
private event Action EFAccessA;
internal event Action EFAccessB;
protected event Action EFAccessC;
protected internal event Action EFAccessD;
public event Action EFAccessE;
private C(string s);
internal C(long l);
protected C(char c);
protected internal C(short s);
public C(int a);
public C(int a, int b);
public C();
public string FNotStatic;
public static string FStatic;
public string FNotConst;
public const string FConst = ""Const, Indeed"";
private string FAccessA;
internal string FAccessB;
protected string FAccessC;
protected internal string FAccessD;
public string FAccessE;
}
}";
var expected = @"
namespace N
{
public class C
{
public const string FConst;
public static string FStatic;
public string FNotStatic;
public string FNotConst;
public string FAccessE;
protected string FAccessC;
protected internal string FAccessD;
internal string FAccessB;
private string FAccessA;
public C();
public C(int a);
public C(int a, int b);
protected C(char c);
protected internal C(short s);
internal C(long l);
private C(string s);
public int this[int index] { get; }
public int this[int index1, int index2] { get; }
public static int PStatic { get; }
public int PNotStatic { get; }
public int PAccessE { get; }
protected int PAccessD { get; }
protected internal int PAccessC { get; }
internal int PAccessB { get; }
private int PAccessA { get; }
public static event Action EFStatic;
public event Action EFNotStatic;
public event Action EFAccessE;
protected event Action EFAccessC;
protected internal event Action EFAccessD;
internal event Action EFAccessB;
private event Action EFAccessA;
public static int M2Static();
public static void MStatic();
public int M2AccessE();
public int M2Generic<T1, T2>();
public int M2Generic<T>(int param);
public int M2Generic<T>();
public int M2NotStatic();
public void MAccessE();
public void MGeneric<T1, T2>();
public void MGeneric<T>(int param);
public void MGeneric<T>();
public void MNotStatic();
protected int M2AccessD();
protected void MAccessD();
protected internal int M2AccessC();
protected internal void MAccessC();
internal int M2AccessB();
internal void MAccessB();
private int M2AccessA();
private void MAccessA();
public static C operator +(C c);
public static C operator !(C c);
public enum EAccessE
{
}
public enum ENameB
{
}
public enum ENameA
{
}
protected enum EAccessD
{
}
protected internal enum EAccessC
{
}
internal enum EAccessB
{
}
private enum EAccessA
{
}
public interface IAccessE
{
}
public interface IGeneric<T1, T2>
{
}
public interface IGeneric<T>
{
}
protected interface IAccessD
{
}
protected internal interface IAccessC
{
}
internal interface IAccessB
{
}
private interface IAccessA
{
}
public struct SAccessE
{
}
public struct SGeneric<T1, T2>
{
}
public struct SGeneric<T>
{
}
public struct SNameB
{
}
public struct SNameA
{
}
protected struct SAccessD
{
}
protected internal struct SAccessC
{
}
internal struct SAccessB
{
}
private struct SAccessA
{
}
public static class CStatic
{
}
public class CNotStatic
{
}
public class CAccessE
{
}
public class CGeneric<T1, T2>
{
}
public class CGeneric<T>
{
}
protected class CAccessD
{
}
protected internal class CAccessC
{
}
internal class CAccessB
{
}
private class CAccessA
{
}
public delegate void DAccessE();
public delegate void DGeneric<T1, T2>(T1 a, T2 b);
public delegate void DGeneric<T>(T t, int i);
protected delegate void DAccessD();
protected internal delegate void DAccessC();
internal delegate void DAccessB();
private delegate void DAccessA();
}
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
forceLanguage: LanguageNames.CSharp);
initial = "Namespace [|N|] \n End Namespace";
expected = @"
Namespace N
Public Class C
Public Const FConst As String
Public Shared FStatic As String
Public FNotStatic As String
Public FNotConst As String
Public FAccessE As String
Protected FAccessC As String
Protected Friend FAccessD As String
Friend FAccessB As String
Private FAccessA As String
Public Sub New()
Public Sub New(a As Integer)
Public Sub New(a As Integer, b As Integer)
Protected Sub New(c As Char)
Protected Friend Sub New(s As Short)
Friend Sub New(l As Long)
Private Sub New(s As String)
Public Shared ReadOnly Property PStatic As Integer
Public ReadOnly Property PNotStatic As Integer
Public ReadOnly Property PAccessE As Integer
Default Public ReadOnly Property this[](index1 As Integer, index2 As Integer) As Integer
Default Public ReadOnly Property this[](index As Integer) As Integer
Protected ReadOnly Property PAccessD As Integer
Protected Friend ReadOnly Property PAccessC As Integer
Friend ReadOnly Property PAccessB As Integer
Private ReadOnly Property PAccessA As Integer
Public Shared Event EFStatic As Action
Public Event EFNotStatic As Action
Public Event EFAccessE As Action
Protected Event EFAccessC As Action
Protected Friend Event EFAccessD As Action
Friend Event EFAccessB As Action
Private Event EFAccessA As Action
Public Shared Sub MStatic()
Public Sub MNotStatic()
Public Sub MAccessE()
Public Sub MGeneric(Of T1, T2)()
Public Sub MGeneric(Of T)(param As Integer)
Public Sub MGeneric(Of T)()
Protected Sub MAccessD()
Protected Friend Sub MAccessC()
Friend Sub MAccessB()
Private Sub MAccessA()
Public Shared Function M2Static() As Integer
Public Function M2NotStatic() As Integer
Public Function M2AccessE() As Integer
Public Function M2Generic(Of T1, T2)() As Integer
Public Function M2Generic(Of T)(param As Integer) As Integer
Public Function M2Generic(Of T)() As Integer
Protected Function M2AccessD() As Integer
Protected Friend Function M2AccessC() As Integer
Friend Function M2AccessB() As Integer
Private Function M2AccessA() As Integer
Public Shared Operator +(c As C) As C
Public Shared Operator Not(c As C) As C
Public Enum EAccessE
End Enum
Public Enum ENameB
End Enum
Public Enum ENameA
End Enum
Protected Enum EAccessD
End Enum
Protected Friend Enum EAccessC
End Enum
Friend Enum EAccessB
End Enum
Private Enum EAccessA
End Enum
Public Interface IAccessE
End Interface
Public Interface IGeneric(Of T1, T2)
End Interface
Public Interface IGeneric(Of T)
End Interface
Protected Interface IAccessD
End Interface
Protected Friend Interface IAccessC
End Interface
Friend Interface IAccessB
End Interface
Private Interface IAccessA
End Interface
Public Structure SAccessE
End Structure
Public Structure SGeneric(Of T1, T2)
End Structure
Public Structure SGeneric(Of T)
End Structure
Public Structure SNameB
End Structure
Public Structure SNameA
End Structure
Protected Structure SAccessD
End Structure
Protected Friend Structure SAccessC
End Structure
Friend Structure SAccessB
End Structure
Private Structure SAccessA
End Structure
Public Class CNotStatic
End Class
Public Class CStatic
End Class
Public Class CAccessE
End Class
Public Class CGeneric(Of T1, T2)
End Class
Public Class CGeneric(Of T)
End Class
Protected Class CAccessD
End Class
Protected Friend Class CAccessC
End Class
Friend Class CAccessB
End Class
Private Class CAccessA
End Class
Public Delegate Sub DAccessE()
Public Delegate Sub DGeneric(Of T1, T2)(a As T1, b As T2)
Public Delegate Sub DGeneric(Of T)(t As T, i As Integer)
Protected Delegate Sub DAccessD()
Protected Friend Delegate Sub DAccessC()
Friend Delegate Sub DAccessB()
Private Delegate Sub DAccessA()
End Class
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
forceLanguage: LanguageNames.VisualBasic);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task TestSortingDefaultTypeMemberAccessibility1()
{
var generationSource = "public class [|C|] { private string B; public string C; }";
var initial = "public class [|C|] { string A; }";
var expected = @"
public class C
{
public string C;
string A;
private string B;
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "public struct [|S|] { string A; }";
expected = @"
public struct S
{
public string C;
string A;
private string B;
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Class [|C|] \n Dim A As String \n End Class";
expected = @"
Public Class C
Public C As String
Dim A As String
Private B As String
End Class";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Module [|M|] \n Dim A As String \n End Module";
expected = @"
Public Module M
Public C As String
Dim A As String
Private B As String
End Module";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Structure [|S|] \n Dim A As String \n End Structure";
expected = @"
Public Structure S
Dim A As String
Public C As String
Private B As String
End Structure";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task TestDefaultTypeMemberAccessibility2()
{
var generationSource = "public class [|C|] { private void B(){} public void C(){} }";
var initial = "public interface [|I|] { void A(); }";
var expected = @"
public interface I
{
void A();
void B();
void C();
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Interface [|I|] \n Sub A() \n End Interface";
expected = @"
Public Interface I
Sub A()
Sub B()
Sub C()
End Interface";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Class [|C|] \n Sub A() \n End Sub \n End Class";
expected = @"
Public Class C
Sub A()
End Sub
Public Sub C()
End Sub
Private Sub B()
End Sub
End Class";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
initial = "Public Module [|M|] \n Sub A() \n End Sub \n End Module";
expected = @"
Public Module M
Sub A()
End Sub
Public Sub C()
End Sub
Private Sub B()
End Sub
End Module";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected, onlyGenerateMembers: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task TestDefaultNamespaceMemberAccessibility1()
{
var generationSource = "internal class [|B|]{}";
var initial = "namespace [|N|] { class A{} }";
var expected = "namespace N { class A{} internal class B{} }";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected);
initial = "Namespace [|N|] \n Class A \n End Class \n End Namespace";
expected = "Namespace N \n Class A \n End Class \n Friend Class B \n End Class \n End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task TestDefaultNamespaceMemberAccessibility2()
{
var generationSource = "public class [|C|]{}";
var initial = "namespace [|N|] { class A{} }";
var expected = "namespace N { public class C{} class A{} }";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected);
initial = "Namespace [|N|] \n Class A \n End Class \n End Namespace";
expected = "Namespace N \n Public Class C \n End Class \n Class A \n End Class \n End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestDocumentationComment()
{
var generationSource = @"
public class [|C|]
{
/// <summary>When in need, a documented method is a friend, indeed.</summary>
public C() { }
}";
var initial = "public class [|C|] { }";
var expected = @"
public class C
{
/// <summary>When in need, a documented method is a friend, indeed.</summary>
public C();
}";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false, generateDocumentationComments: true),
onlyGenerateMembers: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestModifiers()
{
var generationSource = @"
namespace [|N|]
{
public class A
{
public virtual string Property { get { return null; } }
public static abstract string Property1 { get; }
public virtual void Method1() {}
public static abstract void Method2() {}
}
public class C
{
public sealed override string Property { get { return null; } }
public sealed override void Method1() {}
}
}";
var initial = "namespace [|N|] { }";
var expected = @"
namespace N
{
namespace N
{
public class A
{
public static abstract string Property1 { get; }
public virtual string Property { get; }
public abstract static void Method2();
public virtual void Method1();
}
public class C
{
public sealed override string Property { get; }
public sealed override void Method1();
}
}
}
";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
var initialVB = "Namespace [|N|] End Namespace";
var expectedVB = @"
Namespace N
Namespace N
Public Class A
Public Shared MustOverride ReadOnly Property Property1 As String
Public Overridable ReadOnly Property [Property] As String
Public MustOverride Shared Sub Method2()
Public Overridable Sub Method1()
End Class
Public Class C
Public Overrides NotOverridable ReadOnly Property [Property] As String
Public NotOverridable Overrides Sub Method1()
End Class
End Namespace
";
await TestGenerateFromSourceSymbolAsync(generationSource, initialVB, expectedVB,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Logging;
namespace QuantConnect.Securities
{
/// <summary>
/// Represents a holding of a currency in cash.
/// </summary>
public class Cash
{
private bool _isBaseCurrency;
private bool _invertRealTimePrice;
private readonly object _locker = new object();
/// <summary>
/// Gets the symbol of the security required to provide conversion rates.
/// If this cash represents the account currency, then <see cref="QuantConnect.Symbol.Empty"/>
/// is returned
/// </summary>
public Symbol SecuritySymbol => ConversionRateSecurity?.Symbol ?? QuantConnect.Symbol.Empty;
/// <summary>
/// Gets the security used to apply conversion rates.
/// If this cash represents the account currency, then null is returned.
/// </summary>
[JsonIgnore]
public Security ConversionRateSecurity { get; private set; }
/// <summary>
/// Gets the symbol used to represent this cash
/// </summary>
public string Symbol { get; }
/// <summary>
/// Gets or sets the amount of cash held
/// </summary>
public decimal Amount { get; private set; }
/// <summary>
/// Gets the conversion rate into account currency
/// </summary>
public decimal ConversionRate { get; internal set; }
/// <summary>
/// The symbol of the currency, such as $
/// </summary>
public string CurrencySymbol { get; }
/// <summary>
/// Gets the value of this cash in the account currency
/// </summary>
public decimal ValueInAccountCurrency => Amount * ConversionRate;
/// <summary>
/// Initializes a new instance of the <see cref="Cash"/> class
/// </summary>
/// <param name="symbol">The symbol used to represent this cash</param>
/// <param name="amount">The amount of this currency held</param>
/// <param name="conversionRate">The initial conversion rate of this currency into the <see cref="CashBook.AccountCurrency"/></param>
public Cash(string symbol, decimal amount, decimal conversionRate)
{
if (symbol == null || symbol.Length != 3)
{
throw new ArgumentException("Cash symbols must be exactly 3 characters.");
}
Amount = amount;
ConversionRate = conversionRate;
Symbol = symbol.ToUpper();
CurrencySymbol = Currencies.GetCurrencySymbol(Symbol);
}
/// <summary>
/// Updates this cash object with the specified data
/// </summary>
/// <param name="data">The new data for this cash object</param>
public void Update(BaseData data)
{
if (_isBaseCurrency) return;
var rate = data.Value;
if (_invertRealTimePrice)
{
rate = 1/rate;
}
ConversionRate = rate;
}
/// <summary>
/// Adds the specified amount of currency to this Cash instance and returns the new total.
/// This operation is thread-safe
/// </summary>
/// <param name="amount">The amount of currency to be added</param>
/// <returns>The amount of currency directly after the addition</returns>
public decimal AddAmount(decimal amount)
{
lock (_locker)
{
Amount += amount;
return Amount;
}
}
/// <summary>
/// Sets the Quantity to the specified amount
/// </summary>
/// <param name="amount">The amount to set the quantity to</param>
public void SetAmount(decimal amount)
{
lock (_locker)
{
Amount = amount;
}
}
/// <summary>
/// Ensures that we have a data feed to convert this currency into the base currency.
/// This will add a subscription at the lowest resolution if one is not found.
/// </summary>
/// <param name="securities">The security manager</param>
/// <param name="subscriptions">The subscription manager used for searching and adding subscriptions</param>
/// <param name="marketHoursDatabase">A security exchange hours provider instance used to resolve exchange hours for new subscriptions</param>
/// <param name="symbolPropertiesDatabase">A symbol properties database instance</param>
/// <param name="marketMap">The market map that decides which market the new security should be in</param>
/// <param name="cashBook">The cash book - used for resolving quote currencies for created conversion securities</param>
/// <param name="changes"></param>
/// <returns>Returns the added currency security if needed, otherwise null</returns>
public Security EnsureCurrencyDataFeed(SecurityManager securities,
SubscriptionManager subscriptions,
MarketHoursDatabase marketHoursDatabase,
SymbolPropertiesDatabase symbolPropertiesDatabase,
IReadOnlyDictionary<SecurityType, string> marketMap,
CashBook cashBook,
SecurityChanges changes
)
{
// this gets called every time we add securities using universe selection,
// so must of the time we've already resolved the value and don't need to again
if (ConversionRateSecurity != null)
{
return null;
}
if (Symbol == CashBook.AccountCurrency)
{
ConversionRateSecurity = null;
_isBaseCurrency = true;
ConversionRate = 1.0m;
return null;
}
// we require a security that converts this into the base currency
string normal = Symbol + CashBook.AccountCurrency;
string invert = CashBook.AccountCurrency + Symbol;
var securitiesToSearch = securities.Select(kvp => kvp.Value)
.Concat(changes.AddedSecurities)
.Where(s => s.Type == SecurityType.Forex || s.Type == SecurityType.Cfd || s.Type == SecurityType.Crypto);
foreach (var security in securitiesToSearch)
{
if (security.Symbol.Value == normal)
{
ConversionRateSecurity = security;
return null;
}
if (security.Symbol.Value == invert)
{
ConversionRateSecurity = security;
_invertRealTimePrice = true;
return null;
}
}
// if we've made it here we didn't find a security, so we'll need to add one
// Create a SecurityType to Market mapping with the markets from SecurityManager members
var markets = securities.Select(x => x.Key).GroupBy(x => x.SecurityType).ToDictionary(x => x.Key, y => y.First().ID.Market);
if (markets.ContainsKey(SecurityType.Cfd) && !markets.ContainsKey(SecurityType.Forex))
{
markets.Add(SecurityType.Forex, markets[SecurityType.Cfd]);
}
if (markets.ContainsKey(SecurityType.Forex) && !markets.ContainsKey(SecurityType.Cfd))
{
markets.Add(SecurityType.Cfd, markets[SecurityType.Forex]);
}
var potentials = Currencies.CurrencyPairs.Select(fx => CreateSymbol(marketMap, fx, markets, SecurityType.Forex))
.Concat(Currencies.CfdCurrencyPairs.Select(cfd => CreateSymbol(marketMap, cfd, markets, SecurityType.Cfd)))
.Concat(Currencies.CryptoCurrencyPairs.Select(crypto => CreateSymbol(marketMap, crypto, markets, SecurityType.Crypto)));
var minimumResolution = subscriptions.Subscriptions.Select(x => x.Resolution).DefaultIfEmpty(Resolution.Minute).Min();
var objectType = minimumResolution == Resolution.Tick ? typeof (Tick) : typeof (QuoteBar);
foreach (var symbol in potentials)
{
if (symbol.Value == normal || symbol.Value == invert)
{
_invertRealTimePrice = symbol.Value == invert;
var securityType = symbol.ID.SecurityType;
var symbolProperties = symbolPropertiesDatabase.GetSymbolProperties(symbol.ID.Market, symbol.Value, securityType, Symbol);
Cash quoteCash;
if (!cashBook.TryGetValue(symbolProperties.QuoteCurrency, out quoteCash))
{
throw new Exception("Unable to resolve quote cash: " + symbolProperties.QuoteCurrency + ". This is required to add conversion feed: " + symbol.Value);
}
var marketHoursDbEntry = marketHoursDatabase.GetEntry(symbol.ID.Market, symbol.Value, symbol.ID.SecurityType);
var exchangeHours = marketHoursDbEntry.ExchangeHours;
// set this as an internal feed so that the data doesn't get sent into the algorithm's OnData events
var config = subscriptions.Add(objectType, TickType.Quote, symbol, minimumResolution, marketHoursDbEntry.DataTimeZone, exchangeHours.TimeZone, false, true, false, true);
Security security;
if (securityType == SecurityType.Cfd)
{
security = new Cfd.Cfd(exchangeHours, quoteCash, config, symbolProperties);
}
else if (securityType == SecurityType.Crypto)
{
security = new Crypto.Crypto(exchangeHours, quoteCash, config, symbolProperties);
}
else
{
security = new Forex.Forex(exchangeHours, quoteCash, config, symbolProperties);
}
ConversionRateSecurity = security;
securities.Add(config.Symbol, security);
Log.Trace("Cash.EnsureCurrencyDataFeed(): Adding " + symbol.Value + " for cash " + Symbol + " currency feed");
return security;
}
}
// if this still hasn't been set then it's an error condition
throw new ArgumentException(string.Format("In order to maintain cash in {0} you are required to add a subscription for Forex pair {0}{1} or {1}{0}", Symbol, CashBook.AccountCurrency));
}
/// <summary>
/// Returns a <see cref="string"/> that represents the current <see cref="Cash"/>.
/// </summary>
/// <returns>A <see cref="string"/> that represents the current <see cref="Cash"/>.</returns>
public override string ToString()
{
// round the conversion rate for output
var rate = ConversionRate;
rate = rate < 1000 ? rate.RoundToSignificantDigits(5) : Math.Round(rate, 2);
return $"{Symbol}: {CurrencySymbol}{Amount,15:0.00} @ {rate,10:0.00####} = ${Math.Round(ValueInAccountCurrency, 2)}";
}
private static Symbol CreateSymbol(IReadOnlyDictionary<SecurityType, string> marketMap, string crypto, Dictionary<SecurityType, string> markets, SecurityType securityType)
{
string market;
if (!markets.TryGetValue(securityType, out market))
{
market = marketMap[securityType];
}
return QuantConnect.Symbol.Create(crypto, securityType, market);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
namespace Microsoft.Msagl.Layout.Layered {
/// <summary>
/// Defines the anchors for a node; anchors can be not symmetrical in general
///
/// |TopAnchor
///Left anchor|
/// ======Origin==================RightAnchor
/// |
/// |
/// |BottomAnchor
/// </summary>
#if TEST_MSAGL
public
#else
internal
#endif
class Anchor {
/// <summary>
/// ToString
/// </summary>
/// <returns></returns>
public override string ToString() {
return "la:ra " +
la.ToString("#.##", CultureInfo.InvariantCulture) + " " + ra.ToString("#.##", CultureInfo.InvariantCulture) + " ta:ba " + ta.ToString("#.##", CultureInfo.InvariantCulture) + " " + ba.ToString("#.##", CultureInfo.InvariantCulture) + " x:y " + x.ToString("#.##", CultureInfo.InvariantCulture) + " " + y.ToString("#.##", CultureInfo.InvariantCulture);
}
double la;
double ra;
double ta;
double ba;
double labelCornersPreserveCoefficient;
/// <summary>
/// distance for the center of the node to its left boundary
/// </summary>
public double LeftAnchor {
get {
return la;
}
set {
//the absence of this check allows a situation when an edge crosses its label or
// a label which does not belong to the edge
// if(value<-Curve.DistEps)
// throw new Exception("assigning negative value to a anchor");
la = Math.Max(value, 0); ;
}
}
/// <summary>
/// distance from the center of the node to its right boundary
/// </summary>
public double RightAnchor {
get {
return ra;
}
set {
// if(value<-Curve.DistEps)
// throw new Exception("assigning negative value to a anchor: "+value );
ra = Math.Max(value, 0);
}
}
/// <summary>
/// distance from the center of the node to its top boundary
/// </summary>
public double TopAnchor {
get {
return ta;
}
set {
//if(value<-Curve.DistEps)
//throw new Exception("assigning negative value to a anchor");
ta = Math.Max(value, 0);
}
}
/// <summary>
/// distance from the center of the node to it bottom boundary
/// </summary>
public double BottomAnchor {
get {
return ba;
}
set {
//if(value<-Curve.DistEps)
//throw new InvalidOperationException();//"assigning negative value to a anchor");
ba = Math.Max(value, 0);
}
}
/// <summary>
/// Left boundary of the node
/// </summary>
public double Left {
get { return x - la; }
}
/// <summary>
/// right boundary of the node
/// </summary>
public double Right {
get { return x + ra; }
}
/// <summary>
/// top boundary of the node
/// </summary>
public double Top {
get { return y + ta; }
set {
y += value - Top;
}
}
/// <summary>
/// bottom of the node
/// </summary>
public double Bottom {
get { return y - ba; }
set { y += value - Bottom; }
}
/// <summary>
/// Left top corner
/// </summary>
public Point LeftTop {
get { return new Point(Left, Top); }
}
/// <summary>
/// Left bottom of the node
/// </summary>
public Point LeftBottom {
get { return new Point(Left, Bottom); }
}
/// <summary>
/// Right bottom of the node
/// </summary>
public Point RightBottom {
get { return new Point(Right, Bottom); }
}
Node node;
internal Node Node {
get { return node; }
set {
node = value;
this.polygonalBoundary = null;
}
}
/// <summary>
/// Right top of the node
/// </summary>
public Point RightTop {
get { return new Point(Right, Top); }
}
/// <summary>
/// an empty constructor
/// </summary>
public Anchor(double labelCornersPreserveCoefficient) {
this.labelCornersPreserveCoefficient = labelCornersPreserveCoefficient;
}
/// <summary>
/// constructor
/// </summary>
public Anchor(double leftAnchor, double rightAnchor,
double topAnchor, double bottomAnchor, Node node, double labelCornersPreserveCoefficient) {
la = leftAnchor;
ra = rightAnchor;
ta = topAnchor;
ba = bottomAnchor;
Node = node;
this.labelCornersPreserveCoefficient = labelCornersPreserveCoefficient;
}
double x;
/// <summary>
/// the x position
/// </summary>
internal double X {
get {
return x;
}
set {
polygonalBoundary = null;
x = value;
}
}
double y;
/// <summary>
/// the y position
/// </summary>
internal double Y {
get {
return y;
}
set {
polygonalBoundary = null;
y = value;
}
}
/// <summary>
/// Center of the node
/// </summary>
public Point Origin {
get {
return new Point(x, y);
}
}
bool alreadySitsOnASpline;
/// <summary>
/// signals if the spline has been routed already through the node
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811")]
public bool AlreadySitsOnASpline {
get { return alreadySitsOnASpline; }
set { alreadySitsOnASpline = value; }
}
/// <summary>
/// node widths
/// </summary>
public double Width {
get { return this.la + this.ra; }
}
/// <summary>
/// node height
/// </summary>
public double Height {
get { return this.ta + this.ba; }
}
/// <summary>
/// set to true if the anchor has been introduced for a label
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811")]
public bool RepresentsLabel {
get { return LabelToTheRightOfAnchorCenter || LabelToTheLeftOfAnchorCenter; }
}
bool labelIsToTheLeftOfTheSpline;
/// <summary>
/// An anchor for an edge label with the label to the right of the spline has its height equal to the one of the label
/// Its leftAnchor is a reserved space for the spline and the rightAnchor is equal to the label width.
/// </summary>
internal bool LabelToTheLeftOfAnchorCenter {
get { return labelIsToTheLeftOfTheSpline; }
set { labelIsToTheLeftOfTheSpline = value; }
}
bool labelIsToTheRightOfTheSpline;
/// <summary>
/// An anchor for an edge label with the label to the left of the spline has its height equal to the one of the label
/// Its rightAnchor is a reserved space for the spline and the leftAnchor is equal to the label width.
/// </summary>
internal bool LabelToTheRightOfAnchorCenter {
get { return labelIsToTheRightOfTheSpline; }
set { labelIsToTheRightOfTheSpline = value; }
}
internal bool HasLabel {
get { return LabelToTheRightOfAnchorCenter || LabelToTheLeftOfAnchorCenter; }
}
internal double LabelWidth {
get {
if (LabelToTheLeftOfAnchorCenter)
return LeftAnchor;
if (LabelToTheRightOfAnchorCenter)
return RightAnchor;
throw new InvalidOperationException();
}
}
Polyline polygonalBoundary;
/// <summary>
/// the polygon representing the boundary of a node
/// </summary>
#if TEST_MSAGL
public
#else
internal
#endif
Polyline PolygonalBoundary {
get {
if (polygonalBoundary != null)
return polygonalBoundary;
return polygonalBoundary = Pad(CreatPolygonalBoundaryWithoutPadding(),Padding);
}
}
static Polyline Pad(Polyline curve, double padding) {
if (padding == 0)
return curve;
if (CurveIsConvex(curve)) {
return PadConvexCurve(curve, padding);
} else
return PadConvexCurve(Curve.StandardRectBoundary(curve), padding);
}
static void PadCorner(Polyline poly, PolylinePoint p0, PolylinePoint p1, PolylinePoint p2, double padding) {
Point a, b;
int numberOfPoints=GetPaddedCorner(p0, p1, p2, out a, out b, padding);
poly.AddPoint(a);
if (numberOfPoints==2)
poly.AddPoint(b);
}
static Polyline PadConvexCurve(Polyline poly, double padding) {
Polyline ret = new Polyline();
PadCorner(ret, poly.EndPoint.Prev, poly.EndPoint, poly.StartPoint, padding);
PadCorner(ret, poly.EndPoint, poly.StartPoint, poly.StartPoint.Next, padding);
for (PolylinePoint pp = poly.StartPoint; pp.Next.Next != null; pp = pp.Next)
PadCorner(ret, pp, pp.Next, pp.Next.Next, padding);
ret.Closed = true;
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <param name="third"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="padding"></param>
/// <returns>number of new points</returns>
static int GetPaddedCorner(PolylinePoint first, PolylinePoint second, PolylinePoint third, out Point a, out Point b,
double padding) {
Point u = first.Point;
Point v = second.Point;
Point w = third.Point;
System.Diagnostics.Debug.Assert(Point.GetTriangleOrientation(u, v, w) == TriangleOrientation.Clockwise);
Point uvPerp = (v - u).Rotate(Math.PI / 2).Normalize();
////uvPerp has to look outside of the curve
//if (uvPerp * (v - Origin) < 0)
// uvPerp *= -1;
Point l = (v - u).Normalize() + (v - w).Normalize();
if (l.Length < ApproximateComparer.IntersectionEpsilon) {
a = b = v + padding * uvPerp;
return 1;
}
Point d = l.Normalize() * padding;
Point dp = d.Rotate(Math.PI / 2);
//look for a in the form d+x*dp
//we have: Padding=(d+x*dp)*uvPerp
double xp = (padding - d * uvPerp) / (dp * uvPerp);
a = d + xp * dp + v;
b = d - xp * dp + v;
return 2; //number of points to add
}
static bool CurveIsConvex(Polyline poly) {
TriangleOrientation orientation = Point.GetTriangleOrientation(poly.EndPoint.Point, poly.StartPoint.Point, poly.StartPoint.Next.Point);
if (Point.GetTriangleOrientation(poly.EndPoint.Prev.Point, poly.EndPoint.Point, poly.StartPoint.Point) != orientation)
return false;
PolylinePoint pp = poly.StartPoint;
while (pp.Next.Next != null) {
if (Point.GetTriangleOrientation(pp.Point, pp.Next.Point, pp.Next.Next.Point) != orientation)
return false;
pp = pp.Next;
}
return true;
}
//private static double TurnAfterSeg(Curve curve, int i) {
// return Point.SignedDoubledTriangleArea(curve.Segments[i].Start, curve.Segments[i].End, curve.Segments[(i + 1) / curve.Segments.Count].End);
//}
private Polyline CreatPolygonalBoundaryWithoutPadding() {
Polyline ret;
if (this.HasLabel)
ret = LabelToTheLeftOfAnchorCenter ? PolygonOnLeftLabel() : PolygonOnRightLabel();
else if (this.NodeBoundary == null)
ret = StandardRectBoundary();
else
ret = Curve.PolylineAroundClosedCurve(this.NodeBoundary);
return ret;
}
private Polyline StandardRectBoundary() {
Polyline poly = new Polyline();
poly.AddPoint(LeftTop);
poly.AddPoint(RightTop);
poly.AddPoint(RightBottom);
poly.AddPoint(LeftBottom);
poly.Closed = true;
return poly;
}
private Polyline PolygonOnLeftLabel() {
Polyline poly = new Polyline();
double t = Left + (1 - this.labelCornersPreserveCoefficient) * LabelWidth;
poly.AddPoint(new Point(t, Top));
poly.AddPoint(RightTop);
poly.AddPoint(RightBottom);
poly.AddPoint(new Point(t, Bottom));
poly.AddPoint(new Point(Left, Y));
poly.Closed = true;
return poly;
}
private Polyline PolygonOnRightLabel() {
Polyline poly = new Polyline();
double t = Right - (1 - this.labelCornersPreserveCoefficient) * LabelWidth;
poly.AddPoint(t, Top);
poly.AddPoint(Right, Y);
poly.AddPoint(t, Bottom);
poly.AddPoint(Left, Bottom);
poly.AddPoint(Left, Top);
poly.Closed = true;
return poly;
}
internal ICurve NodeBoundary {
get { return Node!=null?Node.BoundaryCurve:null; }
}
double padding;
/// <summary>
/// node padding
/// </summary>
public double Padding {
get { return padding; }
set { padding = value; }
}
internal void Move(Point p){
this.X += p.X;
this.Y += p.Y;
}
internal void MoveTo(Point p) {
this.X = p.X;
this.Y = p.Y;
}
#if TEST_MSAGL
/// <summary>
/// UserData
/// </summary>
public object UserData { get; set; }
#endif
}
}
| |
//
// Microsoft.VisualBasic.VBCodeProvider.cs
//
// Author:
// Jochen Wezel ([email protected])
//
// (C) 2003 Jochen Wezel (CompuMaster GmbH)
//
// Last modifications:
// 2003-12-10 JW: publishing of this file
//
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Specialized;
using System.Globalization;
using System.Reflection;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.VisualBasic;
using NUnit.Framework;
namespace MonoTests.Microsoft.VisualBasic
{
enum OsType
{
Windows,
Unix,
Mac
}
[TestFixture]
public class VBCodeProviderTest
{
private string _tempDir;
private CodeDomProvider _codeProvider;
private static OsType OS;
private static char DSC = Path.DirectorySeparatorChar;
private static readonly string _sourceTest1 = "Public Class Test1" +
Environment.NewLine + "End Class";
private static readonly string _sourceTest2 = "Public Class Test2" +
Environment.NewLine + "End Class";
[SetUp]
public void GetReady ()
{
if ('/' == DSC) {
OS = OsType.Unix;
} else if ('\\' == DSC) {
OS = OsType.Windows;
} else {
OS = OsType.Mac;
}
_codeProvider = new VBCodeProvider ();
_tempDir = CreateTempDirectory ();
}
[TearDown]
public void TearDown ()
{
RemoveDirectory (_tempDir);
}
[Test]
public void FileExtension ()
{
Assert.AreEqual ("vb", _codeProvider.FileExtension, "#JW10");
}
[Test]
public void LanguageOptionsTest ()
{
Assert.AreEqual (LanguageOptions.CaseInsensitive, _codeProvider.LanguageOptions, "#JW20");
}
[Test]
public void GeneratorSupports ()
{
ICodeGenerator codeGenerator = _codeProvider.CreateGenerator ();
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareEnums), "#1");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ArraysOfArrays), "#2");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.AssemblyAttributes), "#3");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ChainedConstructorArguments), "#4");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ComplexExpressions), "#5");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareDelegates), "#6");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareEnums), "#7");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareEvents), "#8");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareInterfaces), "#9");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareValueTypes), "#10");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.EntryPointMethod), "#11");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.GotoStatements), "#12");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.MultidimensionalArrays), "#13");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.MultipleInterfaceMembers), "#14");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.NestedTypes), "#15");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ParameterAttributes), "#16");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.PublicStaticMembers), "#17");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ReferenceParameters), "#18");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.ReturnTypeAttributes), "#19");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.StaticConstructors), "#20");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.TryCatchStatements), "#21");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.Win32Resources), "#22");
#if NET_2_0
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.DeclareIndexerProperties), "#23");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.GenericTypeDeclaration), "#24");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.GenericTypeReference), "#25");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.PartialTypes), "#26");
Assert.IsTrue (codeGenerator.Supports (GeneratorSupport.Resources), "#27");
#endif
}
[Test]
#if NET_2_0
// there's not yet an mbas for the 2.0 profile
[Category ("NotWorking")]
#else
[Ignore ("Bug #75223")]
#endif
public void CreateCompiler ()
{
// Prepare the compilation
ICodeCompiler codeCompiler = _codeProvider.CreateCompiler ();
Assert.IsNotNull (codeCompiler, "#JW30 - CreateCompiler");
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = true;
options.IncludeDebugInformation = true;
options.TreatWarningsAsErrors = true;
// process compilation
CompilerResults compilerResults = codeCompiler.CompileAssemblyFromSource (options,
"public class TestModule" + Environment.NewLine + "public shared sub Main()"
+ Environment.NewLine + "System.Console.Write(\"Hello world!\")"
+ Environment.NewLine + "End Sub" + Environment.NewLine + "End Class");
// Analyse the compilation success/messages
StringCollection MyOutput = compilerResults.Output;
string MyOutStr = "";
foreach (string MyStr in MyOutput) {
MyOutStr += MyStr + Environment.NewLine + Environment.NewLine;
}
if (compilerResults.Errors.Count != 0) {
Assert.Fail ("#JW31 - Hello world compilation: " + MyOutStr);
}
try {
Assembly MyAss = compilerResults.CompiledAssembly;
} catch (Exception ex) {
Assert.Fail ("#JW32 - compilerResults.CompiledAssembly hasn't been an expected object" +
Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
}
// Execute the test app
ProcessStartInfo NewProcInfo = new ProcessStartInfo ();
if (Windows) {
NewProcInfo.FileName = compilerResults.CompiledAssembly.Location;
} else {
NewProcInfo.FileName = "mono";
NewProcInfo.Arguments = compilerResults.CompiledAssembly.Location;
}
NewProcInfo.RedirectStandardOutput = true;
NewProcInfo.UseShellExecute = false;
NewProcInfo.CreateNoWindow = true;
string TestAppOutput = "";
try {
Process MyProc = Process.Start (NewProcInfo);
MyProc.WaitForExit ();
TestAppOutput = MyProc.StandardOutput.ReadToEnd ();
MyProc.Close ();
MyProc.Dispose ();
} catch (Exception ex) {
Assert.Fail ("#JW34 - " + ex.Message + Environment.NewLine + ex.StackTrace);
}
Assert.AreEqual ("Hello world!", TestAppOutput, "#JW33 - Application output");
// Clean up
try {
File.Delete (NewProcInfo.FileName);
} catch { }
}
[Test]
public void CreateGenerator ()
{
ICodeGenerator MyVBCodeGen;
MyVBCodeGen = _codeProvider.CreateGenerator ();
Assert.IsNotNull (MyVBCodeGen, "#JW40 - CreateGenerator");
Assert.IsTrue (MyVBCodeGen.Supports (GeneratorSupport.DeclareEnums), "#JW41");
}
[Test]
#if NET_2_0
// there's not yet an mbas for the 2.0 profile
[Category ("NotWorking")]
#endif
public void CompileFromFile_InMemory ()
{
// create vb source file
string sourceFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream f = new FileStream (sourceFile, FileMode.Create)) {
using (StreamWriter s = new StreamWriter (f)) {
s.Write (_sourceTest1);
s.Close ();
}
f.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromFile (options,
sourceFile);
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test1"), "#3");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#4");
Assert.AreEqual (sourceFile, tempFiles[0], "#5");
}
[Test]
#if NET_2_0
// there's not yet an mbas for the 2.0 profile
[Category ("NotWorking")]
#endif
public void CompileFromFileBatch_InMemory ()
{
// create vb source file
string sourceFile1 = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream f = new FileStream (sourceFile1, FileMode.Create)) {
using (StreamWriter s = new StreamWriter (f)) {
s.Write (_sourceTest1);
s.Close ();
}
f.Close ();
}
string sourceFile2 = Path.Combine (_tempDir, "file2." + _codeProvider.FileExtension);
using (FileStream f = new FileStream (sourceFile2, FileMode.Create)) {
using (StreamWriter s = new StreamWriter (f)) {
s.Write (_sourceTest2);
s.Close ();
}
f.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromFileBatch (options,
new string[] { sourceFile1, sourceFile2 });
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test1"), "#3");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test2"), "#4");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (2, tempFiles.Length, "#5");
Assert.IsTrue (File.Exists (sourceFile1), "#6");
Assert.IsTrue (File.Exists (sourceFile2), "#7");
}
[Test]
#if NET_2_0
// there's not yet an mbas for the 2.0 profile
[Category ("NotWorking")]
#endif
public void CompileFromSource_InMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromSource (options,
_sourceTest1);
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test1"), "#3");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#4");
Assert.AreEqual (tempFile, tempFiles[0], "#5");
}
[Test]
#if NET_2_0
// there's not yet an mbas for the 2.0 profile
[Category ("NotWorking")]
#endif
public void CompileFromSourceBatch_InMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromSourceBatch (options,
new string[] { _sourceTest1, _sourceTest2 });
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test1"), "#3");
Assert.IsNotNull (results.CompiledAssembly.GetType ("Test2"), "#4");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#5");
Assert.AreEqual (tempFile, tempFiles[0], "#6");
}
[Test]
#if NET_2_0
// there's not yet an mbas for the 2.0 profile
[Category ("NotWorking")]
#endif
public void CompileFromDom_NotInMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
// compile and verify result in separate appdomain to avoid file locks
AppDomain testDomain = CreateTestDomain ();
CrossDomainTester compileTester = CreateCrossDomainTester (testDomain);
string outputAssembly = null;
try {
outputAssembly = compileTester.CompileAssemblyFromDom (_tempDir);
} finally {
AppDomain.Unload (testDomain);
}
// there should be two files in temp dir: temp file and output assembly
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (2, tempFiles.Length, "#1");
Assert.IsTrue (File.Exists (outputAssembly), "#2");
Assert.IsTrue (File.Exists (tempFile), "#3");
}
[Test]
#if NET_2_0
// there's not yet an mbas for the 2.0 profile
[Category ("NotWorking")]
#endif
public void CompileFromDomBatch_NotInMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
// compile and verify result in separate appdomain to avoid file locks
AppDomain testDomain = CreateTestDomain ();
CrossDomainTester compileTester = CreateCrossDomainTester (testDomain);
string outputAssembly = null;
try {
outputAssembly = compileTester.CompileAssemblyFromDomBatch (_tempDir);
} finally {
AppDomain.Unload (testDomain);
}
// there should be two files in temp dir: temp file and output assembly
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (2, tempFiles.Length, "#1");
Assert.IsTrue (File.Exists (outputAssembly), "#2");
Assert.IsTrue (File.Exists (tempFile), "#3");
}
[Test]
#if NET_2_0
// there's not yet an mbas for the 2.0 profile
[Category ("NotWorking")]
#endif
public void CompileFromDom_InMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDom (options, new CodeCompileUnit ());
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#3");
Assert.AreEqual (tempFile, tempFiles[0], "#4");
}
[Test]
#if NET_2_0
// there's not yet an mbas for the 2.0 profile
[Category ("NotWorking")]
#endif
public void CompileFromDomBatch_InMemory ()
{
// create a file in temp directory to ensure that compiler is not removing
// too much (temporary) files
string tempFile = Path.Combine (_tempDir, "file." + _codeProvider.FileExtension);
using (FileStream fs = File.Create (tempFile)) {
fs.Close ();
}
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.TempFiles = new TempFileCollection (_tempDir);
ICodeCompiler compiler = _codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDomBatch (options,
new CodeCompileUnit[] { new CodeCompileUnit (), new CodeCompileUnit () });
// verify compilation was successful
AssertCompileResults (results, true);
Assert.AreEqual (string.Empty, results.CompiledAssembly.Location, "#1");
Assert.IsNull (results.PathToAssembly, "#2");
// verify we don't cleanup files in temp directory too agressively
string[] tempFiles = Directory.GetFiles (_tempDir);
Assert.AreEqual (1, tempFiles.Length, "#3");
Assert.AreEqual (tempFile, tempFiles[0], "#4");
}
//TODO: [Test]
public void CreateParser ()
{
//System.CodeDom.Compiler.ICodeParser CreateParser()
}
//TODO: [Test]
public void CreateObjRef ()
{
//System.Runtime.Remoting.ObjRef CreateObjRef(System.Type requestedType)
}
bool Windows
{
get {
return OS == OsType.Windows;
}
}
bool Unix
{
get {
return OS == OsType.Unix;
}
}
bool Mac
{
get {
return OS == OsType.Mac;
}
}
private static string CreateTempDirectory ()
{
// create a uniquely named zero-byte file
string tempFile = Path.GetTempFileName ();
// remove the temporary file
File.Delete (tempFile);
// create a directory named after the unique temporary file
Directory.CreateDirectory (tempFile);
// return the path to the temporary directory
return tempFile;
}
private static void RemoveDirectory (string path)
{
try {
if (Directory.Exists (path)) {
string[] directoryNames = Directory.GetDirectories (path);
foreach (string directoryName in directoryNames) {
RemoveDirectory (directoryName);
}
string[] fileNames = Directory.GetFiles (path);
foreach (string fileName in fileNames) {
File.Delete (fileName);
}
Directory.Delete (path, true);
}
} catch (Exception ex) {
throw new AssertionException ("Unable to cleanup '" + path + "'.", ex);
}
}
private static void AssertCompileResults (CompilerResults results, bool allowWarnings)
{
foreach (CompilerError compilerError in results.Errors) {
if (allowWarnings && compilerError.IsWarning) {
continue;
}
Assert.Fail (compilerError.ToString ());
}
}
private static AppDomain CreateTestDomain ()
{
return AppDomain.CreateDomain ("CompileFromDom", AppDomain.CurrentDomain.Evidence,
AppDomain.CurrentDomain.SetupInformation);
}
private static CrossDomainTester CreateCrossDomainTester (AppDomain domain)
{
Type testerType = typeof (CrossDomainTester);
return (CrossDomainTester) domain.CreateInstanceAndUnwrap (
testerType.Assembly.FullName, testerType.FullName, false,
BindingFlags.Public | BindingFlags.Instance, null, new object[0],
CultureInfo.InvariantCulture, new object[0], domain.Evidence);
}
private class CrossDomainTester : MarshalByRefObject
{
public string CompileAssemblyFromDom (string tempDir)
{
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = false;
options.TempFiles = new TempFileCollection (tempDir);
VBCodeProvider codeProvider = new VBCodeProvider ();
ICodeCompiler compiler = codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDom (options, new CodeCompileUnit ());
// verify compilation was successful
AssertCompileResults (results, true);
Assert.IsTrue (results.CompiledAssembly.Location.Length != 0,
"Location should not be empty string");
Assert.IsNotNull (results.PathToAssembly, "PathToAssembly should not be null");
return results.PathToAssembly;
}
public string CompileAssemblyFromDomBatch (string tempDir)
{
CompilerParameters options = new CompilerParameters ();
options.GenerateExecutable = false;
options.GenerateInMemory = false;
options.TempFiles = new TempFileCollection (tempDir);
VBCodeProvider codeProvider = new VBCodeProvider ();
ICodeCompiler compiler = codeProvider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { new CodeCompileUnit (), new CodeCompileUnit () });
// verify compilation was successful
AssertCompileResults (results, true);
Assert.IsTrue (results.CompiledAssembly.Location.Length != 0,
"Location should not be empty string");
Assert.IsNotNull (results.PathToAssembly, "PathToAssembly should not be null");
return results.PathToAssembly;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace CloudBox.Controller
{
public class ColorPickerCombobox : DropdownContainerControl<Color>
{
static ColorPickerCtrl m_colorPicker;
static DropdownContainer<Color> m_container;
public new Color SelectedItem
{
get { return base.SelectedItem; }
set { base.SelectedItem = value; }
}
public ColorPickerCombobox()
{
SelectedItem = Color.Wheat;
}
protected void CreateDropdown()
{
if (m_container == null)
{
m_container = new DropdownContainer<Color>(this);
m_colorPicker = new ColorPickerCtrl();
m_container.SetControl(m_colorPicker);
}
DropdownContainer = m_container;
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
}
protected override void ShowDropdown()
{
CreateDropdown();
m_colorPicker.SelectedColor = SelectedItem;
// only need to register / unregister because the dropdown is static and shared
DropdownContainer.KeyDown += new KeyEventHandler(OnDropdownKeyDown);
base.ShowDropdown();
}
public override void CloseDropdown(bool acceptValue)
{
DropdownContainer.KeyDown -= new KeyEventHandler(OnDropdownKeyDown);
base.CloseDropdown(acceptValue);
if (acceptValue)
SelectedItem = m_colorPicker.SelectedColor;
}
protected override void DrawItem(Graphics dc, Rectangle itemrect)
{
Brush b = new SolidBrush(SelectedItem);
dc.FillRectangle(b, itemrect);
}
void OnDropdownKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
e.Handled = true;
CloseDropdown(true);
}
}
}
public class DropdownContainerControl<T> : Control
{
T m_selectedItem;
bool m_mouseIn = false;
DropdownContainer<T> m_container = null;
public T SelectedItem
{
get { return m_selectedItem; }
set
{
m_selectedItem = value;
Invalidate();
}
}
public DropdownContainer<T> DropdownContainer
{
get { return m_container; }
set { m_container = value; }
}
public bool DroppedDown
{
get { return m_container.Visible; }
}
public DropdownContainerControl()
{
this.DoubleBuffered = true;
m_container = new DropdownContainer<T>(this);
}
public virtual void CloseDropdown(bool acceptValue)
{
HideDropdown();
}
public Rectangle ItemRectangle
{
get
{
Rectangle r = ClientRectangle;
r.Y += 2;
r.Height -= 4;
r.X += 2;
r.Width = ButtonRectangle.Left - 4;
return r;
}
}
public Rectangle ButtonRectangle
{
get
{
Rectangle r = ClientRectangle;
r.Y += 1;
r.Height -= 2;
r.X = r.Right - 18;
r.Width = 17;
return r;
}
}
protected override void OnPaint(PaintEventArgs e)
{
//base.OnPaint(e);
Rectangle r = ClientRectangle;
ComboBoxRenderer.DrawTextBox(e.Graphics, r, System.Windows.Forms.VisualStyles.ComboBoxState.Normal);
r = ButtonRectangle;
if (m_mouseIn)
ComboBoxRenderer.DrawDropDownButton(e.Graphics, r, System.Windows.Forms.VisualStyles.ComboBoxState.Hot);
else
ComboBoxRenderer.DrawDropDownButton(e.Graphics, r, System.Windows.Forms.VisualStyles.ComboBoxState.Normal);
r = ItemRectangle;
r.Inflate(-1,-1);
DrawItem(e.Graphics, ItemRectangle);
if (Focused)
ControlPaint.DrawFocusRectangle(e.Graphics, ItemRectangle);
RaisePaintEvent(this, e);
}
protected virtual void DrawItem(Graphics dc, Rectangle itemrect)
{
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
Invalidate();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
Focus();
if (DroppedDown)
HideDropdown();
else
ShowDropdown();
}
}
protected virtual void ShowDropdown()
{
Point location = Parent.PointToScreen(Location);
location.Y += Height + 2;
// adjust dropdown location in case it goes off the screen;
Rectangle r = Parent.RectangleToScreen(Bounds);
Rectangle screen = Screen.GetWorkingArea(this);
if (location.X + m_container.Width > screen.Right)
location.X = r.Right - m_container.Width;
if (location.X < 0)
location.X = 0;
if (location.Y + m_container.Height > screen.Bottom)
location.Y = r.Top - m_container.Height;
if (location.Y < 0)
location.Y = 0;
m_container.Location = location;
m_container.ShowDropdown(this);
}
protected virtual void HideDropdown()
{
m_container.Hide();
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
m_mouseIn = true;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
m_mouseIn = false;
Invalidate();
}
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Down && DroppedDown == false)
{
ShowDropdown();
return true;
}
return base.ProcessDialogKey(keyData);
}
}
public class DropdownContainer<T> : Form
{
int m_captionHeight = 18;
int m_buttonAreaHeight = 24;
int m_frameMargin = 4;
Button m_acceptButton;
Button m_cancelButton;
DropdownContainerControl<T> m_owner;
Hook m_hook = new Hook();
public DropdownContainer(DropdownContainerControl<T> owner)
{
m_owner = owner;
// this is for the window to show at correct location first time it is opened
WinUtil.SetWindowPos(Handle, IntPtr.Zero, 0, 0, 0, 0, WinUtil.SWP_NOACTIVATE);
FormBorderStyle = FormBorderStyle.None;
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
SetTopLevel(true);
ShowInTaskbar = false;
Hide();
Rectangle r = WindowRectangle;
r.Inflate(-2,-2);
r.Y--;
m_cancelButton = new Button();
m_cancelButton.Text = "Cancel";
m_cancelButton.Size = new Size(60,m_buttonAreaHeight-2);
m_cancelButton.Location = new Point(r.Right - m_cancelButton.Size.Width, r.Bottom - m_cancelButton.Height);
m_cancelButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
m_cancelButton.Click += new EventHandler(OnCancelClick);
Controls.Add(m_cancelButton);
m_acceptButton = new Button();
m_acceptButton.Text = "Accept";
m_acceptButton.Size = new Size(60,m_buttonAreaHeight-2);
m_acceptButton.Location = new Point(m_cancelButton.Left - m_acceptButton.Size.Width - 1, r.Bottom - m_acceptButton.Height);
m_acceptButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
m_acceptButton.Click += new EventHandler(OnAcceptClick);
Controls.Add(m_acceptButton);
m_hook.OnKeyDown += new Hook.KeyboardDelegate(OnHookKeyDown);
}
public virtual Rectangle WindowRectangle
{
get { return base.ClientRectangle; }
}
public virtual new Rectangle ClientRectangle
{
get
{
Rectangle r = WindowRectangle;
r.Y += m_frameMargin + m_captionHeight;
r.Height -= m_frameMargin*2 + m_captionHeight + m_buttonAreaHeight;
r.X += m_frameMargin;
r.Width -= m_frameMargin*2;
return r;
}
}
public void SetControl(Control ctrl)
{
Controls.Clear();
if (m_acceptButton != null)
Controls.Add(m_acceptButton);
if (m_cancelButton != null)
Controls.Add(m_cancelButton);
Rectangle client = ClientRectangle;
this.Width += ctrl.Width - client.Width;
this.Height += ctrl.Height - client.Height;
ctrl.Location = ClientRectangle.Location;
Controls.Add(ctrl);
ctrl.TabIndex = 0;
m_acceptButton.TabIndex = 1;
m_cancelButton.TabIndex = 2;
}
public virtual void Cancel()
{
m_hook.SetHook(false);
Hide();
if (m_owner != null)
m_owner.CloseDropdown(false);
}
public virtual void Accept()
{
m_hook.SetHook(false);
Hide();
if (m_owner != null)
m_owner.CloseDropdown(true);
}
public virtual void ShowDropdown(DropdownContainerControl<T> owner)
{
if (owner != null)
m_owner = owner;
Show();
m_hook.SetHook(true);
}
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
Cancel();
}
protected virtual Rectangle CancelButtonRect
{
get
{
Rectangle r = WindowRectangle;
r.Y += 2;
r.Height = m_captionHeight;
r.X = r.Width - (m_captionHeight + 2);
r.Width = m_captionHeight;
return r;
}
}
protected virtual Rectangle AcceptButtonRect
{
get
{
Rectangle r = CancelButtonRect;
r.X -= (m_captionHeight + 2);
return r;
}
}
protected override void OnPaint(PaintEventArgs e)
{
//base.OnPaint(e);
Rectangle r = WindowRectangle;
r.Width--;
r.Height--;
Util.DrawFrame(e.Graphics, r, 6, Color.CadetBlue);
e.Graphics.DrawImage(PopupContainerImages.Image(PopupContainerImages.eIndexes.Close), CancelButtonRect);
e.Graphics.DrawImage(PopupContainerImages.Image(PopupContainerImages.eIndexes.Check), AcceptButtonRect);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
Point p = new Point(e.X, e.Y);
if (AcceptButtonRect.Contains(p))
Accept();
if (CancelButtonRect.Contains(p))
Cancel();
}
void OnHookKeyDown(KeyEventArgs e)
{
OnKeyDown(e);
if (e.Handled)
return;
if (e.KeyCode == Keys.Escape)
{
Cancel();
e.Handled = true;
}
if (e.KeyCode == Keys.Return)
{
Accept();
e.Handled = true;
}
}
void OnAcceptClick(object sender, EventArgs e)
{
Accept();
}
void OnCancelClick(object sender, EventArgs e)
{
Cancel();
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Text;
using GitTools.Testing;
using GitVersion;
using GitVersion.BuildAgents;
using GitVersion.Configuration;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation.Cache;
using GitVersionCore.Tests.Helpers;
using LibGit2Sharp;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NUnit.Framework;
using Shouldly;
using Environment = System.Environment;
using RepositoryExtensions = GitVersion.RepositoryExtensions;
namespace GitVersionCore.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class GitVersionExecutorTests : TestBase
{
private IFileSystem fileSystem;
private ILog log;
private IGitVersionCache gitVersionCache;
private IServiceProvider sp;
[Test]
public void CacheKeySameAfterReNormalizing()
{
using var fixture = new EmptyRepositoryFixture();
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var targetBranch = "refs/head/master";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl, TargetBranch = targetBranch },
WorkingDirectory = fixture.RepositoryPath,
Settings = { NoNormalize = false }
};
var environment = new TestEnvironment();
environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, "true");
sp = GetServiceProvider(gitVersionOptions, environment: environment);
var preparer = sp.GetService<IGitPreparer>();
preparer.Prepare();
var cacheKeyFactory = sp.GetService<IGitVersionCacheKeyFactory>();
var cacheKey1 = cacheKeyFactory.Create(null);
preparer.Prepare();
var cacheKey2 = cacheKeyFactory.Create(null);
cacheKey2.Value.ShouldBe(cacheKey1.Value);
}
[Test]
public void GitPreparerShouldNotFailWhenTargetPathNotInitialized()
{
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl },
WorkingDirectory = null
};
Should.NotThrow(() =>
{
sp = GetServiceProvider(gitVersionOptions);
sp.GetService<IGitPreparer>();
});
}
[Test]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void CacheKeyForWorktree()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString());
try
{
// create a branch and a new worktree for it
var repo = new Repository(fixture.RepositoryPath);
repo.Worktrees.Add("worktree", worktreePath, false);
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl, TargetBranch = "master" },
WorkingDirectory = worktreePath
};
sp = GetServiceProvider(gitVersionOptions);
var preparer = sp.GetService<IGitPreparer>();
preparer.Prepare();
var cacheKey = sp.GetService<IGitVersionCacheKeyFactory>().Create(null);
cacheKey.Value.ShouldNotBeEmpty();
}
finally
{
DirectoryHelper.DeleteDirectory(worktreePath);
}
}
[Test]
public void CacheFileExistsOnDisk()
{
const string versionCacheFileContent = @"
Major: 4
Minor: 10
Patch: 3
PreReleaseTag: test.19
PreReleaseTagWithDash: -test.19
PreReleaseLabel: test
PreReleaseLabelWithDash: -test
PreReleaseNumber: 19
WeightedPreReleaseNumber: 19
BuildMetaData:
BuildMetaDataPadded:
FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
MajorMinorPatch: 4.10.3
SemVer: 4.10.3-test.19
LegacySemVer: 4.10.3-test19
LegacySemVerPadded: 4.10.3-test0019
AssemblySemVer: 4.10.3.0
AssemblySemFileVer: 4.10.3.0
FullSemVer: 4.10.3-test.19
InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
BranchName: feature/test
EscapedBranchName: feature-test
Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
ShortSha: dd2a29af
NuGetVersionV2: 4.10.3-test0019
NuGetVersion: 4.10.3-test0019
NuGetPreReleaseTagV2: test0019
NuGetPreReleaseTag: test0019
VersionSourceSha: 4.10.2
CommitsSinceVersionSource: 19
CommitsSinceVersionSourcePadded: 0019
CommitDate: 2015-11-10
UncommittedChanges: 0
";
var stringBuilder = new StringBuilder();
void Action(string s) => stringBuilder.AppendLine(s);
var logAppender = new TestLogAppender(Action);
log = new Log(logAppender);
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, log);
var versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("4.10.3.0");
var logsMessages = stringBuilder.ToString();
logsMessages.ShouldContain("Deserializing version variables from cache file", Case.Insensitive, logsMessages);
}
[Test]
public void CacheFileExistsOnDiskWhenOverrideConfigIsSpecifiedVersionShouldBeDynamicallyCalculatedWithoutSavingInCache()
{
const string versionCacheFileContent = @"
Major: 4
Minor: 10
Patch: 3
PreReleaseTag: test.19
PreReleaseTagWithDash: -test.19
PreReleaseLabel: test
PreReleaseLabelWithDash: -test
PreReleaseNumber: 19
BuildMetaData:
BuildMetaDataPadded:
FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
MajorMinorPatch: 4.10.3
SemVer: 4.10.3-test.19
LegacySemVer: 4.10.3-test19
LegacySemVerPadded: 4.10.3-test0019
AssemblySemVer: 4.10.3.0
AssemblySemFileVer: 4.10.3.0
FullSemVer: 4.10.3-test.19
InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
BranchName: feature/test
EscapedBranchName: feature-test
Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
ShortSha: dd2a29af
NuGetVersionV2: 4.10.3-test0019
NuGetVersion: 4.10.3-test0019
NuGetPreReleaseTagV2: test0019
NuGetPreReleaseTag: test0019
CommitsSinceVersionSource: 19
CommitsSinceVersionSourcePadded: 0019
CommitDate: 2015-11-10
UncommittedChanges: 0
";
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, log);
var versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent);
var cacheDirectory = gitVersionCache.GetCacheDirectory();
var cacheDirectoryTimestamp = fileSystem.GetLastDirectoryWrite(cacheDirectory);
var config = new ConfigurationBuilder().Add(new Config { TagPrefix = "prefix" }).Build();
gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath, ConfigInfo = { OverrideConfig = config } };
gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
var cachedDirectoryTimestampAfter = fileSystem.GetLastDirectoryWrite(cacheDirectory);
cachedDirectoryTimestampAfter.ShouldBe(cacheDirectoryTimestamp, "Cache was updated when override config was set");
}
[Test]
public void CacheFileIsMissing()
{
var stringBuilder = new StringBuilder();
void Action(string s) => stringBuilder.AppendLine(s);
var logAppender = new TestLogAppender(Action);
log = new Log(logAppender);
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
fixture.Repository.MakeACommit();
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, log, fixture.Repository.ToGitRepository());
gitVersionCalculator.CalculateVersionVariables();
var logsMessages = stringBuilder.ToString();
logsMessages.ShouldContain("yml not found", Case.Insensitive, logsMessages);
}
[Test]
public void ConfigChangeInvalidatesCache()
{
const string versionCacheFileContent = @"
Major: 4
Minor: 10
Patch: 3
PreReleaseTag: test.19
PreReleaseTagWithDash: -test.19
PreReleaseLabel: test
PreReleaseLabelWithDash: -test
PreReleaseNumber: 19
WeightedPreReleaseNumber: 19
BuildMetaData:
BuildMetaDataPadded:
FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
MajorMinorPatch: 4.10.3
SemVer: 4.10.3-test.19
LegacySemVer: 4.10.3-test19
LegacySemVerPadded: 4.10.3-test0019
AssemblySemVer: 4.10.3.0
AssemblySemFileVer: 4.10.3.0
FullSemVer: 4.10.3-test.19
InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
BranchName: feature/test
EscapedBranchName: feature-test
Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
ShortSha: dd2a29af
NuGetVersionV2: 4.10.3-test0019
NuGetVersion: 4.10.3-test0019
NuGetPreReleaseTagV2: test0019
NuGetPreReleaseTag: test0019
VersionSourceSha: 4.10.2
CommitsSinceVersionSource: 19
CommitsSinceVersionSourcePadded: 0019
CommitDate: 2015-11-10
UncommittedChanges: 0
";
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
fixture.Repository.MakeACommit();
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
var versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
versionVariables.FileName.ShouldNotBeNullOrEmpty();
fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("4.10.3.0");
var configPath = Path.Combine(fixture.RepositoryPath, DefaultConfigFileLocator.DefaultFileName);
fileSystem.WriteAllText(configPath, "next-version: 5.0");
gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, fs: fileSystem);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("5.0.0.0");
}
[Test]
public void NoCacheBypassesCache()
{
const string versionCacheFileContent = @"
Major: 4
Minor: 10
Patch: 3
PreReleaseTag: test.19
PreReleaseTagWithDash: -test.19
PreReleaseLabel: test
PreReleaseLabelWithDash: -test
PreReleaseNumber: 19
WeightedPreReleaseNumber: 19
BuildMetaData:
BuildMetaDataPadded:
FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
MajorMinorPatch: 4.10.3
SemVer: 4.10.3-test.19
LegacySemVer: 4.10.3-test19
LegacySemVerPadded: 4.10.3-test0019
AssemblySemVer: 4.10.3.0
AssemblySemFileVer: 4.10.3.0
FullSemVer: 4.10.3-test.19
InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
BranchName: feature/test
EscapedBranchName: feature-test
Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
ShortSha: dd2a29af
NuGetVersionV2: 4.10.3-test0019
NuGetVersion: 4.10.3-test0019
NuGetPreReleaseTagV2: test0019
NuGetPreReleaseTag: test0019
VersionSourceSha: 4.10.2
CommitsSinceVersionSource: 19
CommitsSinceVersionSourcePadded: 0019
CommitDate: 2015-11-10
UncommittedChanges: 0
";
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
fixture.Repository.MakeACommit();
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
var versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
versionVariables.FileName.ShouldNotBeNullOrEmpty();
fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("4.10.3.0");
gitVersionOptions.Settings.NoCache = true;
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
}
[Test]
public void WorkingDirectoryWithoutGit()
{
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = Environment.SystemDirectory };
var exception = Assert.Throws<DirectoryNotFoundException>(() =>
{
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
gitVersionCalculator.CalculateVersionVariables();
});
exception.Message.ShouldContain("Cannot find the .git directory");
}
[Test]
public void WorkingDirectoryWithoutCommits()
{
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
var exception = Assert.Throws<GitVersionException>(() =>
{
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
gitVersionCalculator.CalculateVersionVariables();
});
exception.Message.ShouldContain("No commits found on the current branch.");
}
[Test]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void GetProjectRootDirectoryWorkingDirectoryWithWorktree()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString());
try
{
// create a branch and a new worktree for it
var repo = new Repository(fixture.RepositoryPath);
repo.Worktrees.Add("worktree", worktreePath, false);
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl },
WorkingDirectory = worktreePath
};
sp = GetServiceProvider(gitVersionOptions);
var repositoryInfo = sp.GetService<IGitRepositoryInfo>();
repositoryInfo?.ProjectRootDirectory.TrimEnd('/', '\\').ShouldBe(worktreePath);
}
finally
{
DirectoryHelper.DeleteDirectory(worktreePath);
}
}
[Test]
public void GetProjectRootDirectoryNoWorktree()
{
using var fixture = new EmptyRepositoryFixture();
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl },
WorkingDirectory = fixture.RepositoryPath
};
sp = GetServiceProvider(gitVersionOptions);
var repositoryInfo = sp.GetService<IGitRepositoryInfo>();
var expectedPath = fixture.RepositoryPath.TrimEnd('/', '\\');
repositoryInfo?.ProjectRootDirectory.TrimEnd('/', '\\').ShouldBe(expectedPath);
}
[Test]
public void GetDotGitDirectoryNoWorktree()
{
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions
{
WorkingDirectory = fixture.RepositoryPath
};
sp = GetServiceProvider(gitVersionOptions);
var repositoryInfo = sp.GetService<IGitRepositoryInfo>();
var expectedPath = Path.Combine(fixture.RepositoryPath, ".git");
repositoryInfo?.DotGitDirectory.ShouldBe(expectedPath);
}
[Test]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void GetDotGitDirectoryWorktree()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString());
try
{
// create a branch and a new worktree for it
var repo = new Repository(fixture.RepositoryPath);
repo.Worktrees.Add("worktree", worktreePath, false);
var gitVersionOptions = new GitVersionOptions
{
WorkingDirectory = worktreePath
};
sp = GetServiceProvider(gitVersionOptions);
var repositoryInfo = sp.GetService<IGitRepositoryInfo>();
var expectedPath = Path.Combine(fixture.RepositoryPath, ".git");
repositoryInfo?.DotGitDirectory.ShouldBe(expectedPath);
}
finally
{
DirectoryHelper.DeleteDirectory(worktreePath);
}
}
[Test]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void CalculateVersionFromWorktreeHead()
{
// Setup
using var fixture = new EmptyRepositoryFixture();
var repoDir = new DirectoryInfo(fixture.RepositoryPath);
var worktreePath = Path.Combine(repoDir.Parent.FullName, $"{repoDir.Name}-v1");
fixture.Repository.MakeATaggedCommit("v1.0.0");
var branchV1 = fixture.Repository.CreateBranch("support/1.0");
fixture.Repository.MakeATaggedCommit("v2.0.0");
fixture.Repository.Worktrees.Add(branchV1.CanonicalName, "1.0", worktreePath, false);
using var worktreeFixture = new LocalRepositoryFixture(new Repository(worktreePath));
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = worktreeFixture.RepositoryPath };
var sut = GetGitVersionCalculator(gitVersionOptions);
// Execute
var version = sut.CalculateVersionVariables();
// Verify
version.SemVer.ShouldBe("1.0.0");
var commits = worktreeFixture.Repository.Head.Commits;
version.Sha.ShouldBe(commits.First().Sha);
}
private IGitVersionCalculateTool GetGitVersionCalculator(GitVersionOptions gitVersionOptions, ILog logger = null, IGitRepository repository = null, IFileSystem fs = null)
{
sp = GetServiceProvider(gitVersionOptions, logger, repository, fs);
fileSystem = sp.GetService<IFileSystem>();
log = sp.GetService<ILog>();
gitVersionCache = sp.GetService<IGitVersionCache>();
return sp.GetService<IGitVersionCalculateTool>();
}
private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null, IGitRepository repository = null, IFileSystem fileSystem = null, IEnvironment environment = null)
{
return ConfigureServices(services =>
{
if (log != null) services.AddSingleton(log);
if (fileSystem != null) services.AddSingleton(fileSystem);
if (repository != null) services.AddSingleton(repository);
if (environment != null) services.AddSingleton(environment);
var options = Options.Create(gitVersionOptions);
services.AddSingleton(options);
services.AddSingleton(RepositoryExtensions.ToGitRepositoryInfo(options));
});
}
}
}
| |
// -- FILE ------------------------------------------------------------------
// name : WeekTest.cs
// project : Itenso Time Period
// created : Jani Giannoudis - 2011.02.18
// language : C# 4.0
// environment: .NET 2.0
// copyright : (c) 2011-2012 by Itenso GmbH, Switzerland
// --------------------------------------------------------------------------
using System;
using System.Globalization;
using Itenso.TimePeriod;
using Xunit;
namespace Itenso.TimePeriodTests
{
// ------------------------------------------------------------------------
public sealed class WeekTest : TestUnitBase
{
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void DefaultCalendarTest()
{
const int startWeek = 1;
int currentYear = ClockProxy.Clock.Now.Year;
CultureTestData cultures = new CultureTestData();
foreach ( CultureInfo culture in cultures )
{
foreach ( YearWeekType yearWeekType in Enum.GetValues( typeof( YearWeekType ) ) )
{
int weeksOfYear = TimeTool.GetWeeksOfYear( currentYear, culture, yearWeekType );
for ( int weekOfYear = startWeek; weekOfYear < weeksOfYear; weekOfYear++ )
{
Week week = new Week( currentYear, weekOfYear, TimeCalendar.New( culture, YearMonth.January, yearWeekType ) );
Assert.Equal( week.Year, currentYear );
DateTime weekStart = TimeTool.GetStartOfYearWeek( currentYear, weekOfYear, culture, yearWeekType );
DateTime weekEnd = weekStart.AddDays( TimeSpec.DaysPerWeek );
Assert.Equal( week.Start, weekStart.Add( week.Calendar.StartOffset ) );
Assert.Equal( week.End, weekEnd.Add( week.Calendar.EndOffset ) );
}
}
}
} // DefaultCalendarTest
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void EnAuCultureTest()
{
CultureInfo cultureInfo = new CultureInfo( "en-AU" );
// cultureInfo.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
TimeCalendar calendar = new TimeCalendar( new TimeCalendarConfig { Culture = cultureInfo } );
Week week = new Week( new DateTime( 2011, 4, 1, 9, 0, 0 ), calendar );
Assert.Equal( week.Start, new DateTime( 2011, 3, 28 ) );
} // EnAuCultureTest
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void DanishUsCultureTest()
{
CultureInfo danishCulture = new CultureInfo( "da-DK" );
Week danishWeek = new Week( 2011, 36, new TimeCalendar( new TimeCalendarConfig { Culture = danishCulture } ) );
Assert.Equal( danishWeek.Start.Date, new DateTime( 2011, 9, 5 ) );
Assert.Equal( danishWeek.End.Date, new DateTime( 2011, 9, 11 ) );
CultureInfo usCulture = new CultureInfo( "en-US" );
usCulture.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
Week usWeek = new Week( 2011, 36, new TimeCalendar( new TimeCalendarConfig { Culture = usCulture } ) );
Assert.Equal( usWeek.Start.Date, new DateTime( 2011, 9, 4 ) );
Assert.Equal( usWeek.End.Date, new DateTime( 2011, 9, 10 ) );
} // DanishUsCultureTest
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void Iso8601WithMondayAsStartWeekTest()
{
CultureInfo usCulture = new CultureInfo( "en-US" );
usCulture.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
usCulture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Monday;
TimeCalendar isoCalendar = new TimeCalendar(
new TimeCalendarConfig
{
YearWeekType = YearWeekType.Iso8601,
Culture = usCulture
} );
Week weekFrom20131229 = new Week( new DateTime( 2013, 12, 29 ), isoCalendar );
Assert.Equal( weekFrom20131229.Start.Date, new DateTime( 2013, 12, 23 ) );
Assert.Equal( weekFrom20131229.End.Date, new DateTime( 2013, 12, 29 ) );
Assert.Equal(52, weekFrom20131229.WeekOfYear);
Week weekFrom20131230 = new Week( new DateTime( 2013, 12, 30 ), isoCalendar );
Assert.Equal( weekFrom20131230.Start.Date, new DateTime( 2013, 12, 30 ) );
Assert.Equal( weekFrom20131230.End.Date, new DateTime( 2014, 1, 5 ) );
Assert.Equal(1, weekFrom20131230.WeekOfYear);
Week weekFrom20140105 = new Week( new DateTime( 2014, 1, 5 ), isoCalendar );
Assert.Equal( weekFrom20140105.Start.Date, new DateTime( 2013, 12, 30 ) );
Assert.Equal( weekFrom20140105.End.Date, new DateTime( 2014, 1, 5 ) );
Assert.Equal(1, weekFrom20140105.WeekOfYear);
Week weekFrom20140106 = new Week( new DateTime( 2014, 1, 6 ), isoCalendar );
Assert.Equal( weekFrom20140106.Start.Date, new DateTime( 2014, 1, 6 ) );
Assert.Equal( weekFrom20140106.End.Date, new DateTime( 2014, 1, 12 ) );
Assert.Equal(2, weekFrom20140106.WeekOfYear);
} // Iso8601WithMondayAsStartWeekTest
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void Iso8601WithTuesdayAsStartWeekTest()
{
CultureInfo usCulture = new CultureInfo( "en-US" );
usCulture.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
usCulture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Tuesday;
TimeCalendar isoCalendar = new TimeCalendar(
new TimeCalendarConfig
{
YearWeekType = YearWeekType.Iso8601,
Culture = usCulture
} );
Week weekFrom20131230 = new Week( new DateTime( 2013, 12, 30 ), isoCalendar );
Assert.Equal( weekFrom20131230.Start.Date, new DateTime( 2013, 12, 24 ) );
Assert.Equal( weekFrom20131230.End.Date, new DateTime( 2013, 12, 30 ) );
Assert.Equal(52, weekFrom20131230.WeekOfYear);
Week weekFrom20131231 = new Week( new DateTime( 2013, 12, 31 ), isoCalendar );
Assert.Equal( weekFrom20131231.Start.Date, new DateTime( 2013, 12, 31 ) );
Assert.Equal( weekFrom20131231.End.Date, new DateTime( 2014, 1, 6 ) );
Assert.Equal(1, weekFrom20131231.WeekOfYear);
Week weekFrom20140106 = new Week( new DateTime( 2014, 1, 6 ), isoCalendar );
Assert.Equal( weekFrom20140106.Start.Date, new DateTime( 2013, 12, 31 ) );
Assert.Equal( weekFrom20140106.End.Date, new DateTime( 2014, 1, 6 ) );
Assert.Equal(1, weekFrom20140106.WeekOfYear);
Week weekFrom20140107 = new Week( new DateTime( 2014, 1, 7 ), isoCalendar );
Assert.Equal( weekFrom20140107.Start.Date, new DateTime( 2014, 1, 7 ) );
Assert.Equal( weekFrom20140107.End.Date, new DateTime( 2014, 1, 13 ) );
Assert.Equal(2, weekFrom20140107.WeekOfYear);
} // Iso8601WithTuesdayAsStartWeekTest
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void Iso8601WithWednesdayAsStartWeekTest()
{
CultureInfo usCulture = new CultureInfo( "en-US" );
usCulture.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
usCulture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Wednesday;
TimeCalendar isoCalendar = new TimeCalendar(
new TimeCalendarConfig
{
YearWeekType = YearWeekType.Iso8601,
Culture = usCulture
} );
Week weekFrom20131231 = new Week( new DateTime( 2013, 12, 31 ), isoCalendar );
Assert.Equal( weekFrom20131231.Start.Date, new DateTime( 2013, 12, 25 ) );
Assert.Equal( weekFrom20131231.End.Date, new DateTime( 2013, 12, 31 ) );
Assert.Equal(52, weekFrom20131231.WeekOfYear);
Week weekFrom20140101 = new Week( new DateTime( 2014, 1, 1 ), isoCalendar );
Assert.Equal( weekFrom20140101.Start.Date, new DateTime( 2014, 1, 1 ) );
Assert.Equal( weekFrom20140101.End.Date, new DateTime( 2014, 1, 7 ) );
Assert.Equal(1, weekFrom20140101.WeekOfYear);
Week weekFrom20140107 = new Week( new DateTime( 2014, 1, 7 ), isoCalendar );
Assert.Equal( weekFrom20140107.Start.Date, new DateTime( 2014, 1, 1 ) );
Assert.Equal( weekFrom20140107.End.Date, new DateTime( 2014, 1, 7 ) );
Assert.Equal(1, weekFrom20140107.WeekOfYear);
Week weekFrom20140108 = new Week( new DateTime( 2014, 1, 8 ), isoCalendar );
Assert.Equal( weekFrom20140108.Start.Date, new DateTime( 2014, 1, 8 ) );
Assert.Equal( weekFrom20140108.End.Date, new DateTime( 2014, 1, 14 ) );
Assert.Equal(2, weekFrom20140108.WeekOfYear);
} // Iso8601WithWednesdayAsStartWeekTest
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void Iso8601WithThursdayAsStartWeekTest()
{
CultureInfo usCulture = new CultureInfo( "en-US" );
usCulture.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
usCulture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Thursday;
TimeCalendar isoCalendar = new TimeCalendar(
new TimeCalendarConfig
{
YearWeekType = YearWeekType.Iso8601,
Culture = usCulture
} );
Week weekFrom20140101 = new Week( new DateTime( 2014, 1, 1 ), isoCalendar );
Assert.Equal( weekFrom20140101.Start.Date, new DateTime( 2013, 12, 26 ) );
Assert.Equal( weekFrom20140101.End.Date, new DateTime( 2014, 1, 1 ) );
Assert.Equal(52, weekFrom20140101.WeekOfYear);
Week weekFrom20140102 = new Week( new DateTime( 2014, 1, 2 ), isoCalendar );
Assert.Equal( weekFrom20140102.Start.Date, new DateTime( 2014, 1, 2 ) );
Assert.Equal( weekFrom20140102.End.Date, new DateTime( 2014, 1, 8 ) );
Assert.Equal(1, weekFrom20140102.WeekOfYear);
Week weekFrom20140108 = new Week( new DateTime( 2014, 1, 8 ), isoCalendar );
Assert.Equal( weekFrom20140108.Start.Date, new DateTime( 2014, 1, 2 ) );
Assert.Equal( weekFrom20140108.End.Date, new DateTime( 2014, 1, 8 ) );
Assert.Equal(1, weekFrom20140108.WeekOfYear);
Week weekFrom20140109 = new Week( new DateTime( 2014, 1, 9 ), isoCalendar );
Assert.Equal( weekFrom20140109.Start.Date, new DateTime( 2014, 1, 9 ) );
Assert.Equal( weekFrom20140109.End.Date, new DateTime( 2014, 1, 15 ) );
Assert.Equal(2, weekFrom20140109.WeekOfYear);
} // Iso8601WithThursdayAsStartWeekTest
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void Iso8601WithFridayAsStartWeekTest()
{
CultureInfo usCulture = new CultureInfo( "en-US" );
usCulture.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
usCulture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Friday;
TimeCalendar isoCalendar = new TimeCalendar(
new TimeCalendarConfig
{
YearWeekType = YearWeekType.Iso8601,
Culture = usCulture
} );
Week weekFrom20140102 = new Week( new DateTime( 2014, 1, 2 ), isoCalendar );
Assert.Equal( weekFrom20140102.Start.Date, new DateTime( 2013, 12, 27 ) );
Assert.Equal( weekFrom20140102.End.Date, new DateTime( 2014, 1, 2 ) );
Assert.Equal(52, weekFrom20140102.WeekOfYear);
Week weekFrom20140103 = new Week( new DateTime( 2014, 1, 3 ), isoCalendar );
Assert.Equal( weekFrom20140103.Start.Date, new DateTime( 2014, 1, 3 ) );
Assert.Equal( weekFrom20140103.End.Date, new DateTime( 2014, 1, 9 ) );
Assert.Equal(1, weekFrom20140103.WeekOfYear);
Week weekFrom20140109 = new Week( new DateTime( 2014, 1, 9 ), isoCalendar );
Assert.Equal( weekFrom20140109.Start.Date, new DateTime( 2014, 1, 3 ) );
Assert.Equal( weekFrom20140109.End.Date, new DateTime( 2014, 1, 9 ) );
Assert.Equal(1, weekFrom20140109.WeekOfYear);
Week weekFrom20140110 = new Week( new DateTime( 2014, 1, 10 ), isoCalendar );
Assert.Equal( weekFrom20140110.Start.Date, new DateTime( 2014, 1, 10 ) );
Assert.Equal( weekFrom20140110.End.Date, new DateTime( 2014, 1, 16 ) );
Assert.Equal(2, weekFrom20140110.WeekOfYear);
} // Iso8601WithFridayAsStartWeekTest
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void Iso8601WithSaturdayAsStartWeekTest()
{
CultureInfo usCulture = new CultureInfo( "en-US" );
usCulture.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
usCulture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Saturday;
TimeCalendar isoCalendar = new TimeCalendar(
new TimeCalendarConfig
{
YearWeekType = YearWeekType.Iso8601,
Culture = usCulture
} );
Week weekFrom20140103 = new Week( new DateTime( 2014, 1, 3 ), isoCalendar );
Assert.Equal( weekFrom20140103.Start.Date, new DateTime( 2013, 12, 28 ) );
Assert.Equal( weekFrom20140103.End.Date, new DateTime( 2014, 1, 3 ) );
Assert.Equal(53, weekFrom20140103.WeekOfYear);
Week weekFrom20140104 = new Week( new DateTime( 2014, 1, 4 ), isoCalendar );
Assert.Equal( weekFrom20140104.Start.Date, new DateTime( 2014, 1, 4 ) );
Assert.Equal( weekFrom20140104.End.Date, new DateTime( 2014, 1, 10 ) );
Assert.Equal(1, weekFrom20140104.WeekOfYear);
Week weekFrom20140110 = new Week( new DateTime( 2014, 1, 10 ), isoCalendar );
Assert.Equal( weekFrom20140110.Start.Date, new DateTime( 2014, 1, 4 ) );
Assert.Equal( weekFrom20140110.End.Date, new DateTime( 2014, 1, 10 ) );
Assert.Equal(1, weekFrom20140110.WeekOfYear);
Week weekFrom20140111 = new Week( new DateTime( 2014, 1, 11 ), isoCalendar );
Assert.Equal( weekFrom20140111.Start.Date, new DateTime( 2014, 1, 11 ) );
Assert.Equal( weekFrom20140111.End.Date, new DateTime( 2014, 1, 17 ) );
Assert.Equal(2, weekFrom20140111.WeekOfYear);
} // Iso8601WithSaturdayAsStartWeekTest
// ----------------------------------------------------------------------
[Trait("Category", "Week")]
[Fact]
public void Iso8601WithSundayAsStartWeekTest()
{
CultureInfo usCulture = new CultureInfo( "en-US" );
usCulture.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
usCulture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Sunday;
TimeCalendar isoCalendar = new TimeCalendar(
new TimeCalendarConfig
{
YearWeekType = YearWeekType.Iso8601,
Culture = usCulture
} );
Week weekFrom20131228 = new Week( new DateTime( 2013, 12, 28 ), isoCalendar );
Assert.Equal( weekFrom20131228.Start.Date, new DateTime( 2013, 12, 22 ) );
Assert.Equal( weekFrom20131228.End.Date, new DateTime( 2013, 12, 28 ) );
Assert.Equal(52, weekFrom20131228.WeekOfYear);
Week weekFrom20131229 = new Week( new DateTime( 2013, 12, 29 ), isoCalendar );
Assert.Equal( weekFrom20131229.Start.Date, new DateTime( 2013, 12, 29 ) );
Assert.Equal( weekFrom20131229.End.Date, new DateTime( 2014, 1, 4 ) );
Assert.Equal(1, weekFrom20131229.WeekOfYear);
Week weekFrom20140104 = new Week( new DateTime( 2014, 1, 4 ), isoCalendar );
Assert.Equal( weekFrom20140104.Start.Date, new DateTime( 2013, 12, 29 ) );
Assert.Equal( weekFrom20140104.End.Date, new DateTime( 2014, 1, 4 ) );
Assert.Equal(1, weekFrom20140104.WeekOfYear);
Week weekFrom20140105 = new Week( new DateTime( 2014, 1, 5 ), isoCalendar );
Assert.Equal( weekFrom20140105.Start.Date, new DateTime( 2014, 1, 5 ) );
Assert.Equal( weekFrom20140105.End.Date, new DateTime( 2014, 1, 11 ) );
Assert.Equal(2, weekFrom20140105.WeekOfYear);
} // Iso8601WithSundayAsStartWeekTest
} // class WeekTest
} // namespace Itenso.TimePeriodTests
// -- EOF -------------------------------------------------------------------
| |
namespace Shopify.UIToolkit {
using UnityEngine;
using UnityEngine.Events;
using Shopify.Unity;
using Shopify.Unity.SDK;
using System;
using System.Linq;
using System.Collections.Generic;
/// <summary>
// A wrapper struct that encapsulates the information we want from a CartLineItem (Quantity) and the
// ProductVariant it has to help with constructing the UI for the cart.
/// </summary>
public struct CartItem {
public ProductVariant Variant;
public Product Product;
public long Quantity;
public CartItem(ProductVariant variant, Product product, long quantity) {
Product = product;
Variant = variant;
Quantity = quantity;
}
}
[System.Serializable]
public class CartController {
[System.Serializable]
public class QuantityChangeEvent : UnityEvent<int> {}
[System.Serializable]
public class PurchaseFailedEvent : UnityEvent<ShopifyError> {}
[System.Serializable]
public class CartItemsChangeEvent : UnityEvent<List<CartItem>> {}
private Cart Cart;
public UnityEvent OnPurchaseStarted = new UnityEvent();
public QuantityChangeEvent OnQuantityChange = new QuantityChangeEvent();
public CartItemsChangeEvent OnCartItemsChange = new CartItemsChangeEvent();
public UnityEvent OnPurchaseComplete = new UnityEvent();
public UnityEvent OnPurchaseCancelled = new UnityEvent();
public PurchaseFailedEvent OnPurchaseFailed = new PurchaseFailedEvent();
#if UNITY_IOS
private string _appleMerchantID;
#endif
private struct ProductAndVariantPair {
public readonly Product Product;
public readonly ProductVariant Variant;
public ProductAndVariantPair(Product product, ProductVariant variant) {
Product = product;
Variant = variant;
}
}
private Dictionary<string, ProductAndVariantPair> _idsToProductPairs = new Dictionary<string, ProductAndVariantPair>();
#if UNITY_IOS
public CartController(Cart cart, string appleMerchantID) {
SetCart(cart);
_appleMerchantID = appleMerchantID;
}
#endif
public CartController(Cart cart) {
SetCart(cart);
}
public void SetCart(Cart cart) {
Cart = cart;
_idsToProductPairs.Clear();
}
public CartLineItems LineItems {
get {
return Cart.LineItems;
}
}
public List<CartItem> CartItems {
get {
var items = new List<CartItem>();
foreach (var lineItem in LineItems.All()) {
var pair = _idsToProductPairs[lineItem.VariantId];
items.Add(new CartItem(pair.Variant, pair.Product, lineItem.Quantity));
}
return items;
}
}
/// <summary>
/// Adds a variant to the cart
/// </summary>
/// <param name="variant">The variant to add to the cart</param>
/// <param name="product">The product the variant belongs to</param>
public void AddVariant(ProductVariant variant, Product product) {
var existingItem = Cart.LineItems.Get(variant);
var newQuantity = existingItem == null ? 1 : existingItem.Quantity + 1;
Cart.LineItems.AddOrUpdate(variant, newQuantity);
CacheProductVariantPair(variant, product);
OnQuantityChange.Invoke(TotalItemsInCart());
OnCartItemsChange.Invoke(CartItems);
}
/// <summary>
/// Sets the variant to the specified quantity in the cart.
/// </summary>
/// <param name="variant">The variant to modify</param>
/// <param name="product">The product the variant belongs to</param>
/// <param name="quantity">The desired quantity</param>
public void UpdateVariant(ProductVariant variant, Product product, long quantity) {
if (quantity <= 0) {
Cart.LineItems.Delete(variant);
RemoveProductVariantPairByIDFromCache(variant.id());
} else {
Cart.LineItems.AddOrUpdate(variant, quantity);
CacheProductVariantPair(variant, product);
}
OnQuantityChange.Invoke(TotalItemsInCart());
OnCartItemsChange.Invoke(CartItems);
}
/// <summary>
/// Removes a variant from the cart.
/// </summary>
/// <param name="variant">The variant to remove from the cart</param>
/// <param name="product">The product the variant belongs to</param>
public void RemoveVariant(ProductVariant variant, Product product) {
var existingItem = Cart.LineItems.Get(variant);
if (existingItem == null) return;
var newQuantity = existingItem.Quantity - 1;
if (newQuantity == 0) {
Cart.LineItems.Delete(variant);
RemoveProductVariantPairByIDFromCache(variant.id());
} else {
Cart.LineItems.AddOrUpdate(variant, newQuantity);
CacheProductVariantPair(variant, product);
}
OnQuantityChange.Invoke(TotalItemsInCart());
OnCartItemsChange.Invoke(CartItems);
}
/// <summary>
/// Clears all items from the cart
/// </summary>
public void ClearCart() {
Cart.Reset();
_idsToProductPairs.Clear();
OnQuantityChange.Invoke(0);
OnCartItemsChange.Invoke(CartItems);
}
public void CanCheckoutWithNativePay(CanCheckoutWithNativePayCallback callback) {
Cart.CanCheckoutWithNativePay(callback);
}
/// <summary>
/// Start a purchase with the current cart.
/// </summary>
/// <param name="mode">How do you want to make the purchase? Native, Web or Auto</param>
public void StartPurchase(CheckoutMode mode) {
var nativePayKey = NativePayKeyForCurrentPlatform();
OnPurchaseStarted.Invoke();
switch (mode) {
case CheckoutMode.Native:
Cart.CheckoutWithNativePay(nativePayKey, OnPurchaseComplete.Invoke, OnPurchaseCancelled.Invoke, OnPurchaseFailed.Invoke);
break;
case CheckoutMode.Web:
Cart.CheckoutWithWebView(OnPurchaseComplete.Invoke, OnPurchaseCancelled.Invoke, OnPurchaseFailed.Invoke);
break;
case CheckoutMode.Auto:
Cart.CanCheckoutWithNativePay((canCheckoutWithNativePay) => {
if (canCheckoutWithNativePay) {
Cart.CheckoutWithNativePay(nativePayKey, OnPurchaseComplete.Invoke, OnPurchaseCancelled.Invoke, OnPurchaseFailed.Invoke);
} else {
Cart.CheckoutWithWebView(OnPurchaseComplete.Invoke, OnPurchaseCancelled.Invoke, OnPurchaseFailed.Invoke);
}
});
break;
}
}
private string NativePayKeyForCurrentPlatform() {
#if UNITY_IOS
return _appleMerchantID;
#else
return null;
#endif
}
private int TotalItemsInCart() {
return Cart.LineItems.All().Sum((x) => (int) x.Quantity);
}
private void CacheProductVariantPair(ProductVariant variant, Product product) {
if (!_idsToProductPairs.ContainsKey(variant.id())) {
var pair = new ProductAndVariantPair(product, variant);
_idsToProductPairs.Add(variant.id(), pair);
}
}
private void RemoveProductVariantPairByIDFromCache(string variantId) {
_idsToProductPairs.Remove(variantId);
}
}
}
| |
namespace Simple.Data.QueryPolyfills
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Extensions;
internal class WhereClauseHandler
{
private readonly Dictionary<SimpleExpressionType, Func<SimpleExpression, Func<IDictionary<string, object>, bool>>> _expressionFormatters;
private readonly string _mainTableName;
private readonly WhereClause _whereClause;
public WhereClauseHandler(string mainTableName, WhereClause whereClause)
{
_mainTableName = mainTableName;
_whereClause = whereClause;
_expressionFormatters = new Dictionary<SimpleExpressionType, Func<SimpleExpression, Func<IDictionary<string, object>, bool>>>
{
{SimpleExpressionType.And, LogicalExpressionToWhereClause},
{SimpleExpressionType.Or, LogicalExpressionToWhereClause},
{SimpleExpressionType.Equal, EqualExpressionToWhereClause},
{SimpleExpressionType.NotEqual, NotEqualExpressionToWhereClause},
{SimpleExpressionType.Function, FunctionExpressionToWhereClause},
{SimpleExpressionType.GreaterThan, GreaterThanToWhereClause},
{SimpleExpressionType.LessThan, LessThanToWhereClause},
{SimpleExpressionType.GreaterThanOrEqual, GreaterThanOrEqualToWhereClause},
{SimpleExpressionType.LessThanOrEqual, LessThanOrEqualToWhereClause},
{SimpleExpressionType.Empty, expr => _ => true },
};
}
private Func<IDictionary<string, object>, bool> FunctionExpressionToWhereClause(SimpleExpression arg)
{
var function = arg.RightOperand as SimpleFunction;
if (ReferenceEquals(function, null)) throw new InvalidOperationException("Expression type of function but no function supplied.");
if (function.Name.Equals("like", StringComparison.OrdinalIgnoreCase) ||
function.Name.Equals("notlike", StringComparison.OrdinalIgnoreCase))
{
var pattern = function.Args[0].ToString();
if (pattern.Contains("%") || pattern.Contains("_")) // SQL Server LIKE
{
pattern = pattern.Replace("%", ".*").Replace('_', '.');
}
var regex = new Regex("^" + pattern + "$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
if (function.Name.Equals("like", StringComparison.OrdinalIgnoreCase))
{
return d => Resolve(d, arg.LeftOperand).Count > 0 && Resolve(d, arg.LeftOperand).OfType<string>().Any(regex.IsMatch);
}
if (function.Name.Equals("notlike", StringComparison.OrdinalIgnoreCase))
{
return d => Resolve(d, arg.LeftOperand).Count > 0 && Resolve(d, arg.LeftOperand).OfType<string>().All(input => !regex.IsMatch(input));
}
}
throw new NotSupportedException("Expression Function not supported.");
}
private Func<IDictionary<string, object>, bool> GreaterThanToWhereClause(SimpleExpression arg)
{
return d => Resolve(d, arg.LeftOperand).OfType<IComparable>().Any(o => o.CompareTo(arg.RightOperand) > 0);
}
private Func<IDictionary<string, object>, bool> LessThanToWhereClause(SimpleExpression arg)
{
return d => Resolve(d, arg.LeftOperand).OfType<IComparable>().Any(o => o.CompareTo(arg.RightOperand) < 0);
}
private Func<IDictionary<string, object>, bool> GreaterThanOrEqualToWhereClause(SimpleExpression arg)
{
return d => Resolve(d, arg.LeftOperand).OfType<IComparable>().Any(o => o.CompareTo(arg.RightOperand) >= 0);
}
private Func<IDictionary<string, object>, bool> LessThanOrEqualToWhereClause(SimpleExpression arg)
{
return d => Resolve(d, arg.LeftOperand).OfType<IComparable>().Any(o => o.CompareTo(arg.RightOperand) <= 0);
}
private Func<IDictionary<string, object>, bool> NotEqualExpressionToWhereClause(SimpleExpression arg)
{
var equal = EqualExpressionToWhereClause(arg);
return d => !equal(d);
}
private Func<IDictionary<string, object>, bool> EqualExpressionToWhereClause(SimpleExpression arg)
{
if (ReferenceEquals(arg.RightOperand, null))
{
return d => Resolve(d, arg.LeftOperand).Count == 0 || Resolve(d, arg.LeftOperand).Any(o => ReferenceEquals(o, null));
}
if (arg.RightOperand.GetType().IsArray)
{
return
d =>
{
var resolvedLeftOperand = Resolve(d, arg.LeftOperand);
if (resolvedLeftOperand.Any(o => !(o is string) && o is IEnumerable))
{
return resolvedLeftOperand.OfType<IEnumerable>().Any(
o => o.Cast<object>().SequenceEqual(((IEnumerable)arg.RightOperand).Cast<object>()));
}
return resolvedLeftOperand.Any(
o => ((IEnumerable)arg.RightOperand).Cast<object>().Contains(o));
};
}
return d => Resolve(d, arg.LeftOperand).Contains(arg.RightOperand);
}
private Func<IDictionary<string, object>, bool> Format(SimpleExpression expression)
{
Func<SimpleExpression, Func<IDictionary<string, object>, bool>> formatter;
if (_expressionFormatters.TryGetValue(expression.Type, out formatter))
{
return formatter(expression);
}
return _ => true;
}
private Func<IDictionary<string, object>, bool> LogicalExpressionToWhereClause(SimpleExpression arg)
{
var left = Format((SimpleExpression)arg.LeftOperand);
var right = Format((SimpleExpression)arg.RightOperand);
if (arg.Type == SimpleExpressionType.Or)
{
return d => (left(d) || right(d));
}
return d => (left(d) && right(d));
}
private IList<object> Resolve(IDictionary<string, object> dict, object operand, string key = null)
{
var objectReference = operand as ObjectReference;
if (objectReference.IsNull()) return new object[0];
key = key ?? objectReference.GetAliasOrName();
var keys = objectReference.GetAllObjectNames();
if (keys.Length > 2)
{
if (_mainTableName.Contains("."))
{
keys = keys.Skip(1).ToArray();
keys[0] = _mainTableName;
}
}
if (keys.Length > 2)
{
return ResolveSubs(dict, objectReference.GetOwner(), key).ToList();
}
if (keys.Length == 2 && !HomogenizedEqualityComparer.DefaultInstance.Equals(keys[0].Singularize(), _mainTableName.Singularize()))
{
var joinedDict = dict[keys[0]] as IDictionary<string, object>;
if (joinedDict != null && joinedDict.ContainsKey(keys[1]))
{
return new[] { joinedDict[keys[1]] };
}
var joinedDicts = dict[keys[0]] as IEnumerable<IDictionary<string, object>>;
if (joinedDicts != null)
{
return joinedDicts.Select(d => d.ContainsKey(keys[1]) ? d[keys[1]] : null).ToArray();
}
}
if (dict.ContainsKey(key))
return new[] { dict[key] };
return new object[0];
}
private IEnumerable<object> ResolveSubs(IDictionary<string, object> dict, ObjectReference objectReference, string key)
{
if (objectReference.IsNull()) return Enumerable.Empty<object>();
if (dict.ContainsKey(objectReference.GetName()))
{
var master = dict[objectReference.GetName()] as IDictionary<string, object>;
if (master != null)
{
if (master.ContainsKey(key))
{
return new[] { master[key] };
}
}
var detail = dict[objectReference.GetName()] as IEnumerable<IDictionary<string, object>>;
if (detail != null)
{
return detail.SelectMany(d => Resolve(d, objectReference, key));
}
}
return ResolveSubs(dict, objectReference.GetOwner(), key);
}
public IEnumerable<IDictionary<string, object>> Run(IEnumerable<IDictionary<string, object>> source)
{
var predicate = Format(_whereClause.Criteria);
return source.Where(predicate);
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2017 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Collections.Generic;
#if NETSTANDARD1_1
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // NETSTANDARD1_1
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using MsgPack.Serialization.AbstractSerializers;
using MsgPack.Serialization.Reflection;
namespace MsgPack.Serialization.EmittingSerializers
{
partial class SerializerEmitter
{
private static readonly Type[] ConstructorParameterTypesWithoutCapabilities = { typeof( SerializationContext ) };
private static readonly Type[] ConstructorParameterTypesWithCapabilities = { typeof( SerializationContext ), typeof( SerializerCapabilities ) };
private static readonly Type[] CollectionConstructorParameterTypes = { typeof( SerializationContext ), typeof( PolymorphismSchema ), typeof( SerializerCapabilities ) };
#region -- Dependent Serializer Management --
private readonly Dictionary<SerializerFieldKey, SerializerFieldInfo> _serializers = new Dictionary<SerializerFieldKey, SerializerFieldInfo>();
/// <summary>
/// Regisgters <see cref="MessagePackSerializer{T}"/> of target type usage to the current emitting session.
/// </summary>
/// <param name="targetType">The type of the member to be serialized/deserialized.</param>
/// <param name="enumMemberSerializationMethod">The enum serialization method of the member to be serialized/deserialized.</param>
/// <param name="dateTimeConversionMethod">The date time conversion method of the member to be serialized/deserialized.</param>
/// <param name="polymorphismSchema">The schema for polymorphism support.</param>
/// <param name="schemaRegenerationCodeProvider">The delegate to provide constructs to emit schema regeneration codes.</param>
/// <returns><see cref="FieldBuilder"/>.</returns>
public FieldBuilder RegisterSerializer(
Type targetType,
EnumMemberSerializationMethod enumMemberSerializationMethod,
DateTimeMemberConversionMethod dateTimeConversionMethod,
PolymorphismSchema polymorphismSchema,
Func<IEnumerable<ILConstruct>> schemaRegenerationCodeProvider
)
{
var key = new SerializerFieldKey( targetType, enumMemberSerializationMethod, dateTimeConversionMethod, polymorphismSchema );
SerializerFieldInfo result;
if ( !this._serializers.TryGetValue( key, out result ) )
{
result =
new SerializerFieldInfo(
this.DefineInitonlyField(
"_serializer" + this._serializers.Count,
typeof( MessagePackSerializer<> ).MakeGenericType( targetType )
),
il =>
{
foreach ( var construct in schemaRegenerationCodeProvider() )
{
construct.Evaluate( il );
}
}
);
this._serializers.Add( key, result );
}
return result.Field;
}
private struct SerializerFieldInfo
{
public readonly FieldBuilder Field;
public readonly Action<TracingILGenerator> SchemaProvider;
public SerializerFieldInfo( FieldBuilder field, Action<TracingILGenerator> schemaProvider )
{
this.Field = field;
this.SchemaProvider = schemaProvider;
}
}
#endregion -- Dependent Serializer Management --
#region -- FieldInfo Cache Management --
#if !NETSTANDARD1_1 && !NETSTANDARD1_3
private readonly Dictionary<RuntimeFieldHandle, CachedFieldInfo> _cachedFieldInfos = new Dictionary<RuntimeFieldHandle, CachedFieldInfo>();
#else
private readonly Dictionary<FieldInfo, CachedFieldInfo> _cachedFieldInfos = new Dictionary<FieldInfo, CachedFieldInfo>();
#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3
/// <summary>
/// Regisgters <see cref="FieldInfo"/> usage to the current emitting session.
/// </summary>
/// <param name="field">The <see cref="FieldInfo"/> to be registered.</param>
/// <returns>
/// <see cref=" Action{T1,T2}"/> to emit serializer retrieval instructions.
/// The 1st argument should be <see cref="TracingILGenerator"/> to emit instructions.
/// The 2nd argument should be argument index of the serializer holder, normally 0 (this pointer).
/// This value will not be <c>null</c>.
/// </returns>
public Action<TracingILGenerator, int> RegisterFieldCache( FieldInfo field )
{
#if !NETSTANDARD1_1 && !NETSTANDARD1_3
var key = field.FieldHandle;
#else
var key = field;
#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3
CachedFieldInfo result;
if ( !this._cachedFieldInfos.TryGetValue( key, out result ) )
{
Contract.Assert( field.DeclaringType != null, "field.DeclaringType != null" );
result =
new CachedFieldInfo(
field,
this.DefineInitonlyField(
"_field" + field.DeclaringType.Name + "_" + field.Name + this._cachedFieldInfos.Count,
typeof( FieldInfo )
)
);
this._cachedFieldInfos.Add( key, result );
}
return
( il, thisIndex ) =>
{
il.EmitAnyLdarg( thisIndex );
il.EmitLdfld( result.StorageFieldBuilder );
};
}
private struct CachedFieldInfo
{
public readonly FieldBuilder StorageFieldBuilder;
public readonly FieldInfo Target;
public CachedFieldInfo( FieldInfo target, FieldBuilder storageFieldBuilder )
{
this.Target = target;
this.StorageFieldBuilder = storageFieldBuilder;
}
}
#endregion -- FieldInfo Cache Management --
#region -- MethodInfo Cache Management --
#if !NETSTANDARD1_1 && !NETSTANDARD1_3
private readonly Dictionary<RuntimeMethodHandle, CachedMethodBase> _cachedMethodBases = new Dictionary<RuntimeMethodHandle, CachedMethodBase>();
#else
private readonly Dictionary<MethodBase, CachedMethodBase> _cachedMethodBases = new Dictionary<MethodBase, CachedMethodBase>();
#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3
/// <summary>
/// Regisgters <see cref="MethodBase"/> usage to the current emitting session.
/// </summary>
/// <param name="method">The <see cref="MethodBase"/> to be registered.</param>
/// <returns>
/// <see cref=" Action{T1,T2}"/> to emit serializer retrieval instructions.
/// The 1st argument should be <see cref="TracingILGenerator"/> to emit instructions.
/// The 2nd argument should be argument index of the serializer holder, normally 0 (this pointer).
/// This value will not be <c>null</c>.
/// </returns>
public Action<TracingILGenerator, int> RegisterMethodCache( MethodBase method )
{
#if !NETSTANDARD1_1 && !NETSTANDARD1_3
var key = method.MethodHandle;
#else
var key = method;
#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3
CachedMethodBase result;
if ( !this._cachedMethodBases.TryGetValue( key, out result ) )
{
Contract.Assert( method.DeclaringType != null, "method.DeclaringType != null" );
result =
new CachedMethodBase(
method,
this.DefineInitonlyField(
"_function" + method.DeclaringType.Name + "_" + method.Name + this._cachedMethodBases.Count,
typeof( MethodBase )
)
);
this._cachedMethodBases.Add( key, result );
}
return
( il, thisIndex ) =>
{
il.EmitAnyLdarg( thisIndex );
il.EmitLdfld( result.StorageFieldBuilder );
};
}
private struct CachedMethodBase
{
public readonly FieldBuilder StorageFieldBuilder;
public readonly MethodBase Target;
public CachedMethodBase( MethodBase target, FieldBuilder storageFieldBuilder )
{
this.Target = target;
this.StorageFieldBuilder = storageFieldBuilder;
}
}
#endregion -- MethodInfo Cache Management --
#region -- UnpackingContext Management --
private TypeBuilder _unpackingContextType;
public void DefineUnpackingContext( string name, IList<KeyValuePair<string, Type>> fields, out Type type, out ConstructorInfo constructor )
{
this._unpackingContextType =
this._host.DefineType(
this._typeBuilder.FullName + "_" + name,
TypeAttributes.Class | TypeAttributes.UnicodeClass | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit
);
var parameterTypes = fields.Select( kv => kv.Value ).ToArray();
var ctor =
this._unpackingContextType.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
parameterTypes
);
var il = this.GetILGenerator( ctor, parameterTypes );
try
{
// call object.ctor
il.EmitLdargThis();
il.EmitCallConstructor( Metadata._Object.Ctor );
for ( var i = 0; i < fields.Count; i++ )
{
var field = this._unpackingContextType.DefineField( fields[ i ].Key, fields[ i ].Value, FieldAttributes.Public );
il.EmitLdargThis();
il.EmitAnyLdarg( i + 1 );
il.EmitStfld( field );
}
il.EmitRet();
}
finally
{
il.FlushTrace();
#if DEBUG
SerializerDebugging.FlushTraceData();
#endif // DEBUG
}
#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0
type = this._unpackingContextType.CreateType();
#else
type = this._unpackingContextType.CreateTypeInfo().AsType();
#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0
constructor = type.GetConstructors().Single();
}
#endregion -- UnpackingContext Management --
/// <summary>
/// Creates the serializer type built now and returns its new instance.
/// </summary>
/// <param name="context">The <see cref="SerializationContext"/> to holds serializers.</param>
/// <param name="builder">The builder which implements actions initialization emit.</param>
/// <param name="targetInfo">The information of the target.</param>
/// <param name="schema">The <see cref="PolymorphismSchema"/> for this instance.</param>
/// <param name="capabilities">The capabilities of the generating serializer.</param>
/// <returns>
/// Newly built <see cref="MessagePackSerializer"/> instance.
/// This value will not be <c>null</c>.
/// </returns>
public MessagePackSerializer CreateObjectInstance(
AssemblyBuilderEmittingContext context,
AssemblyBuilderSerializerBuilder builder,
SerializationTarget targetInfo,
PolymorphismSchema schema,
SerializerCapabilities? capabilities
)
{
return this.CreateObjectConstructor( context, builder, targetInfo, capabilities )( context.SerializationContext, schema );
}
/// <summary>
/// Creates the serializer type built now and returns its constructor.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="builder">The builder which implements actions initialization emit.</param>
/// <param name="targetInfo">The information of the targe.t</param>
/// <param name="capabilities">The <see cref="SerializerCapabilities"/> for object serializer. <c>null</c> for other types.</param>
/// <returns>
/// Newly built <see cref="MessagePackSerializer{T}"/> type constructor.
/// This value will not be <c>null</c>.
/// </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Reflection objects" )]
public Func<SerializationContext, PolymorphismSchema, MessagePackSerializer> CreateObjectConstructor(
AssemblyBuilderEmittingContext context,
AssemblyBuilderSerializerBuilder builder,
SerializationTarget targetInfo,
SerializerCapabilities? capabilities
)
{
var hasPackActions = targetInfo != null && !typeof( IPackable ).IsAssignableFrom( builder.TargetType );
var hasUnpackActions = targetInfo != null && !typeof( IUnpackable ).IsAssignableFrom( builder.TargetType );
var hasUnpackActionTables = hasUnpackActions && targetInfo.Members.Any( m => m.Member != null ); // Except tuples
#if FEATURE_TAP
var hasPackAsyncActions = targetInfo != null && !typeof( IAsyncPackable ).IsAssignableFrom( builder.TargetType );
var hasUnpackAsyncActions = targetInfo != null && !typeof( IAsyncUnpackable ).IsAssignableFrom( builder.TargetType );
var hasUnpackAsyncActionTables = hasUnpackAsyncActions && targetInfo.Members.Any( m => m.Member != null ); // Except tuples
#endif // FEATURE_TAP
// ReSharper disable RedundantDelegateCreation
Func<bool, Func<ILConstruct>> packActionsInitialization =
isAsync =>
new Func<ILConstruct>( () => builder.EmitPackOperationListInitialization( context, targetInfo, isAsync ) );
Func<bool, Func<ILConstruct>> packActionTableInitialization =
isAsync =>
new Func<ILConstruct>( () => builder.EmitPackOperationTableInitialization( context, targetInfo, isAsync ) );
Func<ILConstruct> nullCheckerTableInitializtion = () => builder.EmitPackNullCheckerTableInitialization( context, targetInfo );
Func<bool, Func<ILConstruct>> unpackActionsInitialization =
isAsync => new Func<ILConstruct>( () => builder.EmitUnpackOperationListInitialization( context, targetInfo, isAsync ) );
Func<bool, Func<ILConstruct>> unpackActionTableInitialization =
isAsync => new Func<ILConstruct>( () => builder.EmitUnpackOperationTableInitialization( context, targetInfo, isAsync ) );
// ReSharper restore RedundantDelegateCreation
var contextfulConstructor =
this.CreateConstructor(
MethodAttributes.Public,
ConstructorParameterTypesWithoutCapabilities,
( type, il ) =>
this.CreateContextfulObjectConstructor(
context,
type,
capabilities,
il,
hasPackActions
? packActionsInitialization( false )
: default( Func<ILConstruct> ),
hasPackActions
? packActionTableInitialization( false )
: default( Func<ILConstruct> ),
#if DEBUG
!SerializerDebugging.UseLegacyNullMapEntryHandling &&
#endif // DEBUG
hasPackActions
#if FEATURE_TAP
|| hasPackAsyncActions
#endif // FEATURE_TAP
? nullCheckerTableInitializtion
: default( Func<ILConstruct> ),
hasUnpackActions
? unpackActionsInitialization( false )
: default( Func<ILConstruct> ),
hasUnpackActionTables
? unpackActionTableInitialization( false )
: default( Func<ILConstruct> ),
#if FEATURE_TAP
hasPackAsyncActions && context.SerializationContext.SerializerOptions.WithAsync
? packActionsInitialization( true )
: default( Func<ILConstruct> ),
hasPackAsyncActions && context.SerializationContext.SerializerOptions.WithAsync
? packActionTableInitialization( true )
: default( Func<ILConstruct> ),
hasUnpackAsyncActions && context.SerializationContext.SerializerOptions.WithAsync
? unpackActionsInitialization( true )
: default( Func<ILConstruct> ),
hasUnpackAsyncActionTables && context.SerializationContext.SerializerOptions.WithAsync
? unpackActionTableInitialization( true )
: default( Func<ILConstruct> ),
#endif // FEATURE_TAP
(
hasUnpackActions
#if FEATURE_TAP
|| hasUnpackAsyncActions
#endif // FEATURE_TAP
) ? () => builder.EmitMemberListInitialization( context, targetInfo )
: default( Func<ILConstruct> ),
context.IsUnpackToUsed
? () => builder.EmitUnpackToInitialization( context )
: default( Func<ILConstruct> )
)
);
this.CreateConstructor(
MethodAttributes.Public,
ReflectionAbstractions.EmptyTypes,
( _, il ) => CreateDefaultObjectConstructor( contextfulConstructor, il )
);
#if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0
var ctor = this._typeBuilder.CreateType().GetConstructor( ConstructorParameterTypesWithoutCapabilities );
#else
var ctor = this._typeBuilder.CreateTypeInfo().GetConstructor( ConstructorParameterTypesWithoutCapabilities );
#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0
#if DEBUG
Contract.Assert( ctor != null, "ctor != null" );
#endif
var actualFunc = ctor.CreateConstructorDelegate<Func<SerializationContext, MessagePackSerializer>>();
return ( c, _ ) => actualFunc( c );
}
private static void CreateDefaultObjectConstructor( ConstructorBuilder contextfulConstructorBuilder, TracingILGenerator il )
{
/*
* .ctor() : this(null)
* {}
*/
// : this(null)
il.EmitAnyLdarg( 0 );
il.EmitLdnull();
il.EmitCallConstructor( contextfulConstructorBuilder );
il.EmitRet();
}
private void CreateContextfulObjectConstructor(
AssemblyBuilderEmittingContext context,
Type baseType,
SerializerCapabilities? capabilities,
TracingILGenerator il,
Func<ILConstruct> packActionListInitializerProvider,
Func<ILConstruct> packActionTableInitializerProvider,
Func<ILConstruct> nullCheckerTableInitializerProvider,
Func<ILConstruct> unpackActionListInitializerProvider,
Func<ILConstruct> unpackActionTableInitializerProvider,
#if FEATURE_TAP
Func<ILConstruct> packAsyncActionListInitializerProvider,
Func<ILConstruct> packAsyncActionTableInitializerProvider,
Func<ILConstruct> unpackAsyncActionListInitializerProvider,
Func<ILConstruct> unpackAsyncActionTableInitializerProvider,
#endif // FEATURE_TAP
Func<ILConstruct> memberNamesInitializerProvider,
Func<ILConstruct> unpackToInitializerProvider
)
{
/*
* .ctor( SerializationContext context )
* : base( ( context ?? SerializationContext.Default ).CompabilityOptions.PackerCompatibilityOptions )
* {
* this._serializer0 = context.GetSerializer<T0>();
* this._serializer1 = context.GetSerializer<T1>();
* this._serializer2 = context.GetSerializer<T2>();
* :
* }
*/
// : base()
il.EmitLdarg_0();
il.EmitLdarg_1();
if ( this._specification.TargetCollectionTraits.CollectionType == CollectionKind.NotCollection )
{
if ( capabilities.HasValue )
{
il.EmitAnyLdc_I4( ( int )capabilities.Value );
il.EmitCallConstructor(
baseType.GetRuntimeConstructor( ConstructorParameterTypesWithCapabilities )
);
}
else
{
il.EmitCallConstructor(
baseType.GetRuntimeConstructor( ConstructorParameterTypesWithoutCapabilities )
);
}
}
else
{
Contract.Assert( capabilities.HasValue );
il.EmitCall( this._methodTable[ MethodName.RestoreSchema ] );
il.EmitAnyLdc_I4( ( int )capabilities.Value );
il.EmitCallConstructor(
baseType.GetRuntimeConstructor( CollectionConstructorParameterTypes )
);
}
// this._serializerN = context.GetSerializer<T>();
foreach ( var entry in this._serializers )
{
var targetType = Type.GetTypeFromHandle( entry.Key.TypeHandle );
MethodInfo getMethod = Metadata._SerializationContext.GetSerializer1_Parameter_Method.MakeGenericMethod( targetType );
il.EmitLdarg_0();
il.EmitLdarg_1();
if ( targetType.GetIsEnum() )
{
il.EmitLdarg_1();
il.EmitTypeOf( targetType );
il.EmitAnyLdc_I4( ( int )entry.Key.EnumSerializationMethod );
il.EmitCall( Metadata._EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethodMethod );
il.EmitBox( typeof( EnumSerializationMethod ) );
}
else if ( DateTimeMessagePackSerializerHelpers.IsDateTime( targetType ) )
{
il.EmitLdarg_1();
il.EmitAnyLdc_I4( ( int )entry.Key.DateTimeConversionMethod );
il.EmitCall( Metadata._DateTimeMessagePackSerializerHelpers.DetermineDateTimeConversionMethodMethod );
il.EmitBox( typeof( DateTimeConversionMethod ) );
}
else
{
if ( entry.Key.PolymorphismSchema == null )
{
il.EmitLdnull();
}
else
{
entry.Value.SchemaProvider( il );
}
}
il.EmitCallvirt( getMethod );
il.EmitStfld( entry.Value.Field );
}
foreach ( var entry in this._cachedFieldInfos )
{
il.EmitLdarg_0();
il.EmitLdtoken( entry.Value.Target );
il.EmitLdtoken( entry.Value.Target.DeclaringType );
il.EmitCall( Metadata._FieldInfo.GetFieldFromHandle );
il.EmitStfld( entry.Value.StorageFieldBuilder );
}
foreach ( var entry in this._cachedMethodBases )
{
il.EmitLdarg_0();
il.EmitLdtoken( entry.Value.Target );
il.EmitLdtoken( entry.Value.Target.DeclaringType );
il.EmitCall( Metadata._MethodBase.GetMethodFromHandle );
il.EmitStfld( entry.Value.StorageFieldBuilder );
}
if ( packActionListInitializerProvider != null )
{
packActionListInitializerProvider().Evaluate( il );
}
#if FEATURE_TAP
if ( packAsyncActionListInitializerProvider != null )
{
packAsyncActionListInitializerProvider().Evaluate( il );
}
#endif // FEATURE_TAP
if ( nullCheckerTableInitializerProvider != null )
{
nullCheckerTableInitializerProvider().Evaluate( il );
}
if ( packActionTableInitializerProvider != null )
{
packActionTableInitializerProvider().Evaluate( il );
}
#if FEATURE_TAP
if ( packAsyncActionTableInitializerProvider != null )
{
packAsyncActionTableInitializerProvider().Evaluate( il );
}
#endif // FEATURE_TAP
if ( unpackActionListInitializerProvider != null )
{
unpackActionListInitializerProvider().Evaluate( il );
}
#if FEATURE_TAP
if ( unpackAsyncActionListInitializerProvider != null )
{
unpackAsyncActionListInitializerProvider().Evaluate( il );
}
#endif // FEATURE_TAP
if ( unpackActionTableInitializerProvider != null )
{
unpackActionTableInitializerProvider().Evaluate( il );
}
#if FEATURE_TAP
if ( unpackAsyncActionTableInitializerProvider != null )
{
unpackAsyncActionTableInitializerProvider().Evaluate( il );
}
#endif // FEATURE_TAP
if ( memberNamesInitializerProvider != null )
{
memberNamesInitializerProvider().Evaluate( il );
}
if ( unpackToInitializerProvider != null )
{
unpackToInitializerProvider().Evaluate( il );
}
foreach ( var cachedDelegateInfo in context.GetCachedDelegateInfos() )
{
// this for stfld
il.EmitLdargThis();
var delegateType = cachedDelegateInfo.BackingField.FieldType.ResolveRuntimeType();
// Declare backing field now.
var field = context.GetDeclaredField( cachedDelegateInfo.BackingField.FieldName ).ResolveRuntimeField();
if ( cachedDelegateInfo.IsThisInstance )
{
il.EmitLdargThis();
}
else
{
il.EmitLdnull();
}
// OK this should not be ldvirtftn because target is private or static.
il.EmitLdftn( cachedDelegateInfo.TargetMethod.ResolveRuntimeMethod() );
// call extern .ctor(Object, void*)
il.EmitNewobj( delegateType.GetConstructors().Single() );
il.EmitStfld( field );
}
il.EmitRet();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Primitive.
/// </summary>
public static partial class PrimitiveExtensions
{
/// <summary>
/// Get complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IntWrapper GetInt(this IPrimitive operations)
{
return operations.GetIntAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IntWrapper> GetIntAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetIntWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put -1 and 2
/// </param>
public static void PutInt(this IPrimitive operations, IntWrapper complexBody)
{
operations.PutIntAsync(complexBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put -1 and 2
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutIntAsync(this IPrimitive operations, IntWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutIntWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static LongWrapper GetLong(this IPrimitive operations)
{
return operations.GetLongAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LongWrapper> GetLongAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLongWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 1099511627775 and -999511627788
/// </param>
public static void PutLong(this IPrimitive operations, LongWrapper complexBody)
{
operations.PutLongAsync(complexBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 1099511627775 and -999511627788
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLongAsync(this IPrimitive operations, LongWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutLongWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static FloatWrapper GetFloat(this IPrimitive operations)
{
return operations.GetFloatAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FloatWrapper> GetFloatAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 1.05 and -0.003
/// </param>
public static void PutFloat(this IPrimitive operations, FloatWrapper complexBody)
{
operations.PutFloatAsync(complexBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 1.05 and -0.003
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutFloatAsync(this IPrimitive operations, FloatWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutFloatWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DoubleWrapper GetDouble(this IPrimitive operations)
{
return operations.GetDoubleAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DoubleWrapper> GetDoubleAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 3e-100 and
/// -0.000000000000000000000000000000000000000000000000000000005
/// </param>
public static void PutDouble(this IPrimitive operations, DoubleWrapper complexBody)
{
operations.PutDoubleAsync(complexBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 3e-100 and
/// -0.000000000000000000000000000000000000000000000000000000005
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDoubleAsync(this IPrimitive operations, DoubleWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutDoubleWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static BooleanWrapper GetBool(this IPrimitive operations)
{
return operations.GetBoolAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BooleanWrapper> GetBoolAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBoolWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put true and false
/// </param>
public static void PutBool(this IPrimitive operations, BooleanWrapper complexBody)
{
operations.PutBoolAsync(complexBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put true and false
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutBoolAsync(this IPrimitive operations, BooleanWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutBoolWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static StringWrapper GetString(this IPrimitive operations)
{
return operations.GetStringAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StringWrapper> GetStringAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetStringWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 'goodrequest', '', and null
/// </param>
public static void PutString(this IPrimitive operations, StringWrapper complexBody)
{
operations.PutStringAsync(complexBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 'goodrequest', '', and null
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutStringAsync(this IPrimitive operations, StringWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutStringWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateWrapper GetDate(this IPrimitive operations)
{
return operations.GetDateAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateWrapper> GetDateAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01' and '2016-02-29'
/// </param>
public static void PutDate(this IPrimitive operations, DateWrapper complexBody)
{
operations.PutDateAsync(complexBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01' and '2016-02-29'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDateAsync(this IPrimitive operations, DateWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutDateWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DatetimeWrapper GetDateTime(this IPrimitive operations)
{
return operations.GetDateTimeAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DatetimeWrapper> GetDateTimeAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'
/// </param>
public static void PutDateTime(this IPrimitive operations, DatetimeWrapper complexBody)
{
operations.PutDateTimeAsync(complexBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDateTimeAsync(this IPrimitive operations, DatetimeWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutDateTimeWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Datetimerfc1123Wrapper GetDateTimeRfc1123(this IPrimitive operations)
{
return operations.GetDateTimeRfc1123Async().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Datetimerfc1123Wrapper> GetDateTimeRfc1123Async(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDateTimeRfc1123WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00
/// GMT'
/// </param>
public static void PutDateTimeRfc1123(this IPrimitive operations, Datetimerfc1123Wrapper complexBody)
{
operations.PutDateTimeRfc1123Async(complexBody).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='complexBody'>
/// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00
/// GMT'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDateTimeRfc1123Async(this IPrimitive operations, Datetimerfc1123Wrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutDateTimeRfc1123WithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with duration properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DurationWrapper GetDuration(this IPrimitive operations)
{
return operations.GetDurationAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with duration properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DurationWrapper> GetDurationAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDurationWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with duration properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='field'>
/// </param>
public static void PutDuration(this IPrimitive operations, System.TimeSpan? field = default(System.TimeSpan?))
{
operations.PutDurationAsync(field).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with duration properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='field'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDurationAsync(this IPrimitive operations, System.TimeSpan? field = default(System.TimeSpan?), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutDurationWithHttpMessagesAsync(field, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static ByteWrapper GetByte(this IPrimitive operations)
{
return operations.GetByteAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ByteWrapper> GetByteAsync(this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByteWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='field'>
/// </param>
public static void PutByte(this IPrimitive operations, byte[] field = default(byte[]))
{
operations.PutByteAsync(field).GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='field'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutByteAsync(this IPrimitive operations, byte[] field = default(byte[]), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PutByteWithHttpMessagesAsync(field, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Serialization;
using CALI.Database.Contracts;
using CALI.Database.Contracts.Data;
//////////////////////////////////////////////////////////////
//Do not modify this file. Use a partial class to extend. //
//Override methods in the logic front class. //
//////////////////////////////////////////////////////////////
namespace CALI.Database.Logic.Data
{
[Serializable]
public abstract partial class LogLogicBase : LogicBase<LogLogicBase>
{
//Put your code in a separate file. This is auto generated.
[XmlArray] public List<LogContract> Results;
public LogLogicBase()
{
Results = new List<LogContract>();
}
/// <summary>
/// Run Log_Insert.
/// </summary>
/// <param name="fldRunOnMachineName">Value for RunOnMachineName</param>
/// <param name="fldLogContents">Value for LogContents</param>
/// <param name="fldRunTime">Value for RunTime</param>
/// <returns>The new ID</returns>
public virtual int? Insert(string fldRunOnMachineName
, string fldLogContents
, DateTime fldRunTime
)
{
int? result = null;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@RunOnMachineName", fldRunOnMachineName)
,
new SqlParameter("@LogContents", fldLogContents)
,
new SqlParameter("@RunTime", fldRunTime)
});
result = (int?)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Run Log_Insert.
/// </summary>
/// <param name="fldRunOnMachineName">Value for RunOnMachineName</param>
/// <param name="fldLogContents">Value for LogContents</param>
/// <param name="fldRunTime">Value for RunTime</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The new ID</returns>
public virtual int? Insert(string fldRunOnMachineName
, string fldLogContents
, DateTime fldRunTime
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Log_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@RunOnMachineName", fldRunOnMachineName)
,
new SqlParameter("@LogContents", fldLogContents)
,
new SqlParameter("@RunTime", fldRunTime)
});
return (int?)cmd.ExecuteScalar();
}
}
/// <summary>
/// Insert by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(LogContract row)
{
int? result = null;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@RunOnMachineName", row.RunOnMachineName)
,
new SqlParameter("@LogContents", row.LogContents)
,
new SqlParameter("@RunTime", row.RunTime)
});
result = (int?)cmd.ExecuteScalar();
row.LogId = result;
}
});
return result != null ? 1 : 0;
}
/// <summary>
/// Insert by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(LogContract row, SqlConnection connection, SqlTransaction transaction)
{
int? result = null;
using (
var cmd = new SqlCommand("[Data].[Log_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@RunOnMachineName", row.RunOnMachineName)
,
new SqlParameter("@LogContents", row.LogContents)
,
new SqlParameter("@RunTime", row.RunTime)
});
result = (int?)cmd.ExecuteScalar();
row.LogId = result;
}
return result != null ? 1 : 0;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<LogContract> rows)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
rowCount = InsertAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<LogContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Insert(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run Log_Update.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldLogId">Value for LogId</param>
/// <param name="fldRunOnMachineName">Value for RunOnMachineName</param>
/// <param name="fldLogContents">Value for LogContents</param>
/// <param name="fldRunTime">Value for RunTime</param>
public virtual int Update(int fldLogId
, string fldRunOnMachineName
, string fldLogContents
, DateTime fldRunTime
)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", fldLogId)
,
new SqlParameter("@RunOnMachineName", fldRunOnMachineName)
,
new SqlParameter("@LogContents", fldLogContents)
,
new SqlParameter("@RunTime", fldRunTime)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run Log_Update.
/// </summary>
/// <param name="fldLogId">Value for LogId</param>
/// <param name="fldRunOnMachineName">Value for RunOnMachineName</param>
/// <param name="fldLogContents">Value for LogContents</param>
/// <param name="fldRunTime">Value for RunTime</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(int fldLogId
, string fldRunOnMachineName
, string fldLogContents
, DateTime fldRunTime
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Log_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", fldLogId)
,
new SqlParameter("@RunOnMachineName", fldRunOnMachineName)
,
new SqlParameter("@LogContents", fldLogContents)
,
new SqlParameter("@RunTime", fldRunTime)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(LogContract row)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", row.LogId)
,
new SqlParameter("@RunOnMachineName", row.RunOnMachineName)
,
new SqlParameter("@LogContents", row.LogContents)
,
new SqlParameter("@RunTime", row.RunTime)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Update by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(LogContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Log_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", row.LogId)
,
new SqlParameter("@RunOnMachineName", row.RunOnMachineName)
,
new SqlParameter("@LogContents", row.LogContents)
,
new SqlParameter("@RunTime", row.RunTime)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<LogContract> rows)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
rowCount = UpdateAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<LogContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Update(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run Log_Delete.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldLogId">Value for LogId</param>
public virtual int Delete(int fldLogId
)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", fldLogId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run Log_Delete.
/// </summary>
/// <param name="fldLogId">Value for LogId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(int fldLogId
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Log_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", fldLogId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(LogContract row)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", row.LogId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Delete by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(LogContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[Log_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", row.LogId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<LogContract> rows)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
rowCount = DeleteAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<LogContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Delete(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldLogId">Value for LogId</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldLogId
)
{
bool result = false;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_Exists]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", fldLogId)
});
result = (bool)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldLogId">Value for LogId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldLogId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Log_Exists]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", fldLogId)
});
return (bool)cmd.ExecuteScalar();
}
}
/// <summary>
/// Run Log_Search, and return results as a list of LogRow.
/// </summary>
/// <param name="fldRunOnMachineName">Value for RunOnMachineName</param>
/// <param name="fldLogContents">Value for LogContents</param>
/// <returns>A collection of LogRow.</returns>
public virtual bool Search(string fldRunOnMachineName
, string fldLogContents
)
{
var result = false;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_Search]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@RunOnMachineName", fldRunOnMachineName)
,
new SqlParameter("@LogContents", fldLogContents)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Log_Search, and return results as a list of LogRow.
/// </summary>
/// <param name="fldRunOnMachineName">Value for RunOnMachineName</param>
/// <param name="fldLogContents">Value for LogContents</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of LogRow.</returns>
public virtual bool Search(string fldRunOnMachineName
, string fldLogContents
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Log_Search]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@RunOnMachineName", fldRunOnMachineName)
,
new SqlParameter("@LogContents", fldLogContents)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Log_SelectAll, and return results as a list of LogRow.
/// </summary>
/// <returns>A collection of LogRow.</returns>
public virtual bool SelectAll()
{
var result = false;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_SelectAll]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Log_SelectAll, and return results as a list of LogRow.
/// </summary>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of LogRow.</returns>
public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Log_SelectAll]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run Log_SelectBy_LogId, and return results as a list of LogRow.
/// </summary>
/// <param name="fldLogId">Value for LogId</param>
/// <returns>A collection of LogRow.</returns>
public virtual bool SelectBy_LogId(int fldLogId
)
{
var result = false;
CALIDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[Log_SelectBy_LogId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", fldLogId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run Log_SelectBy_LogId, and return results as a list of LogRow.
/// </summary>
/// <param name="fldLogId">Value for LogId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of LogRow.</returns>
public virtual bool SelectBy_LogId(int fldLogId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[Log_SelectBy_LogId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@LogId", fldLogId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Read all items into this collection
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadAll(SqlDataReader reader)
{
var canRead = ReadOne(reader);
var result = canRead;
while (canRead) canRead = ReadOne(reader);
return result;
}
/// <summary>
/// Read one item into Results
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadOne(SqlDataReader reader)
{
if (reader.Read())
{
Results.Add(
new LogContract
{
LogId = reader.GetInt32(0),
RunOnMachineName = reader.GetString(1),
LogContents = reader.GetString(2),
RunTime = reader.GetDateTime(3),
});
return true;
}
return false;
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(LogContract row)
{
if(row == null) return 0;
if(row.LogId != null) return Update(row);
return Insert(row);
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(LogContract row, SqlConnection connection, SqlTransaction transaction)
{
if(row == null) return 0;
if(row.LogId != null) return Update(row, connection, transaction);
return Insert(row, connection, transaction);
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<LogContract> rows)
{
var rowCount = 0;
CALIDb.ConnectThen(x =>
{
foreach(var row in rows) rowCount += Save(row, x, null);
});
return rowCount;
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<LogContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Save(row, connection, transaction);
return rowCount;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Host;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace System.Management.Automation.Internal.Host
{
/// <summary>
/// Wraps PSHost instances to provide a shim layer
/// between InternalCommand and the host-supplied PSHost instance.
///
/// This class exists for the purpose of ensuring that an externally-supplied PSHost meets the minimum proper required
/// implementation, and also to provide a leverage point at which the monad engine can hook the interaction between the engine,
/// cmdlets, and that external host.
///
/// That leverage may be necessary to manage concurrent access between multiple pipelines sharing the same instance of
/// PSHost.
/// </summary>
internal class InternalHost : PSHost, IHostSupportsInteractiveSession
{
/// <summary>
/// There should only be one instance of InternalHost per runspace (i.e. per engine), and all engine use of the host
/// should be through that single instance. If we ever accidentally create more than one instance of InternalHost per
/// runspace, then some of the internal state checks that InternalHost makes, like checking the nestedPromptCounter, can
/// be messed up.
///
/// To ensure that this constraint is met, I wanted to make this class a singleton. However, Hitesh rightly pointed out
/// that a singleton would be appdomain-global, which would prevent having multiple runspaces per appdomain. So we will
/// just have to be careful not to create extra instances of InternalHost per runspace.
/// </summary>
internal InternalHost(PSHost externalHost, ExecutionContext executionContext)
{
Dbg.Assert(externalHost != null, "must supply an PSHost");
Dbg.Assert(externalHost is not InternalHost, "try to create an InternalHost from another InternalHost");
Dbg.Assert(executionContext != null, "must supply an ExecutionContext");
_externalHostRef = new ObjectRef<PSHost>(externalHost);
Context = executionContext;
PSHostUserInterface ui = externalHost.UI;
_internalUIRef = new ObjectRef<InternalHostUserInterface>(new InternalHostUserInterface(ui, this));
_zeroGuid = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
_idResult = _zeroGuid;
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="NotImplementedException">
/// when the external host's Name is null or empty.
/// </exception>
public override string Name
{
get
{
if (string.IsNullOrEmpty(_nameResult))
{
_nameResult = _externalHostRef.Value.Name;
#pragma warning disable 56503
if (string.IsNullOrEmpty(_nameResult))
{
throw PSTraceSource.NewNotImplementedException();
}
#pragma warning restore 56503
}
return _nameResult;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="NotImplementedException">
/// when the external host's Version is null.
/// </exception>
public override System.Version Version
{
get
{
if (_versionResult == null)
{
_versionResult = _externalHostRef.Value.Version;
#pragma warning disable 56503
if (_versionResult == null)
{
throw PSTraceSource.NewNotImplementedException();
}
#pragma warning restore 56503
}
return _versionResult;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception cref="NotImplementedException">
/// when the external host's InstanceId is a zero Guid.
/// </exception>
public override System.Guid InstanceId
{
get
{
if (_idResult == _zeroGuid)
{
_idResult = _externalHostRef.Value.InstanceId;
#pragma warning disable 56503
if (_idResult == _zeroGuid)
{
throw PSTraceSource.NewNotImplementedException();
}
#pragma warning restore 56503
}
return _idResult;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value>
/// </value>
public override System.Management.Automation.Host.PSHostUserInterface UI
{
get
{
return _internalUIRef.Value;
}
}
/// <summary>
/// Interface to be used for interaction with internal
/// host UI. InternalHostUserInterface wraps the host UI
/// supplied during construction. Use this wrapper to access
/// functionality specific to InternalHost.
/// </summary>
internal InternalHostUserInterface InternalUI
{
get
{
return _internalUIRef.Value;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value>
/// </value>
/// <exception cref="NotImplementedException">
/// when the external host's CurrentCulture is null.
/// </exception>
public override System.Globalization.CultureInfo CurrentCulture
{
get
{
CultureInfo ci = _externalHostRef.Value.CurrentCulture ?? CultureInfo.InvariantCulture;
return ci;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value>
/// </value>
/// <exception cref="NotImplementedException">
/// If the external host's CurrentUICulture is null.
/// </exception>
public override CultureInfo CurrentUICulture
{
get
{
CultureInfo ci = _externalHostRef.Value.CurrentUICulture ?? CultureInfo.InstalledUICulture;
return ci;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <param name="exitCode"></param>
public override void SetShouldExit(int exitCode)
{
_externalHostRef.Value.SetShouldExit(exitCode);
}
/// <summary>
/// See base class
/// <seealso cref="ExitNestedPrompt"/>
/// </summary>
public override void EnterNestedPrompt()
{
EnterNestedPrompt(null);
}
private struct PromptContextData
{
public object SavedCurrentlyExecutingCommandVarValue;
public object SavedPSBoundParametersVarValue;
public ExecutionContext.SavedContextData SavedContextData;
public RunspaceAvailability RunspaceAvailability;
public PSLanguageMode LanguageMode;
}
/// <summary>
/// Internal proxy for EnterNestedPrompt.
/// </summary>
/// <param name="callingCommand"></param>
internal void EnterNestedPrompt(InternalCommand callingCommand)
{
// Ensure we are in control of the pipeline
LocalRunspace localRunspace = null;
// This needs to be in a try / catch, since the LocalRunspace cast
// tries to verify that the host supports interactive sessions.
// Tests hosts do not.
try { localRunspace = this.Runspace as LocalRunspace; }
catch (PSNotImplementedException) { }
if (localRunspace != null)
{
Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline();
if ((currentlyRunningPipeline != null) &&
(currentlyRunningPipeline == localRunspace.PulsePipeline))
throw new InvalidOperationException();
}
// NTRAID#Windows OS Bugs-986407-2004/07/29 When kumarp has done the configuration work in the engine, it
// should include setting a bit that indicates that the initialization is complete, and code should be
// added here to throw an exception if this function is called before that bit is set.
if (NestedPromptCount < 0)
{
Dbg.Assert(false, "nested prompt counter should never be negative.");
throw PSTraceSource.NewInvalidOperationException(
InternalHostStrings.EnterExitNestedPromptOutOfSync);
}
// Increment our nesting counter. When we set the value of the variable, we will replace any existing variable
// of the same name. This is good, as any existing value is either 1) ours, and we have claim to replace it, or
// 2) is a squatter, and we have claim to clobber it.
++NestedPromptCount;
Context.SetVariable(SpecialVariables.NestedPromptCounterVarPath, NestedPromptCount);
// On entering a subshell, save and reset values of certain bits of session state
PromptContextData contextData = new PromptContextData();
contextData.SavedContextData = Context.SaveContextData();
contextData.SavedCurrentlyExecutingCommandVarValue = Context.GetVariableValue(SpecialVariables.CurrentlyExecutingCommandVarPath);
contextData.SavedPSBoundParametersVarValue = Context.GetVariableValue(SpecialVariables.PSBoundParametersVarPath);
contextData.RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability;
contextData.LanguageMode = Context.LanguageMode;
PSPropertyInfo commandInfoProperty = null;
PSPropertyInfo stackTraceProperty = null;
object oldCommandInfo = null;
object oldStackTrace = null;
if (callingCommand != null)
{
Dbg.Assert(callingCommand.Context == Context, "I expect that the contexts should match");
// Populate $CurrentlyExecutingCommand to facilitate debugging. One of the gotchas is that we are going to want
// to expose more and more debug info. We could just populate more and more local variables but that is probably
// a lousy approach as it pollutes the namespace. A better way to do it is to add NOTES to the variable value
// object.
PSObject newValue = PSObject.AsPSObject(callingCommand);
commandInfoProperty = newValue.Properties["CommandInfo"];
if (commandInfoProperty == null)
{
newValue.Properties.Add(new PSNoteProperty("CommandInfo", callingCommand.CommandInfo));
}
else
{
oldCommandInfo = commandInfoProperty.Value;
commandInfoProperty.Value = callingCommand.CommandInfo;
}
stackTraceProperty = newValue.Properties["StackTrace"];
if (stackTraceProperty == null)
{
newValue.Properties.Add(new PSNoteProperty("StackTrace", new System.Diagnostics.StackTrace()));
}
else
{
oldStackTrace = stackTraceProperty.Value;
stackTraceProperty.Value = new System.Diagnostics.StackTrace();
}
Context.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, newValue);
}
_contextStack.Push(contextData);
Dbg.Assert(_contextStack.Count == NestedPromptCount, "number of saved contexts should equal nesting count");
Context.PSDebugTraceStep = false;
Context.PSDebugTraceLevel = 0;
Context.ResetShellFunctionErrorOutputPipe();
// Lock down the language in the nested prompt
if (Context.HasRunspaceEverUsedConstrainedLanguageMode)
{
Context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
}
this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true);
try
{
_externalHostRef.Value.EnterNestedPrompt();
}
catch
{
// So where things really go south is this path; which is possible for hosts (like our ConsoleHost)
// that don't return from EnterNestedPrompt immediately.
// EnterNestedPrompt() starts
// ExitNestedPrompt() called
// EnterNestedPrompt throws
ExitNestedPromptHelper();
throw;
}
finally
{
if (commandInfoProperty != null)
{
commandInfoProperty.Value = oldCommandInfo;
}
if (stackTraceProperty != null)
{
stackTraceProperty.Value = oldStackTrace;
}
}
Dbg.Assert(NestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0");
}
private void ExitNestedPromptHelper()
{
--NestedPromptCount;
Context.SetVariable(SpecialVariables.NestedPromptCounterVarPath, NestedPromptCount);
// restore the saved context
Dbg.Assert(_contextStack.Count > 0, "ExitNestedPrompt: called without any saved context");
if (_contextStack.Count > 0)
{
PromptContextData pcd = _contextStack.Pop();
pcd.SavedContextData.RestoreContextData(Context);
Context.LanguageMode = pcd.LanguageMode;
Context.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, pcd.SavedCurrentlyExecutingCommandVarValue);
Context.SetVariable(SpecialVariables.PSBoundParametersVarPath, pcd.SavedPSBoundParametersVarValue);
this.Context.CurrentRunspace.UpdateRunspaceAvailability(pcd.RunspaceAvailability, true);
}
Dbg.Assert(_contextStack.Count == NestedPromptCount, "number of saved contexts should equal nesting count");
}
/// <summary>
/// See base class
/// <seealso cref="EnterNestedPrompt()"/>
/// </summary>
public override void ExitNestedPrompt()
{
Dbg.Assert(NestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0");
if (NestedPromptCount == 0)
return;
try
{
_externalHostRef.Value.ExitNestedPrompt();
}
finally
{
ExitNestedPromptHelper();
}
ExitNestedPromptException enpe = new ExitNestedPromptException();
throw enpe;
}
/// <summary>
/// See base class.
/// </summary>
public override PSObject PrivateData
{
get
{
PSObject result = _externalHostRef.Value.PrivateData;
return result;
}
}
/// <summary>
/// See base class
/// <seealso cref="NotifyEndApplication"/>
/// </summary>
public override void NotifyBeginApplication()
{
_externalHostRef.Value.NotifyBeginApplication();
}
/// <summary>
/// Called by the engine to notify the host that the execution of a legacy command has completed.
/// <seealso cref="NotifyBeginApplication"/>
/// </summary>
public override void NotifyEndApplication()
{
_externalHostRef.Value.NotifyEndApplication();
}
/// <summary>
/// This property enables and disables the host debugger if debugging is supported.
/// </summary>
public override bool DebuggerEnabled { get; set; } = true;
/// <summary>
/// Gets the external host as an IHostSupportsInteractiveSession if it implements this interface;
/// throws an exception otherwise.
/// </summary>
private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession()
{
if (!(_externalHostRef.Value is IHostSupportsInteractiveSession host))
{
throw new PSNotImplementedException();
}
return host;
}
/// <summary>
/// Called by the engine to notify the host that a runspace push has been requested.
/// </summary>
/// <seealso cref="PopRunspace"/>
public void PushRunspace(System.Management.Automation.Runspaces.Runspace runspace)
{
IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();
host.PushRunspace(runspace);
}
/// <summary>
/// Called by the engine to notify the host that a runspace pop has been requested.
/// </summary>
/// <seealso cref="PushRunspace"/>
public void PopRunspace()
{
IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();
host.PopRunspace();
}
/// <summary>
/// True if a runspace is pushed; false otherwise.
/// </summary>
public bool IsRunspacePushed
{
get
{
IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();
return host.IsRunspacePushed;
}
}
/// <summary>
/// Returns the current runspace associated with this host.
/// </summary>
public Runspace Runspace
{
get
{
IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();
return host.Runspace;
}
}
/// <summary>
/// Checks if the host is in a nested prompt.
/// </summary>
/// <returns>True, if host in nested prompt
/// false, otherwise.</returns>
internal bool HostInNestedPrompt()
{
if (NestedPromptCount > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Sets the reference to the external host and the internal UI to a temporary
/// new host and its UI. This exists so that if the PowerShell/Pipeline
/// object has a different host from the runspace it can set it's host during its
/// invocation, and then revert it after the invocation is completed.
/// </summary>
/// <seealso cref="RevertHostRef"/> and
internal void SetHostRef(PSHost psHost)
{
_externalHostRef.Override(psHost);
_internalUIRef.Override(new InternalHostUserInterface(psHost.UI, this));
}
/// <summary>
/// Reverts the temporary host set by SetHost. If no host was temporarily set, this has no effect.
/// </summary>
/// <seealso cref="SetHostRef"/> and
internal void RevertHostRef()
{
// nothing to revert if Host reference is not set.
if (!IsHostRefSet) { return; }
_externalHostRef.Revert();
_internalUIRef.Revert();
}
/// <summary>
/// Returns true if the external host reference is temporarily set to another host, masking the original host.
/// </summary>
internal bool IsHostRefSet
{
get { return _externalHostRef.IsOverridden; }
}
internal ExecutionContext Context { get; }
internal PSHost ExternalHost
{
get
{
return _externalHostRef.Value;
}
}
internal int NestedPromptCount { get; private set; }
// Masked variables.
private readonly ObjectRef<PSHost> _externalHostRef;
private readonly ObjectRef<InternalHostUserInterface> _internalUIRef;
// Private variables.
private string _nameResult;
private Version _versionResult;
private Guid _idResult;
private readonly Stack<PromptContextData> _contextStack = new Stack<PromptContextData>();
private readonly Guid _zeroGuid;
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
using FlatRedBall.Attributes;
using Microsoft.Xna.Framework.Content;
using System.Collections;
using FlatRedBall.Utilities;
using FlatRedBall.Content.Scene;
namespace FlatRedBall.Content
{
#region XML Docs
/// <summary>
/// Class used by the FlatRedBall pipeline to read in XNBs.
/// </summary>
#endregion
public static class ObjectReader
{
public static bool UseReflection = false;
public static T ReadObject<T>(ContentReader input)
{
Type type = typeof(T);
object objectToReturn = default(T);
if (type.Name == "SpriteSave")
{
objectToReturn = SpriteReader.ReadUsingGeneratedCode(input);
}
else if (type.Name == "TextSave")
{
objectToReturn = TextReader.ReadTextSave(input);
}
else if (type.Name == "AnimationChainListSave")
{
objectToReturn = AnimationChainListReader.ReadAnimationChainListSave(input);
}
else if (type.Name == "AnimationChainSave")
{
objectToReturn = AnimationChainListReader.ReadAnimationChainSave(input);
}
else if (type.Name == "AnimationFrameSave")
{
objectToReturn = AnimationChainListReader.ReadAnimationFrameSave(input);
}
else
{
//If T is primitive
#region Read primative values
//Immediately Read if this is a primative type
if ((type.IsPrimitive) || type == typeof(string) || type == typeof(decimal))
{
objectToReturn = input.ReadObject<T>();
}
//Read an Int for the Enum value
else if (type.BaseType == typeof(System.Enum))
{
objectToReturn = (T)Enum.ToObject(typeof(T), (byte)input.ReadInt32());
}
#endregion
//If T is a Collection
#region Read Collections
//Check if this type is a collection
else if (GetInterface(type, "IEnumerable") != null)
{
/*
#if XBOX360
MethodInfo[] methods = typeof(ObjectReader).GetMethods(BindingFlags.Static | BindingFlags.NonPublic);
MethodInfo readCollection = methods[9];
readCollection = readCollection.MakeGenericMethod(new Type[1] { typeof(T) });
objectToReturn = readCollection.Invoke(null, new object[2] { input, false });
#else
objectToReturn = ReadCollection<T>(input, false);
#endif
*/
objectToReturn = ReadCollection<T>(input, false);
}
#endregion
//If T is an object
#region Read Objects
else
{
List<MemberInfo> members = GetMembersToRead(type);
//obtain the location of null fields for this object
bool[] isNullArray = ReadBoolArray(input);
if (members.Count != isNullArray.Length)
{
// Used to be FileLoadException, but that's not
// supported on the 360.
throw new Exception("The object of type " +
type.ToString() + " has " + members.Count + " members, but the ObjectReader " +
"read " + isNullArray.Length + " bools for null members.");
}
if (!type.IsValueType && !HasParameterlessConstructor(type))
{
// Reference types must have no-argument constructors or else they can't be created.
throw new ArgumentException("The type " + type.Name + " does not have a parameterless constructor. " +
"This is needed to properly load the object through the Content Pipeline.");
}
//Build the instance
objectToReturn = System.Activator.CreateInstance<T>();
#region Read each Field and Property
int i = 0;
foreach (MemberInfo member in members)
{
//If this member is a property
if (member.MemberType == MemberTypes.Property)
{
#region Read Property
PropertyInfo field = (member as PropertyInfo);
if (!isNullArray[i++])
{
object memberValue = RecursiveRead(field.PropertyType, input);
//check if it's tagged with XmlIgnore
if (IsIgnored(field)) continue;
if (type.IsValueType) objectToReturn = BoxAndSetValue((object)objectToReturn, field, memberValue);
else field.SetValue(objectToReturn, memberValue, null);
}
else
{
if (field.PropertyType == typeof(string))
{
if (type.IsValueType) objectToReturn = BoxAndSetValue((object)objectToReturn, field, String.Empty);
else field.SetValue(objectToReturn, String.Empty, null);
}
}
#endregion
}
else
{
#region Read Field
FieldInfo field = (member as FieldInfo);
//if this value isn't meant to be null, read it
if (!isNullArray[i++])
{
if (IsExternalInstance(field))
{
ReadExternalInstance(field, ref objectToReturn, input);
}
else
{
object memberValue;
if (typeof(T) == typeof(FlatRedBall.Content.Instructions.InstructionSave) && field.Name.Equals("Value"))
{
string typeName = (objectToReturn as FlatRedBall.Content.Instructions.InstructionSave).Type;
memberValue = RecursiveRead(System.Type.GetType(typeName), input);
}
else memberValue = RecursiveRead(field.FieldType, input);
//check if it's tagged with XmlIgnore
if (IsIgnored(field)) continue;
if (type.IsValueType)
objectToReturn = BoxAndSetValue((object)objectToReturn, field, memberValue);
else
field.SetValue(objectToReturn, memberValue);
}
}
//if it is meant to be null, leave it as null or set it to String.Empty(for strings)
else
{
if (field.FieldType == typeof(string))
{
if (type.IsValueType)
objectToReturn = BoxAndSetValue((object)objectToReturn, field, String.Empty);
else
field.SetValue(objectToReturn, String.Empty);
}
}
#endregion
}
}
#endregion
}
#endregion
}
return (T)objectToReturn;
}
#region Private Methods
private static object BoxAndSetValue(object valueType, MemberInfo member, object value)
{
if (member.MemberType == MemberTypes.Field)
(member as FieldInfo).SetValue(valueType, value);
else
(member as PropertyInfo).SetValue(valueType, value, null);
return valueType;
}
private static Type GetInterface(Type type, string interfaceName)
{
Type[] interfaces = type.GetInterfaces();
foreach (Type interfaceType in interfaces)
{
if (interfaceType.Name == interfaceName)
return interfaceType;
}
return null;
}
private static bool HasParameterlessConstructor(Type type)
{
return type.GetConstructor(new Type[0]) != null;
}
private static bool IsExternalInstance(FieldInfo field)
{
ExternalInstance instance = null;
ExternalInstanceList instanceList = null;
foreach (object attribute in field.GetCustomAttributes(true))
{
instance = (attribute as ExternalInstance);
instanceList = (attribute as ExternalInstanceList);
if (instance != null || instanceList != null)
break;
}
if (instance == null && instanceList == null) return false;
else return true;
}
private static bool IsIgnored(FieldInfo field)
{
System.Xml.Serialization.XmlIgnoreAttribute ignoreAttribute = null;
foreach (object attribute in field.GetCustomAttributes(true))
{
ignoreAttribute = (attribute as System.Xml.Serialization.XmlIgnoreAttribute);
if (ignoreAttribute != null) break;
}
if (ignoreAttribute == null) return false;
else return true;
}
private static bool IsExternalInstanceList(FieldInfo field)
{
ExternalInstanceList instanceList = null;
foreach (object attribute in field.GetCustomAttributes(true))
{
instanceList = (attribute as ExternalInstanceList);
if (instanceList != null) break;
}
if (instanceList == null) return false;
else return true;
}
private static bool IsExternalInstance(PropertyInfo property)
{
ExternalInstance instance = null;
ExternalInstanceList instanceList = null;
foreach (object attribute in property.GetCustomAttributes(true))
{
instance = (attribute as ExternalInstance);
instanceList = (attribute as ExternalInstanceList);
if (instance != null || instanceList != null) break;
}
if (instance == null && instanceList == null) return false;
else return true;
}
private static bool IsIgnored(PropertyInfo property)
{
System.Xml.Serialization.XmlIgnoreAttribute ignoreAttribute = null;
foreach (object attribute in property.GetCustomAttributes(true))
{
ignoreAttribute = (attribute as System.Xml.Serialization.XmlIgnoreAttribute);
if (ignoreAttribute != null) break;
}
if (ignoreAttribute == null) return false;
else return true;
}
private static List<MemberInfo> GetMembersToRead(Type type)
{
List<MemberInfo> returnList = new List<MemberInfo>();
returnList.AddRange(type.GetProperties(BindingFlags.Public | BindingFlags.Instance));
returnList.AddRange(type.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic));
returnList.AddRange(type.GetFields(BindingFlags.Instance | BindingFlags.Public));
returnList.Sort(SortMembersForReading);
for (int i = returnList.Count - 1; i > -1; i--)
{
if (IsPrivateField(returnList[i]))
{
returnList.RemoveAt(i);
}
}
// This doesn't seem to work in XNA4 on the 360:
//returnList.RemoveAll(IsPrivateField);
return returnList;
}
#region Reading Helpers
private static T ReadCollection<T>(ContentReader input, bool isExternal)
{
if (!isExternal)
return ReadCollection<T>(input, false, null);
else
throw new ArgumentException("Must provide the expected Type to be read when Reading a collection of External References");
}
private static T ReadCollection<T>(ContentReader input, bool isExternal, Type readType)
{
object objectToReturn = null;
Type type = typeof(T);
int count = input.ReadInt32();
bool[] isNullArray = ReadBoolArray(input);
if (count != isNullArray.Length)
{
// Used to be FileLoadException, but that's not supported
// on the Xbox 360
throw new Exception("The collection of type " +
type.ToString() + " has " + count + " entries, but the ObjectReader " +
"read " + isNullArray.Length + " bools for null entries.");
}
//If type is an Array or List
if (GetInterface(type, "IList") != null)
{
MethodInfo listRecur = default(MethodInfo);
//If this is an array
if (type.IsArray)
{
#region Read Array
Type elementType = type.GetElementType();
//Build the instance to return and the recursive call.
objectToReturn = Array.CreateInstance(type.GetElementType(), count);
//If this field is marked with the ExternalInstance attribute.
if (isExternal)
{
//If the elements of this array are also Collections
if (GetInterface(elementType, "IEnumerable") != null)
{
listRecur = typeof(ObjectReader).GetMethod("ReadCollection", BindingFlags.NonPublic | BindingFlags.Static,
null, new Type[] {input.GetType(), typeof(bool), typeof(Type)},
null);
//Check if null, which will be the case if running on the 360
if (listRecur == null)
{
listRecur = GetPrivateObjectReaderMethod("ReadCollection", new Type[] { input.GetType(), typeof(bool), typeof(Type) });
}
listRecur = listRecur.MakeGenericMethod(new Type[1] { elementType });
for (int i = 0; i < count; ++i)
{
if (!isNullArray[i])
(objectToReturn as System.Collections.IList)[i] = listRecur.Invoke(null, new object[3] { input, true, elementType });
}
}
else
{
listRecur = typeof(ContentReader).GetMethod("ReadExternalReference").MakeGenericMethod(new Type[1] { elementType });
for (int i = 0; i < count; ++i)
{
if (!isNullArray[i])
(objectToReturn as System.Collections.IList)[i] = listRecur.Invoke(input, new object[0] { });
}
}
}
else
{
listRecur = typeof(ObjectReader).GetMethod("ReadObject").MakeGenericMethod(new Type[1] { elementType });
for (int i = 0; i < count; ++i)
{
//invoke the recursive call for each element.
if (!isNullArray[i])
(objectToReturn as System.Collections.IList)[i] = listRecur.Invoke(null, new object[1] { input });
}
}
#endregion
}
//Similar process, but for Lists
else
{
#region Read List
Type tempType = type;
objectToReturn = System.Activator.CreateInstance<T>();
//Move up the inheritence tree until you get a Generic definition
while (!tempType.IsGenericType)
{
if (tempType.BaseType != null)
tempType = tempType.BaseType;
}
if (count != 0)
{
//Build the recursive call with the Generic type
Type[] genericParam = tempType.GetGenericArguments();
if (genericParam[0] == typeof(FlatRedBall.Content.Scene.SpriteSave))
{
for (int i = 0; i < count; ++i)
{
if (!isNullArray[i])
{
FlatRedBall.Content.Scene.SpriteSave ss =
ObjectReader.ReadObject<FlatRedBall.Content.Scene.SpriteSave>(input);
(objectToReturn as System.Collections.IList).Add(ss);
}
}
}
else
{
Type objectReaderType = typeof(ObjectReader);
MethodInfo nonGenericReadObject = objectReaderType.GetMethod("ReadObject");
listRecur = nonGenericReadObject.MakeGenericMethod(genericParam);
for (int i = 0; i < count; ++i)
{
if (!isNullArray[i])
(objectToReturn as System.Collections.IList).Add(listRecur.Invoke(null, new object[1] { input }));
}
}
}
#endregion
}
}
//For Dictionaries
//ToDo: Test
else if (GetInterface(type, "IDictionary") != null)
{
#region Read Dictionary
objectToReturn = System.Activator.CreateInstance<T>();
Type[] genericParam = type.GetGenericArguments();
MethodInfo dictRecur1 = typeof(ObjectReader).GetMethod("ReadObject").MakeGenericMethod(new Type[1] { genericParam[0] });
MethodInfo dictRecur2 = typeof(ObjectReader).GetMethod("ReadObject").MakeGenericMethod(new Type[1] { genericParam[1] });
for (int i = 0; i < count; ++i)
{
//Dictionary values are allowed to be null, but their keys are not.
if (!isNullArray[i])
{
(objectToReturn as System.Collections.IDictionary).Add(dictRecur1.Invoke(null, new object[1] { input }),
dictRecur2.Invoke(null, new object[1] { input }));
}
else
{
(objectToReturn as System.Collections.IDictionary).Add(dictRecur1.Invoke(null, new object[1] { input }),
null);
}
}
#endregion
}
//For Stacks
else if (GetInterface(type, "Stack") != null)
{
#if WINDOWS_PHONE || XBOX360
throw new NotImplementedException();
#else
#region Read Stack
objectToReturn = System.Activator.CreateInstance<T>();
Type[] genericParam = type.GetGenericArguments();
MethodInfo stackRecur = typeof(ObjectReader).GetMethod("ReadObject").MakeGenericMethod(new Type[1] { genericParam[0] });
for (int i = 0; i < count; ++i)
{
if (!isNullArray[i])
(objectToReturn as System.Collections.Stack).Push(stackRecur.Invoke(null, new object[1] { input }));
}
#endregion
#endif
}
//And for Queues
else if (GetInterface(type, "Queue") != null)
{
#if XNA4
throw new NotImplementedException();
#else
#region Read Queue
objectToReturn = System.Activator.CreateInstance<T>();
Type[] genericParam = type.GetGenericArguments();
MethodInfo queueRecur = typeof(ObjectReader).GetMethod("ReadObject").MakeGenericMethod(new Type[1] { genericParam[0] });
for (int i = 0; i < count; ++i)
{
if (!isNullArray[i])
(objectToReturn as System.Collections.Queue).Enqueue(queueRecur.Invoke(null, new object[1] { input }));
}
#endregion
#endif
}
return (T)objectToReturn;
}
private static object RecursiveRead(Type type, ContentReader input)
{
MethodInfo call = typeof(ObjectReader).GetMethod("ReadObject").MakeGenericMethod(new Type[1] { type });
//try
//{
return call.Invoke(null, new object[1] { input });
//}
//catch (Exception e)
//{
// System.Diagnostics.Trace.Write(e.Message);
//}
//return null;
}
private static void ReadExternalInstance(FieldInfo field, ref object container, ContentReader input)
{
if (GetInterface(field.FieldType, "IEnumerable") == null)
{
Type refType = field.FieldType;
MethodInfo readRef = typeof(ContentReader).GetMethod("ReadExternalReference").MakeGenericMethod(new Type[1] { refType });
field.SetValue(container, readRef.Invoke(input, null));
}
else if (IsExternalInstanceList(field))
{
Type refType = field.FieldType;
MethodInfo readCollectionMethod =
typeof(ObjectReader).GetMethod("ReadCollection",
BindingFlags.NonPublic | BindingFlags.Static,
null,
new Type[] { input.GetType(), typeof(bool), typeof(Type) },
null);
if (readCollectionMethod == null)
{
//The 360 doesn't seem to like methods with generic retern types, so GetMethod() ignores them. However
//GetMethods() still includes them...So to prevent errors such as the one TrashMan360 experienced, we loop
//through all methods and check names before throwing the exception(if it's not found)
readCollectionMethod = GetPrivateObjectReaderMethod("ReadCollection", new Type[3] { input.GetType(),
typeof(bool),
typeof(Type)});
if(readCollectionMethod == null)
throw new NullReferenceException("No ReadCollection method");
}
MethodInfo readRef =
readCollectionMethod.MakeGenericMethod(new Type[1] { refType });
if (readRef == null)
{
throw new NullReferenceException("No generic ReadCollection method");
}
try
{
field.SetValue(container, readRef.Invoke(input, new object[3] { input, true, refType }));
}
catch (Exception)
{
//
}
}
else
{
Type refType = field.FieldType;
MethodInfo readRef = typeof(ContentReader).GetMethod("ReadExternalReference").MakeGenericMethod(new Type[1] { refType });
field.SetValue(container, readRef.Invoke(input, null));
}
}
static V Cast<V>(object val)
{
return (V)val;
}
private static MethodInfo GetPrivateObjectReaderMethod(string methodName, Type[] methodArgs)
{
MethodInfo toReturn = null;
MethodInfo[] methods = typeof(ObjectReader).GetMethods(BindingFlags.NonPublic | BindingFlags.Static);
foreach (MethodInfo method in methods)
{
if (method.Name.Equals(methodName))
{
bool passing = true;
MethodInfo genMethod = method.MakeGenericMethod(new Type[1] { typeof(bool) });
ParameterInfo[] parameters = genMethod.GetParameters();
if (parameters.Length == methodArgs.Length)
{
for (int i = 0; i < methodArgs.Length && passing; ++i)
{
if (parameters[i].ParameterType != methodArgs[i])
passing = false;
}
}
else passing = false;
if (passing)
{
toReturn = method;
break;
}
}
}
return toReturn;
}
private static bool[] ReadBoolArray(ContentReader input)
{
int count = input.ReadInt32();
bool[] returnArray = new bool[count];
for (int i = 0; i < count; ++i)
{
returnArray[i] = input.ReadBoolean();
}
return returnArray;
}
#endregion
#region Sorting Helpers
public static bool DoesMemberSortFirst(MemberInfo memberInfo)
{
object[] attributes = memberInfo.GetCustomAttributes(true);
foreach (object attribute in attributes)
{
if (attribute is ContentSorting)
{
return ((ContentSorting)attribute).SortingStyle == SortingStyle.First;
}
}
return false;
}
private static int SortMembersForReading(MemberInfo m1, MemberInfo m2)
{
if (ObjectReader.DoesMemberSortFirst(m1))
{
return -1;
}
else if (ObjectReader.DoesMemberSortFirst(m2))
{
return 1;
}
else if (m1.MemberType == m2.MemberType)
{
if (m1.MemberType == MemberTypes.Field)
return SortFieldsByType((m1 as FieldInfo), (m2 as FieldInfo));
else
return SortPropertiesByType((m1 as PropertyInfo), (m2 as PropertyInfo));
}
else
{
if (m1.MemberType == MemberTypes.Field)
return -1;
else
return 1;
}
}
private static int SortPropertiesByType(PropertyInfo p1, PropertyInfo p2)
{
if (p1.PropertyType == p2.PropertyType)
{
if (IsExternalInstance(p1)) throw new Exception("Objects read through the ObjectReader may not have properties tagged with ExternalInstance. Please load ExternalReference content into fields.");
else return SortMembersByName((p1 as MemberInfo), (p2 as MemberInfo));
}
else
{
if (IsExternalInstance(p1))
{
throw new Exception("Objects read through the ObjectReader may not have properties tagged with ExternalInstance. Please load ExternalReference content into fields.");
}
else if (IsExternalInstance(p2))
{
throw new Exception("Objects read through the ObjectReader may not have properties tagged with ExternalInstance. Please load ExternalReference content into fields.");
}
else
{
return SortMembersByName((p1 as MemberInfo), (p2 as MemberInfo));
// return String.Compare(p1.PropertyType.FullName, p2.PropertyType.FullName, false);
}
}
}
public static int SortFieldsByType(FieldInfo f1, FieldInfo f2)
{
if (f1.FieldType == f2.FieldType)
{
#if WINDOWS_PHONE || XBOX360
if (IsExternalInstance(f1)) return String.Compare(f1.Name, f2.Name,StringComparison.InvariantCultureIgnoreCase);
#else
if (IsExternalInstance(f1)) return String.Compare(f1.Name, f2.Name, false);
#endif
return SortMembersByName((f1 as MemberInfo), (f2 as MemberInfo));
}
else
{
if (IsExternalInstance(f1))
{
if (IsExternalInstance(f2))
{
#if WINDOWS_PHONE || XBOX360
return String.Compare(f1.Name, f2.Name, StringComparison.InvariantCultureIgnoreCase);
#else
return String.Compare(f1.Name, f2.Name, false);
#endif
}
else
{
return 1;
}
}
else if (IsExternalInstance(f2))
{
return -1;
}
else
{
/*int result = String.Compare(f1.FieldType.FullName, f2.FieldType.FullName, false);
if (result < 0)
return -1;
else
return 1;*/
return SortMembersByName((f1 as MemberInfo), (f2 as MemberInfo));
}
}
}
private static int SortMembersByName(MemberInfo m1, MemberInfo m2)
{
#if WINDOWS_PHONE || XBOX360
int retValue = String.Compare(m1.Name, m2.Name, StringComparison.InvariantCultureIgnoreCase);
#else
int retValue = String.Compare(m1.Name, m2.Name, false);
#endif
if (retValue == 0)
{
if (!m1.DeclaringType.Equals(m2.DeclaringType))
{
string errorMessage = "ObjectReader cannot deserialize using this object as a container. Type " + m1.DeclaringType + " and type " + m2.DeclaringType +
" both declare a member of the same type and name, " + m1.Name + ".";
throw new AmbiguousMatchException(errorMessage);
}
else return retValue;
}
else return retValue;
}
private static bool IsPrivateField(MemberInfo member)
{
if (member.MemberType == MemberTypes.Field)
{
FieldInfo field = (member as FieldInfo);
if (field.IsPrivate && !IsExternalInstance(field)) return true;
else return false;
}
else if (member.MemberType == MemberTypes.Property)
{
PropertyInfo property = (member as PropertyInfo);
if (!property.CanWrite) return true;
else if (property.GetIndexParameters().Length > 0) return true;
else return false;
}
else return false;
}
#endregion
#endregion
}
}
| |
namespace Microsoft.WindowsAzure.Management.HDInsight.TestUtilities
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Data.Rdfe;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Data;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient.PaasClusters;
using Microsoft.WindowsAzure.Management.HDInsight.Contracts;
using Microsoft.WindowsAzure.Management.HDInsight.Contracts.May2014;
using Microsoft.WindowsAzure.Management.HDInsight.Contracts.May2014.Components;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning;
public class RootHandlerSimulatorController : ApiController
{
//Mapping between subscription id and Cluster
internal static readonly IDictionary<string, List<Cluster>> _clustersAvailable = new Dictionary<string, List<Cluster>>();
[System.Web.Http.Route("~/{subscriptionId}/cloudservices")]
[HttpGet]
public HttpResponseMessage ListCloudServicesAsync(string subscriptionId)
{
var requestMessage = this.Request;
var detailLevel = requestMessage.RequestUri.ParseQueryString()["detailLevel"];
List<Cluster> clusters;
bool subExists = _clustersAvailable.TryGetValue(subscriptionId, out clusters);
if (!subExists)
{
return this.Request.CreateResponse(HttpStatusCode.Accepted, new CloudServiceList());
}
var clustersByLocation = clusters.GroupBy(c => c.Location);
var cloudServiceList = new CloudServiceList();
foreach (var locationcluster in clustersByLocation)
{
var cloudService = new CloudService();
cloudService.Description = "test description";
cloudService.GeoRegion = locationcluster.Key;
cloudService.Label = "test label";
cloudService.Resources = new ResourceList();
foreach (Cluster cluster in locationcluster)
{
var resource = new Resource();
resource.Name = cluster.DnsName;
resource.Type = PaasClustersPocoClient.ClustersResourceType;
resource.State = cluster.State.ToString();
resource.OutputItems = this.GetOutputItems(cluster);
cloudService.Resources.Add(resource);
}
cloudServiceList.Add(cloudService);
}
return this.Request.CreateResponse(HttpStatusCode.Accepted, cloudServiceList);;
}
[System.Web.Http.Route("~/{subscriptionId}/cloudservices/{cloudServiceName}/resources/{resourceNamespace}/clusters/{dnsName}")]
[HttpDelete]
public HttpResponseMessage DeleteCluster(string subscriptionId, string cloudServiceName, string resourceNamespace, string dnsName)
{
var requestMessage = this.Request;
List<Cluster> clusters;
bool subExists = _clustersAvailable.TryGetValue(subscriptionId, out clusters);
if (!subExists)
{
return null;
}
var cluster = clusters.SingleOrDefault(c => c.DnsName.Equals(dnsName) && cloudServiceName.Contains(c.Location.Replace(" ", "-")));
if (cluster != null)
{
clusters.Remove(cluster);
_clustersAvailable[subscriptionId] = clusters;
}
return this.Request.CreateResponse(HttpStatusCode.OK);
}
[Route("~/{subscriptionId}/cloudservices/{cloudServiceName}/resources/{resourceNamespace}/~/clusters/{dnsName}")]
[HttpGet]
public PassthroughResponse GetCluster(string subscriptionId, string cloudServiceName, string resourceNamespace, string dnsName)
{
return new PassthroughResponse { Data = this.GetCluster(dnsName, cloudServiceName, subscriptionId) };
}
[Route("~/{subscriptionId}/services")]
[HttpPut]
public HttpResponseMessage RegisterSubscriptionIfNotExists(string subscriptionId)
{
return this.Request.CreateResponse(HttpStatusCode.OK);
}
[Route("~/{subscriptionId}/cloudservices/{cloudServiceName}")]
[HttpPut]
public async Task<HttpResponseMessage> PutCloudServiceAsync(string subscriptionId, string cloudServiceName)
{
var cloudServiceFromRequest = await this.Request.Content.ReadAsAsync<CloudService>();
return this.Request.CreateResponse(HttpStatusCode.Created);
}
[Route("~/{subscriptionId}/cloudservices/{cloudServiceName}/resources/{resourceNamespace}/clusters/{dnsName}")]
[HttpPut]
public async Task<HttpResponseMessage> CreateCluster(string subscriptionId, string cloudServiceName, string resourceNamespace, string dnsName)
{
var requestMessage = this.Request;
var rdfeResource = await requestMessage.Content.ReadAsAsync<RDFEResource>();
XmlNode node = rdfeResource.IntrinsicSettings[0];
MemoryStream stm = new MemoryStream();
StreamWriter stw = new StreamWriter(stm);
stw.Write(node.OuterXml);
stw.Flush();
stm.Position = 0;
DataContractSerializer ser = new DataContractSerializer(typeof(ClusterCreateParameters));
ClusterCreateParameters clusterCreateParams = (ClusterCreateParameters)ser.ReadObject(stm);
// Spark cluster creation in introduced after schema version 3.0
if (clusterCreateParams.Components.Any(c => c.GetType() == typeof(SparkComponent)))
{
if (!requestMessage.Headers.GetValues("SchemaVersion").Any(v => v.Equals("3.0")))
{
throw new NotSupportedException(ClustersTestConstants.NotSupportedBySubscriptionException);
}
}
var testCluster = new Cluster
{
ClusterRoleCollection = clusterCreateParams.ClusterRoleCollection,
CreatedTime = DateTime.UtcNow,
Error = null,
FullyQualifiedDnsName = clusterCreateParams.DnsName,
State = ClusterState.Running,
UpdatedTime = DateTime.UtcNow,
DnsName = clusterCreateParams.DnsName,
Components = clusterCreateParams.Components,
ExtensionData = clusterCreateParams.ExtensionData,
Location = clusterCreateParams.Location,
Version = ClusterVersionUtils.TryGetVersionNumber(clusterCreateParams.Version),
VirtualNetworkConfiguration = clusterCreateParams.VirtualNetworkConfiguration
};
List<Cluster> clusters;
bool subExists = _clustersAvailable.TryGetValue(subscriptionId, out clusters);
if (subExists)
{
clusters.Add(testCluster);
_clustersAvailable[subscriptionId] = clusters;
}
else
{
_clustersAvailable.Add(
new KeyValuePair<string, List<Cluster>>(subscriptionId, new List<Cluster> { testCluster }));
}
return this.Request.CreateResponse(HttpStatusCode.Created);
}
[Route("~/{subscriptionId}/cloudservices/{cloudServiceName}/resources/{resourceNamespace}/~/clusters/{dnsName}/roles")]
[HttpPost]
public async Task<PassthroughResponse> UpdateRole(string subscriptionId, string cloudServiceName, string resourceNamespace, string dnsName)
{
var requestMessage = this.Request;
if (requestMessage.Headers.GetValues("SchemaVersion").Any(v => v.Equals("1.0")))
{
throw new NotSupportedException(ClustersTestConstants.NotSupportedBySubscriptionException);
}
ClusterRoleCollection roleCollection = await requestMessage.Content.ReadAsAsync<ClusterRoleCollection>();
var actionValue = requestMessage.RequestUri.ParseQueryString()["action"];
PassthroughResponse response;
//If no action is specified then RP defaults to Enable Rdp action.
if (string.IsNullOrEmpty(actionValue))
{
this.EnableRdp(roleCollection, subscriptionId, cloudServiceName, dnsName);
}
switch (actionValue.ToLowerInvariant())
{
case "resize":
response = this.ResizeCluster(roleCollection, subscriptionId, cloudServiceName, dnsName);
break;
case "enablerdp":
response = this.EnableDisableRdp(roleCollection, subscriptionId, cloudServiceName, dnsName);
break;
default:
throw new NotSupportedException(string.Format(ClustersTestConstants.NotSupportedAction,
actionValue));
}
return response;
}
private PassthroughResponse EnableDisableRdp(ClusterRoleCollection roleCollection, string subscriptionId,
string cloudServiceName, string dnsName)
{
Assert.IsNotNull(roleCollection);
Assert.IsTrue(roleCollection.Count > 0);
var firstRole = roleCollection.FirstOrDefault();
Assert.IsNotNull(firstRole);
Assert.IsNotNull(firstRole.RemoteDesktopSettings);
if (firstRole.RemoteDesktopSettings.IsEnabled)
{
return this.EnableRdp(roleCollection, subscriptionId, cloudServiceName, dnsName);
}
else
{
return this.DisableRdp(roleCollection, subscriptionId, cloudServiceName, dnsName);
}
}
private PassthroughResponse ResizeCluster(ClusterRoleCollection roleCollection, string subscriptionId,
string cloudServiceName, string dnsName)
{
var workerNode = roleCollection.SingleOrDefault(role => role.FriendlyName.Equals("WorkerNodeRole"));
if (workerNode == null)
{
throw new NullReferenceException(ClustersTestConstants.NoDataNodeException);
}
int instanceCount = workerNode.InstanceCount;
var cluster = this.GetCluster(dnsName, cloudServiceName, subscriptionId);
if (cluster == null)
{
throw new ArgumentNullException(string.Format(ClustersTestConstants.ClusterDoesNotExistException, dnsName, subscriptionId));
}
var clusterWorkerRole = cluster.ClusterRoleCollection.SingleOrDefault(role => role.FriendlyName.Equals("WorkerNodeRole"));
if (clusterWorkerRole == null)
{
throw new NullReferenceException(ClustersTestConstants.NoDataNodeException);
}
clusterWorkerRole.InstanceCount = instanceCount;
return new PassthroughResponse { Data = new Contracts.May2014.Operation { OperationId = Guid.NewGuid().ToString(), Status = Contracts.May2014.OperationStatus.InProgress, } };
}
private PassthroughResponse EnableRdp(ClusterRoleCollection roleCollection, string subscriptionId,
string cloudServiceName, string dnsName)
{
Assert.IsNotNull(roleCollection, "Role collection is null");
Assert.IsTrue(roleCollection.Count > 0, "There are no roles in the role collection");
var cluster = this.GetCluster(dnsName, cloudServiceName, subscriptionId);
if (cluster == null)
{
throw new ArgumentNullException(string.Format(ClustersTestConstants.ClusterDoesNotExistException, dnsName, subscriptionId));
}
ClusterRole previousRole = null;
foreach (var role in roleCollection)
{
Assert.IsNotNull(role,"The role is null");
Assert.IsTrue(role.RemoteDesktopSettings.IsEnabled);
if (previousRole != null)
{
Assert.IsTrue(
previousRole.RemoteDesktopSettings.AuthenticationCredential.Username ==
role.RemoteDesktopSettings.AuthenticationCredential.Username,
"rdpUsername between roles doesn't match");
Assert.IsTrue(
previousRole.RemoteDesktopSettings.AuthenticationCredential.Password ==
role.RemoteDesktopSettings.AuthenticationCredential.Password,
"rdpPassword between roles doesn't match");
Assert.IsTrue(previousRole.RemoteDesktopSettings.RemoteAccessExpiry ==
role.RemoteDesktopSettings.RemoteAccessExpiry,
"RemoteAccessExpory between roles doesn't match");
}
else
{
Assert.IsNotNull(role.RemoteDesktopSettings.AuthenticationCredential.Username,
"rdpUsername is null");
Assert.IsNotNull(role.RemoteDesktopSettings.AuthenticationCredential.Password,
"rdpPassword is null");
Assert.IsNotNull(role.RemoteDesktopSettings.RemoteAccessExpiry,
"RemoteAccessExpory is numm");
}
previousRole = role;
}
cluster.ClusterRoleCollection = roleCollection;
return new PassthroughResponse { Data = new Contracts.May2014.Operation { OperationId = Guid.NewGuid().ToString(), Status = Contracts.May2014.OperationStatus.InProgress, } };
}
private PassthroughResponse DisableRdp(ClusterRoleCollection roleCollection, string subscriptionId,
string cloudServiceName, string dnsName)
{
var cluster = this.GetCluster(dnsName, cloudServiceName, subscriptionId);
if (cluster == null)
{
throw new ArgumentNullException(string.Format(ClustersTestConstants.ClusterDoesNotExistException, dnsName, subscriptionId));
}
cluster.ClusterRoleCollection = roleCollection;
return new PassthroughResponse { Data = new Contracts.May2014.Operation { OperationId = Guid.NewGuid().ToString(), Status = Contracts.May2014.OperationStatus.InProgress, } };
}
private Cluster GetCluster(string dnsName, string cloudserviceName, string subscriptionId)
{
List<Cluster> clusters;
bool subExists = _clustersAvailable.TryGetValue(subscriptionId, out clusters);
if (!subExists)
{
return null;
}
var cluster = clusters.SingleOrDefault(c => c.DnsName.Equals(dnsName) && cloudserviceName.Contains(c.Location.Replace(" ", "-")));
if (cluster == null)
{
return null;
}
return cluster;
}
private OutputItemList GetOutputItems(Cluster cluster)
{
var oi = new OutputItemList();
var version = new OutputItem();
version.Key = "Version";
version.Value = cluster.Version;
oi.Add(version);
var components = new OutputItem();
components.Key = "ClusterComponents";
components.Value = this.GetClusterComponents(cluster);
oi.Add(components);
return oi;
}
private string GetClusterComponents(Cluster cluster)
{
return string.Join(",", cluster.Components.Select(c => c.GetType().Name));
}
}
}
| |
// 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.Security;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace System.Globalization
{
public partial class CompareInfo
{
private unsafe void InitSort(CultureInfo culture)
{
_sortName = culture.SortName;
m_name = culture._name;
_sortName = culture.SortName;
if (_invariantMode)
{
_sortHandle = IntPtr.Zero;
}
else
{
const uint LCMAP_SORTHANDLE = 0x20000000;
IntPtr handle;
int ret = Interop.Kernel32.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero);
_sortHandle = ret > 0 ? handle : IntPtr.Zero;
}
}
private static unsafe int FindStringOrdinal(
uint dwFindStringOrdinalFlags,
string stringSource,
int offset,
int cchSource,
string value,
int cchValue,
bool bIgnoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
fixed (char* pSource = stringSource)
fixed (char* pValue = value)
{
int ret = Interop.Kernel32.FindStringOrdinal(
dwFindStringOrdinalFlags,
pSource + offset,
cchSource,
pValue,
cchValue,
bIgnoreCase ? 1 : 0);
return ret < 0 ? ret : ret + offset;
}
}
private static unsafe int FindStringOrdinal(
uint dwFindStringOrdinalFlags,
ReadOnlySpan<char> source,
ReadOnlySpan<char> value,
bool bIgnoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pValue = &MemoryMarshal.GetReference(value))
{
int ret = Interop.Kernel32.FindStringOrdinal(
dwFindStringOrdinalFlags,
pSource,
source.Length,
pValue,
value.Length,
bIgnoreCase ? 1 : 0);
return ret;
}
}
internal static int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
}
internal static int IndexOfOrdinalCore(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source.Length != 0);
Debug.Assert(value.Length != 0);
return FindStringOrdinal(FIND_FROMSTART, source, value, ignoreCase);
}
internal static int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
}
private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(source != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int flags = GetNativeCompareFlags(options);
int tmpHash = 0;
#if CORECLR
tmpHash = InternalGetGlobalizedHashCode(_sortHandle, _sortName, source, source.Length, flags);
#else
fixed (char* pSource = source)
{
if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
LCMAP_HASH | (uint)flags,
pSource, source.Length,
&tmpHash, sizeof(int),
null, null, _sortHandle) == 0)
{
Environment.FailFast("LCMapStringEx failed!");
}
}
#endif
return tmpHash;
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
Debug.Assert(!GlobalizationMode.Invariant);
// Use the OS to compare and then convert the result to expected value by subtracting 2
return Interop.Kernel32.CompareStringOrdinal(string1, count1, string2, count2, true) - 2;
}
// TODO https://github.com/dotnet/coreclr/issues/13827:
// This method shouldn't be necessary, as we should be able to just use the overload
// that takes two spans. But due to this issue, that's adding significant overhead.
private unsafe int CompareString(ReadOnlySpan<char> string1, string string2, CompareOptions options)
{
Debug.Assert(string2 != null);
Debug.Assert(!_invariantMode);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pString1 = &MemoryMarshal.GetReference(string1))
fixed (char* pString2 = &string2.GetRawStringData())
{
int result = Interop.Kernel32.CompareStringEx(
pLocaleName,
(uint)GetNativeCompareFlags(options),
pString1,
string1.Length,
pString2,
string2.Length,
null,
null,
_sortHandle);
if (result == 0)
{
Environment.FailFast("CompareStringEx failed");
}
// Map CompareStringEx return value to -1, 0, 1.
return result - 2;
}
}
private unsafe int CompareString(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pString1 = &MemoryMarshal.GetReference(string1))
fixed (char* pString2 = &MemoryMarshal.GetReference(string2))
{
int result = Interop.Kernel32.CompareStringEx(
pLocaleName,
(uint)GetNativeCompareFlags(options),
pString1,
string1.Length,
pString2,
string2.Length,
null,
null,
_sortHandle);
if (result == 0)
{
Environment.FailFast("CompareStringEx failed");
}
// Map CompareStringEx return value to -1, 0, 1.
return result - 2;
}
}
private unsafe int FindString(
uint dwFindNLSStringFlags,
ReadOnlySpan<char> lpStringSource,
ReadOnlySpan<char> lpStringValue,
int* pcchFound)
{
Debug.Assert(!_invariantMode);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pSource = &MemoryMarshal.GetReference(lpStringSource))
fixed (char* pValue = &MemoryMarshal.GetReference(lpStringValue))
{
return Interop.Kernel32.FindNLSStringEx(
pLocaleName,
dwFindNLSStringFlags,
pSource,
lpStringSource.Length,
pValue,
lpStringValue.Length,
pcchFound,
null,
null,
_sortHandle);
}
}
private unsafe int FindString(
uint dwFindNLSStringFlags,
string lpStringSource,
int startSource,
int cchSource,
string lpStringValue,
int startValue,
int cchValue,
int* pcchFound)
{
Debug.Assert(!_invariantMode);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pSource = lpStringSource)
fixed (char* pValue = lpStringValue)
{
char* pS = pSource + startSource;
char* pV = pValue + startValue;
return Interop.Kernel32.FindNLSStringEx(
pLocaleName,
dwFindNLSStringFlags,
pS,
cchSource,
pV,
cchValue,
pcchFound,
null,
null,
_sortHandle);
}
}
internal unsafe int IndexOfCore(String source, String target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(!_invariantMode);
Debug.Assert(source != null);
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
if (matchLengthPtr != null)
*matchLengthPtr = 0;
return startIndex;
}
if (source.Length == 0)
{
return -1;
}
if ((options & CompareOptions.Ordinal) != 0)
{
int retValue = FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false);
if (retValue >= 0)
{
if (matchLengthPtr != null)
*matchLengthPtr = target.Length;
}
return retValue;
}
else
{
int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count,
target, 0, target.Length, matchLengthPtr);
if (retValue >= 0)
{
return retValue + startIndex;
}
}
return -1;
}
internal unsafe int IndexOfCore(ReadOnlySpan<char> source, ReadOnlySpan<char> target, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(!_invariantMode);
Debug.Assert(source.Length != 0);
Debug.Assert(target.Length != 0);
Debug.Assert((options == CompareOptions.None || options == CompareOptions.IgnoreCase));
int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, target, matchLengthPtr);
return retValue;
}
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
if (target.Length == 0)
return startIndex; // keep Whidbey compatibility
if ((options & CompareOptions.Ordinal) != 0)
{
return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true);
}
else
{
int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options), source, startIndex - count + 1,
count, target, 0, target.Length, null);
if (retValue >= 0)
{
return retValue + startIndex - (count - 1);
}
}
return -1;
}
private unsafe bool StartsWith(string source, string prefix, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(prefix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length,
prefix, 0, prefix.Length, null) >= 0;
}
private unsafe bool StartsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!prefix.IsEmpty);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, prefix, null) >= 0;
}
private unsafe bool EndsWith(string source, string suffix, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(suffix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length,
suffix, 0, suffix.Length, null) >= 0;
}
private unsafe bool EndsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!suffix.IsEmpty);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, suffix, null) >= 0;
}
// PAL ends here
[NonSerialized]
private IntPtr _sortHandle;
private const uint LCMAP_SORTKEY = 0x00000400;
private const uint LCMAP_HASH = 0x00040000;
private const int FIND_STARTSWITH = 0x00100000;
private const int FIND_ENDSWITH = 0x00200000;
private const int FIND_FROMSTART = 0x00400000;
private const int FIND_FROMEND = 0x00800000;
// TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false?
private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex)
{
int retValue = -1;
int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex;
fixed (char* pSource = source, spTarget = target)
{
char* spSubSource = pSource + sourceStartIndex;
if (findLastIndex)
{
int startPattern = (sourceCount - 1) - targetCount + 1;
if (startPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex - sourceCount + 1;
}
}
else
{
int endPattern = (sourceCount - 1) - targetCount + 1;
if (endPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex;
}
}
}
return retValue;
}
private unsafe SortKey CreateSortKey(String source, CompareOptions options)
{
Debug.Assert(!_invariantMode);
if (source == null) { throw new ArgumentNullException(nameof(source)); }
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
byte [] keyData = null;
if (source.Length == 0)
{
keyData = Array.Empty<byte>();
}
else
{
fixed (char *pSource = source)
{
int result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options),
pSource, source.Length,
null, 0,
null, null, _sortHandle);
if (result == 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, "source");
}
keyData = new byte[result];
fixed (byte* pBytes = keyData)
{
result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options),
pSource, source.Length,
pBytes, keyData.Length,
null, null, _sortHandle);
}
}
}
return new SortKey(Name, source, options, keyData);
}
private static unsafe bool IsSortable(char* text, int length)
{
Debug.Assert(!GlobalizationMode.Invariant);
return Interop.Kernel32.IsNLSDefinedString(Interop.Kernel32.COMPARE_STRING, 0, IntPtr.Zero, text, length);
}
private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal
private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead)
private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal.
private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead)
private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols.
private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character.
private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing
private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols.
private static int GetNativeCompareFlags(CompareOptions options)
{
// Use "linguistic casing" by default (load the culture's casing exception tables)
int nativeCompareFlags = NORM_LINGUISTIC_CASING;
if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; }
if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; }
if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; }
if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; }
if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; }
if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; }
// TODO: Can we try for GetNativeCompareFlags to never
// take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special
// in some places.
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
CompareOptions.IgnoreWidth |
CompareOptions.StringSort)) == 0) ||
(options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
return nativeCompareFlags;
}
private unsafe SortVersion GetSortVersion()
{
Debug.Assert(!_invariantMode);
Interop.Kernel32.NlsVersionInfoEx nlsVersion = new Interop.Kernel32.NlsVersionInfoEx();
nlsVersion.dwNLSVersionInfoSize = Marshal.SizeOf(typeof(Interop.Kernel32.NlsVersionInfoEx));
Interop.Kernel32.GetNLSVersionEx(Interop.Kernel32.COMPARE_STRING, _sortName, &nlsVersion);
return new SortVersion(
nlsVersion.dwNLSVersion,
nlsVersion.dwEffectiveId == 0 ? LCID : nlsVersion.dwEffectiveId,
nlsVersion.guidCustomVersion);
}
#if CORECLR
// Get a locale sensitive sort hash code from native code -- COMNlsInfo::InternalGetGlobalizedHashCode
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern int InternalGetGlobalizedHashCode(IntPtr handle, string localeName, string source, int length, int dwFlags);
#endif
}
}
| |
#region --- License & Copyright Notice ---
/*
Copyright (c) 2005-2012 Jeevan James
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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Id3.Frames;
using Id3.Internal;
namespace Id3.Id3v2
{
internal sealed partial class Id3v23Handler : Id3v2Handler
{
internal override void DeleteTag(Stream stream)
{
if (!HasTag(stream))
return;
var buffer = new byte[BufferSize];
int tagSize = GetTagSize(stream);
int readPos = tagSize, writePos = 0;
int bytesRead;
do
{
stream.Seek(readPos, SeekOrigin.Begin);
bytesRead = stream.Read(buffer, 0, BufferSize);
if (bytesRead == 0)
continue;
stream.Seek(writePos, SeekOrigin.Begin);
stream.Write(buffer, 0, bytesRead);
readPos += bytesRead;
writePos += bytesRead;
} while (bytesRead == BufferSize);
stream.SetLength(stream.Length - tagSize);
stream.Flush();
}
internal override byte[] GetTagBytes(Stream stream)
{
if (!HasTag(stream))
return null;
var sizeBytes = new byte[4];
stream.Seek(6, SeekOrigin.Begin);
stream.Read(sizeBytes, 0, 4);
int tagSize = SyncSafeNumber.DecodeSafe(sizeBytes, 0, 4);
var tagBytes = new byte[tagSize + 10];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(tagBytes, 0, tagBytes.Length);
return tagBytes;
}
internal override bool HasTag(Stream stream)
{
stream.Seek(0, SeekOrigin.Begin);
var headerBytes = new byte[5];
stream.Read(headerBytes, 0, 5);
string magic = AsciiEncoding.GetString(headerBytes, 0, 3);
return magic == "ID3" && headerBytes[3] == 3;
}
internal override Id3Tag ReadTag(Stream stream)
{
if (!HasTag(stream))
return null;
var tag = new Id3Tag {
MajorVersion = 2,
MinorVersion = 3,
Family = Id3TagFamily.Version2x,
IsSupported = true,
};
stream.Seek(4, SeekOrigin.Begin);
var headerBytes = new byte[6];
stream.Read(headerBytes, 0, 6);
var headerContainer = new Id3v2Header();
tag.AdditionalData = headerContainer;
byte flags = headerBytes[1];
var header = new Id3v2StandardHeader {
Revision = headerBytes[0],
Unsyncronization = (flags & 0x80) > 0,
ExtendedHeader = (flags & 0x40) > 0,
Experimental = (flags & 0x20) > 0
};
headerContainer.Header = header;
int tagSize = SyncSafeNumber.DecodeSafe(headerBytes, 2, 4);
var tagData = new byte[tagSize];
stream.Read(tagData, 0, tagSize);
int currentPos = 0;
if (header.ExtendedHeader)
{
SyncSafeNumber.DecodeSafe(tagData, currentPos, 4);
currentPos += 4;
var extendedHeader = new Id3v2ExtendedHeader {
PaddingSize = SyncSafeNumber.DecodeNormal(tagData, currentPos + 2, 4)
};
if ((tagData[currentPos] & 0x80) > 0)
{
extendedHeader.Crc32 = SyncSafeNumber.DecodeNormal(tagData, currentPos + 6, 4);
currentPos += 10;
} else
currentPos += 6;
headerContainer.ExtendedHeader = extendedHeader;
}
while (currentPos < tagSize && tagData[currentPos] != 0x00)
{
string frameId = AsciiEncoding.GetString(tagData, currentPos, 4);
currentPos += 4;
int frameSize = SyncSafeNumber.DecodeNormal(tagData, currentPos, 4);
currentPos += 4;
var frameFlags = (ushort)((tagData[currentPos] << 0x08) + tagData[currentPos + 1]);
currentPos += 2;
var frameData = new byte[frameSize];
Array.Copy(tagData, currentPos, frameData, 0, frameSize);
FrameHandler mapping = FrameHandlers[frameId];
if (!(mapping == null || mapping.Decoder==null))
{
Id3Frame frame = mapping.Decoder(frameData);
tag.Frames.Add(frame);
}
currentPos += frameSize;
}
return tag;
}
internal override bool WriteTag(Stream stream, Id3Tag tag)
{
byte[] tagBytes = GetTagBytes(tag);
int requiredTagSize = tagBytes.Length;
if (HasTag(stream))
{
int currentTagSize = GetTagSize(stream);
if (requiredTagSize > currentTagSize)
MakeSpaceForTag(stream, currentTagSize, requiredTagSize);
} else
MakeSpaceForTag(stream, 0, requiredTagSize);
stream.Seek(0, SeekOrigin.Begin);
stream.Write(tagBytes, 0, requiredTagSize);
stream.Flush();
return true;
}
internal override int MinorVersion
{
get { return 3; }
}
protected override void BuildFrameHandlers(FrameHandlers mappings)
{
mappings.Add<AlbumFrame>("TALB", EncodeAlbum, DecodeAlbum);
mappings.Add<ArtistsFrame>("TPE1", EncodeArtists, DecodeArtists);
mappings.Add<ArtistUrlFrame>("WOAR", EncodeArtistUrl, DecodeArtistUrl);
//mappings.Add<AudioEncryptionFrame>("AENC", null, null);
mappings.Add<AudioFileUrlFrame>("WOAF", EncodeAudioFileUrl, DecodeAudioFileUrl);
mappings.Add<AudioSourceUrlFrame>("WOAS", EncodeAudioSourceUrl, DecodeAudioSourceUrl);
mappings.Add<BandFrame>("TPE2", EncodeBand, DecodeBand);
mappings.Add<BeatsPerMinuteFrame>("TBPM", EncodeBeatsPerMinute, DecodeBeatsPerMinute);
mappings.Add<CommentFrame>("COMM", EncodeComment, DecodeComment);
//mappings.Add<CommercialFrame>("COMR", null, null);
mappings.Add<CommercialUrlFrame>("WCOM", EncodeCommercialUrl, DecodeCommercialUrl);
mappings.Add<ComposersFrame>("TCOM", EncodeComposers, DecodeComposers);
mappings.Add<ConductorFrame>("TPE3", EncodeConductor, DecodeConductor);
mappings.Add<ContentGroupDescriptionFrame>("TIT1", EncodeContentGroupDescription, DecodeContentGroupDescription);
mappings.Add<CopyrightFrame>("TCOP", null, null);
mappings.Add<CopyrightUrlFrame>("WCOP", EncodeCopyrightUrl, DecodeCopyrightUrl);
mappings.Add<CustomTextFrame>("TXXX", EncodeCustomText, DecodeCustomText);
mappings.Add<CustomUrlLinkFrame>("WXXX", EncodeCustomUrlLink, DecodeCustomUrlLink);
mappings.Add<EncoderFrame>("TENC", EncodeEncoder, DecodeEncoder);
mappings.Add<EncodingSettingsFrame>("TSSE", EncodeEncodingSettings, DecodeEncodingSettings);
//mappings.Add<EncryptionMethodRegistrationFrame>("ENCR", null, null);
//mappings.Add<EqualizationFrame>("EQUA", null, null);
//mappings.Add<EventTimingCodesFrame>("ETCO", null, null);
mappings.Add<FileOwnerFrame>("TOWN", EncodeFileOwner, DecodeFileOwner);
mappings.Add<FileTypeFrame>("TFLT", null, null);
//mappings.Add<GeneralEncapsulationObjectFrame>("GEOB", null, null);
mappings.Add<GenreFrame>("TCON", EncodeGenre, DecodeGenre);
//mappings.Add<GroupIdentificationRegistrationFrame>("GRID", null, null);
//mappings.Add<InitialKeyFrame>("TKEY", null, null);
//mappings.Add<InvolvedPeopleFrame>("IPLS", null, null);
//mappings.Add<LanguagesFrame>("TLAN", null, null);
mappings.Add<LengthFrame>("TLEN", null, null);
//mappings.Add<LinkedInformationFrame>("LINK", null, null);
mappings.Add<LyricistsFrame>("TEXT", null, null);
mappings.Add<LyricsFrame>("USLT", EncodeLyrics, DecodeLyrics);
//mappings.Add<MediaTypeFrame>("TMED", null, null);
//mappings.Add<ModifiersFrame>("TPE4", null, null);
//mappings.Add<MusicCDIdentifierFrame>("MCDI", null, null);
//mappings.Add<MPEGLocationLookupTableFrame>("MLLT", null, null);
//mappings.Add<OriginalAlbumFrame>("TOAL", null, null);
//mappings.Add<OriginalArtistsFrame>("TOPE", null, null);
//mappings.Add<OriginalFilenameFrame>("TOFN", null, null);
//mappings.Add<OriginalLyricistFrame>("TOLY", null, null);
//mappings.Add<OriginalReleaseYearFrame>("TORY", null, null);
//mappings.Add<OwnershipFrame>("OWNE", null, null);
//mappings.Add<PartOfASetFrame>("TPOS", null, null);
mappings.Add<PaymentUrlFrame>("WPAY", EncodePaymentUrl, DecodePaymentUrl);
mappings.Add<PictureFrame>("APIC", EncodePicture, DecodePicture);
//mappings.Add<PlayCounterFrame>("PCNT", null, null);
//mappings.Add<PlaylistDelayFrame>("TDLY", null, null);
//mappings.Add<PopularimeterFrame>("POPM", null, null);
//mappings.Add<PositionSynchronizationFrame>("POSS", null, null);
mappings.Add<PrivateFrame>("PRIV", EncodePrivate, DecodePrivate);
mappings.Add<PublisherFrame>("TPUB", EncodePublisher, DecodePublisher);
//mappings.Add<PublisherUrlFrame>("WPUB", null, null);
//mappings.Add<RadioStationNameFrame>("TRSN", null, null);
//mappings.Add<RadioStationOwnerFrame>("TRSO", null, null);
//mappings.Add<RadioStationUrlFrame>("WORS", null, null);
//mappings.Add<RecommendedBufferSizeFrame>("RBUF", null, null);
mappings.Add<RecordingDateFrame>("TDAT", EncodeRecordingDate, DecodeRecordingDate);
//mappings.Add<RecordingDatesFrame>("TRDA", null, null);
//mappings.Add<RelativeVolumeAdjustmentFrame>("RVAD", null, null);
//mappings.Add<ReverbFrame>("RVRB", null, null);
//mappings.Add<SizeFrame>("TSIZ", null, null);
//mappings.Add<StandardRecordingCodeFrame>("TSRC", null, null);
mappings.Add<SubtitleFrame>("TIT3", EncodeSubtitle, DecodeSubtitle);
//mappings.Add<SynchronizedTempoCodesFrame>("SYTC", null, null);
//mappings.Add<SynchronizedTextFrame>("SYLT", null, null);
//mappings.Add<TermsOfUseFrame>("USER", null, null);
//mappings.Add<TimeFrame>("TIME", null, null);
mappings.Add<TitleFrame>("TIT2", EncodeTitle, DecodeTitle);
mappings.Add<TrackFrame>("TRCK", EncodeTrack, DecodeTrack);
//mappings.Add<UniqueFileIDFrame>("UFID", null, null);
mappings.Add<YearFrame>("TYER", EncodeYear, DecodeYear);
}
private byte[] GetTagBytes(Id3Tag tag)
{
var bytes = new List<byte>();
bytes.AddRange(AsciiEncoding.GetBytes("ID3"));
bytes.AddRange(new byte[] { 3, 0, 0 });
foreach (Id3Frame frame in tag.Frames)
{
if (frame.IsAssigned)
{
FrameHandler mapping = FrameHandlers[frame.GetType()];
if (mapping != null)
{
byte[] frameBytes = mapping.Encoder(frame);
bytes.AddRange(AsciiEncoding.GetBytes(GetFrameIdFromFrame(frame)));
bytes.AddRange(SyncSafeNumber.EncodeNormal(frameBytes.Length));
bytes.AddRange(new byte[] {0, 0});
bytes.AddRange(frameBytes);
}
}
}
int framesSize = bytes.Count - 6;
bytes.InsertRange(6, SyncSafeNumber.EncodeSafe(framesSize));
return bytes.ToArray();
}
private static int GetTagSize(Stream stream)
{
stream.Seek(6, SeekOrigin.Begin);
var sizeBytes = new byte[4];
stream.Read(sizeBytes, 0, 4);
int tagSize = SyncSafeNumber.DecodeSafe(sizeBytes, 0, 4) + 10;
return tagSize;
}
private static void MakeSpaceForTag(Stream stream, int currentTagSize, int requiredTagSize)
{
if (currentTagSize >= requiredTagSize)
return;
int increaseRequired = requiredTagSize - currentTagSize;
var readPos = (int)stream.Length;
int writePos = readPos + increaseRequired;
stream.SetLength(writePos);
var buffer = new byte[BufferSize];
while (readPos > currentTagSize)
{
int bytesToRead = (readPos - BufferSize < currentTagSize) ? readPos - currentTagSize : BufferSize;
readPos -= bytesToRead;
stream.Seek(readPos, SeekOrigin.Begin);
stream.Read(buffer, 0, bytesToRead);
writePos -= bytesToRead;
stream.Seek(writePos, SeekOrigin.Begin);
stream.Write(buffer, 0, bytesToRead);
}
}
private const int BufferSize = 8192;
}
}
| |
<?cs include:"doctype.cs" ?>
<?cs include:"macros.cs" ?>
<html>
<?cs include:"head_tag.cs" ?>
<body class="<?cs var:class.since ?>">
<?cs include:"header.cs" ?>
<div class="g-unit" id="doc-content">
<div id="api-info-block">
<?cs # are there inherited members ?>
<?cs each:cl=class.inherited ?>
<?cs if:subcount(cl.methods) ?>
<?cs set:inhmethods = #1 ?>
<?cs /if ?>
<?cs if:subcount(cl.constants) ?>
<?cs set:inhconstants = #1 ?>
<?cs /if ?>
<?cs if:subcount(cl.fields) ?>
<?cs set:inhfields = #1 ?>
<?cs /if ?>
<?cs if:subcount(cl.attrs) ?>
<?cs set:inhattrs = #1 ?>
<?cs /if ?>
<?cs /each ?>
<div class="sum-details-links">
Summary:
<?cs if:subcount(class.inners) ?>
<a href="#nestedclasses">Nested Classes</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:subcount(class.attrs) ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#lattrs">XML Attrs</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:inhattrs ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#inhattrs">Inherited XML Attrs</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:subcount(class.enumConstants) ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#enumconstants">Enums</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:subcount(class.constants) ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#constants">Constants</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:inhconstants ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#inhconstants">Inherited Constants</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:subcount(class.fields) ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#lfields">Fields</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:inhfields ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#inhfields">Inherited Fields</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:subcount(class.ctors.public) ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#pubctors">Ctors</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:subcount(class.ctors.protected) ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#proctors">Protected Ctors</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:subcount(class.methods.public) ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#pubmethods">Methods</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:subcount(class.methods.protected) ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#promethods">Protected Methods</a>
<?cs set:linkcount = #1 ?>
<?cs /if ?>
<?cs if:inhmethods ?>
<?cs if:linkcount ?>| <?cs /if ?><a href="#inhmethods">Inherited Methods</a>
<?cs /if ?>
<?cs if:inhattrs || inhconstants || inhfields || inhmethods || subcount(class.subclasses.direct) || subcount(class.subclasses.indirect) ?>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
<?cs /if ?>
</div><!-- end sum-details-links -->
<div class="api-level">
<?cs call:since_tags(class) ?>
</div>
</div><!-- end api-info-block -->
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
<?cs var:class.scope ?>
<?cs var:class.static ?>
<?cs var:class.final ?>
<?cs var:class.abstract ?>
<?cs var:class.kind ?>
<h1><?cs var:class.name ?></h1>
<?cs set:colspan = subcount(class.inheritance) ?>
<?cs each:supr = class.inheritance ?>
<?cs if:colspan == 2 ?>
extends <?cs call:type_link(supr.short_class) ?><br/>
<?cs /if ?>
<?cs if:last(supr) && subcount(supr.interfaces) ?>
implements
<?cs each:t=supr.interfaces ?>
<?cs call:type_link(t) ?>
<?cs /each ?>
<?cs /if ?>
<?cs set:colspan = colspan-1 ?>
<?cs /each ?>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-<?cs var:class.since ?>">
<table class="jd-inheritance-table">
<?cs set:colspan = subcount(class.inheritance) ?>
<?cs each:supr = class.inheritance ?>
<tr>
<?cs loop:i = 1, (subcount(class.inheritance)-colspan), 1 ?>
<td class="jd-inheritance-space"> <?cs if:(subcount(class.inheritance)-colspan) == i ?> ↳<?cs /if ?></td>
<?cs /loop ?>
<td colspan="<?cs var:colspan ?>" class="jd-inheritance-class-cell"><?cs
if:colspan == 1
?><?cs call:class_name(class.qualifiedType) ?><?cs
else
?><?cs call:type_link(supr.class) ?><?cs
/if ?></td>
</tr>
<?cs set:colspan = colspan-1 ?>
<?cs /each ?>
</table>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<?cs if:subcount(class.subclasses.direct) ?>
<table class="jd-sumtable jd-sumtable-subclasses"><tr><td colspan="12" style="border:none;margin:0;padding:0;">
<?cs call:expando_trigger("subclasses-direct", "closed") ?>Known Direct Subclasses
<?cs call:expandable_class_list("subclasses-direct", class.subclasses.direct, "list") ?>
</td></tr></table>
<?cs /if ?>
<?cs if:subcount(class.subclasses.indirect) ?>
<table class="jd-sumtable jd-sumtable-subclasses"><tr><td colspan="12" style="border:none;margin:0;padding:0;">
<?cs call:expando_trigger("subclasses-indirect", "closed") ?>Known Indirect Subclasses
<?cs call:expandable_class_list("subclasses-indirect", class.subclasses.indirect, "list") ?>
</td></tr></table>
<?cs /if ?>
<div class="jd-descr">
<?cs call:deprecated_warning(class) ?>
<?cs if:subcount(class.descr) ?>
<h2>Class Overview</h2>
<p><?cs call:tag_list(class.descr) ?></p>
<?cs /if ?>
<?cs call:see_also_tags(class.seeAlso) ?>
</div><!-- jd-descr -->
<?cs # summary macros ?>
<?cs def:write_method_summary(methods, included) ?>
<?cs set:count = #1 ?>
<?cs each:method = methods ?>
<?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?>
<tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:method.since ?>" >
<td class="jd-typecol"><nobr>
<?cs var:method.abstract ?>
<?cs var:method.synchronized ?>
<?cs var:method.final ?>
<?cs var:method.static ?>
<?cs call:type_link(method.generic) ?>
<?cs call:type_link(method.returnType) ?></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><?cs call:cond_link(method.name, toroot, method.href, included) ?></span>(<?cs call:parameter_list(method.params) ?>)</nobr>
<?cs if:subcount(method.shortDescr) || subcount(method.deprecated) ?>
<div class="jd-descrdiv"><?cs call:short_descr(method) ?></div>
<?cs /if ?>
</td></tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs def:write_field_summary(fields, included) ?>
<?cs set:count = #1 ?>
<?cs each:field=fields ?>
<tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:field.since ?>" >
<td class="jd-typecol"><nobr>
<?cs var:field.scope ?>
<?cs var:field.static ?>
<?cs var:field.final ?>
<?cs call:type_link(field.type) ?></nobr></td>
<td class="jd-linkcol"><?cs call:cond_link(field.name, toroot, field.href, included) ?></td>
<td class="jd-descrcol" width="100%"><?cs call:short_descr(field) ?></td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs def:write_constant_summary(fields, included) ?>
<?cs set:count = #1 ?>
<?cs each:field=fields ?>
<tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:field.since ?>" >
<td class="jd-typecol"><?cs call:type_link(field.type) ?></td>
<td class="jd-linkcol"><?cs call:cond_link(field.name, toroot, field.href, included) ?></td>
<td class="jd-descrcol" width="100%"><?cs call:short_descr(field) ?></td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs def:write_attr_summary(attrs, included) ?>
<?cs set:count = #1 ?>
<tr>
<td><nobr><em>Attribute Name</em></nobr></td>
<td><nobr><em>Related Method</em></nobr></td>
<td><nobr><em>Description</em></nobr></td>
</tr>
<?cs each:attr=attrs ?>
<tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:attr.since ?>" >
<td class="jd-linkcol"><?cs if:included ?><a href="<?cs var:toroot ?><?cs var:attr.href ?>"><?cs /if ?><?cs var:attr.name ?><?cs if:included ?></a><?cs /if ?></td>
<td class="jd-linkcol"><?cs each:m=attr.methods ?>
<?cs call:cond_link(m.name, toroot, m.href, included) ?>
<?cs /each ?>
</td>
<td class="jd-descrcol" width="100%"><?cs call:short_descr(attr) ?> </td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs def:write_inners_summary(classes) ?>
<?cs set:count = #1 ?>
<?cs each:cl=class.inners ?>
<tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:cl.since ?>" >
<td class="jd-typecol"><nobr>
<?cs var:cl.scope ?>
<?cs var:cl.static ?>
<?cs var:cl.final ?>
<?cs var:cl.abstract ?>
<?cs var:cl.kind ?></nobr></td>
<td class="jd-linkcol"><?cs call:type_link(cl.type) ?></td>
<td class="jd-descrcol" width="100%"><?cs call:short_descr(cl) ?> </td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /def ?>
<?cs # end macros ?>
<div class="jd-descr">
<h2>Summary</h2>
<?cs if:subcount(class.inners) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ======== NESTED CLASS SUMMARY ======== -->
<table id="nestedclasses" class="jd-sumtable"><tr><th colspan="12">Nested Classes</th></tr>
<?cs call:write_inners_summary(class.inners) ?>
<?cs /if ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<?cs if:subcount(class.attrs) ?>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lattrs" class="jd-sumtable"><tr><th colspan="12">XML Attributes</th></tr>
<?cs call:write_attr_summary(class.attrs, 1) ?>
<?cs /if ?>
<?cs # if there are inherited attrs, write the table ?>
<?cs if:inhattrs ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== FIELD SUMMARY =========== -->
<table id="inhattrs" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited XML Attributes</div></th></tr>
<?cs each:cl=class.inherited ?>
<?cs if:subcount(cl.attrs) ?>
<tr class="api apilevel-<?cs var:cl.since ?>" >
<td colspan="12">
<?cs call:expando_trigger("inherited-attrs-"+cl.qualified, "closed") ?>From <?cs var:cl.kind ?>
<?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?>
<div id="inherited-attrs-<?cs var:cl.qualified ?>">
<div id="inherited-attrs-<?cs var:cl.qualified ?>-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-attrs-<?cs var:cl.qualified ?>-summary" style="display: none;">
<table class="jd-sumtable-expando">
<?cs call:write_attr_summary(cl.attrs, cl.included) ?></table>
</div>
</div>
</td></tr>
<?cs /if ?>
<?cs /each ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.enumConstants) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="enumconstants" class="jd-sumtable"><tr><th colspan="12">Enum Values</th></tr>
<?cs set:count = #1 ?>
<?cs each:field=class.enumConstants ?>
<tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:field.since ?>" >
<td class="jd-descrcol"><?cs call:type_link(field.type) ?> </td>
<td class="jd-linkcol"><?cs call:cond_link(field.name, toroot, field.href, cl.included) ?> </td>
<td class="jd-descrcol" width="100%"><?cs call:short_descr(field) ?> </td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
<?cs /if ?>
<?cs if:subcount(class.constants) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="constants" class="jd-sumtable"><tr><th colspan="12">Constants</th></tr>
<?cs call:write_constant_summary(class.constants, 1) ?>
</table>
<?cs /if ?>
<?cs # if there are inherited constants, write the table ?>
<?cs if:inhconstants ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="inhconstants" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Constants</div></th></tr>
<?cs each:cl=class.inherited ?>
<?cs if:subcount(cl.constants) ?>
<tr class="api apilevel-<?cs var:cl.since ?>" >
<td colspan="12">
<?cs call:expando_trigger("inherited-constants-"+cl.qualified, "closed") ?>From <?cs var:cl.kind ?>
<?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?>
<div id="inherited-constants-<?cs var:cl.qualified ?>">
<div id="inherited-constants-<?cs var:cl.qualified ?>-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-constants-<?cs var:cl.qualified ?>-summary" style="display: none;">
<table class="jd-sumtable-expando">
<?cs call:write_constant_summary(cl.constants, cl.included) ?></table>
</div>
</div>
</td></tr>
<?cs /if ?>
<?cs /each ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.fields) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr>
<?cs call:write_field_summary(class.fields, 1) ?>
</table>
<?cs /if ?>
<?cs # if there are inherited fields, write the table ?>
<?cs if:inhfields ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- =========== FIELD SUMMARY =========== -->
<table id="inhfields" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Fields</div></th></tr>
<?cs each:cl=class.inherited ?>
<?cs if:subcount(cl.fields) ?>
<tr class="api apilevel-<?cs var:cl.since ?>" >
<td colspan="12">
<?cs call:expando_trigger("inherited-fields-"+cl.qualified, "closed") ?>From <?cs var:cl.kind ?>
<?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?>
<div id="inherited-fields-<?cs var:cl.qualified ?>">
<div id="inherited-fields-<?cs var:cl.qualified ?>-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-fields-<?cs var:cl.qualified ?>-summary" style="display: none;">
<table class="jd-sumtable-expando">
<?cs call:write_field_summary(cl.fields, cl.included) ?></table>
</div>
</div>
</td></tr>
<?cs /if ?>
<?cs /each ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.ctors.public) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr>
<?cs call:write_method_summary(class.ctors.public, 1) ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.ctors.protected) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="proctors" class="jd-sumtable"><tr><th colspan="12">Protected Constructors</th></tr>
<?cs call:write_method_summary(class.ctors.protected, 1) ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.methods.public) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<?cs call:write_method_summary(class.methods.public, 1) ?>
</table>
<?cs /if ?>
<?cs if:subcount(class.methods.protected) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========== METHOD SUMMARY =========== -->
<table id="promethods" class="jd-sumtable"><tr><th colspan="12">Protected Methods</th></tr>
<?cs call:write_method_summary(class.methods.protected, 1) ?>
</table>
<?cs /if ?>
<?cs # if there are inherited methods, write the table ?>
<?cs if:inhmethods ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<?cs each:cl=class.inherited ?>
<?cs if:subcount(cl.methods) ?>
<tr class="api apilevel-<?cs var:cl.since ?>" >
<td colspan="12"><?cs call:expando_trigger("inherited-methods-"+cl.qualified, "closed") ?>
From <?cs var:cl.kind ?> <?cs call:cond_link(cl.qualified, toroot, cl.link, cl.included) ?>
<div id="inherited-methods-<?cs var:cl.qualified ?>">
<div id="inherited-methods-<?cs var:cl.qualified ?>-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-<?cs var:cl.qualified ?>-summary" style="display: none;">
<table class="jd-sumtable-expando">
<?cs call:write_method_summary(cl.methods, cl.included) ?></table>
</div>
</div>
</td></tr>
<?cs /if ?>
<?cs /each ?>
</table>
<?cs /if ?>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<?cs def:write_field_details(fields) ?>
<?cs each:field=fields ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<?cs # the A tag in the next line must remain where it is, so that Eclipse can parse the docs ?>
<A NAME="<?cs var:field.anchor ?>"></A>
<?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?>
<div class="jd-details api apilevel-<?cs var:field.since ?>">
<h4 class="jd-details-title">
<span class="normal">
<?cs var:field.scope ?>
<?cs var:field.static ?>
<?cs var:field.final ?>
<?cs call:type_link(field.type) ?>
</span>
<?cs var:field.name ?>
</h4>
<div class="api-level">
<?cs call:since_tags(field) ?>
</div>
<div class="jd-details-descr">
<?cs call:description(field) ?>
<?cs if:subcount(field.constantValue) ?>
<div class="jd-tagdata">
<span class="jd-tagtitle">Constant Value: </span>
<span>
<?cs if:field.constantValue.isString ?>
<?cs var:field.constantValue.str ?>
<?cs else ?>
<?cs var:field.constantValue.dec ?>
(<?cs var:field.constantValue.hex ?>)
<?cs /if ?>
</span>
</div>
<?cs /if ?>
</div>
</div>
<?cs /each ?>
<?cs /def ?>
<?cs def:write_method_details(methods) ?>
<?cs each:method=methods ?>
<?cs # the A tag in the next line must remain where it is, so that Eclipse can parse the docs ?>
<A NAME="<?cs var:method.anchor ?>"></A>
<?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?>
<div class="jd-details api apilevel-<?cs var:method.since ?>">
<h4 class="jd-details-title">
<span class="normal">
<?cs var:method.scope ?>
<?cs var:method.static ?>
<?cs var:method.final ?>
<?cs var:method.abstract ?>
<?cs var:method.synchronized ?>
<?cs call:type_link(method.returnType) ?>
</span>
<span class="sympad"><?cs var:method.name ?></span>
<span class="normal">(<?cs call:parameter_list(method.params) ?>)</span>
</h4>
<div class="api-level">
<?cs call:since_tags(method) ?>
</div>
<div class="jd-details-descr">
<?cs call:description(method) ?>
</div>
</div>
<?cs /each ?>
<?cs /def ?>
<?cs def:write_attr_details(attrs) ?>
<?cs each:attr=attrs ?>
<?cs # the A tag in the next line must remain where it is, so that Eclipse can parse the docs ?>
<A NAME="<?cs var:attr.anchor ?>"></A>
<?cs # The apilevel-N class MUST BE LAST in the sequence of class names ?>
<div class="jd-details api apilevel-<?cs var:attr.since ?>">
<h4 class="jd-details-title"><?cs var:attr.name ?>
</h4>
<div class="api-level">
<?cs call:since_tags(attr) ?>
</div>
<div class="jd-details-descr">
<?cs call:description(attr) ?>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Related Methods</h5>
<ul class="nolist">
<?cs each:m=attr.methods ?>
<li><a href="<?cs var:toroot ?><?cs var:m.href ?>"><?cs var:m.name ?></a></li>
<?cs /each ?>
</ul>
</div>
</div>
</div>
<?cs /each ?>
<?cs /def ?>
<!-- XML Attributes -->
<?cs if:subcount(class.attrs) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= FIELD DETAIL ======== -->
<h2>XML Attributes</h2>
<?cs call:write_attr_details(class.attrs) ?>
<?cs /if ?>
<!-- Enum Values -->
<?cs if:subcount(class.enumConstants) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= ENUM CONSTANTS DETAIL ======== -->
<h2>Enum Values</h2>
<?cs call:write_field_details(class.enumConstants) ?>
<?cs /if ?>
<!-- Constants -->
<?cs if:subcount(class.constants) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= ENUM CONSTANTS DETAIL ======== -->
<h2>Constants</h2>
<?cs call:write_field_details(class.constants) ?>
<?cs /if ?>
<!-- Fields -->
<?cs if:subcount(class.fields) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= FIELD DETAIL ======== -->
<h2>Fields</h2>
<?cs call:write_field_details(class.fields) ?>
<?cs /if ?>
<!-- Public ctors -->
<?cs if:subcount(class.ctors.public) ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2>Public Constructors</h2>
<?cs call:write_method_details(class.ctors.public) ?>
<?cs /if ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<?cs if:subcount(class.ctors.protected) ?>
<h2>Protected Constructors</h2>
<?cs call:write_method_details(class.ctors.protected) ?>
<?cs /if ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<?cs if:subcount(class.methods.public) ?>
<h2>Public Methods</h2>
<?cs call:write_method_details(class.methods.public) ?>
<?cs /if ?>
<?cs # this next line must be exactly like this to be parsed by eclipse ?>
<!-- ========= METHOD DETAIL ======== -->
<?cs if:subcount(class.methods.protected) ?>
<h2>Protected Methods</h2>
<?cs call:write_method_details(class.methods.protected) ?>
<?cs /if ?>
<?cs # the next two lines must be exactly like this to be parsed by eclipse ?>
<!-- ========= END OF CLASS DATA ========= -->
<A NAME="navbar_top"></A>
<?cs include:"footer.cs" ?>
</div> <!-- jd-content -->
</div><!-- end doc-content -->
<?cs include:"trailer.cs" ?>
</body>
</html>
| |
namespace Epi
{
/// <summary>
/// String constants for various commands
/// </summary>
public static class CommandNames
{
/// <summary>
/// ABS absolute value numeric function
/// </summary>
public const string ABS = "ABS";
/// <summary>
/// AND logical operator
/// </summary>
public const string AND = "AND";
/// <summary>
/// ALWAYS key word used with AUTOSEARCH command to run search on existing records as well as new.
/// </summary>
public const string ALWAYS = "ALWAYS";
/// <summary>
/// Append data when exporting
/// </summary>
public const string APPEND = "APPEND";
/// <summary>
/// Sort data in descending order
/// </summary>
public const string ASCENDING = "ASCENDING";
/// <summary>
/// Assign a value or the result of an expression to a defined variable
/// </summary>
///
public const string ASSIGN = "ASSIGN";
/// <summary>
/// Autosearches particular field(s)
/// </summary>
public const string AUTOSEARCH = "AUTOSEARCH";
/// <summary>
/// Generate a beep
/// </summary>
public const string BEEP = "BEEP";
/// <summary>
/// Calls a definded sub-routine
/// </summary>
public const string CALL = "CALL";
/// <summary>
/// Cancels the current select command
/// </summary>
public const string CANCELSELECT = "SELECT";
/// <summary>
/// Cancels the current sort command
/// </summary>
public const string CANCELSORT = "SORT";
/// <summary>
/// Clears a field(s)
/// </summary>
public const string CLEAR = "CLEAR";
/// <summary>
/// Stops routing the current output to the specified output file
/// </summary>
public const string CLOSEOUT = "CLOSEOUT";
/// <summary>
/// Column size for output of analysis command tables.
/// </summary>
public const string COLUMNSIZE = "COLUMNSIZE";
/// <summary>
/// COS numeric function
/// </summary>
public const string COS = "COS";
/// <summary>
/// Cox Proportional Hazards
/// </summary>
public const string COXPH = "COXPH";
/// <summary>
/// Currency parameter of FORMAT function
/// </summary>
public const string CURRENCY_FORMAT = "\"Currency\"";
/// <summary>
/// System function returning the Current User signed in
/// </summary>
public const string CURRENTUSER = "CURRENTUSER";
/// <summary>
/// Dialog format Database list
/// </summary>
public const string DATABASES = "DATABASES";
/// <summary>
/// DAY date function
/// </summary>
public const string DAY = "DAY";
/// <summary>
/// DAYS date function
/// </summary>
public const string DAYS = "DAYS";
/// <summary>
/// Used in Dialog command
/// </summary>
public const string DBVALUES = "DBVALUES";
/// <summary>
/// Display database variables
/// </summary>
public const string DBVARIABLES = "DBVARIABLES";
/// <summary>
/// Dialog format Views list and Display Views
/// </summary>
public const string DBVIEWS = "DBVIEWS";
/// <summary>
/// Sort data in descending order
/// </summary>
public const string DESCENDING = "DESCENDING";
/// <summary>
/// Define a variable of standard, global or permanent scope
/// </summary>
public const string DEFINE = "DEFINE";
/// <summary>
/// Delete table, file or records
/// </summary>
public const string DELETE = "DELETE";
/// <summary>
/// Creates a dialog box
/// </summary>
public const string DIALOG = "DIALOG";
/// <summary>
/// Command to disable a field
/// </summary>
public const string DISABLE = "DISABLE";
/// <summary>
/// Command to send the current output file to the default Display
/// </summary>
public const string DISPLAY = "DISPLAY";
/// <summary>
/// Command to display only selected fields in AUTOSEARCH results; Used with AUTOSEARCH command
/// </summary>
public const string DISPLAYLIST = "DISPLAYLIST";
/// <summary>
/// Else of If command
/// </summary>
public const string ELSE = "ELSE";
/// <summary>
/// Command to enable a field
/// </summary>
public const string ENABLE = "ENABLE";
/// <summary>
/// End of If command
/// </summary>
public const string END = "END";
/// <summary>
/// ENVIRON system function
/// </summary>
public const string ENVIRON = "ENVIRON";
/// <summary>
/// EPIWEEK date function
/// </summary>
public const string EPIWEEK = "EPIWEEK";
/// <summary>
/// Columns excluded from the List command
/// </summary>
public const string EXCEPT = "EXCEPT";
/// <summary>
/// Executes a program
/// </summary>
public const string EXECUTE = "EXECUTE";
/// <summary>
/// EXISTS system function
/// </summary>
public const string EXISTS = "EXISTS";
/// <summary>
/// Exits Analysis
/// </summary>
public const string EXIT = "EXIT";
/// <summary>
/// EXP exponentiation numeric function
/// </summary>
public const string EXP = "EXP";
/// <summary>
/// FIELDVAR, used is DISPLAY DBVARIABLES
/// </summary>
public const string FIELDVAR = "FIELDVAR";
/// <summary>
/// FILEDATE system function
/// </summary>
public const string FILEDATE = "FILEDATE";
/// <summary>
/// FINDTEXT text function
/// </summary>
public const string FINDTEXT = "FINDTEXT";
/// <summary>
/// Fixed parameter of FORMAT function
/// </summary>
public const string FIXED_FORMAT = "\"Fixed\"";
/// <summary>
/// Computes the frequency of any column(s) in the current dataset or a user defined standard variable(s)
/// </summary>
public const string FREQ = "FREQ";
/// <summary>
/// Frequency Graph Command
/// </summary>
public const string FREQGRAPH = "FREQGRAPH";
/// <summary>
/// FORMAT text function
/// </summary>
public const string FORMAT = "FORMAT";
/// <summary>
/// General Date parameter of FORMAT function
/// </summary>
public const string GENERAL_DATE_FORMAT = "\"General Date\"";
/// <summary>
/// General Number parameter of FORMAT function
/// </summary>
public const string GENERAL_NUMBER_FORMAT = "\"General Number\"";
/// <summary>
/// Sets the focus on a page, field or new record
/// </summary>
public const string GOTO = "GOTO";
/// <summary>
///
/// </summary>
public const string GRAPH = "GRAPH";
/// <summary>
/// Type of graph to be displayed following CoxPH, KMSurvival, etc.
/// </summary>
public const string GRAPHTYPE = "GRAPHTYPE";
/// <summary>
/// Data is displayed as a grid in the List command
/// </summary>
public const string GRIDTABLE = "GRIDTABLE";
/// <summary>
/// Constant for "Define Group" Command
/// </summary>
public const string GROUPVAR = "GROUPVAR";
/// <summary>
/// Creates a header in the output .HTM document
/// </summary>
public const string HEADER = "HEADER";
/// <summary>
/// Opens a .HTM or .CHM help document
/// </summary>
public const string HELP = "HELP";
/// <summary>
/// Hides field(s)
/// </summary>
public const string HIDE = "HIDE";
/// <summary>
/// Highlight a field
/// </summary>
public const string HIGHLIGHT = "HIGHLIGHT";
/// <summary>
/// Highest value
/// </summary>
public const string HIVALUE = "HIVALUE";
/// <summary>
/// HOUR time function
/// </summary>
public const string HOUR = "HOUR";
/// <summary>
/// HOURS time function
/// </summary>
public const string HOURS = "HOURS";
/// <summary>
/// Hyperlinks Command
/// </summary>
public const string HYPERLINKS = "HYPERLINKS";
/// <summary>
/// Perform a command or a set of commands conditionally
/// </summary>
public const string IF = "IF";
/// <summary>
/// Kaplan-Meier Survival
/// </summary>
public const string KMSURVIVAL = "KMSURVIVAL";
/// <summary>
/// String comparison operator LIKE that compares strings that have LIKE wildcard characters (*).
/// </summary>
public const string LIKE = "LIKE";
/// <summary>
/// Line Break text function
/// </summary>
public const string LINEBREAK = "LINEBREAK";
/// <summary>
/// Lists values of column(s) or user defined standard variable(s) in the current dataset
/// </summary>
public const string LIST = "LIST";
/// <summary>
/// LN (natural log) numeric function
/// </summary>
public const string LN = "LN";
/// <summary>
/// LOG (decimal log) numeric function
/// </summary>
public const string LOG = "LOG";
/// <summary>
/// Logistic regression command
/// </summary>
public const string LOGISTIC = "LOGISTIC";
/// <summary>
/// Long Date parameter of FORMAT function
/// </summary>
public const string LONG_DATE_FORMAT = "\"Long Date\"";
/// <summary>
/// Long Time parameter of FORMAT function
/// </summary>
public const string LONG_TIME_FORMAT = "\"Long Time\"";
/// <summary>
/// Lowest value
/// </summary>
public const string LOVALUE = "LOVALUE";
/// <summary>
/// Performs a matched analysis of specified exposure and outcome variables
/// </summary>
public const string MATCH = "MATCH";
/// <summary>
/// Matched analysis
/// </summary>
public const string MATCHVAR = "MATCHVAR";
/// <summary>
/// Means command
/// </summary>
public const string MEANS = "MEANS";
/// <summary>
/// Merge command
/// </summary>
public const string MERGE = "MERGE";
/// <summary>
/// MINUTE time function
/// </summary>
public const string MINUTE = "MINUTE";
/// <summary>
/// MINUTES time function
/// </summary>
public const string MINUTES = "MINUTES";
/// <summary>
/// Missing command
/// </summary>
public const string MISSING = "MISSING";
/// <summary>
/// MOD function (modulus or remainder)
/// </summary>
public const string MOD = "MOD";
/// <summary>
/// MONTH date function
/// </summary>
public const string MONTH = "MONTH";
/// <summary>
/// MONTHS date function
/// </summary>
public const string MONTHS = "MONTHS";
/// <summary>
/// Creates a new record
/// </summary>
public const string NEWRECORD = "NEWRECORD";
/// <summary>
/// No Intercept in Logistic Regression
/// </summary>
public const string NOINTERCEPT = "NOINTERCEPT";
/// <summary>
/// NOT logical operator
/// </summary>
public const string NOT = "NOT";
/// <summary>
/// Do not wait for program to exit
/// </summary>
public const string NOWAITFOREXIT = "NOWAITFOREXIT";
/// <summary>
/// Prevents line breaks from being inserted in Analysis output so columns as wide as longest line.
/// </summary>
public const string NOWRAP = "NOWRAP";
/// <summary>
/// NUMTODATE numeric function
/// </summary>
public const string NUMTODATE = "NUMTODATE";
/// <summary>
/// NUMTOTIME numeric function
/// </summary>
public const string NUMTOTIME = "NUMTOTIME";
/// <summary>
/// On/Off parameter of FORMAT function
/// </summary>
public const string ON_OFF_FORMAT = "\"On/Off\"";
/// <summary>
/// OR logical operator
/// </summary>
public const string OR = "OR";
/// <summary>
/// for specifying the output 'table'
/// </summary>
public const string OUTTABLE = "OUTTABLE";
/// <summary>
/// Percent number parameter of FORMAT function
/// </summary>
public const string PERCENT_FORMAT = "\"Percent\"";
/// <summary>
/// Percents command
/// </summary>
public const string PERCENTS = "PERCENTS";
/// <summary>
/// Scope of the defined variable is permanent
/// </summary>
public const string PERMANENT = "PERMANENT";
/// <summary>
/// Command to calculate the P value from the Z-score
/// </summary>
public const string PFROMZ = "PFROMZ";
/// <summary>
/// Command to send the current output file to the default printer
/// </summary>
public const string PRINTOUT = "PRINTOUT";
/// <summary>
/// For SET PROCESS = (undeleted, deleted, both) records.
/// </summary>
public const string PROCESS = "PROCESS";
/// <summary>
/// Variable for the Primary Sampling Unit (PSU) in Complex Sample commands.
/// </summary>
public const string PSUVAR = "PSUVAR";
/// <summary>
/// Variable for the Primary Sampling Unit (PSU) in Complex Sample commands.
/// </summary>
public const string PVALUE = "PVALUE";
/// <summary>
/// Command to exit Analysis module
/// </summary>
public const string QUIT = "QUIT";
/// <summary>
/// Command to read project data from an Access 97, Access 2000, SQL Server 2000 or MSDE 2000 database
/// </summary>
public const string READ = "READ";
/// <summary>
/// Translates data in a column or a standard variable to another column or standard variable
/// </summary>
public const string RECODE = "RECODE";
/// <summary>
/// Command to return the current count of saved records (not counting * new record)
/// </summary>
public const string RECORDCOUNT = "RECORDCOUNT";
/// <summary>
/// Linear regression command
/// </summary>
public const string REGRESS = "REGRESS";
/// <summary>
/// Replaces an existing output file or an output table while exporting data
/// </summary>
public const string REPLACE = "REPLACE";
/// <summary>
/// Join tables.
/// </summary>
public const string RELATE = "RELATE";
/// <summary>
/// RND (random) numeric function
/// </summary>
public const string RND = "RND";
/// <summary>
/// Report command keyword
/// </summary>
public const string REPORT = "REPORT";
/// <summary>
/// ROUND numeric function
/// </summary>
public const string ROUND = "ROUND";
/// <remarks>If no output is selected Epi Info will create a new file with a sequential number.</remarks>
/// <example>ROUTEOUT 'D:\EPIInfo\Monthly_Report.htm' REPLACE</example>
/// </summary>
public const string ROUTEOUT = "ROUTEOUT";
/// <summary>
/// Runs an existing program
/// </summary>
public const string RUNPGM = "RUNPGM";
/// <summary>
/// No confirmatory messages will be displayed
/// </summary>
public const string RUNSILENT = "RUNSILENT";
/// <summary>
/// Data tables will not be deleted
/// </summary>
public const string SAVEDATA = "SAVEDATA";
/// <summary>
/// Scientific number parameter of FORMAT function
/// </summary>
public const string SCIENTIFIC_FORMAT = "\"Scientific\"";
/// <summary>
/// SECOND time function
/// </summary>
public const string SECOND = "SECOND";
/// <summary>
/// SECONDS time function
/// </summary>
public const string SECONDS = "SECONDS";
/// <summary>
/// Selects only the records that match the specified expression
/// </summary>
public const string SELECT = "SELECT";
/// <summary>
/// Sets various options that affect the performance and output of Analysis
/// </summary>
public const string SET = "SET";
/// <summary>
/// Sets the attribute required = true for one or more fields in Check Code.
/// </summary>
public const string SET_REQUIRED = "SET-REQUIRED";
/// <summary>
/// Sets the attribute required = false for one or more fields in Check Code.
/// </summary>
public const string SET_NOT_REQUIRED = "SET-NOT-REQUIRED";
/// <summary>
/// Short Date parameter of FORMAT function
/// </summary>
public const string SHORT_DATE_FORMAT = "\"Short Date\"";
/// <summary>
/// Short Time parameter of FORMAT function
/// </summary>
public const string SHORT_TIME_FORMAT = "\"Short Time\"";
/// <summary>
/// Show prompts command
/// </summary>
public const string SHOWPROMPTS = "SHOWPROMPTS";
/// <summary>
/// SIN numeric function
/// </summary>
public const string SIN = "SIN";
/// <summary>
/// Sorts the data in the current dataset by columns or variables and sort order specified
/// </summary>
public const string SORT = "SORT";
/// <summary>
/// Standard number parameter of FORMAT function
/// </summary>
public const string STANDARD_FORMAT = "\"Standard\"";
/// <summary>
/// Statistics Command
/// </summary>
public const string STATISTICS = "STATISTICS";
/// <summary>
/// Step Command
/// </summary>
public const string STEP = "STEP";
/// <summary>
/// Stratify by the variable
/// </summary>
public const string STRATAVAR = "STRATAVAR";
///<summary>
/// STRLEN text function
///</summary>
public const string STRLEN = "STRLEN";
///<summary>
/// SUBSTRING text function
///</summary>
public const string SUBSTRING = "SUBSTRING";
/// <summary>
/// Computes the aggregates of a column in the current dataset or a standard variable
/// </summary>
public const string SUMMARIZE = "SUMMARIZE";
/// <summary>
/// SYSTEMDATE system function
/// </summary>
public const string SYSTEMDATE = "SYSTEMDATE";
/// <summary>
/// SYSTEMTIME system function
/// </summary>
public const string SYSTEMTIME = "SYSTEMTIME";
/// <summary>
/// Performs a cross-tabulation of the specified exposure and outcome variables
/// </summary>
public const string TABLES = "TABLES";
/// <summary>
/// TAN numeric function
/// </summary>
public const string TAN = "TAN";
/// <summary>
/// A dialogs title text
/// </summary>
public const string TITLETEXT = "TITLETEXT";
/// <summary>
/// TYPEOUT Command font modifier.
/// </summary>
public const string TEXTFONT = "TEXTFONT";
/// <summary>
/// The THEN Command
/// </summary>
public const string THEN = "THEN";
/// <summary>
/// Unit of time used for graphs following CoxPH, KMSurvival, etc.
/// </summary>
public const string TIMEUNIT = "TIMEUNIT";
/// <summary>
/// In Summarize command, the table to which output is written
/// </summary>
public const string TO = "TO";
/// <summary>
/// True/False parameter of FORMAT function
/// </summary>
public const string TRUE_FALSE_FORMAT = "\"True/False\"";
/// <summary>
/// TRUNC (truncate) numeric function
/// </summary>
public const string TRUNC = "TRUNC";
/// <summary>
/// The TYPEOUT Command inserts text, either a string or the
/// contents of a file, into the output.
/// <remarks>Typical uses might include comments or boilerplate.</remarks>
/// <example>TYPEOUT 'My Fancy Logo.htm'</example>
/// </summary>
public const string TYPEOUT = "TYPEOUT";
/// <summary>
/// TXTTODATE text function
/// </summary>
public const string TXTTODATE = "TXTTODATE";
/// <summary>
/// TXTTONUM text function
/// </summary>
public const string TXTTONUM = "TXTTONUM";
/// <summary>
/// Undefine a defined variable
/// </summary>
public const string UNDEFINE = "UNDEFINE";
/// <summary>
/// Undelete records that were marked as deleted
/// </summary>
public const string UNDELETE = "UNDELETE";
/// <summary>
/// Unhide field(s)
/// </summary>
public const string UNHIDE = "UNHIDE";
/// <summary>
/// Unhighlight a field
/// </summary>
public const string UNHIGHLIGHT = "UNHIGHLIGHT";
/// <summary>
/// Allows update of data in the List command
/// </summary>
public const string UPDATE = "UPDATE";
/// <summary>
/// UPPERCASE text function
/// </summary>
public const string UPPERCASE = "UPPERCASE";
/// <summary>
/// Wait for program to exit
/// </summary>
public const string WAITFOREXIT = "WAITFOREXIT";
/// <summary>
/// Weight variable
/// </summary>
public const string WEIGHTVAR = "WEIGHTVAR";
/// <summary>
/// Export the data to an output table in the current project or a different project
/// </summary>
public const string WRITE = "WRITE";
/// <summary>
/// XOR--exclusive OR logical operator
/// </summary>
public const string XOR = "XOR";
/// <summary>
/// Yes/No number parameter of FORMAT function
/// </summary>
public const string YESNO_FORMAT = "\"Yes/No\"";
/// <summary>
/// A dialog format in Dialog command
/// </summary>
public const string YN = "YN";
/// <summary>
/// YEAR date function
/// </summary>
public const string YEAR = "YEAR";
/// <summary>
/// YEARS date function
/// </summary>
public const string YEARS = "YEARS";
/// <summary>
/// ZSCORE numeric function
/// </summary>
public const string ZSCORE = "ZSCORE";
}
}
| |
using EIDSS.Reports.Parameterized.Human.GG.DataSet;
using EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthDataSetTableAdapters;
using EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewDataSetTableAdapters;
using EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewHeaderDataSetTableAdapters;
namespace EIDSS.Reports.Parameterized.Human.GG.Report
{
partial class InfectiousDiseasesMonthNew
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InfectiousDiseasesMonthNew));
DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary();
this.tableCustomHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell84 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.EnTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell75 = new DevExpress.XtraReports.UI.XRTableCell();
this.InfectiousDiseaseHeaderDataSet = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewHeaderDataSet();
this.xrTableCell85 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell86 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell87 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell80 = new DevExpress.XtraReports.UI.XRTableCell();
this.EnTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell81 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell82 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell83 = new DevExpress.XtraReports.UI.XRTableCell();
this.GgTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell88 = new DevExpress.XtraReports.UI.XRTableCell();
this.GgTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell89 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell92 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell93 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell95 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell97 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell90 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell91 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow23 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell70 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow21 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellNameOfrespondent = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellActualAddress = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellTelephone = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellReportedPeriod = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.InfectiousDiseaseDataSet = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewDataSet();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.tableCustomFooter = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.DayFooterCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.MonthFooterCell = new DevExpress.XtraReports.UI.XRTableCell();
this.YearFooterCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.ChiefFooterCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow25 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell79 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.tableBody = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell71 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell67 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell72 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell68 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell69 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell65 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.CustomDetail = new DevExpress.XtraReports.UI.DetailBand();
this.PageBreakAtLine36 = new DevExpress.XtraReports.UI.XRPageBreak();
this.formattingRule2 = new DevExpress.XtraReports.UI.FormattingRule();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.formattingRule3 = new DevExpress.XtraReports.UI.FormattingRule();
this.xrTableRow22 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell73 = new DevExpress.XtraReports.UI.XRTableCell();
this.strDiseaseName = new DevExpress.XtraReports.UI.XRTableCell();
this.cellICD10 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_0_1 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_1_4 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_5_14 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_15_19 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_20_29 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_30_59 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAge_60_more = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell94 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellTotal = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell96 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellLabTested = new DevExpress.XtraReports.UI.XRTableCell();
this.cellLabConfirmed = new DevExpress.XtraReports.UI.XRTableCell();
this.cellTotalConfirmed = new DevExpress.XtraReports.UI.XRTableCell();
this.CustomReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.SpRepHumMonthlyInfectiousDiseaseNewTableAdapter = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewDataSetTableAdapters.spRepHumMonthlyInfectiousDiseaseNewTableAdapter();
this.SpRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewHeaderDataSetTableAdapters.spRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter();
this.cellLocation = new DevExpress.XtraReports.UI.XRLabel();
this.formattingRule1 = new DevExpress.XtraReports.UI.FormattingRule();
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.InfectiousDiseaseHeaderDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.InfectiousDiseaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomFooter)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBody)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// tableInterval
//
resources.ApplyResources(this.tableInterval, "tableInterval");
this.tableInterval.StylePriority.UseBorders = false;
this.tableInterval.StylePriority.UseFont = false;
this.tableInterval.StylePriority.UsePadding = false;
//
// cellLanguage
//
resources.ApplyResources(this.cellLanguage, "cellLanguage");
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.Multiline = true;
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Expanded = false;
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableCustomHeader});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.StylePriority.UsePadding = false;
this.ReportHeader.Controls.SetChildIndex(this.tableCustomHeader, 0);
this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0);
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.cellLocation});
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
this.cellReportHeader.Weight = 1.553228412422955D;
this.cellReportHeader.Controls.SetChildIndex(this.tableInterval, 0);
this.cellReportHeader.Controls.SetChildIndex(this.lblReportName, 0);
this.cellReportHeader.Controls.SetChildIndex(this.cellLocation, 0);
//
// cellBaseSite
//
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
this.cellBaseSite.Weight = 1.553228412422955D;
//
// cellBaseCountry
//
resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry");
this.cellBaseCountry.StylePriority.UseFont = false;
//
// cellBaseLeftHeader
//
resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader");
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// tableCustomHeader
//
resources.ApplyResources(this.tableCustomHeader, "tableCustomHeader");
this.tableCustomHeader.Name = "tableCustomHeader";
this.tableCustomHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2,
this.xrTableRow3,
this.xrTableRow4,
this.EnTableRow1,
this.EnTableRow2,
this.GgTableRow1,
this.GgTableRow2,
this.xrTableRow23,
this.xrTableRow21,
this.xrTableRow8,
this.xrTableRow9,
this.xrTableRow11,
this.xrTableRow12,
this.xrTableRow13,
this.xrTableRow14,
this.xrTableRow15});
this.tableCustomHeader.StylePriority.UseFont = false;
this.tableCustomHeader.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 0.750000381469843D;
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
this.xrTableCell1.StylePriority.UseTextAlignment = false;
this.xrTableCell1.Weight = 3D;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2});
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.Weight = 1.1199996614642658D;
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Multiline = true;
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseFont = false;
this.xrTableCell2.StylePriority.UseTextAlignment = false;
this.xrTableCell2.Weight = 3D;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6,
this.xrTableCell84});
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.StylePriority.UseFont = false;
this.xrTableRow3.StylePriority.UseTextAlignment = false;
this.xrTableRow3.Weight = 0.799999715166168D;
//
// xrTableCell5
//
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Multiline = true;
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.Padding = new DevExpress.XtraPrinting.PaddingInfo(44, 2, 2, 2, 100F);
this.xrTableCell5.StylePriority.UseFont = false;
this.xrTableCell5.StylePriority.UsePadding = false;
this.xrTableCell5.StylePriority.UseTextAlignment = false;
this.xrTableCell5.Weight = 1.4873598055652759D;
//
// xrTableCell6
//
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.Weight = 1.2640449033664152D;
//
// xrTableCell84
//
resources.ApplyResources(this.xrTableCell84, "xrTableCell84");
this.xrTableCell84.Name = "xrTableCell84";
this.xrTableCell84.StylePriority.UseFont = false;
this.xrTableCell84.StylePriority.UseTextAlignment = false;
this.xrTableCell84.Weight = 0.24859529106830902D;
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell14,
this.xrTableCell29});
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
this.xrTableRow4.Name = "xrTableRow4";
this.xrTableRow4.StylePriority.UseFont = false;
this.xrTableRow4.StylePriority.UseTextAlignment = false;
this.xrTableRow4.Weight = 0.79999975252393962D;
//
// xrTableCell9
//
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.Weight = 1.4873598055652759D;
//
// xrTableCell14
//
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseFont = false;
this.xrTableCell14.StylePriority.UseTextAlignment = false;
this.xrTableCell14.Weight = 1.2640451605370615D;
//
// xrTableCell29
//
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.Weight = 0.24859503389766274D;
//
// EnTableRow1
//
this.EnTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell38,
this.xrTableCell3,
this.xrTableCell75,
this.xrTableCell85,
this.xrTableCell86,
this.xrTableCell87,
this.xrTableCell80});
resources.ApplyResources(this.EnTableRow1, "EnTableRow1");
this.EnTableRow1.Name = "EnTableRow1";
this.EnTableRow1.StylePriority.UseFont = false;
this.EnTableRow1.StylePriority.UsePadding = false;
this.EnTableRow1.StylePriority.UseTextAlignment = false;
this.EnTableRow1.Weight = 0.59999989211962645D;
//
// xrTableCell38
//
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
this.xrTableCell38.Name = "xrTableCell38";
this.xrTableCell38.Weight = 1.4873598055652759D;
//
// xrTableCell3
//
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.Weight = 0.41713477439190716D;
//
// xrTableCell75
//
this.xrTableCell75.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell75.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strOrderNumber")});
resources.ApplyResources(this.xrTableCell75, "xrTableCell75");
this.xrTableCell75.Name = "xrTableCell75";
this.xrTableCell75.StylePriority.UseBorders = false;
this.xrTableCell75.StylePriority.UseFont = false;
this.xrTableCell75.StylePriority.UseTextAlignment = false;
this.xrTableCell75.Weight = 0.16853935473827475D;
//
// InfectiousDiseaseHeaderDataSet
//
this.InfectiousDiseaseHeaderDataSet.DataSetName = "InfectiousDiseaseMonthNewHeaderDataSet";
this.InfectiousDiseaseHeaderDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// xrTableCell85
//
resources.ApplyResources(this.xrTableCell85, "xrTableCell85");
this.xrTableCell85.Name = "xrTableCell85";
this.xrTableCell85.Weight = 0.10533709671142175D;
//
// xrTableCell86
//
this.xrTableCell86.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell86.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strOrderDate")});
resources.ApplyResources(this.xrTableCell86, "xrTableCell86");
this.xrTableCell86.Name = "xrTableCell86";
this.xrTableCell86.StylePriority.UseBorders = false;
this.xrTableCell86.StylePriority.UseTextAlignment = false;
this.xrTableCell86.Weight = 0.21067419342284349D;
//
// xrTableCell87
//
resources.ApplyResources(this.xrTableCell87, "xrTableCell87");
this.xrTableCell87.Name = "xrTableCell87";
this.xrTableCell87.Weight = 0.36235948410196772D;
//
// xrTableCell80
//
resources.ApplyResources(this.xrTableCell80, "xrTableCell80");
this.xrTableCell80.Name = "xrTableCell80";
this.xrTableCell80.Weight = 0.2485952910683091D;
//
// EnTableRow2
//
this.EnTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell81,
this.xrTableCell82,
this.xrTableCell83});
resources.ApplyResources(this.EnTableRow2, "EnTableRow2");
this.EnTableRow2.Name = "EnTableRow2";
this.EnTableRow2.StylePriority.UseFont = false;
this.EnTableRow2.StylePriority.UsePadding = false;
this.EnTableRow2.StylePriority.UseTextAlignment = false;
this.EnTableRow2.Weight = 0.59999977767874335D;
//
// xrTableCell81
//
resources.ApplyResources(this.xrTableCell81, "xrTableCell81");
this.xrTableCell81.Name = "xrTableCell81";
this.xrTableCell81.Weight = 1.4873598055652759D;
//
// xrTableCell82
//
resources.ApplyResources(this.xrTableCell82, "xrTableCell82");
this.xrTableCell82.Name = "xrTableCell82";
this.xrTableCell82.StylePriority.UseFont = false;
this.xrTableCell82.Weight = 1.2640451605370615D;
//
// xrTableCell83
//
resources.ApplyResources(this.xrTableCell83, "xrTableCell83");
this.xrTableCell83.Name = "xrTableCell83";
this.xrTableCell83.Weight = 0.24859503389766274D;
//
// GgTableRow1
//
this.GgTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell8,
this.xrTableCell88});
resources.ApplyResources(this.GgTableRow1, "GgTableRow1");
this.GgTableRow1.Name = "GgTableRow1";
this.GgTableRow1.StylePriority.UseFont = false;
this.GgTableRow1.StylePriority.UsePadding = false;
this.GgTableRow1.StylePriority.UseTextAlignment = false;
this.GgTableRow1.Weight = 0.59999977767874346D;
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.Weight = 1.4873598055652759D;
//
// xrTableCell8
//
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseFont = false;
this.xrTableCell8.Tag = "UnchangedFont";
this.xrTableCell8.Weight = 1.2640451605370615D;
//
// xrTableCell88
//
resources.ApplyResources(this.xrTableCell88, "xrTableCell88");
this.xrTableCell88.Name = "xrTableCell88";
this.xrTableCell88.Weight = 0.24859503389766274D;
//
// GgTableRow2
//
this.GgTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell89,
this.xrTableCell92,
this.xrTableCell93,
this.xrTableCell95,
this.xrTableCell97,
this.xrTableCell90,
this.xrTableCell91});
resources.ApplyResources(this.GgTableRow2, "GgTableRow2");
this.GgTableRow2.Name = "GgTableRow2";
this.GgTableRow2.StylePriority.UseFont = false;
this.GgTableRow2.StylePriority.UsePadding = false;
this.GgTableRow2.StylePriority.UseTextAlignment = false;
this.GgTableRow2.Weight = 0.59999977767874335D;
//
// xrTableCell89
//
resources.ApplyResources(this.xrTableCell89, "xrTableCell89");
this.xrTableCell89.Name = "xrTableCell89";
this.xrTableCell89.Weight = 1.4873598055652759D;
//
// xrTableCell92
//
resources.ApplyResources(this.xrTableCell92, "xrTableCell92");
this.xrTableCell92.Name = "xrTableCell92";
this.xrTableCell92.StylePriority.UseFont = false;
this.xrTableCell92.Tag = "UnchangedFont";
this.xrTableCell92.Weight = 0.54775290289939327D;
//
// xrTableCell93
//
this.xrTableCell93.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell93.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strOrderDate")});
resources.ApplyResources(this.xrTableCell93, "xrTableCell93");
this.xrTableCell93.Name = "xrTableCell93";
this.xrTableCell93.StylePriority.UseBorders = false;
this.xrTableCell93.StylePriority.UseFont = false;
this.xrTableCell93.StylePriority.UseTextAlignment = false;
this.xrTableCell93.Tag = "UnchangedFont";
this.xrTableCell93.Weight = 0.18960677408055929D;
//
// xrTableCell95
//
resources.ApplyResources(this.xrTableCell95, "xrTableCell95");
this.xrTableCell95.Name = "xrTableCell95";
this.xrTableCell95.StylePriority.UseFont = false;
this.xrTableCell95.Tag = "UnchangedFont";
this.xrTableCell95.Weight = 0.14747193539599057D;
//
// xrTableCell97
//
this.xrTableCell97.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell97.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strOrderNumber")});
resources.ApplyResources(this.xrTableCell97, "xrTableCell97");
this.xrTableCell97.Name = "xrTableCell97";
this.xrTableCell97.StylePriority.UseBorders = false;
this.xrTableCell97.StylePriority.UseFont = false;
this.xrTableCell97.StylePriority.UseTextAlignment = false;
this.xrTableCell97.Tag = "UnchangedFont";
this.xrTableCell97.Weight = 0.14747193539599043D;
//
// xrTableCell90
//
resources.ApplyResources(this.xrTableCell90, "xrTableCell90");
this.xrTableCell90.Name = "xrTableCell90";
this.xrTableCell90.StylePriority.UseFont = false;
this.xrTableCell90.Tag = "UnchangedFont";
this.xrTableCell90.Weight = 0.23174161276512789D;
//
// xrTableCell91
//
resources.ApplyResources(this.xrTableCell91, "xrTableCell91");
this.xrTableCell91.Name = "xrTableCell91";
this.xrTableCell91.Weight = 0.24859503389766274D;
//
// xrTableRow23
//
this.xrTableRow23.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell70});
resources.ApplyResources(this.xrTableRow23, "xrTableRow23");
this.xrTableRow23.Name = "xrTableRow23";
this.xrTableRow23.StylePriority.UseTextAlignment = false;
this.xrTableRow23.Weight = 1.5999994678745826D;
//
// xrTableCell70
//
resources.ApplyResources(this.xrTableCell70, "xrTableCell70");
this.xrTableCell70.Multiline = true;
this.xrTableCell70.Name = "xrTableCell70";
this.xrTableCell70.StylePriority.UseFont = false;
this.xrTableCell70.StylePriority.UseTextAlignment = false;
this.xrTableCell70.Weight = 3D;
//
// xrTableRow21
//
this.xrTableRow21.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell16,
this.xrTableCell27,
this.xrTableCell15});
resources.ApplyResources(this.xrTableRow21, "xrTableRow21");
this.xrTableRow21.Name = "xrTableRow21";
this.xrTableRow21.Weight = 1.5999995070409951D;
//
// xrTableCell16
//
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.Weight = 1.4873598055652757D;
//
// xrTableCell27
//
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Multiline = true;
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.StylePriority.UseFont = false;
this.xrTableCell27.Weight = 1.2640449033664152D;
//
// xrTableCell15
//
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
this.xrTableCell15.Weight = 0.24859529106830913D;
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell10,
this.cellNameOfrespondent,
this.xrTableCell11});
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
this.xrTableRow8.Name = "xrTableRow8";
this.xrTableRow8.Weight = 0.47999982954698456D;
//
// xrTableCell10
//
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseFont = false;
this.xrTableCell10.Weight = 1.3230339346954576D;
//
// cellNameOfrespondent
//
resources.ApplyResources(this.cellNameOfrespondent, "cellNameOfrespondent");
this.cellNameOfrespondent.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.cellNameOfrespondent.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strNameOfRespondent")});
this.cellNameOfrespondent.Name = "cellNameOfrespondent";
this.cellNameOfrespondent.StylePriority.UseBackColor = false;
this.cellNameOfrespondent.StylePriority.UseBorders = false;
this.cellNameOfrespondent.StylePriority.UseFont = false;
this.cellNameOfrespondent.Weight = 1.4325845152753365D;
//
// xrTableCell11
//
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.StylePriority.UseFont = false;
this.xrTableCell11.StylePriority.UseTextAlignment = false;
this.xrTableCell11.Weight = 0.24438155002920606D;
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell12,
this.cellActualAddress,
this.xrTableCell13});
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
this.xrTableRow9.Name = "xrTableRow9";
this.xrTableRow9.Weight = 0.47999982954698439D;
//
// xrTableCell12
//
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseFont = false;
this.xrTableCell12.Weight = 1.3230339346954576D;
//
// cellActualAddress
//
resources.ApplyResources(this.cellActualAddress, "cellActualAddress");
this.cellActualAddress.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.cellActualAddress.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strActualAddress")});
this.cellActualAddress.Name = "cellActualAddress";
this.cellActualAddress.StylePriority.UseBackColor = false;
this.cellActualAddress.StylePriority.UseBorders = false;
this.cellActualAddress.StylePriority.UseFont = false;
this.cellActualAddress.Weight = 1.4325845152753363D;
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseFont = false;
this.xrTableCell13.StylePriority.UseTextAlignment = false;
this.xrTableCell13.Weight = 0.24438155002920595D;
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell17,
this.xrTableCell18,
this.xrTableCell19});
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
this.xrTableRow11.Name = "xrTableRow11";
this.xrTableRow11.Weight = 0.47999982954698428D;
//
// xrTableCell17
//
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.StylePriority.UseFont = false;
this.xrTableCell17.Weight = 1.3230339346954576D;
//
// xrTableCell18
//
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseBackColor = false;
this.xrTableCell18.StylePriority.UseBorders = false;
this.xrTableCell18.StylePriority.UseFont = false;
this.xrTableCell18.Weight = 1.4325845152753363D;
//
// xrTableCell19
//
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseFont = false;
this.xrTableCell19.StylePriority.UseTextAlignment = false;
this.xrTableCell19.Weight = 0.24438155002920595D;
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell20,
this.xrTableCell21,
this.xrTableCell22});
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
this.xrTableRow12.Name = "xrTableRow12";
this.xrTableRow12.Weight = 0.4799998295469845D;
//
// xrTableCell20
//
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseFont = false;
this.xrTableCell20.Weight = 1.3230339346954576D;
//
// xrTableCell21
//
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseBackColor = false;
this.xrTableCell21.StylePriority.UseBorders = false;
this.xrTableCell21.StylePriority.UseFont = false;
this.xrTableCell21.Weight = 1.43258425810469D;
//
// xrTableCell22
//
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseFont = false;
this.xrTableCell22.StylePriority.UseTextAlignment = false;
this.xrTableCell22.Weight = 0.24438180719985223D;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell23,
this.xrTableCell24,
this.xrTableCell25});
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
this.xrTableRow13.Name = "xrTableRow13";
this.xrTableRow13.Weight = 0.47999982954698445D;
//
// xrTableCell23
//
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseFont = false;
this.xrTableCell23.Weight = 1.3230339346954576D;
//
// xrTableCell24
//
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseBackColor = false;
this.xrTableCell24.StylePriority.UseBorders = false;
this.xrTableCell24.StylePriority.UseFont = false;
this.xrTableCell24.Weight = 1.4325845152753363D;
//
// xrTableCell25
//
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.StylePriority.UseFont = false;
this.xrTableCell25.StylePriority.UseTextAlignment = false;
this.xrTableCell25.Weight = 0.24438155002920595D;
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell26,
this.cellTelephone,
this.xrTableCell28});
resources.ApplyResources(this.xrTableRow14, "xrTableRow14");
this.xrTableRow14.Name = "xrTableRow14";
this.xrTableRow14.Weight = 0.47999982954698428D;
//
// xrTableCell26
//
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseFont = false;
this.xrTableCell26.Weight = 1.3230339346954576D;
//
// cellTelephone
//
resources.ApplyResources(this.cellTelephone, "cellTelephone");
this.cellTelephone.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.cellTelephone.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strTelephone")});
this.cellTelephone.Name = "cellTelephone";
this.cellTelephone.StylePriority.UseBackColor = false;
this.cellTelephone.StylePriority.UseBorders = false;
this.cellTelephone.StylePriority.UseFont = false;
this.cellTelephone.Weight = 1.4325845152753363D;
//
// xrTableCell28
//
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
this.xrTableCell28.Name = "xrTableCell28";
this.xrTableCell28.StylePriority.UseFont = false;
this.xrTableCell28.Weight = 0.24438155002920595D;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellReportedPeriod,
this.xrTableCell30,
this.xrTableCell31});
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
this.xrTableRow15.Name = "xrTableRow15";
this.xrTableRow15.Weight = 0.4799998295469845D;
//
// cellReportedPeriod
//
resources.ApplyResources(this.cellReportedPeriod, "cellReportedPeriod");
this.cellReportedPeriod.Name = "cellReportedPeriod";
this.cellReportedPeriod.StylePriority.UseFont = false;
this.cellReportedPeriod.Weight = 1.3230339346954576D;
//
// xrTableCell30
//
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Name = "xrTableCell30";
this.xrTableCell30.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell30.StylePriority.UseFont = false;
this.xrTableCell30.StylePriority.UsePadding = false;
this.xrTableCell30.Weight = 1.4283710314068794D;
//
// xrTableCell31
//
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Name = "xrTableCell31";
this.xrTableCell31.Weight = 0.24859503389766283D;
//
// InfectiousDiseaseDataSet
//
this.InfectiousDiseaseDataSet.DataSetName = "InfectiousDiseaseMonthNewDataSet";
this.InfectiousDiseaseDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// ReportFooter
//
this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableCustomFooter});
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
this.ReportFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.ReportFooter.StylePriority.UseFont = false;
this.ReportFooter.StylePriority.UsePadding = false;
this.ReportFooter.StylePriority.UseTextAlignment = false;
//
// tableCustomFooter
//
resources.ApplyResources(this.tableCustomFooter, "tableCustomFooter");
this.tableCustomFooter.Name = "tableCustomFooter";
this.tableCustomFooter.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow18,
this.xrTableRow25,
this.xrTableRow5});
this.tableCustomFooter.StylePriority.UseFont = false;
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell35,
this.DayFooterCell,
this.xrTableCell34,
this.MonthFooterCell,
this.YearFooterCell,
this.xrTableCell32,
this.ChiefFooterCell,
this.xrTableCell4});
resources.ApplyResources(this.xrTableRow18, "xrTableRow18");
this.xrTableRow18.Name = "xrTableRow18";
this.xrTableRow18.Weight = 1D;
//
// xrTableCell35
//
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
this.xrTableCell35.Name = "xrTableCell35";
this.xrTableCell35.Weight = 0.042253524694000635D;
//
// DayFooterCell
//
this.DayFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.DayFooterCell, "DayFooterCell");
this.DayFooterCell.Name = "DayFooterCell";
this.DayFooterCell.StylePriority.UseBorders = false;
this.DayFooterCell.StylePriority.UseTextAlignment = false;
this.DayFooterCell.Weight = 0.16901409897125619D;
//
// xrTableCell34
//
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.Weight = 0.042253521038213115D;
//
// MonthFooterCell
//
this.MonthFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.MonthFooterCell, "MonthFooterCell");
this.MonthFooterCell.Name = "MonthFooterCell";
this.MonthFooterCell.StylePriority.UseBorders = false;
this.MonthFooterCell.StylePriority.UseTextAlignment = false;
this.MonthFooterCell.Weight = 0.50704226900465355D;
//
// YearFooterCell
//
this.YearFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.YearFooterCell, "YearFooterCell");
this.YearFooterCell.Name = "YearFooterCell";
this.YearFooterCell.StylePriority.UseBorders = false;
this.YearFooterCell.Weight = 0.19859169425273882D;
//
// xrTableCell32
//
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Name = "xrTableCell32";
this.xrTableCell32.Weight = 0.40985909319214486D;
//
// ChiefFooterCell
//
this.ChiefFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.ChiefFooterCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strChief")});
resources.ApplyResources(this.ChiefFooterCell, "ChiefFooterCell");
this.ChiefFooterCell.Name = "ChiefFooterCell";
this.ChiefFooterCell.StylePriority.UseBorders = false;
this.ChiefFooterCell.Weight = 1.2929581144817024D;
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseFont = false;
this.xrTableCell4.Weight = 0.33802768436529051D;
//
// xrTableRow25
//
this.xrTableRow25.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell79});
resources.ApplyResources(this.xrTableRow25, "xrTableRow25");
this.xrTableRow25.Name = "xrTableRow25";
this.xrTableRow25.Weight = 1.5D;
//
// xrTableCell79
//
this.xrTableCell79.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrTableCell79, "xrTableCell79");
this.xrTableCell79.Name = "xrTableCell79";
this.xrTableCell79.StylePriority.UseBorders = false;
this.xrTableCell79.Weight = 3D;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell33});
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
this.xrTableRow5.Name = "xrTableRow5";
this.xrTableRow5.Weight = 1D;
//
// xrTableCell33
//
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.StylePriority.UseTextAlignment = false;
this.xrTableCell33.Weight = 3D;
//
// tableBody
//
this.tableBody.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.tableBody, "tableBody");
this.tableBody.Name = "tableBody";
this.tableBody.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow19,
this.xrTableRow20});
this.tableBody.StylePriority.UseBorders = false;
//
// xrTableRow19
//
this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell71,
this.xrTableCell43,
this.xrTableCell47,
this.xrTableCell40,
this.xrTableCell46,
this.xrTableCell44,
this.xrTableCell48,
this.xrTableCell41,
this.xrTableCell49,
this.xrTableCell52,
this.xrTableCell66,
this.xrTableCell45,
this.xrTableCell67,
this.xrTableCell51,
this.xrTableCell50,
this.xrTableCell42});
resources.ApplyResources(this.xrTableRow19, "xrTableRow19");
this.xrTableRow19.Name = "xrTableRow19";
this.xrTableRow19.Weight = 3.4510522092487617D;
//
// xrTableCell71
//
resources.ApplyResources(this.xrTableCell71, "xrTableCell71");
this.xrTableCell71.Name = "xrTableCell71";
this.xrTableCell71.StylePriority.UseFont = false;
this.xrTableCell71.Weight = 0.12676056191221669D;
//
// xrTableCell43
//
resources.ApplyResources(this.xrTableCell43, "xrTableCell43");
this.xrTableCell43.Name = "xrTableCell43";
this.xrTableCell43.StylePriority.UseFont = false;
this.xrTableCell43.Weight = 0.83239434956416392D;
//
// xrTableCell47
//
resources.ApplyResources(this.xrTableCell47, "xrTableCell47");
this.xrTableCell47.Name = "xrTableCell47";
this.xrTableCell47.StylePriority.UseFont = false;
this.xrTableCell47.Weight = 0.25352105573348971D;
//
// xrTableCell40
//
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
this.xrTableCell40.Name = "xrTableCell40";
this.xrTableCell40.StylePriority.UseFont = false;
this.xrTableCell40.Weight = 0.15633802370428213D;
//
// xrTableCell46
//
resources.ApplyResources(this.xrTableCell46, "xrTableCell46");
this.xrTableCell46.Name = "xrTableCell46";
this.xrTableCell46.StylePriority.UseFont = false;
this.xrTableCell46.Weight = 0.15633802370428229D;
//
// xrTableCell44
//
resources.ApplyResources(this.xrTableCell44, "xrTableCell44");
this.xrTableCell44.Name = "xrTableCell44";
this.xrTableCell44.StylePriority.UseFont = false;
this.xrTableCell44.Weight = 0.15633802370428232D;
//
// xrTableCell48
//
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
this.xrTableCell48.Name = "xrTableCell48";
this.xrTableCell48.StylePriority.UseFont = false;
this.xrTableCell48.Weight = 0.15633802370428221D;
//
// xrTableCell41
//
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.StylePriority.UseFont = false;
this.xrTableCell41.Weight = 0.156338039822721D;
//
// xrTableCell49
//
resources.ApplyResources(this.xrTableCell49, "xrTableCell49");
this.xrTableCell49.Name = "xrTableCell49";
this.xrTableCell49.StylePriority.UseFont = false;
this.xrTableCell49.Weight = 0.15633802370428207D;
//
// xrTableCell52
//
resources.ApplyResources(this.xrTableCell52, "xrTableCell52");
this.xrTableCell52.Name = "xrTableCell52";
this.xrTableCell52.StylePriority.UseFont = false;
this.xrTableCell52.Weight = 0.15633810698288259D;
//
// xrTableCell66
//
resources.ApplyResources(this.xrTableCell66, "xrTableCell66");
this.xrTableCell66.Name = "xrTableCell66";
this.xrTableCell66.Weight = 0.0084503816749598171D;
//
// xrTableCell45
//
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
this.xrTableCell45.Name = "xrTableCell45";
this.xrTableCell45.StylePriority.UseFont = false;
this.xrTableCell45.Weight = 0.16901434035131324D;
//
// xrTableCell67
//
resources.ApplyResources(this.xrTableCell67, "xrTableCell67");
this.xrTableCell67.Name = "xrTableCell67";
this.xrTableCell67.Weight = 0.008450962729544D;
//
// xrTableCell51
//
this.xrTableCell51.Angle = 90F;
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
this.xrTableCell51.Name = "xrTableCell51";
this.xrTableCell51.StylePriority.UseFont = false;
this.xrTableCell51.Weight = 0.1690138237704843D;
//
// xrTableCell50
//
this.xrTableCell50.Angle = 90F;
resources.ApplyResources(this.xrTableCell50, "xrTableCell50");
this.xrTableCell50.Name = "xrTableCell50";
this.xrTableCell50.StylePriority.UseFont = false;
this.xrTableCell50.Weight = 0.16901408245629254D;
//
// xrTableCell42
//
this.xrTableCell42.Angle = 90F;
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
this.xrTableCell42.Name = "xrTableCell42";
this.xrTableCell42.StylePriority.UseFont = false;
this.xrTableCell42.Weight = 0.16901411200676422D;
//
// xrTableRow20
//
this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell72,
this.xrTableCell53,
this.xrTableCell54,
this.xrTableCell55,
this.xrTableCell56,
this.xrTableCell57,
this.xrTableCell58,
this.xrTableCell59,
this.xrTableCell60,
this.xrTableCell61,
this.xrTableCell68,
this.xrTableCell62,
this.xrTableCell69,
this.xrTableCell63,
this.xrTableCell64,
this.xrTableCell65});
resources.ApplyResources(this.xrTableRow20, "xrTableRow20");
this.xrTableRow20.Name = "xrTableRow20";
this.xrTableRow20.StylePriority.UseBorders = false;
this.xrTableRow20.StylePriority.UsePadding = false;
this.xrTableRow20.Weight = 0.34510517859058065D;
//
// xrTableCell72
//
resources.ApplyResources(this.xrTableCell72, "xrTableCell72");
this.xrTableCell72.Name = "xrTableCell72";
this.xrTableCell72.Weight = 0.1267605457937778D;
//
// xrTableCell53
//
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseFont = false;
this.xrTableCell53.Weight = 0.83239436568260272D;
//
// xrTableCell54
//
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
this.xrTableCell54.Name = "xrTableCell54";
this.xrTableCell54.StylePriority.UseFont = false;
this.xrTableCell54.Weight = 0.25352118468100016D;
//
// xrTableCell55
//
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
this.xrTableCell55.Name = "xrTableCell55";
this.xrTableCell55.StylePriority.UseFont = false;
this.xrTableCell55.Weight = 0.15633776580926131D;
//
// xrTableCell56
//
resources.ApplyResources(this.xrTableCell56, "xrTableCell56");
this.xrTableCell56.Name = "xrTableCell56";
this.xrTableCell56.StylePriority.UseFont = false;
this.xrTableCell56.Weight = 0.15633828159930321D;
//
// xrTableCell57
//
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
this.xrTableCell57.Name = "xrTableCell57";
this.xrTableCell57.StylePriority.UseFont = false;
this.xrTableCell57.Weight = 0.1563378947567719D;
//
// xrTableCell58
//
resources.ApplyResources(this.xrTableCell58, "xrTableCell58");
this.xrTableCell58.Name = "xrTableCell58";
this.xrTableCell58.StylePriority.UseFont = false;
this.xrTableCell58.Weight = 0.15633802370428229D;
//
// xrTableCell59
//
resources.ApplyResources(this.xrTableCell59, "xrTableCell59");
this.xrTableCell59.Name = "xrTableCell59";
this.xrTableCell59.StylePriority.UseFont = false;
this.xrTableCell59.Weight = 0.15633802370428224D;
//
// xrTableCell60
//
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
this.xrTableCell60.Name = "xrTableCell60";
this.xrTableCell60.StylePriority.UseFont = false;
this.xrTableCell60.Weight = 0.15633802370428213D;
//
// xrTableCell61
//
resources.ApplyResources(this.xrTableCell61, "xrTableCell61");
this.xrTableCell61.Name = "xrTableCell61";
this.xrTableCell61.StylePriority.UseFont = false;
this.xrTableCell61.Weight = 0.15633802639068856D;
//
// xrTableCell68
//
resources.ApplyResources(this.xrTableCell68, "xrTableCell68");
this.xrTableCell68.Name = "xrTableCell68";
this.xrTableCell68.Weight = 0.0084507209529619265D;
//
// xrTableCell62
//
resources.ApplyResources(this.xrTableCell62, "xrTableCell62");
this.xrTableCell62.Name = "xrTableCell62";
this.xrTableCell62.StylePriority.UseFont = false;
this.xrTableCell62.Weight = 0.16901409778394394D;
//
// xrTableCell69
//
resources.ApplyResources(this.xrTableCell69, "xrTableCell69");
this.xrTableCell69.Name = "xrTableCell69";
this.xrTableCell69.Weight = 0.0084514777287984927D;
//
// xrTableCell63
//
resources.ApplyResources(this.xrTableCell63, "xrTableCell63");
this.xrTableCell63.Name = "xrTableCell63";
this.xrTableCell63.StylePriority.UseFont = false;
this.xrTableCell63.Weight = 0.16901356666625073D;
//
// xrTableCell64
//
resources.ApplyResources(this.xrTableCell64, "xrTableCell64");
this.xrTableCell64.Name = "xrTableCell64";
this.xrTableCell64.StylePriority.UseFont = false;
this.xrTableCell64.Weight = 0.1690140824562926D;
//
// xrTableCell65
//
resources.ApplyResources(this.xrTableCell65, "xrTableCell65");
this.xrTableCell65.Name = "xrTableCell65";
this.xrTableCell65.StylePriority.UseFont = false;
this.xrTableCell65.Weight = 0.16901385411174336D;
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.CustomDetail,
this.CustomReportHeader});
this.DetailReport.DataAdapter = this.SpRepHumMonthlyInfectiousDiseaseNewTableAdapter;
this.DetailReport.DataMember = "spRepHumMonthlyInfectiousDiseaseNew";
this.DetailReport.DataSource = this.InfectiousDiseaseDataSet;
resources.ApplyResources(this.DetailReport, "DetailReport");
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
this.DetailReport.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// CustomDetail
//
this.CustomDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.PageBreakAtLine36,
this.xrTable1});
resources.ApplyResources(this.CustomDetail, "CustomDetail");
this.CustomDetail.Name = "CustomDetail";
this.CustomDetail.StylePriority.UseFont = false;
this.CustomDetail.StylePriority.UseTextAlignment = false;
//
// PageBreakAtLine36
//
resources.ApplyResources(this.PageBreakAtLine36, "PageBreakAtLine36");
this.PageBreakAtLine36.FormattingRules.Add(this.formattingRule2);
this.PageBreakAtLine36.Name = "PageBreakAtLine36";
//
// formattingRule2
//
this.formattingRule2.Condition = "[DataSource.CurrentRowIndex] ==36";
this.formattingRule2.DataMember = "spRepHumMonthlyInfectiousDiseaseNew";
this.formattingRule2.DataSource = this.InfectiousDiseaseDataSet;
//
//
//
this.formattingRule2.Formatting.Visible = DevExpress.Utils.DefaultBoolean.True;
this.formattingRule2.Name = "formattingRule2";
//
// xrTable1
//
this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.FormattingRules.Add(this.formattingRule3);
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow22});
this.xrTable1.StylePriority.UseBorders = false;
this.xrTable1.StylePriority.UseFont = false;
this.xrTable1.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// formattingRule3
//
this.formattingRule3.Condition = "[DataSource.CurrentRowIndex] ==36";
//
//
//
this.formattingRule3.Formatting.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.formattingRule3.Name = "formattingRule3";
//
// xrTableRow22
//
this.xrTableRow22.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell73,
this.strDiseaseName,
this.cellICD10,
this.cellAge_0_1,
this.cellAge_1_4,
this.cellAge_5_14,
this.cellAge_15_19,
this.cellAge_20_29,
this.cellAge_30_59,
this.cellAge_60_more,
this.xrTableCell94,
this.cellTotal,
this.xrTableCell96,
this.cellLabTested,
this.cellLabConfirmed,
this.cellTotalConfirmed});
resources.ApplyResources(this.xrTableRow22, "xrTableRow22");
this.xrTableRow22.Name = "xrTableRow22";
this.xrTableRow22.StylePriority.UseBorders = false;
this.xrTableRow22.Weight = 0.34510518943249707D;
//
// xrTableCell73
//
resources.ApplyResources(this.xrTableCell73, "xrTableCell73");
this.xrTableCell73.Name = "xrTableCell73";
this.xrTableCell73.StylePriority.UseFont = false;
resources.ApplyResources(xrSummary1, "xrSummary1");
xrSummary1.Func = DevExpress.XtraReports.UI.SummaryFunc.RecordNumber;
xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Report;
this.xrTableCell73.Summary = xrSummary1;
this.xrTableCell73.Weight = 0.12676056191221657D;
this.xrTableCell73.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.NumberingCellBeforePrint);
//
// strDiseaseName
//
this.strDiseaseName.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.strDiseaseName")});
resources.ApplyResources(this.strDiseaseName, "strDiseaseName");
this.strDiseaseName.Name = "strDiseaseName";
this.strDiseaseName.StylePriority.UseFont = false;
this.strDiseaseName.StylePriority.UseTextAlignment = false;
this.strDiseaseName.Weight = 0.83239434956416425D;
this.strDiseaseName.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellICD10
//
this.cellICD10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.strICD10")});
resources.ApplyResources(this.cellICD10, "cellICD10");
this.cellICD10.Name = "cellICD10";
this.cellICD10.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.cellICD10.StylePriority.UseFont = false;
this.cellICD10.StylePriority.UsePadding = false;
this.cellICD10.Weight = 0.25352112020724493D;
this.cellICD10.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_0_1
//
this.cellAge_0_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_0_1")});
resources.ApplyResources(this.cellAge_0_1, "cellAge_0_1");
this.cellAge_0_1.Name = "cellAge_0_1";
this.cellAge_0_1.StylePriority.UseFont = false;
this.cellAge_0_1.Weight = 0.15633802370428218D;
this.cellAge_0_1.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_1_4
//
this.cellAge_1_4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_1_4")});
resources.ApplyResources(this.cellAge_1_4, "cellAge_1_4");
this.cellAge_1_4.Name = "cellAge_1_4";
this.cellAge_1_4.StylePriority.UseFont = false;
this.cellAge_1_4.Weight = 0.15633815265179279D;
this.cellAge_1_4.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_5_14
//
this.cellAge_5_14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_5_14")});
resources.ApplyResources(this.cellAge_5_14, "cellAge_5_14");
this.cellAge_5_14.Name = "cellAge_5_14";
this.cellAge_5_14.StylePriority.UseFont = false;
this.cellAge_5_14.Weight = 0.15633776580926137D;
this.cellAge_5_14.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_15_19
//
this.cellAge_15_19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_15_19")});
resources.ApplyResources(this.cellAge_15_19, "cellAge_15_19");
this.cellAge_15_19.Name = "cellAge_15_19";
this.cellAge_15_19.StylePriority.UseFont = false;
this.cellAge_15_19.Weight = 0.15633802370428224D;
this.cellAge_15_19.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_20_29
//
this.cellAge_20_29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_20_29")});
resources.ApplyResources(this.cellAge_20_29, "cellAge_20_29");
this.cellAge_20_29.Name = "cellAge_20_29";
this.cellAge_20_29.StylePriority.UseFont = false;
this.cellAge_20_29.Weight = 0.15633802370428221D;
this.cellAge_20_29.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_30_59
//
this.cellAge_30_59.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_30_59")});
resources.ApplyResources(this.cellAge_30_59, "cellAge_30_59");
this.cellAge_30_59.Name = "cellAge_30_59";
this.cellAge_30_59.StylePriority.UseFont = false;
this.cellAge_30_59.Weight = 0.156338281599303D;
this.cellAge_30_59.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// cellAge_60_more
//
this.cellAge_60_more.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_60_more")});
resources.ApplyResources(this.cellAge_60_more, "cellAge_60_more");
this.cellAge_60_more.Name = "cellAge_60_more";
this.cellAge_60_more.StylePriority.UseFont = false;
this.cellAge_60_more.Weight = 0.15633812310132142D;
this.cellAge_60_more.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint);
//
// xrTableCell94
//
resources.ApplyResources(this.xrTableCell94, "xrTableCell94");
this.xrTableCell94.Name = "xrTableCell94";
this.xrTableCell94.Weight = 0.0084501890444813876D;
//
// cellTotal
//
this.cellTotal.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intTotal")});
resources.ApplyResources(this.cellTotal, "cellTotal");
this.cellTotal.Name = "cellTotal";
this.cellTotal.StylePriority.UseFont = false;
this.cellTotal.Weight = 0.16901382377048424D;
this.cellTotal.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellTotalBeforePrint);
//
// xrTableCell96
//
resources.ApplyResources(this.xrTableCell96, "xrTableCell96");
this.xrTableCell96.Name = "xrTableCell96";
this.xrTableCell96.Weight = 0.008451219833777654D;
//
// cellLabTested
//
this.cellLabTested.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intLabTested")});
resources.ApplyResources(this.cellLabTested, "cellLabTested");
this.cellLabTested.Name = "cellLabTested";
this.cellLabTested.StylePriority.UseFont = false;
this.cellLabTested.Weight = 0.16901382456127156D;
this.cellLabTested.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellLabBeforePrint);
//
// cellLabConfirmed
//
this.cellLabConfirmed.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intLabConfirmed")});
resources.ApplyResources(this.cellLabConfirmed, "cellLabConfirmed");
this.cellLabConfirmed.Name = "cellLabConfirmed";
this.cellLabConfirmed.StylePriority.UseFont = false;
this.cellLabConfirmed.Weight = 0.16901408245629257D;
this.cellLabConfirmed.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellLabBeforePrint);
//
// cellTotalConfirmed
//
this.cellTotalConfirmed.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intTotalConfirmed")});
resources.ApplyResources(this.cellTotalConfirmed, "cellTotalConfirmed");
this.cellTotalConfirmed.Name = "cellTotalConfirmed";
this.cellTotalConfirmed.StylePriority.UseFont = false;
this.cellTotalConfirmed.Weight = 0.16901436990178509D;
this.cellTotalConfirmed.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellLabBeforePrint);
//
// CustomReportHeader
//
this.CustomReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableBody});
resources.ApplyResources(this.CustomReportHeader, "CustomReportHeader");
this.CustomReportHeader.Name = "CustomReportHeader";
this.CustomReportHeader.StylePriority.UseTextAlignment = false;
//
// SpRepHumMonthlyInfectiousDiseaseNewTableAdapter
//
this.SpRepHumMonthlyInfectiousDiseaseNewTableAdapter.ClearBeforeFill = true;
//
// SpRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter
//
this.SpRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter.ClearBeforeFill = true;
//
// cellLocation
//
this.cellLocation.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.cellLocation.BorderWidth = 0;
resources.ApplyResources(this.cellLocation, "cellLocation");
this.cellLocation.Name = "cellLocation";
this.cellLocation.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.cellLocation.StylePriority.UseBorders = false;
this.cellLocation.StylePriority.UseBorderWidth = false;
this.cellLocation.StylePriority.UseFont = false;
this.cellLocation.StylePriority.UseTextAlignment = false;
//
// formattingRule1
//
this.formattingRule1.Name = "formattingRule1";
//
// InfectiousDiseasesMonthNew
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.ReportFooter,
this.DetailReport});
resources.ApplyResources(this, "$this");
this.FormattingRuleSheet.AddRange(new DevExpress.XtraReports.UI.FormattingRule[] {
this.formattingRule1,
this.formattingRule2,
this.formattingRule3});
this.Landscape = false;
this.PageHeight = 1169;
this.PageWidth = 827;
this.Version = "11.1";
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportFooter, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.InfectiousDiseaseHeaderDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.InfectiousDiseaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableCustomFooter)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBody)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.XRTable tableCustomHeader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell cellNameOfrespondent;
private DevExpress.XtraReports.UI.XRTableCell cellActualAddress;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell cellTelephone;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell cellReportedPeriod;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
private DevExpress.XtraReports.UI.XRTable tableCustomFooter;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow18;
private DevExpress.XtraReports.UI.XRTable tableBody;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell42;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell43;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell47;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell46;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell44;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell45;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell56;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell57;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell58;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell59;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell61;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell62;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell63;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell64;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell65;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell66;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell67;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell68;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell69;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand CustomDetail;
private DevExpress.XtraReports.UI.ReportHeaderBand CustomReportHeader;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow22;
private DevExpress.XtraReports.UI.XRTableCell strDiseaseName;
private DevExpress.XtraReports.UI.XRTableCell cellICD10;
private DevExpress.XtraReports.UI.XRTableCell cellAge_0_1;
private DevExpress.XtraReports.UI.XRTableCell cellAge_1_4;
private DevExpress.XtraReports.UI.XRTableCell cellAge_5_14;
private DevExpress.XtraReports.UI.XRTableCell cellAge_15_19;
private DevExpress.XtraReports.UI.XRTableCell cellAge_20_29;
private DevExpress.XtraReports.UI.XRTableCell cellAge_30_59;
private DevExpress.XtraReports.UI.XRTableCell cellAge_60_more;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell94;
private DevExpress.XtraReports.UI.XRTableCell cellTotal;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell96;
private DevExpress.XtraReports.UI.XRTableCell cellLabTested;
private DevExpress.XtraReports.UI.XRTableCell cellLabConfirmed;
private DevExpress.XtraReports.UI.XRTableCell cellTotalConfirmed;
private InfectiousDiseaseMonthNewDataSet InfectiousDiseaseDataSet;
private InfectiousDiseaseMonthNewHeaderDataSet InfectiousDiseaseHeaderDataSet;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell70;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRTableCell ChiefFooterCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell79;
private spRepHumMonthlyInfectiousDiseaseNewTableAdapter SpRepHumMonthlyInfectiousDiseaseNewTableAdapter;
private spRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter SpRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter;
private DevExpress.XtraReports.UI.XRLabel cellLocation;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell84;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.XRTableRow EnTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell75;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell80;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell81;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell82;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell83;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell85;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell86;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell87;
private DevExpress.XtraReports.UI.XRTableRow EnTableRow2;
private DevExpress.XtraReports.UI.XRTableRow GgTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell88;
private DevExpress.XtraReports.UI.XRTableRow GgTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell89;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell92;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell93;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell95;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell97;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell90;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell91;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell71;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell72;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell73;
private DevExpress.XtraReports.UI.XRTableCell MonthFooterCell;
private DevExpress.XtraReports.UI.XRTableCell YearFooterCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableCell DayFooterCell;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.FormattingRule formattingRule1;
private DevExpress.XtraReports.UI.XRPageBreak PageBreakAtLine36;
private DevExpress.XtraReports.UI.FormattingRule formattingRule2;
private DevExpress.XtraReports.UI.FormattingRule formattingRule3;
}
}
| |
namespace NEventStore.Persistence.Sql
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using NEventStore.Logging;
using NEventStore.Serialization;
using ALinq;
public class SqlPersistenceEngine : IPersistStreams
{
private static readonly ILog Logger = LogFactory.BuildLogger(typeof(SqlPersistenceEngine));
private static readonly DateTime EpochTime = new DateTime(1970, 1, 1);
private readonly IConnectionFactory _connectionFactory;
private readonly ISqlDialect _dialect;
private readonly int _pageSize;
private readonly TransactionScopeOption _scopeOption;
private readonly ISerialize _serializer;
private bool _disposed;
private int _initialized;
private readonly IStreamIdHasher _streamIdHasher;
public SqlPersistenceEngine(
IConnectionFactory connectionFactory,
ISqlDialect dialect,
ISerialize serializer,
TransactionScopeOption scopeOption,
int pageSize)
: this(connectionFactory, dialect, serializer, scopeOption, pageSize, new Sha1StreamIdHasher())
{ }
public SqlPersistenceEngine(
IConnectionFactory connectionFactory,
ISqlDialect dialect,
ISerialize serializer,
TransactionScopeOption scopeOption,
int pageSize,
IStreamIdHasher streamIdHasher)
{
if (connectionFactory == null)
{
throw new ArgumentNullException("connectionFactory");
}
if (dialect == null)
{
throw new ArgumentNullException("dialect");
}
if (serializer == null)
{
throw new ArgumentNullException("serializer");
}
if (pageSize < 0)
{
throw new ArgumentException("pageSize");
}
if (streamIdHasher == null)
{
throw new ArgumentNullException("streamIdHasher");
}
_connectionFactory = connectionFactory;
_dialect = dialect;
_serializer = serializer;
_scopeOption = scopeOption;
_pageSize = pageSize;
_streamIdHasher = new StreamIdHasherValidator(streamIdHasher);
Logger.Debug(Messages.UsingScope, _scopeOption.ToString());
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual async Task Initialize()
{
if (Interlocked.Increment(ref _initialized) > 1)
{
return;
}
Logger.Debug(Messages.InitializingStorage);
await ExecuteCommand(statement => statement.ExecuteWithoutExceptions(_dialect.InitializeStorage));
}
public virtual IAsyncEnumerable<ICommit> GetFrom(string bucketId, string streamId, int minRevision, int maxRevision)
{
Logger.Debug(Messages.GettingAllCommitsBetween, streamId, minRevision, maxRevision);
streamId = _streamIdHasher.GetHash(streamId);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromStartingRevision;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
query.AddParameter(_dialect.StreamRevision, minRevision);
query.AddParameter(_dialect.MaxStreamRevision, maxRevision);
query.AddParameter(_dialect.CommitSequence, 0);
return query
.ExecutePagedQuery(statement, _dialect.NextPageDelegate)
.Select(async x => await x.GetCommit(_serializer, _dialect));
});
}
public virtual IAsyncEnumerable<ICommit> GetFrom(string bucketId, DateTime start)
{
start = start.AddTicks(-(start.Ticks % TimeSpan.TicksPerSecond)); // Rounds down to the nearest second.
start = start < EpochTime ? EpochTime : start;
Logger.Debug(Messages.GettingAllCommitsFrom, start, bucketId);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromInstant;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.CommitStamp, start);
return query.ExecutePagedQuery(statement, (q, r) => { })
.Select(x => x.GetCommit(_serializer, _dialect));
});
}
public Task<ICheckpoint> GetCheckpoint(string checkpointToken)
{
if (string.IsNullOrWhiteSpace(checkpointToken))
{
return Task.FromResult<ICheckpoint>(new LongCheckpoint(-1));
}
return Task.FromResult<ICheckpoint>(LongCheckpoint.Parse(checkpointToken));
}
public virtual IAsyncEnumerable<ICommit> GetFromTo(string bucketId, DateTime start, DateTime end)
{
start = start.AddTicks(-(start.Ticks % TimeSpan.TicksPerSecond)); // Rounds down to the nearest second.
start = start < EpochTime ? EpochTime : start;
end = end < EpochTime ? EpochTime : end;
Logger.Debug(Messages.GettingAllCommitsFromTo, start, end);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromToInstant;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.CommitStampStart, start);
query.AddParameter(_dialect.CommitStampEnd, end);
return query.ExecutePagedQuery(statement, (q, r) => { })
.Select(x => x.GetCommit(_serializer, _dialect));
});
}
public virtual async Task<ICommit> Commit(CommitAttempt attempt)
{
ICommit commit;
try
{
commit = await PersistCommit(attempt);
Logger.Debug(Messages.CommitPersisted, attempt.CommitId);
}
catch (Exception e)
{
if (!(e is UniqueKeyViolationException))
{
throw;
}
if (await DetectDuplicate(attempt))
{
Logger.Info(Messages.DuplicateCommit);
throw new DuplicateCommitException(e.Message, e);
}
Logger.Info(Messages.ConcurrentWriteDetected);
throw new ConcurrencyException(e.Message, e);
}
return commit;
}
public virtual IAsyncEnumerable<ICommit> GetUndispatchedCommits()
{
Logger.Debug(Messages.GettingUndispatchedCommits);
return
ExecuteQuery(query =>
query
.ExecutePagedQuery(_dialect.GetUndispatchedCommits, (q, r) => { }))
.Select(x => x.GetCommit(_serializer, _dialect)
)
.ToArray()
.AsAsyncEnumerable(); // avoid paging
}
public virtual void MarkCommitAsDispatched(ICommit commit)
{
Logger.Debug(Messages.MarkingCommitAsDispatched, commit.CommitId);
string streamId = _streamIdHasher.GetHash(commit.StreamId);
ExecuteCommand(cmd =>
{
cmd.AddParameter(_dialect.BucketId, commit.BucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
cmd.AddParameter(_dialect.CommitSequence, commit.CommitSequence);
return cmd.ExecuteWithoutExceptions(_dialect.MarkCommitAsDispatched);
});
}
public virtual IAsyncEnumerable<IStreamHead> GetStreamsToSnapshot(string bucketId, int maxThreshold)
{
Logger.Debug(Messages.GettingStreamsToSnapshot);
return ExecuteQuery(query =>
{
string statement = _dialect.GetStreamsRequiringSnapshots;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.Threshold, maxThreshold);
return query
.ExecutePagedQuery(
statement,
(q, s) => q.SetParameter(_dialect.StreamId, _dialect.CoalesceParameterValue(s.StreamId()), DbType.AnsiString)
)
.SelectSynch(x => x.GetStreamToSnapshot());
});
}
public virtual Task<ISnapshot> GetSnapshot(string bucketId, string streamId, int maxRevision)
{
Logger.Debug(Messages.GettingRevision, streamId, maxRevision);
var streamIdHash = _streamIdHasher.GetHash(streamId);
return ExecuteQuery(query =>
{
string statement = _dialect.GetSnapshot;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.StreamId, streamIdHash, DbType.AnsiString);
query.AddParameter(_dialect.StreamRevision, maxRevision);
return query
.ExecuteWithQuery(statement)
.SelectSynch(x => (ISnapshot)x.GetSnapshot(_serializer, streamId));
})
.FirstOrDefault();
}
public virtual async Task<bool> AddSnapshot(ISnapshot snapshot)
{
Logger.Debug(Messages.AddingSnapshot, snapshot.StreamId, snapshot.StreamRevision);
string streamId = _streamIdHasher.GetHash(snapshot.StreamId);
var result = await ExecuteCommand(async (connection, cmd) =>
{
cmd.AddParameter(_dialect.BucketId, snapshot.BucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamRevision, snapshot.StreamRevision);
_dialect.AddPayloadParamater(_connectionFactory, connection, cmd, _serializer.Serialize(snapshot.Payload));
return await cmd.ExecuteWithoutExceptions(_dialect.AppendSnapshotToCommit);
});
return result > 0;
}
public virtual async Task Purge()
{
Logger.Warn(Messages.PurgingStorage);
await ExecuteCommand(cmd => cmd.ExecuteNonQuery(_dialect.PurgeStorage));
}
public async Task Purge(string bucketId)
{
Logger.Warn(Messages.PurgingBucket, bucketId);
await ExecuteCommand(cmd =>
{
cmd.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
return cmd.ExecuteNonQuery(_dialect.PurgeBucket);
});
}
public Task Drop()
{
Logger.Warn(Messages.DroppingTables);
return ExecuteCommand(cmd => cmd.ExecuteNonQuery(_dialect.Drop));
}
public Task DeleteStream(string bucketId, string streamId)
{
Logger.Warn(Messages.DeletingStream, streamId, bucketId);
streamId = _streamIdHasher.GetHash(streamId);
return ExecuteCommand(cmd =>
{
cmd.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
return cmd.ExecuteNonQuery(_dialect.DeleteStream);
});
}
public IAsyncEnumerable<ICommit> GetFrom(string bucketId, string checkpointToken)
{
LongCheckpoint checkpoint = LongCheckpoint.Parse(checkpointToken);
Logger.Debug(Messages.GettingAllCommitsFromBucketAndCheckpoint, bucketId, checkpointToken);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromBucketAndCheckpoint;
query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString);
query.AddParameter(_dialect.CheckpointNumber, checkpoint.LongValue);
return query.ExecutePagedQuery(statement, (q, r) => { })
.Select(x => x.GetCommit(_serializer, _dialect));
});
}
public IAsyncEnumerable<ICommit> GetFrom(string checkpointToken)
{
LongCheckpoint checkpoint = LongCheckpoint.Parse(checkpointToken);
Logger.Debug(Messages.GettingAllCommitsFromCheckpoint, checkpointToken);
return ExecuteQuery(query =>
{
string statement = _dialect.GetCommitsFromCheckpoint;
query.AddParameter(_dialect.CheckpointNumber, checkpoint.LongValue);
return query.ExecutePagedQuery(statement, (q, r) => { })
.Select(async x => await x.GetCommit(_serializer, _dialect));
});
}
public bool IsDisposed
{
get { return _disposed; }
}
protected virtual void Dispose(bool disposing)
{
if (!disposing || _disposed)
{
return;
}
Logger.Debug(Messages.ShuttingDownPersistence);
_disposed = true;
}
protected virtual void OnPersistCommit(IDbStatement cmd, CommitAttempt attempt)
{ }
private Task<ICommit> PersistCommit(CommitAttempt attempt)
{
Logger.Debug(Messages.AttemptingToCommit, attempt.Events.Count, attempt.StreamId, attempt.CommitSequence, attempt.BucketId);
string streamId = _streamIdHasher.GetHash(attempt.StreamId);
return ExecuteCommand(async (connection, cmd) =>
{
cmd.AddParameter(_dialect.BucketId, attempt.BucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamIdOriginal, attempt.StreamId);
cmd.AddParameter(_dialect.StreamRevision, attempt.StreamRevision);
cmd.AddParameter(_dialect.Items, attempt.Events.Count);
cmd.AddParameter(_dialect.CommitId, attempt.CommitId);
cmd.AddParameter(_dialect.CommitSequence, attempt.CommitSequence);
cmd.AddParameter(_dialect.CommitStamp, attempt.CommitStamp);
cmd.AddParameter(_dialect.Headers, _serializer.Serialize(attempt.Headers));
_dialect.AddPayloadParamater(_connectionFactory, connection, cmd, _serializer.Serialize(attempt.Events.ToList()));
OnPersistCommit(cmd, attempt);
var checkpointNumber = (await cmd.ExecuteScalar(_dialect.PersistCommit)).ToLong();
return (ICommit)new Commit(
attempt.BucketId,
attempt.StreamId,
attempt.StreamRevision,
attempt.CommitId,
attempt.CommitSequence,
attempt.CommitStamp,
checkpointNumber.ToString(CultureInfo.InvariantCulture),
attempt.Headers,
attempt.Events);
});
}
private Task<bool> DetectDuplicate(CommitAttempt attempt)
{
string streamId = _streamIdHasher.GetHash(attempt.StreamId);
return ExecuteCommand(async cmd =>
{
cmd.AddParameter(_dialect.BucketId, attempt.BucketId, DbType.AnsiString);
cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString);
cmd.AddParameter(_dialect.CommitId, attempt.CommitId);
cmd.AddParameter(_dialect.CommitSequence, attempt.CommitSequence);
object value = await cmd.ExecuteScalar(_dialect.DuplicateCommit);
return (value is long ? (long)value : (int)value) > 0;
});
}
protected virtual IAsyncEnumerable<T> ExecuteQuery<T>(Func<IDbStatement, IAsyncEnumerable<T>> query)
{
return ExecuteQuery(statement => Task.FromResult(query(statement)));
}
protected virtual IAsyncEnumerable<T> ExecuteQuery2<T>(Func<IDbStatement, Task<IAsyncEnumerable<T>>> query)
{
return AsyncEnumerable.Create<T>(async producer =>
{
ThrowWhenDisposed();
TransactionScope scope = OpenQueryScope();
IDbAsyncConnection connection = null;
IDbTransaction transaction = null;
IDbStatement statement = null;
try
{
connection = await _connectionFactory.OpenAsync();
transaction = _dialect.OpenTransaction(connection);
statement = _dialect.BuildStatement(scope, connection, transaction);
statement.PageSize = _pageSize;
Logger.Verbose(Messages.ExecutingQuery);
await producer.Yield(await query(statement));
Logger.Verbose(Messages.ExecutingQuery);
}
catch (Exception e)
{
if (statement != null)
{
statement.Dispose();
}
if (transaction != null)
{
transaction.Dispose();
}
if (connection != null)
{
connection.Dispose();
}
if (scope != null)
{
scope.Dispose();
}
Logger.Debug(Messages.StorageThrewException, e.GetType());
if (e is StorageUnavailableException)
{
throw;
}
throw new StorageException(e.Message, e);
}
});
}
protected virtual IAsyncEnumerable<T> ExecuteQuery<T>(Func<IDbStatement, Task<IAsyncEnumerable<T>>> query)
{
return AsyncEnumerable.Create<T>(async producer =>
{
ThrowWhenDisposed();
using (var scope = OpenQueryScope())
using (var connection = await _connectionFactory.OpenAsync())
using (var transaction = _dialect.OpenTransaction(connection))
using (var statement = _dialect.BuildStatement(scope, connection, transaction))
{
Logger.Verbose(Messages.ExecutingQuery);
try
{
statement.PageSize = _pageSize;
var q = await query(statement);
var enumerator = q.GetEnumerator();
while(await enumerator.MoveNext())
{
await producer.Yield(enumerator.Current);
}
//await producer.Yield(await query(statement));
}
catch (Exception e)
{
Logger.Debug(Messages.StorageThrewException, e.GetType());
if (e is StorageUnavailableException)
{
throw;
}
throw new StorageException(e.Message, e);
}
finally
{
if (scope != null)
scope.Complete();
Logger.Verbose(Messages.QueryCompleted);
}
}
});
}
protected virtual TransactionScope OpenQueryScope()
{
return OpenCommandScope() ?? new TransactionScope(TransactionScopeOption.Suppress);
}
private void ThrowWhenDisposed()
{
if (!_disposed)
{
return;
}
Logger.Warn(Messages.AlreadyDisposed);
throw new ObjectDisposedException(Messages.AlreadyDisposed);
}
private Task<T> ExecuteCommand<T>(Func<IDbStatement, Task<T>> command)
{
return ExecuteCommand((_, statement) => command(statement));
}
protected virtual async Task<T> ExecuteCommand<T>(Func<IDbAsyncConnection, IDbStatement, Task<T>> command)
{
ThrowWhenDisposed();
using (var scope = OpenCommandScope())
using (var connection = await _connectionFactory.OpenAsync())
using (var transaction = _dialect.OpenTransaction(connection))
using (var statement = _dialect.BuildStatement(scope, connection, transaction))
{
try
{
Logger.Verbose(Messages.ExecutingCommand);
T rowsAffected = await command(connection, statement);
Logger.Verbose(Messages.CommandExecuted, rowsAffected);
if (transaction != null)
{
transaction.Commit();
}
if (scope != null)
{
scope.Complete();
}
return rowsAffected;
}
catch (Exception e)
{
Logger.Debug(Messages.StorageThrewException, e.GetType());
if (!RecoverableException(e))
{
throw new StorageException(e.Message, e);
}
Logger.Info(Messages.RecoverableExceptionCompletesScope);
if (scope != null)
{
scope.Complete();
}
throw;
}
}
}
protected virtual TransactionScope OpenCommandScope()
{
return new TransactionScope(_scopeOption, TransactionScopeAsyncFlowOption.Enabled);
}
private static bool RecoverableException(Exception e)
{
return e is UniqueKeyViolationException || e is StorageUnavailableException;
}
private class StreamIdHasherValidator : IStreamIdHasher
{
private readonly IStreamIdHasher _streamIdHasher;
private const int MaxStreamIdHashLength = 40;
public StreamIdHasherValidator(IStreamIdHasher streamIdHasher)
{
if (streamIdHasher == null)
{
throw new ArgumentNullException("streamIdHasher");
}
_streamIdHasher = streamIdHasher;
}
public string GetHash(string streamId)
{
if (string.IsNullOrWhiteSpace(streamId))
{
throw new ArgumentException(Messages.StreamIdIsNullEmptyOrWhiteSpace);
}
string streamIdHash = _streamIdHasher.GetHash(streamId);
if (string.IsNullOrWhiteSpace(streamIdHash))
{
throw new InvalidOperationException(Messages.StreamIdHashIsNullEmptyOrWhiteSpace);
}
if (streamIdHash.Length > MaxStreamIdHashLength)
{
throw new InvalidOperationException(Messages.StreamIdHashTooLong.FormatWith(streamId, streamIdHash, streamIdHash.Length, MaxStreamIdHashLength));
}
return streamIdHash;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL 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.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
using System.Net;
namespace fyiReporting.RDL
{
///<summary>
/// Represents an image. Source of image can from database, external or embedded.
///</summary>
[Serializable]
internal class Image : ReportItem
{
ImageSourceEnum _ImageSource; // Identifies the source of the image:
Expression _Value; // See Source. Expected datatype is string or
// binary, depending on Source. If the Value is
// null, no image is displayed.
Expression _MIMEType; // (string) An expression, the value of which is the
// MIMEType for the image.
// Valid values are: image/bmp, image/jpeg,
// image/gif, image/png, image/x-png
// Required if Source = Database. Ignored otherwise.
ImageSizingEnum _Sizing; // Defines the behavior if the image does not fit within the specified size.
bool _ConstantImage; // true if Image is a constant at runtime
string _EmbeddedImageData; // only for RenderHtml and embeddedImage. we need the embedded image code for html.
private string imageUrl; //Added from forum, User: solidstate http://www.fyireporting.com/forum/viewtopic.php?t=905
private static void CopyStream(Stream src, Stream dst)
{
byte[] buffer = new byte[16 * 1024];
int bytesRead;
while ((bytesRead = src.Read(buffer, 0, buffer.Length)) > 0) {
dst.Write(buffer, 0, bytesRead);
}
}
/// <summary>
/// Only gets set for Images which contain urls rather than coming from the database etc..
/// </summary>
public string ImageUrl
{
get { return imageUrl; }
private set { imageUrl = value; }
}
internal Image(ReportDefn r, ReportLink p, XmlNode xNode):base(r,p,xNode)
{
_ImageSource=ImageSourceEnum.Unknown;
_Value=null;
_MIMEType=null;
_Sizing=ImageSizingEnum.AutoSize;
_ConstantImage = false;
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Source":
_ImageSource = fyiReporting.RDL.ImageSource.GetStyle(xNodeLoop.InnerText);
break;
case "Value":
_Value = new Expression(r, this, xNodeLoop, ExpressionType.Variant);
break;
case "MIMEType":
_MIMEType = new Expression(r, this, xNodeLoop, ExpressionType.String);
break;
case "Sizing":
_Sizing = ImageSizing.GetStyle(xNodeLoop.InnerText, OwnerReport.rl);
break;
default:
if (ReportItemElement(xNodeLoop)) // try at ReportItem level
break;
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown Image element " + xNodeLoop.Name + " ignored.");
break;
}
}
if (_ImageSource==ImageSourceEnum.Unknown)
OwnerReport.rl.LogError(8, "Image requires a Source element.");
if (_Value == null)
OwnerReport.rl.LogError(8, "Image requires the Value element.");
}
// Handle parsing of function in final pass
override internal void FinalPass()
{
base.FinalPass();
_Value.FinalPass();
if (_MIMEType != null)
_MIMEType.FinalPass();
_ConstantImage = this.IsConstant();
return;
}
// Returns true if the image and style remain constant at runtime
bool IsConstant()
{
if (_Value.IsConstant())
{
if (_MIMEType == null || _MIMEType.IsConstant())
{
// if (this.Style == null || this.Style.ConstantStyle)
// return true;
return true; // ok if style changes
}
}
return false;
}
override internal void Run(IPresent ip, Row row)
{
base.Run(ip, row);
string mtype=null;
Stream strm=null;
try
{
strm = GetImageStream(ip.Report(), row, out mtype);
ip.Image(this, row, mtype, strm);
}
catch
{
// image failed to load; continue processing
}
finally
{
if (strm != null)
strm.Close();
}
return;
}
override internal void RunPage(Pages pgs, Row row)
{
Report r = pgs.Report;
bool bHidden = IsHidden(r, row);
WorkClass wc = GetWC(r);
string mtype=null;
Stream strm=null;
System.Drawing.Image im=null;
SetPagePositionBegin(pgs);
if (bHidden)
{
PageImage pi = new PageImage(ImageFormat.Jpeg, null, 0, 0);
this.SetPagePositionAndStyle(r, pi, row);
SetPagePositionEnd(pgs, pi.Y + pi.H);
return;
}
if (wc.PgImage != null)
{ // have we already generated this one
// reuse most of the work; only position will likely change
PageImage pi = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH);
pi.Name = wc.PgImage.Name; // this is name it will be shared under
pi.Sizing = this._Sizing;
this.SetPagePositionAndStyle(r, pi, row);
pgs.CurrentPage.AddObject(pi);
SetPagePositionEnd(pgs, pi.Y + pi.H);
return;
}
try
{
strm = GetImageStream(r, row, out mtype);
if (strm == null)
{
r.rl.LogError(4, string.Format("Unable to load image {0}.", this.Name.Nm));
return;
}
im = System.Drawing.Image.FromStream(strm);
int height = im.Height;
int width = im.Width;
MemoryStream ostrm = new MemoryStream();
strm.Position = 0;
ImageFormat imf;
switch(mtype.ToLower())
{
case "image/jpeg" :
imf = ImageFormat.Jpeg;
CopyStream(strm, ostrm);
break;
case "image/png":
imf = ImageFormat.Png;
CopyStream(strm, ostrm);
break;
default: // from old code where all images convert to jpeg, i don't know why. May be need delete it and add all support formats.
imf = ImageFormat.Jpeg;
System.Drawing.Imaging.ImageCodecInfo[] info;
info = ImageCodecInfo.GetImageEncoders();
EncoderParameters encoderParameters;
encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, ImageQualityManager.EmbeddedImageQuality);
System.Drawing.Imaging.ImageCodecInfo codec = null;
for (int i = 0; i < info.Length; i++)
{
if (info[i].FormatDescription == "JPEG")
{
codec = info[i];
break;
}
}
im.Save(ostrm, codec, encoderParameters);
break;
}
byte[] ba = ostrm.ToArray();
ostrm.Close();
PageImage pi = new PageImage(imf, ba, width, height);
pi.Sizing = this._Sizing;
this.SetPagePositionAndStyle(r, pi, row);
pgs.CurrentPage.AddObject(pi);
if (_ConstantImage)
{
wc.PgImage = pi;
// create unique name; PDF generation uses this to optimize the saving of the image only once
pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString(); // create unique name
}
SetPagePositionEnd(pgs, pi.Y + pi.H);
}
catch (Exception e)
{
// image failed to load, continue processing
r.rl.LogError(4, "Image load failed. " + e.Message);
}
finally
{
if (strm != null)
strm.Close();
if (im != null)
im.Dispose();
}
return;
}
Stream GetImageStream(Report rpt, Row row, out string mtype)
{
mtype=null;
Stream strm=null;
try
{
switch (this.ImageSource)
{
case ImageSourceEnum.Database:
if (_MIMEType == null)
return null;
mtype = _MIMEType.EvaluateString(rpt, row);
object o = _Value.Evaluate(rpt, row);
strm = new MemoryStream((byte[]) o);
break;
case ImageSourceEnum.Embedded:
string name = _Value.EvaluateString(rpt, row);
EmbeddedImage ei = (EmbeddedImage) OwnerReport.LUEmbeddedImages[name];
mtype = ei.MIMEType;
byte[] ba = Convert.FromBase64String(ei.ImageData);
_EmbeddedImageData = ei.ImageData; // we need this for html embedded image
strm = new MemoryStream(ba);
break;
case ImageSourceEnum.External:
//Added Image URL from forum, User: solidstate http://www.fyireporting.com/forum/viewtopic.php?t=905
string fname = this.ImageUrl = _Value.EvaluateString(rpt, row);
mtype = GetMimeType(fname);
if (fname.StartsWith("http:") ||
fname.StartsWith("file:") ||
fname.StartsWith("https:"))
{
WebRequest wreq = WebRequest.Create(fname);
WebResponse wres = wreq.GetResponse();
strm = wres.GetResponseStream();
}
else
strm = new FileStream(fname, System.IO.FileMode.Open, FileAccess.Read);
break;
default:
return null;
}
}
catch (Exception e)
{
if (strm != null)
{
strm.Close();
strm = null;
}
rpt.rl.LogError(4, string.Format("Unable to load image. {0}", e.Message));
}
return strm;
}
internal ImageSourceEnum ImageSource
{
get { return _ImageSource; }
set { _ImageSource = value; }
}
internal Expression Value
{
get { return _Value; }
set { _Value = value; }
}
internal Expression MIMEType
{
get { return _MIMEType; }
set { _MIMEType = value; }
}
internal ImageSizingEnum Sizing
{
get { return _Sizing; }
set { _Sizing = value; }
}
internal bool ConstantImage
{
get { return _ConstantImage; }
}
internal string EmbeddedImageData
{
get { return _EmbeddedImageData; }
}
static internal string GetMimeType(string file)
{
String fileExt;
int startPos = file.LastIndexOf(".") + 1;
fileExt = file.Substring(startPos).ToLower();
switch (fileExt)
{
case "bmp":
return "image/bmp";
case "jpeg":
case "jpe":
case "jpg":
case "jfif":
return "image/jpeg";
case "gif":
return "image/gif";
case "png":
return "image/png";
case "tif":
case "tiff":
return "image/tiff";
default:
return null;
}
}
private WorkClass GetWC(Report rpt)
{
WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass;
if (wc == null)
{
wc = new WorkClass();
rpt.Cache.Add(this, "wc", wc);
}
return wc;
}
private void RemoveImageWC(Report rpt)
{
rpt.Cache.Remove(this, "wc");
}
class WorkClass
{
internal PageImage PgImage; // When ConstantImage is true this will save the PageImage for reuse
internal WorkClass()
{
PgImage=null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure
{
public class DefaultPageActivatorProviderTest
{
[Fact]
public void CreateActivator_ThrowsIfPageTypeInfoIsNull()
{
// Arrange
var descriptor = new CompiledPageActionDescriptor();
var activator = new DefaultPageActivatorProvider();
// Act & Assert
ExceptionAssert.ThrowsArgument(
() => activator.CreateActivator(descriptor),
"actionDescriptor",
"The 'PageTypeInfo' property of 'actionDescriptor' must not be null.");
}
[Theory]
[InlineData(typeof(TestPage))]
[InlineData(typeof(PageWithMultipleConstructors))]
public void CreateActivator_ReturnsFactoryForPage(Type type)
{
// Arrange
var pageContext = new PageContext();
var viewContext = new ViewContext();
var descriptor = new CompiledPageActionDescriptor
{
PageTypeInfo = type.GetTypeInfo(),
};
var activator = new DefaultPageActivatorProvider();
// Act
var factory = activator.CreateActivator(descriptor);
var instance = factory(pageContext, viewContext);
// Assert
Assert.NotNull(instance);
Assert.IsType(type, instance);
}
[Fact]
public void CreateActivator_ThrowsIfTypeDoesNotHaveParameterlessConstructor()
{
// Arrange
var descriptor = new CompiledPageActionDescriptor
{
PageTypeInfo = typeof(PageWithoutParameterlessConstructor).GetTypeInfo(),
};
var pageContext = new PageContext();
var activator = new DefaultPageActivatorProvider();
// Act & Assert
Assert.Throws<ArgumentException>(() => activator.CreateActivator(descriptor));
}
[Theory]
[InlineData(typeof(TestPage))]
[InlineData(typeof(object))]
public void CreateReleaser_ReturnsNullForPagesThatDoNotImplementDisposable(Type pageType)
{
// Arrange
var context = new PageContext();
var activator = new DefaultPageActivatorProvider();
var page = new TestPage();
// Act
var releaser = activator.CreateReleaser(new CompiledPageActionDescriptor
{
PageTypeInfo = pageType.GetTypeInfo()
});
// Assert
Assert.Null(releaser);
}
[Theory]
[InlineData(typeof(TestPage))]
[InlineData(typeof(object))]
public void CreateAsyncReleaser_ReturnsNullForPagesThatDoNotImplementDisposable(Type pageType)
{
// Arrange
var context = new PageContext();
var activator = new DefaultPageActivatorProvider();
var page = new TestPage();
// Act
var releaser = activator.CreateAsyncReleaser(new CompiledPageActionDescriptor
{
PageTypeInfo = pageType.GetTypeInfo()
});
// Assert
Assert.Null(releaser);
}
[Fact]
public void CreateReleaser_CreatesDelegateThatDisposesDisposableTypes()
{
// Arrange
var context = new PageContext();
var viewContext = new ViewContext();
var activator = new DefaultPageActivatorProvider();
var page = new DisposablePage();
// Act & Assert
var disposer = activator.CreateReleaser(new CompiledPageActionDescriptor
{
PageTypeInfo = page.GetType().GetTypeInfo()
});
Assert.NotNull(disposer);
disposer(context, viewContext, page);
// Assert
Assert.True(page.Disposed);
}
[Fact]
public void CreateAsyncReleaser_CreatesDelegateThatDisposesDisposableTypes()
{
// Arrange
var context = new PageContext();
var viewContext = new ViewContext();
var activator = new DefaultPageActivatorProvider();
var page = new DisposablePage();
// Act & Assert
var disposer = activator.CreateAsyncReleaser(new CompiledPageActionDescriptor
{
PageTypeInfo = page.GetType().GetTypeInfo()
});
Assert.NotNull(disposer);
disposer(context, viewContext, page);
// Assert
Assert.True(page.Disposed);
}
[Fact]
public async Task CreateAsyncReleaser_CreatesDelegateThatDisposesAsyncDisposableTypes()
{
// Arrange
var context = new PageContext();
var viewContext = new ViewContext();
var activator = new DefaultPageActivatorProvider();
var page = new AsyncDisposablePage();
// Act & Assert
var disposer = activator.CreateAsyncReleaser(new CompiledPageActionDescriptor
{
PageTypeInfo = page.GetType().GetTypeInfo()
});
Assert.NotNull(disposer);
await disposer(context, viewContext, page);
// Assert
Assert.True(page.Disposed);
}
[Fact]
public async Task CreateAsyncReleaser_CreatesDelegateThatPrefersAsyncDisposeAsyncOverDispose()
{
// Arrange
var context = new PageContext();
var viewContext = new ViewContext();
var activator = new DefaultPageActivatorProvider();
var page = new DisposableAndAsyncDisposablePage();
// Act & Assert
var disposer = activator.CreateAsyncReleaser(new CompiledPageActionDescriptor
{
PageTypeInfo = page.GetType().GetTypeInfo()
});
Assert.NotNull(disposer);
await disposer(context, viewContext, page);
// Assert
Assert.True(page.AsyncDisposed);
Assert.False(page.SyncDisposed);
}
private class TestPage : Page
{
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
private class PageWithMultipleConstructors : Page
{
public PageWithMultipleConstructors(int x)
{
}
public PageWithMultipleConstructors()
{
}
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
private class PageWithoutParameterlessConstructor : Page
{
public PageWithoutParameterlessConstructor(ILogger logger)
{
}
public override Task ExecuteAsync()
{
throw new NotImplementedException();
}
}
private class DisposablePage : TestPage, IDisposable
{
public bool Disposed { get; private set; }
public void Dispose()
{
Disposed = true;
}
}
private class AsyncDisposablePage : TestPage, IAsyncDisposable
{
public bool Disposed { get; private set; }
public ValueTask DisposeAsync()
{
Disposed = true;
return default;
}
}
private class DisposableAndAsyncDisposablePage : TestPage, IDisposable, IAsyncDisposable
{
public bool AsyncDisposed { get; private set; }
public bool SyncDisposed { get; private set; }
public void Dispose()
{
SyncDisposed = true;
}
public ValueTask DisposeAsync()
{
AsyncDisposed = true;
return default;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Sep.Git.Tfs.Core.TfsInterop;
using Sep.Git.Tfs.Commands;
namespace Sep.Git.Tfs.Core
{
class DerivedGitTfsRemote : IGitTfsRemote
{
private readonly string _tfsUrl;
private readonly string _tfsRepositoryPath;
public DerivedGitTfsRemote(string tfsUrl, string tfsRepositoryPath)
{
_tfsUrl = tfsUrl;
_tfsRepositoryPath = tfsRepositoryPath;
}
GitTfsException DerivedRemoteException
{
get
{
return new GitTfsException("Unable to locate a remote for <" + _tfsUrl + ">" + _tfsRepositoryPath)
.WithRecommendation("Try using `git tfs bootstrap` to auto-init TFS remotes.")
.WithRecommendation("Try setting a legacy-url for an existing remote.");
}
}
public bool IsDerived
{
get { return true; }
}
public string Id
{
get { return "(derived)"; }
set { throw DerivedRemoteException; }
}
public string TfsUrl
{
get { return _tfsUrl; }
set { throw DerivedRemoteException; }
}
public bool Autotag
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public string TfsUsername
{
get
{
throw DerivedRemoteException;
}
set
{
throw DerivedRemoteException;
}
}
public string TfsPassword
{
get
{
throw DerivedRemoteException;
}
set
{
throw DerivedRemoteException;
}
}
public string TfsRepositoryPath
{
get { return _tfsRepositoryPath; }
set { throw DerivedRemoteException; }
}
public string[] TfsSubtreePaths
{
get
{
throw DerivedRemoteException;
}
}
#region Equality
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(DerivedGitTfsRemote)) return false;
return Equals((DerivedGitTfsRemote)obj);
}
private bool Equals(DerivedGitTfsRemote other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other._tfsUrl, _tfsUrl) && Equals(other._tfsRepositoryPath, _tfsRepositoryPath);
}
public override int GetHashCode()
{
unchecked
{
return ((_tfsUrl != null ? _tfsUrl.GetHashCode() : 0) * 397) ^ (_tfsRepositoryPath != null ? _tfsRepositoryPath.GetHashCode() : 0);
}
}
public static bool operator ==(DerivedGitTfsRemote left, DerivedGitTfsRemote right)
{
return Equals(left, right);
}
public static bool operator !=(DerivedGitTfsRemote left, DerivedGitTfsRemote right)
{
return !Equals(left, right);
}
#endregion
#region All this is not implemented
public string IgnoreRegexExpression
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public string IgnoreExceptRegexExpression
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public IGitRepository Repository
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public ITfsHelper Tfs
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public long MaxChangesetId
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public string MaxCommitHash
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public string RemoteRef
{
get { throw DerivedRemoteException; }
}
public bool IsSubtree
{
get { return false; }
}
public bool IsSubtreeOwner
{
get { return false; }
}
public string OwningRemoteId
{
get { return null; }
}
public string Prefix
{
get { return null; }
}
public bool ExportMetadatas { get; set; }
public Dictionary<string, string> ExportWorkitemsMapping { get; set; }
public bool ShouldSkip(string path)
{
throw DerivedRemoteException;
}
public IGitTfsRemote InitBranch(RemoteOptions remoteOptions, string tfsRepositoryPath, long shaRootChangesetId, bool fetchParentBranch, string gitBranchNameExpected = null)
{
throw new NotImplementedException();
}
public string GetPathInGitRepo(string tfsPath)
{
throw DerivedRemoteException;
}
public IFetchResult Fetch(bool stopOnFailMergeCommit = false)
{
throw DerivedRemoteException;
}
public IFetchResult FetchWithMerge(long mergeChangesetId, bool stopOnFailMergeCommit = false, params string[] parentCommitsHashes)
{
throw DerivedRemoteException;
}
public void QuickFetch()
{
throw DerivedRemoteException;
}
public void QuickFetch(int changesetId)
{
throw DerivedRemoteException;
}
public void Unshelve(string a, string b, string c, Action<Exception> h, bool force)
{
throw DerivedRemoteException;
}
public void Shelve(string shelvesetName, string treeish, TfsChangesetInfo parentChangeset, bool evaluateCheckinPolicies)
{
throw DerivedRemoteException;
}
public bool HasShelveset(string shelvesetName)
{
throw DerivedRemoteException;
}
public long CheckinTool(string head, TfsChangesetInfo parentChangeset)
{
throw DerivedRemoteException;
}
public long Checkin(string treeish, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null)
{
throw DerivedRemoteException;
}
public long Checkin(string head, string parent, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null)
{
throw DerivedRemoteException;
}
public void CleanupWorkspace()
{
throw DerivedRemoteException;
}
public void CleanupWorkspaceDirectory()
{
throw DerivedRemoteException;
}
public ITfsChangeset GetChangeset(long changesetId)
{
throw DerivedRemoteException;
}
public void UpdateTfsHead(string commitHash, long changesetId)
{
throw DerivedRemoteException;
}
public void EnsureTfsAuthenticated()
{
throw DerivedRemoteException;
}
public bool MatchesUrlAndRepositoryPath(string tfsUrl, string tfsRepositoryPath)
{
throw DerivedRemoteException;
}
public RemoteInfo RemoteInfo
{
get { throw DerivedRemoteException; }
}
public void Merge(string sourceTfsPath, string targetTfsPath)
{
throw DerivedRemoteException;
}
#endregion
}
}
| |
using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
namespace NeHeLesson8
{
public partial class MainWindowController : MonoMac.AppKit.NSWindowController
{
bool isInFullScreenMode;
// full-screen mode
NSWindow fullScreenWindow;
MyOpenGLView fullScreenView;
Scene scene;
bool isAnimating;
#region Constructors
// Call to load from the XIB/NIB file
public MainWindowController () : base("MainWindow")
{
}
#endregion
//strongly typed window accessor
public new MainWindow Window {
get { return (MainWindow)base.Window; }
}
public override void AwakeFromNib ()
{
// Allocate the scene object
scene = new Scene ();
// Assign the view's MainController to us
openGLView.MainController = this;
// reset the viewport and update OpenGL Context
openGLView.UpdateView ();
// Activate the display link now
openGLView.StartAnimation ();
isAnimating = true;
}
partial void goFullScreen (NSObject sender)
{
isInFullScreenMode = true;
// Pause the non-fullscreen view
openGLView.StopAnimation ();
RectangleF mainDisplayRect;
RectangleF viewRect;
// Create a screen-sized window on the display you want to take over
// Note, mainDisplayRect has a non-zero origin if the key window is on a secondary display
mainDisplayRect = NSScreen.MainScreen.Frame;
fullScreenWindow = new NSWindow (mainDisplayRect, NSWindowStyle.Borderless, NSBackingStore.Buffered, true);
// Set the window level to be above the menu bar
fullScreenWindow.Level = NSWindowLevel.MainMenu + 1;
// Perform any other window configuration you desire
fullScreenWindow.IsOpaque = true;
fullScreenWindow.HidesOnDeactivate = true;
// Create a view with a double-buffered OpenGL context and attach it to the window
// By specifying the non-fullscreen context as the shareContext, we automatically inherit the
// OpenGL objects (textures, etc) it has defined
viewRect = new RectangleF (0, 0, mainDisplayRect.Size.Width, mainDisplayRect.Size.Height);
fullScreenView = new MyOpenGLView (viewRect, openGLView.OpenGLContext);
fullScreenWindow.ContentView = fullScreenView;
// Show the window
fullScreenWindow.MakeKeyAndOrderFront (this);
// Set the scene with the full-screen viewport and viewing transformation
Scene.ResizeGLScene (viewRect);
// Assign the view's MainController to self
fullScreenView.MainController = this;
if (!isAnimating) {
// Mark the view as needing drawing to initalize its contents
fullScreenView.NeedsDisplay = true;
} else {
// Start playing the animation
fullScreenView.StartAnimation ();
}
}
public void goWindow ()
{
isInFullScreenMode = false;
// use OrderOut here instead of Close or nasty things will happen with Garbage Collection and a double free
fullScreenWindow.OrderOut (this);
fullScreenView.DeAllocate ();
fullScreenWindow.Dispose ();
fullScreenWindow = null;
// Switch to the non-fullscreen context
openGLView.OpenGLContext.MakeCurrentContext ();
if (!isAnimating) {
// Mark the view as needing drawing
// The animation has advanced while we were in full-screen mode, so its current contents are stale
openGLView.NeedsDisplay = true;
} else {
// continue playing the animation
openGLView.StartAnimation ();
}
}
public void startAnimation ()
{
if (isAnimating)
return;
if (!isInFullScreenMode)
openGLView.StartAnimation ();
else
fullScreenView.StartAnimation ();
isAnimating = true;
}
public void stopAnimation ()
{
if (!isAnimating)
return;
if (!isInFullScreenMode)
openGLView.StopAnimation ();
else
fullScreenView.StopAnimation ();
isAnimating = false;
}
public override void KeyDown (NSEvent theEvent)
{
var c = theEvent.KeyCode;
switch (c) {
// [Esc] exits full-screen mode
case (ushort)NSKey.Escape:
if (isInFullScreenMode)
goWindow ();
break;
case (ushort)NSKey.B:
Scene.IsBlendingOn = !Scene.IsBlendingOn;
break;
case (ushort)NSKey.L:
Scene.IsLightOn = !Scene.IsLightOn;
break;
case (ushort)NSKey.F:
Scene.Filter += 1;
break;
// up arrow key
case 126:
Scene.XSpeed -= 0.05f;
break;
// fn + up arrow key for page up
case 116:
Scene.Distance -= 0.10f;
break;
// down arrow key
case 125:
Scene.XSpeed += 0.05f;
break;
// fn + down arrow key for page down
case 121:
Scene.Distance += 0.10f;
break;
// left arrow key
case 123:
Scene.YSpeed -= 0.05f;
break;
// right arrow key
case 124:
Scene.YSpeed += 0.05f;
break;
default:
break;
}
}
// Accessor property for our scene object
public Scene Scene {
get { return scene; }
}
public void toggleFullScreen (NSObject sender)
{
if (!isInFullScreenMode)
goFullScreen (sender);
else
goWindow ();
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using static VulkanCore.Constant;
namespace VulkanCore
{
/// <summary>
/// Opaque handle to a descriptor set object.
/// <para>Descriptor sets are allocated from descriptor pool objects.</para>
/// </summary>
public unsafe class DescriptorSet : DisposableHandle<long>
{
internal DescriptorSet(DescriptorPool parent, long handle)
{
Parent = parent;
Handle = handle;
}
/// <summary>
/// Gets the parent of the resource.
/// </summary>
public DescriptorPool Parent { get; }
/// <summary>
/// Free descriptor set.
/// </summary>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public override void Dispose()
{
if (!Disposed)
{
long handle = this;
Result result = vkFreeDescriptorSets(Parent.Parent, Parent, 1, &handle);
VulkanException.ThrowForInvalidResult(result);
}
base.Dispose();
}
internal static void Free(DescriptorPool parent, DescriptorSet[] descriptorSets)
{
int count = descriptorSets?.Length ?? 0;
var descriptorSetsPtr = stackalloc long[count];
for (int i = 0; i < count; i++)
descriptorSetsPtr[i] = descriptorSets[i];
Result result = vkFreeDescriptorSets(parent.Parent, parent, count, descriptorSetsPtr);
VulkanException.ThrowForInvalidResult(result);
}
internal static DescriptorSet[] Allocate(DescriptorPool parent, ref DescriptorSetAllocateInfo createInfo)
{
fixed (long* setLayoutsPtr = createInfo.SetLayouts)
{
createInfo.ToNative(out DescriptorSetAllocateInfo.Native nativeCreateInfo, parent, setLayoutsPtr);
int count = createInfo.SetLayouts?.Length ?? 0;
var descriptorSetsPtr = stackalloc long[count];
Result result = vkAllocateDescriptorSets(parent.Parent, &nativeCreateInfo, descriptorSetsPtr);
VulkanException.ThrowForInvalidResult(result);
var descriptorSets = new DescriptorSet[count];
for (int i = 0; i < count; i++)
descriptorSets[i] = new DescriptorSet(parent, descriptorSetsPtr[i]);
return descriptorSets;
}
}
internal static void Update(DescriptorPool parent,
WriteDescriptorSet[] descriptorWrites, CopyDescriptorSet[] descriptorCopies)
{
int descriptorWriteCount = descriptorWrites?.Length ?? 0;
var nativeDescriptorWritesPtr = stackalloc WriteDescriptorSet.Native[descriptorWriteCount];
for (int i = 0; i < descriptorWriteCount; i++)
descriptorWrites[i].ToNative(&nativeDescriptorWritesPtr[i]);
int descriptorCopyCount = descriptorCopies?.Length ?? 0;
for (int i = 0; i < descriptorCopyCount; i++)
descriptorCopies[i].Prepare();
fixed (CopyDescriptorSet* descriptorCopiesPtr = descriptorCopies)
{
vkUpdateDescriptorSets(
parent.Parent,
descriptorWriteCount,
nativeDescriptorWritesPtr,
descriptorCopyCount,
descriptorCopiesPtr);
}
for (int i = 0; i < descriptorWriteCount; i++)
nativeDescriptorWritesPtr[i].Free();
}
private delegate Result vkAllocateDescriptorSetsDelegate(IntPtr device, DescriptorSetAllocateInfo.Native* allocateInfo, long* descriptorSets);
private static readonly vkAllocateDescriptorSetsDelegate vkAllocateDescriptorSets = VulkanLibrary.GetStaticProc<vkAllocateDescriptorSetsDelegate>(nameof(vkAllocateDescriptorSets));
private delegate Result vkFreeDescriptorSetsDelegate(IntPtr device, long descriptorPool, int descriptorSetCount, long* descriptorSets);
private static readonly vkFreeDescriptorSetsDelegate vkFreeDescriptorSets = VulkanLibrary.GetStaticProc<vkFreeDescriptorSetsDelegate>(nameof(vkFreeDescriptorSets));
private delegate void vkUpdateDescriptorSetsDelegate(IntPtr device, int descriptorWriteCount, WriteDescriptorSet.Native* descriptorWrites, int descriptorCopyCount, CopyDescriptorSet* descriptorCopies);
private static readonly vkUpdateDescriptorSetsDelegate vkUpdateDescriptorSets = VulkanLibrary.GetStaticProc<vkUpdateDescriptorSetsDelegate>(nameof(vkUpdateDescriptorSets));
}
/// <summary>
/// Structure specifying the allocation parameters for descriptor sets.
/// </summary>
public unsafe struct DescriptorSetAllocateInfo
{
/// <summary>
/// Determines the number of descriptor sets to be allocated from the pool.
/// </summary>
public int DescriptorSetCount;
/// <summary>
/// An array of <see cref="DescriptorSetLayout"/>, with each member specifying how the
/// corresponding descriptor set is allocated.
/// <para>Array length must be greater than 0.</para>
/// </summary>
public long[] SetLayouts;
/// <summary>
/// Initializes a new instance of the <see cref="DescriptorSetAllocateInfo"/> structure.
/// </summary>
/// <param name="descriptorSetCount">
/// Determines the number of descriptor sets to be allocated from the pool.
/// </param>
/// <param name="setLayouts">
/// An array of descriptor set layouts, with each member specifying how the corresponding
/// descriptor set is allocated.
/// </param>
public DescriptorSetAllocateInfo(int descriptorSetCount, params DescriptorSetLayout[] setLayouts)
{
DescriptorSetCount = descriptorSetCount;
SetLayouts = setLayouts?.ToHandleArray();
}
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public StructureType Type;
public IntPtr Next;
public long DescriptorPool;
public int DescriptorSetCount;
public long* SetLayouts;
}
internal void ToNative(out Native native, DescriptorPool pool, long* setLayouts)
{
native.Type = StructureType.DescriptorSetAllocateInfo;
native.Next = IntPtr.Zero;
native.DescriptorPool = pool;
native.DescriptorSetCount = DescriptorSetCount;
native.SetLayouts = setLayouts;
}
}
/// <summary>
/// Structure specifying the parameters of a descriptor set write operation.
/// </summary>
public unsafe struct WriteDescriptorSet
{
/// <summary>
/// The destination descriptor set to update.
/// </summary>
public long DstSet;
/// <summary>
/// The descriptor binding within that set.
/// </summary>
public int DstBinding;
/// <summary>
/// The starting element in that array.
/// </summary>
public int DstArrayElement;
/// <summary>
/// The number of descriptors to update (the number of elements in <see cref="ImageInfo"/>,
/// <see cref="BufferInfo"/>, or <see cref="TexelBufferView"/>).
/// </summary>
public int DescriptorCount;
/// <summary>
/// Specifies the type of each descriptor in <see cref="ImageInfo"/>, <see
/// cref="BufferInfo"/>, or <see cref="TexelBufferView"/>, as described below. It must be the
/// same type as that specified in <see cref="DescriptorSetLayoutBinding"/> for <see
/// cref="DstSet"/> at <see cref="DstBinding"/>. The type of the descriptor also controls
/// which array the descriptors are taken from.
/// </summary>
public DescriptorType DescriptorType;
/// <summary>
/// An array of <see cref="DescriptorImageInfo"/> structures or is ignored.
/// </summary>
public DescriptorImageInfo[] ImageInfo;
/// <summary>
/// An array of <see cref="DescriptorBufferInfo"/> structures or is ignored.
/// </summary>
public DescriptorBufferInfo[] BufferInfo;
/// <summary>
/// An array of <see cref="BufferView"/> handles or is ignored.
/// </summary>
public long[] TexelBufferView;
/// <summary>
/// Initializes a new instance of the <see cref="WriteDescriptorSet"/> structure.
/// </summary>
/// <param name="dstSet">The destination descriptor set to update.</param>
/// <param name="dstBinding">The descriptor binding within that set.</param>
/// <param name="dstArrayElement">The starting element in that array.</param>
/// <param name="descriptorCount">
/// The number of descriptors to update (the number of elements in <see cref="ImageInfo"/>,
/// <see cref="BufferInfo"/>, or <see cref="TexelBufferView"/>).
/// </param>
/// <param name="descriptorType">
/// Specifies the type of each descriptor in <see cref="ImageInfo"/>, <see
/// cref="BufferInfo"/>, or <see cref="TexelBufferView"/>, as described below. It must be the
/// same type as that specified in <see cref="DescriptorSetLayoutBinding"/> for <see
/// cref="DstSet"/> at <see cref="DstBinding"/>. The type of the descriptor also controls
/// which array the descriptors are taken from.
/// </param>
/// <param name="imageInfo">
/// An array of <see cref="DescriptorImageInfo"/> structures or is ignored.
/// </param>
/// <param name="bufferInfo">
/// An array of <see cref="DescriptorBufferInfo"/> structures or is ignored.
/// </param>
/// <param name="texelBufferView">An array of <see cref="BufferView"/> handles or is ignored.</param>
public WriteDescriptorSet(DescriptorSet dstSet, int dstBinding, int dstArrayElement, int descriptorCount,
DescriptorType descriptorType, DescriptorImageInfo[] imageInfo = null, DescriptorBufferInfo[] bufferInfo = null,
BufferView[] texelBufferView = null)
{
DstSet = dstSet;
DstBinding = dstBinding;
DstArrayElement = dstArrayElement;
DescriptorCount = descriptorCount;
DescriptorType = descriptorType;
ImageInfo = imageInfo;
BufferInfo = bufferInfo;
TexelBufferView = texelBufferView?.ToHandleArray();
}
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public StructureType Type;
public IntPtr Next;
public long DstSet;
public int DstBinding;
public int DstArrayElement;
public int DescriptorCount;
public DescriptorType DescriptorType;
public IntPtr ImageInfo;
public IntPtr BufferInfo;
public IntPtr TexelBufferView;
public void Free()
{
Interop.Free(ImageInfo);
Interop.Free(BufferInfo);
Interop.Free(TexelBufferView);
}
}
internal void ToNative(Native* native)
{
native->Type = StructureType.WriteDescriptorSet;
native->DstSet = DstSet;
native->DstBinding = DstBinding;
native->DescriptorCount = DescriptorCount;
native->DescriptorType = DescriptorType;
native->ImageInfo = Interop.Struct.AllocToPointer(ImageInfo);
native->BufferInfo = Interop.Struct.AllocToPointer(BufferInfo);
native->TexelBufferView = Interop.Struct.AllocToPointer(TexelBufferView);
}
}
/// <summary>
/// Specifies the type of a descriptor in a descriptor set.
/// </summary>
public enum DescriptorType
{
/// <summary>
/// Specifies a sampler descriptor.
/// </summary>
Sampler = 0,
/// <summary>
/// Specifies a combined image sampler descriptor.
/// </summary>
CombinedImageSampler = 1,
/// <summary>
/// Specifies a storage image descriptor.
/// </summary>
SampledImage = 2,
/// <summary>
/// Specifies a sampled image descriptor.
/// </summary>
StorageImage = 3,
/// <summary>
/// Specifies a uniform texel buffer descriptor.
/// </summary>
UniformTexelBuffer = 4,
/// <summary>
/// Specifies a storage texel buffer descriptor.
/// </summary>
StorageTexelBuffer = 5,
/// <summary>
/// Specifies a uniform buffer descriptor.
/// </summary>
UniformBuffer = 6,
/// <summary>
/// Specifies a storage buffer descriptor.
/// </summary>
StorageBuffer = 7,
/// <summary>
/// Specifies a dynamic uniform buffer descriptor.
/// </summary>
UniformBufferDynamic = 8,
/// <summary>
/// Specifies a dynamic storage buffer descriptor.
/// </summary>
StorageBufferDynamic = 9,
/// <summary>
/// Specifies a input attachment descriptor.
/// </summary>
InputAttachment = 10
}
/// <summary>
/// Structure specifying descriptor image info.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DescriptorImageInfo
{
/// <summary>
/// A sampler handle, and is used in descriptor updates for types <see
/// cref="DescriptorType.Sampler"/> and <see cref="DescriptorType.CombinedImageSampler"/> if
/// the binding being updated does not use immutable samplers.
/// </summary>
public long Sampler;
/// <summary>
/// An <see cref="ImageView"/> handle, and is used in descriptor updates for types <see
/// cref="DescriptorType.SampledImage"/>, <see cref="DescriptorType.StorageImage"/>, <see
/// cref="DescriptorType.CombinedImageSampler"/>, and <see cref="DescriptorType.InputAttachment"/>.
/// </summary>
public long ImageView;
/// <summary>
/// The layout that the image subresources accessible from <see cref="ImageView"/> will be in
/// at the time this descriptor is accessed. Is used in descriptor updates for types <see
/// cref="DescriptorType.SampledImage"/>, <see cref="DescriptorType.StorageImage"/>, <see
/// cref="DescriptorType.CombinedImageSampler"/>, and <see cref="DescriptorType.InputAttachment"/>.
/// </summary>
public ImageLayout ImageLayout;
/// <summary>
/// Initializes a new instance of the <see cref="DescriptorImageInfo"/> structure.
/// </summary>
/// <param name="sampler">
/// A sampler handle, and is used in descriptor updates for types <see
/// cref="DescriptorType.Sampler"/> and <see cref="DescriptorType.CombinedImageSampler"/> if
/// the binding being updated does not use immutable samplers.
/// </param>
/// <param name="imageView">
/// An image view handle, and is used in descriptor updates for types <see
/// cref="DescriptorType.SampledImage"/>, <see cref="DescriptorType.StorageImage"/>, <see
/// cref="DescriptorType.CombinedImageSampler"/>, and <see cref="DescriptorType.InputAttachment"/>.
/// </param>
/// <param name="imageLayout">
/// The layout that the image will be in at the time this descriptor is accessed. Is used in
/// descriptor updates for types <see cref="DescriptorType.SampledImage"/>, <see
/// cref="DescriptorType.StorageImage"/>, <see cref="DescriptorType.CombinedImageSampler"/>,
/// and <see cref="DescriptorType.InputAttachment"/>.
/// </param>
public DescriptorImageInfo(Sampler sampler, ImageView imageView, ImageLayout imageLayout)
{
Sampler = sampler;
ImageView = imageView;
ImageLayout = imageLayout;
}
}
/// <summary>
/// Structure specifying descriptor buffer info.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DescriptorBufferInfo
{
/// <summary>
/// The <see cref="Buffer"/> resource.
/// </summary>
public long Buffer;
/// <summary>
/// The offset in bytes from the start of buffer. Access to buffer memory via this descriptor
/// uses addressing that is relative to this starting offset.
/// </summary>
public long Offset;
/// <summary>
/// The size in bytes that is used for this descriptor update, or <see cref="WholeSize"/> to
/// use the range from <see cref="Offset"/> to the end of the buffer.
/// </summary>
public long Range;
/// <summary>
/// Initializes a new instance of the <see cref="DescriptorBufferInfo"/> structure.
/// </summary>
/// <param name="buffer">The buffer resource.</param>
/// <param name="offset">
/// The offset in bytes from the start of buffer. Access to buffer memory via this descriptor
/// uses addressing that is relative to this starting offset.
/// </param>
/// <param name="range">
/// The size in bytes that is used for this descriptor update, or <see cref="WholeSize"/> to
/// use the range from <see cref="Offset"/> to the end of the buffer.
/// </param>
public DescriptorBufferInfo(Buffer buffer, long offset = 0, long range = WholeSize)
{
Buffer = buffer;
Offset = offset;
Range = range;
}
}
/// <summary>
/// Structure specifying a copy descriptor set operation.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CopyDescriptorSet
{
internal StructureType Type;
internal IntPtr Next;
/// <summary>
/// Source <see cref="DescriptorSet"/>.
/// </summary>
public long SrcSet;
/// <summary>
/// Source binding.
/// <para>
/// Must be a valid binding within <see cref="SrcSet"/>. The sum of <see
/// cref="SrcArrayElement"/> and <see cref="DescriptorCount"/> must be less than or equal to
/// the number of array elements in the descriptor set binding specified by <see
/// cref="SrcBinding"/>, and all applicable consecutive bindings.
/// </para>
/// </summary>
public int SrcBinding;
/// <summary>
/// Array element within the source binding to copy from.
/// </summary>
public int SrcArrayElement;
/// <summary>
/// Destination <see cref="DescriptorSet"/>.
/// </summary>
public long DstSet;
/// <summary>
/// Destination binding.
/// <para>
/// Must be a valid binding within <see cref="DstSet"/>. The sum of <see
/// cref="DstArrayElement"/> and <see cref="DescriptorCount"/> must be less than or equal to
/// the number of array elements in the descriptor set binding specified by <see
/// cref="DstBinding"/>, and all applicable consecutive bindings. If <see cref="SrcSet"/> is
/// equal to <see cref="DstSet"/>, then the source and destination ranges of descriptors must
/// not overlap, where the ranges may include array elements from consecutive bindings.
/// </para>
/// </summary>
public int DstBinding;
/// <summary>
/// Array element within the destination binding to copy to.
/// </summary>
public int DstArrayElement;
/// <summary>
/// The number of descriptors to copy from the source to destination.
/// <para>
/// If <see cref="DescriptorCount"/> is greater than the number of remaining array elements
/// in the source or destination binding, those affect consecutive bindings in a manner
/// similar to <see cref="WriteDescriptorSet"/>.
/// </para>
/// </summary>
public int DescriptorCount;
/// <summary>
/// Initializes a new instance of the <see cref="CopyDescriptorSet"/> structure.
/// </summary>
/// <param name="srcSet">Source descriptor set.</param>
/// <param name="srcBinding">Source binding.</param>
/// <param name="srcArrayElement">Array element within the source binding to copy from.</param>
/// <param name="dstSet">Destination descriptor set.</param>
/// <param name="dstBinding">Destination binding.</param>
/// <param name="dstArrayElement">
/// Array element within the destination binding to copy to.
/// </param>
/// <param name="descriptorCount">
/// The number of descriptors to copy from the source to destination.
/// </param>
public CopyDescriptorSet(
DescriptorSet srcSet, int srcBinding, int srcArrayElement,
DescriptorSet dstSet, int dstBinding, int dstArrayElement,
int descriptorCount)
{
Type = StructureType.CopyDescriptorSet;
Next = IntPtr.Zero;
SrcSet = srcSet;
SrcBinding = srcBinding;
SrcArrayElement = srcArrayElement;
DstSet = dstSet;
DstBinding = dstBinding;
DstArrayElement = dstArrayElement;
DescriptorCount = descriptorCount;
}
internal void Prepare()
{
Type = StructureType.CopyDescriptorSet;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebAPIs.Areas.HelpPage.ModelDescriptions;
using WebAPIs.Areas.HelpPage.Models;
namespace WebAPIs.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASCON
{
using System.Threading;
using System.Xml.XPath;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.Common.DataStructures;
using Microsoft.Protocols.TestTools;
/// <summary>
/// Adapter class of MS-ASCON.
/// </summary>
public partial class MS_ASCONAdapter : ManagedAdapterBase, IMS_ASCONAdapter
{
/// <summary>
/// The instance of ActiveSync client.
/// </summary>
private ActiveSyncClient activeSyncClient;
/// <summary>
/// Gets the raw XML request sent to protocol SUT.
/// </summary>
public IXPathNavigable LastRawRequestXml
{
get { return this.activeSyncClient.LastRawRequestXml; }
}
/// <summary>
/// Gets the raw XML response received from protocol SUT.
/// </summary>
public IXPathNavigable LastRawResponseXml
{
get { return this.activeSyncClient.LastRawResponseXml; }
}
/// <summary>
/// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite.
/// </summary>
/// <param name="testSite">Transfer ITestSite into adapter, make adapter can use ITestSite's function.</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
testSite.DefaultProtocolDocShortName = "MS-ASCON";
// Merge the common configuration
Common.MergeConfiguration(testSite);
this.activeSyncClient = new ActiveSyncClient(testSite)
{
UserName = Common.GetConfigurationPropertyValue("User1Name", testSite),
Password = Common.GetConfigurationPropertyValue("User1Password", testSite)
};
}
/// <summary>
/// Change the user authentication.
/// </summary>
/// <param name="userName">The name of a user.</param>
/// <param name="userPassword">The password of a user.</param>
/// <param name="userDomain">The domain which the user belongs to.</param>
public void SwitchUser(string userName, string userPassword, string userDomain)
{
this.activeSyncClient.UserName = userName;
this.activeSyncClient.Password = userPassword;
this.activeSyncClient.Domain = userDomain;
}
/// <summary>
/// Synchronizes changes in a collection between the client and the server.
/// </summary>
/// <param name="syncRequest">A SyncRequest object that contains the request information.</param>
/// <returns>The SyncStore result which is returned from server.</returns>
public SyncStore Sync(SyncRequest syncRequest)
{
SyncResponse syncResponse = this.activeSyncClient.Sync(syncRequest, true);
Site.Assert.IsNotNull(syncResponse, "The Sync response returned from server should not be null.");
SyncStore syncStore = Common.LoadSyncResponse(syncResponse);
if (1 == syncStore.CollectionStatus && syncStore.AddElements.Count != 0)
{
foreach (Sync addElement in syncStore.AddElements)
{
this.VerifySyncCommandResponse(addElement);
}
}
// Verify related requirements.
this.VerifyCommonRequirements();
this.VerifyWBXMLCapture();
return syncStore;
}
/// <summary>
/// Find an email with specific subject.
/// </summary>
/// <param name="syncRequest">A SyncRequest object that contains the request information.</param>
/// <param name="subject">The subject of the email to find.</param>
/// <param name="isRetryNeeded">A boolean whether need retry.</param>
/// <returns>The email with specific subject.</returns>
public Sync SyncEmail(SyncRequest syncRequest, string subject, bool isRetryNeeded)
{
Sync syncResult = this.activeSyncClient.SyncEmail(syncRequest, subject, isRetryNeeded);
// Verify related requirements.
this.VerifyCommonRequirements();
this.VerifyWBXMLCapture();
// If the email should be gotten, then verify the related requirements.
if (isRetryNeeded)
{
this.VerifySyncCommandResponse(syncResult);
}
return syncResult;
}
/// <summary>
/// Find entries address book, mailbox, or document library.
/// </summary>
/// <param name="searchRequest">A SearchRequest object that contains the request information.</param>
/// <param name="expectSuccess">Whether the Search command is expected to be successful.</param>
/// <param name="itemsCount">The count of the items expected to be found.</param>
/// <returns>The SearchStore result which is returned from server.</returns>
public SearchStore Search(SearchRequest searchRequest, bool expectSuccess, int itemsCount)
{
SearchResponse searchResponse;
if (expectSuccess)
{
searchResponse = this.activeSyncClient.Search(searchRequest, true, itemsCount);
}
else
{
searchResponse = this.activeSyncClient.Search(searchRequest);
}
int retryCount = int.Parse(Common.GetConfigurationPropertyValue("RetryCount", this.Site));
int waitTime = int.Parse(Common.GetConfigurationPropertyValue("WaitTime", this.Site));
int counter = 1;
while (counter < retryCount && searchResponse.ResponseData.Status.Equals("10"))
{
Thread.Sleep(waitTime);
if (expectSuccess)
{
searchResponse = this.activeSyncClient.Search(searchRequest, true, itemsCount);
}
else
{
searchResponse = this.activeSyncClient.Search(searchRequest);
}
counter++;
}
Site.Assert.IsNotNull(searchResponse, "The Search response returned from server should not be null.");
// Verify related requirements.
this.VerifyCommonRequirements();
this.VerifyWBXMLCapture();
SearchStore searchStore = Common.LoadSearchResponse(searchResponse, Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site));
return searchStore;
}
/// <summary>
/// Acts as a container for the Fetch element, the EmptyFolderContents element, and the Move element to provide batched online handling of these operations against the server.
/// </summary>
/// <param name="itemOperationsRequest">An ItemOperationsRequest object that contains the request information.</param>
/// <returns>ItemOperations command response.</returns>
public ItemOperationsResponse ItemOperations(ItemOperationsRequest itemOperationsRequest)
{
ItemOperationsResponse itemOperationsResponse = this.activeSyncClient.ItemOperations(itemOperationsRequest, DeliveryMethodForFetch.Inline);
Site.Assert.IsNotNull(itemOperationsResponse, "The ItemOperations response returned from server should not be null.");
// Verify related requirements.
this.VerifyCommonRequirements();
this.VerifyWBXMLCapture();
this.VerifyItemOperationsCommandResponse(itemOperationsResponse);
return itemOperationsResponse;
}
/// <summary>
/// Synchronizes the collection hierarchy
/// </summary>
/// <param name="folderSyncRequest">A FolderSyncRequest object that contains the request information.</param>
/// <returns>FolderSync command response.</returns>
public FolderSyncResponse FolderSync(FolderSyncRequest folderSyncRequest)
{
FolderSyncResponse folderSyncResponse = this.activeSyncClient.FolderSync(folderSyncRequest);
Site.Assert.IsNotNull(folderSyncResponse, "The FolderSync response returned from server should not be null.");
return folderSyncResponse;
}
/// <summary>
/// Sends MIME-formatted e-mail messages to the server.
/// </summary>
/// <param name="sendMailRequest">A SendMailRequest object that contains the request information.</param>
/// <returns>SendMail command response.</returns>
public SendMailResponse SendMail(SendMailRequest sendMailRequest)
{
SendMailResponse sendMailResponse = this.activeSyncClient.SendMail(sendMailRequest);
Site.Assert.IsNotNull(sendMailResponse, "The SendMail response returned from server should not be null.");
return sendMailResponse;
}
/// <summary>
/// Replies to messages without retrieving the full, original message from the server.
/// </summary>
/// <param name="smartReplyRequest">A SmartReplyRequest object that contains the request information.</param>
/// <returns>SmartReply command response.</returns>
public SmartReplyResponse SmartReply(SmartReplyRequest smartReplyRequest)
{
SmartReplyResponse smartReplyResponse = this.activeSyncClient.SmartReply(smartReplyRequest);
Site.Assert.IsNotNull(smartReplyResponse, "The SmartReply response returned from server should not be null.");
return smartReplyResponse;
}
/// <summary>
/// Forwards messages without retrieving the full, original message from the server.
/// </summary>
/// <param name="smartForwardRequest">A SmartForwardRequest object that contains the request information.</param>
/// <returns>SmartForward command response.</returns>
public SmartForwardResponse SmartForward(SmartForwardRequest smartForwardRequest)
{
SmartForwardResponse smartForwardResponse = this.activeSyncClient.SmartForward(smartForwardRequest);
Site.Assert.IsNotNull(smartForwardResponse, "The SmartForward response returned from server should not be null.");
return smartForwardResponse;
}
/// <summary>
/// Moves an item or items from one folder on the server to another.
/// </summary>
/// <param name="moveItemsRequest">A MoveItemsRequest object that contains the request information.</param>
/// <returns>MoveItems command response.</returns>
public MoveItemsResponse MoveItems(MoveItemsRequest moveItemsRequest)
{
MoveItemsResponse moveItemsResponse = this.activeSyncClient.MoveItems(moveItemsRequest);
Site.Assert.IsNotNull(moveItemsResponse, "The MoveItems response returned from server should not be null.");
// Verify related requirements.
this.VerifyCommonRequirements();
this.VerifyWBXMLCapture();
return moveItemsResponse;
}
/// <summary>
/// Gets an estimate of the number of items in a collection or folder on the server that have to be synchronized.
/// </summary>
/// <param name="getItemEstimateRequest">A GetItemEstimateRequest object that contains the request information.</param>
/// <returns>GetItemEstimate command response.</returns>
public GetItemEstimateResponse GetItemEstimate(GetItemEstimateRequest getItemEstimateRequest)
{
GetItemEstimateResponse getItemEstimateResponse = this.activeSyncClient.GetItemEstimate(getItemEstimateRequest);
Site.Assert.IsNotNull(getItemEstimateResponse, "The GetItemEstimate response returned from server should not be null.");
// Verify related requirements.
this.VerifyCommonRequirements();
return getItemEstimateResponse;
}
}
}
| |
/*
* 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.Drawing;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
public enum DrawRoutine
{
Rectangle,
Polygon,
Ellipse
}
public struct face
{
public Point[] pts;
}
public struct DrawStruct
{
public DrawRoutine dr;
public Rectangle rect;
public SolidBrush brush;
public face[] trns;
}
public class MapImageModule : IMapImageGenerator, IRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private IConfigSource m_config;
private IMapTileTerrainRenderer terrainRenderer;
#region IMapImageGenerator Members
public byte[] WriteJpeg2000Image(string gradientmap)
{
byte[] imageData = null;
bool drawPrimVolume = true;
bool textureTerrain = false;
try
{
IConfig startupConfig = m_config.Configs["Startup"];
drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume);
textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain);
}
catch
{
m_log.Warn("[MAPTILE]: Failed to load StartupConfig");
}
if (textureTerrain)
{
terrainRenderer = new TexturedMapTileRenderer();
}
else
{
terrainRenderer = new ShadedMapTileRenderer();
}
terrainRenderer.Initialise(m_scene, m_config);
using (Bitmap mapbmp = new Bitmap((int)Constants.RegionSize, (int)Constants.RegionSize))
{
//long t = System.Environment.TickCount;
//for (int i = 0; i < 10; ++i) {
terrainRenderer.TerrainToBitmap(mapbmp);
//}
//t = System.Environment.TickCount - t;
//m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t);
if (drawPrimVolume)
{
DrawObjectVolume(m_scene, mapbmp);
}
try
{
imageData = OpenJPEG.EncodeFromImage(mapbmp, true);
}
catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke
{
m_log.Error("Failed generating terrain map: " + e);
}
}
return imageData;
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source)
{
m_scene = scene;
m_config = source;
IConfig startupConfig = m_config.Configs["Startup"];
if (startupConfig.GetString("MapImageModule", "MapImageModule") !=
"MapImageModule")
return;
m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "MapImageModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
// TODO: unused:
// private void ShadeBuildings(Bitmap map)
// {
// lock (map)
// {
// lock (m_scene.Entities)
// {
// foreach (EntityBase entity in m_scene.Entities.Values)
// {
// if (entity is SceneObjectGroup)
// {
// SceneObjectGroup sog = (SceneObjectGroup) entity;
//
// foreach (SceneObjectPart primitive in sog.Children.Values)
// {
// int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2));
// int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2));
// int w = (int) primitive.Scale.X;
// int h = (int) primitive.Scale.Y;
//
// int dx;
// for (dx = x; dx < x + w; dx++)
// {
// int dy;
// for (dy = y; dy < y + h; dy++)
// {
// if (x < 0 || y < 0)
// continue;
// if (x >= map.Width || y >= map.Height)
// continue;
//
// map.SetPixel(dx, dy, Color.DarkGray);
// }
// }
// }
// }
// }
// }
// }
// }
private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp)
{
int tc = 0;
double[,] hm = whichScene.Heightmap.GetDoubles();
tc = Environment.TickCount;
m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
List<EntityBase> objs = whichScene.GetEntities();
Dictionary<uint, DrawStruct> z_sort = new Dictionary<uint, DrawStruct>();
//SortedList<float, RectangleDrawStruct> z_sort = new SortedList<float, RectangleDrawStruct>();
List<float> z_sortheights = new List<float>();
List<uint> z_localIDs = new List<uint>();
lock (objs)
{
foreach (EntityBase obj in objs)
{
// Only draw the contents of SceneObjectGroup
if (obj is SceneObjectGroup)
{
SceneObjectGroup mapdot = (SceneObjectGroup)obj;
Color mapdotspot = Color.Gray; // Default color when prim color is white
// Loop over prim in group
foreach (SceneObjectPart part in mapdot.Children.Values)
{
if (part == null)
continue;
// Draw if the object is at least 1 meter wide in any direction
if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f)
{
// Try to get the RGBA of the default texture entry..
//
try
{
// get the null checks out of the way
// skip the ones that break
if (part == null)
continue;
if (part.Shape == null)
continue;
if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass)
continue; // eliminates trees from this since we don't really have a good tree representation
// if you want tree blocks on the map comment the above line and uncomment the below line
//mapdotspot = Color.PaleGreen;
Primitive.TextureEntry textureEntry = part.Shape.Textures;
if (textureEntry == null || textureEntry.DefaultTexture == null)
continue;
Color4 texcolor = textureEntry.DefaultTexture.RGBA;
// Not sure why some of these are null, oh well.
int colorr = 255 - (int)(texcolor.R * 255f);
int colorg = 255 - (int)(texcolor.G * 255f);
int colorb = 255 - (int)(texcolor.B * 255f);
if (!(colorr == 255 && colorg == 255 && colorb == 255))
{
//Try to set the map spot color
try
{
// If the color gets goofy somehow, skip it *shakes fist at Color4
mapdotspot = Color.FromArgb(colorr, colorg, colorb);
}
catch (ArgumentException)
{
}
}
}
catch (IndexOutOfRangeException)
{
// Windows Array
}
catch (ArgumentOutOfRangeException)
{
// Mono Array
}
Vector3 pos = part.GetWorldPosition();
// skip prim outside of retion
if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
continue;
// skip prim in non-finite position
if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) ||
Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y))
continue;
// Figure out if object is under 256m above the height of the terrain
bool isBelow256AboveTerrain = false;
try
{
isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f));
}
catch (Exception)
{
}
if (isBelow256AboveTerrain)
{
// Translate scale by rotation so scale is represented properly when object is rotated
Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z);
Vector3 scale = new Vector3();
Vector3 tScale = new Vector3();
Vector3 axPos = new Vector3(pos.X,pos.Y,pos.Z);
Quaternion llrot = part.GetWorldRotation();
Quaternion rot = new Quaternion(llrot.W, llrot.X, llrot.Y, llrot.Z);
scale = lscale * rot;
// negative scales don't work in this situation
scale.X = Math.Abs(scale.X);
scale.Y = Math.Abs(scale.Y);
scale.Z = Math.Abs(scale.Z);
// This scaling isn't very accurate and doesn't take into account the face rotation :P
int mapdrawstartX = (int)(pos.X - scale.X);
int mapdrawstartY = (int)(pos.Y - scale.Y);
int mapdrawendX = (int)(pos.X + scale.X);
int mapdrawendY = (int)(pos.Y + scale.Y);
// If object is beyond the edge of the map, don't draw it to avoid errors
if (mapdrawstartX < 0 || mapdrawstartX > ((int)Constants.RegionSize - 1) || mapdrawendX < 0 || mapdrawendX > ((int)Constants.RegionSize - 1)
|| mapdrawstartY < 0 || mapdrawstartY > ((int)Constants.RegionSize - 1) || mapdrawendY < 0
|| mapdrawendY > ((int)Constants.RegionSize - 1))
continue;
#region obb face reconstruction part duex
Vector3[] vertexes = new Vector3[8];
// float[] distance = new float[6];
Vector3[] FaceA = new Vector3[6]; // vertex A for Facei
Vector3[] FaceB = new Vector3[6]; // vertex B for Facei
Vector3[] FaceC = new Vector3[6]; // vertex C for Facei
Vector3[] FaceD = new Vector3[6]; // vertex D for Facei
tScale = new Vector3(lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[0].x = pos.X + vertexes[0].x;
//vertexes[0].y = pos.Y + vertexes[0].y;
//vertexes[0].z = pos.Z + vertexes[0].z;
FaceA[0] = vertexes[0];
FaceB[3] = vertexes[0];
FaceA[4] = vertexes[0];
tScale = lscale;
scale = ((tScale * rot));
vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[1].x = pos.X + vertexes[1].x;
// vertexes[1].y = pos.Y + vertexes[1].y;
//vertexes[1].z = pos.Z + vertexes[1].z;
FaceB[0] = vertexes[1];
FaceA[1] = vertexes[1];
FaceC[4] = vertexes[1];
tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[2].x = pos.X + vertexes[2].x;
//vertexes[2].y = pos.Y + vertexes[2].y;
//vertexes[2].z = pos.Z + vertexes[2].z;
FaceC[0] = vertexes[2];
FaceD[3] = vertexes[2];
FaceC[5] = vertexes[2];
tScale = new Vector3(lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[3].x = pos.X + vertexes[3].x;
// vertexes[3].y = pos.Y + vertexes[3].y;
// vertexes[3].z = pos.Z + vertexes[3].z;
FaceD[0] = vertexes[3];
FaceC[1] = vertexes[3];
FaceA[5] = vertexes[3];
tScale = new Vector3(-lscale.X, lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[4].x = pos.X + vertexes[4].x;
// vertexes[4].y = pos.Y + vertexes[4].y;
// vertexes[4].z = pos.Z + vertexes[4].z;
FaceB[1] = vertexes[4];
FaceA[2] = vertexes[4];
FaceD[4] = vertexes[4];
tScale = new Vector3(-lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[5].x = pos.X + vertexes[5].x;
// vertexes[5].y = pos.Y + vertexes[5].y;
// vertexes[5].z = pos.Z + vertexes[5].z;
FaceD[1] = vertexes[5];
FaceC[2] = vertexes[5];
FaceB[5] = vertexes[5];
tScale = new Vector3(-lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[6].x = pos.X + vertexes[6].x;
// vertexes[6].y = pos.Y + vertexes[6].y;
// vertexes[6].z = pos.Z + vertexes[6].z;
FaceB[2] = vertexes[6];
FaceA[3] = vertexes[6];
FaceB[4] = vertexes[6];
tScale = new Vector3(-lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[7].x = pos.X + vertexes[7].x;
// vertexes[7].y = pos.Y + vertexes[7].y;
// vertexes[7].z = pos.Z + vertexes[7].z;
FaceD[2] = vertexes[7];
FaceC[3] = vertexes[7];
FaceD[5] = vertexes[7];
#endregion
//int wy = 0;
//bool breakYN = false; // If we run into an error drawing, break out of the
// loop so we don't lag to death on error handling
DrawStruct ds = new DrawStruct();
ds.brush = new SolidBrush(mapdotspot);
//ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY);
ds.trns = new face[FaceA.Length];
for (int i = 0; i < FaceA.Length; i++)
{
Point[] working = new Point[5];
working[0] = project(FaceA[i], axPos);
working[1] = project(FaceB[i], axPos);
working[2] = project(FaceD[i], axPos);
working[3] = project(FaceC[i], axPos);
working[4] = project(FaceA[i], axPos);
face workingface = new face();
workingface.pts = working;
ds.trns[i] = workingface;
}
z_sort.Add(part.LocalId, ds);
z_localIDs.Add(part.LocalId);
z_sortheights.Add(pos.Z);
//for (int wx = mapdrawstartX; wx < mapdrawendX; wx++)
//{
//for (wy = mapdrawstartY; wy < mapdrawendY; wy++)
//{
//m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy);
//try
//{
// Remember, flip the y!
// mapbmp.SetPixel(wx, (255 - wy), mapdotspot);
//}
//catch (ArgumentException)
//{
// breakYN = true;
//}
//if (breakYN)
// break;
//}
//if (breakYN)
// break;
//}
} // Object is within 256m Z of terrain
} // object is at least a meter wide
} // loop over group children
} // entitybase is sceneobject group
} // foreach loop over entities
float[] sortedZHeights = z_sortheights.ToArray();
uint[] sortedlocalIds = z_localIDs.ToArray();
// Sort prim by Z position
Array.Sort(sortedZHeights, sortedlocalIds);
Graphics g = Graphics.FromImage(mapbmp);
for (int s = 0; s < sortedZHeights.Length; s++)
{
if (z_sort.ContainsKey(sortedlocalIds[s]))
{
DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]];
for (int r = 0; r < rectDrawStruct.trns.Length; r++)
{
g.FillPolygon(rectDrawStruct.brush,rectDrawStruct.trns[r].pts);
}
//g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect);
}
}
g.Dispose();
} // lock entities objs
m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (Environment.TickCount - tc) + " ms");
return mapbmp;
}
private Point project(Vector3 point3d, Vector3 originpos)
{
Point returnpt = new Point();
//originpos = point3d;
//int d = (int)(256f / 1.5f);
//Vector3 topos = new Vector3(0, 0, 0);
// float z = -point3d.z - topos.z;
returnpt.X = (int)point3d.X;//(int)((topos.x - point3d.x) / z * d);
returnpt.Y = (int)(((int)Constants.RegionSize - 1) - point3d.Y);//(int)(255 - (((topos.y - point3d.y) / z * d)));
return returnpt;
}
// TODO: unused:
// #region Deprecated Maptile Generation. Adam may update this
// private Bitmap TerrainToBitmap(string gradientmap)
// {
// Bitmap gradientmapLd = new Bitmap(gradientmap);
//
// int pallete = gradientmapLd.Height;
//
// Bitmap bmp = new Bitmap(m_scene.Heightmap.Width, m_scene.Heightmap.Height);
// Color[] colours = new Color[pallete];
//
// for (int i = 0; i < pallete; i++)
// {
// colours[i] = gradientmapLd.GetPixel(0, i);
// }
//
// lock (m_scene.Heightmap)
// {
// ITerrainChannel copy = m_scene.Heightmap;
// for (int y = 0; y < copy.Height; y++)
// {
// for (int x = 0; x < copy.Width; x++)
// {
// // 512 is the largest possible height before colours clamp
// int colorindex = (int) (Math.Max(Math.Min(1.0, copy[x, y] / 512.0), 0.0) * (pallete - 1));
//
// // Handle error conditions
// if (colorindex > pallete - 1 || colorindex < 0)
// bmp.SetPixel(x, copy.Height - y - 1, Color.Red);
// else
// bmp.SetPixel(x, copy.Height - y - 1, colours[colorindex]);
// }
// }
// ShadeBuildings(bmp);
// return bmp;
// }
// }
// #endregion
}
}
| |
// PendingBuffer.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace TvdbLib.SharpZipLib.Zip.Compression
{
/// <summary>
/// This class is general purpose class for writing data to a buffer.
///
/// It allows you to write bits as well as bytes
/// Based on DeflaterPending.java
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class PendingBuffer
{
#region Instance Fields
/// <summary>
/// Internal work buffer
/// </summary>
byte[] buffer_;
int start;
int end;
uint bits;
int bitCount;
#endregion
#region Constructors
/// <summary>
/// construct instance using default buffer size of 4096
/// </summary>
public PendingBuffer() : this( 4096 )
{
}
/// <summary>
/// construct instance using specified buffer size
/// </summary>
/// <param name="bufferSize">
/// size to use for internal buffer
/// </param>
public PendingBuffer(int bufferSize)
{
buffer_ = new byte[bufferSize];
}
#endregion
/// <summary>
/// Clear internal state/buffers
/// </summary>
public void Reset()
{
start = end = bitCount = 0;
}
/// <summary>
/// Write a byte to buffer
/// </summary>
/// <param name="value">
/// The value to write
/// </param>
public void WriteByte(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte) value);
}
/// <summary>
/// Write a short value to buffer LSB first
/// </summary>
/// <param name="value">
/// The value to write.
/// </param>
public void WriteShort(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte) value);
buffer_[end++] = unchecked((byte) (value >> 8));
}
/// <summary>
/// write an integer LSB first
/// </summary>
/// <param name="value">The value to write.</param>
public void WriteInt(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte) value);
buffer_[end++] = unchecked((byte) (value >> 8));
buffer_[end++] = unchecked((byte) (value >> 16));
buffer_[end++] = unchecked((byte) (value >> 24));
}
/// <summary>
/// Write a block of data to buffer
/// </summary>
/// <param name="block">data to write</param>
/// <param name="offset">offset of first byte to write</param>
/// <param name="length">number of bytes to write</param>
public void WriteBlock(byte[] block, int offset, int length)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
System.Array.Copy(block, offset, buffer_, end, length);
end += length;
}
/// <summary>
/// The number of bits written to the buffer
/// </summary>
public int BitCount {
get {
return bitCount;
}
}
/// <summary>
/// Align internal buffer on a byte boundary
/// </summary>
public void AlignToByte()
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
if (bitCount > 0)
{
buffer_[end++] = unchecked((byte) bits);
if (bitCount > 8) {
buffer_[end++] = unchecked((byte) (bits >> 8));
}
}
bits = 0;
bitCount = 0;
}
/// <summary>
/// Write bits to internal buffer
/// </summary>
/// <param name="b">source of bits</param>
/// <param name="count">number of bits to write</param>
public void WriteBits(int b, int count)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("writeBits("+b+","+count+")");
// }
#endif
bits |= (uint)(b << bitCount);
bitCount += count;
if (bitCount >= 16) {
buffer_[end++] = unchecked((byte) bits);
buffer_[end++] = unchecked((byte) (bits >> 8));
bits >>= 16;
bitCount -= 16;
}
}
/// <summary>
/// Write a short value to internal buffer most significant byte first
/// </summary>
/// <param name="s">value to write</param>
public void WriteShortMSB(int s)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte) (s >> 8));
buffer_[end++] = unchecked((byte) s);
}
/// <summary>
/// Indicates if buffer has been flushed
/// </summary>
public bool IsFlushed {
get {
return end == 0;
}
}
/// <summary>
/// Flushes the pending buffer into the given output array. If the
/// output array is to small, only a partial flush is done.
/// </summary>
/// <param name="output">The output array.</param>
/// <param name="offset">The offset into output array.</param>
/// <param name="length">The maximum number of bytes to store.</param>
/// <returns>The number of bytes flushed.</returns>
public int Flush(byte[] output, int offset, int length)
{
if (bitCount >= 8) {
buffer_[end++] = unchecked((byte) bits);
bits >>= 8;
bitCount -= 8;
}
if (length > end - start) {
length = end - start;
System.Array.Copy(buffer_, start, output, offset, length);
start = 0;
end = 0;
} else {
System.Array.Copy(buffer_, start, output, offset, length);
start += length;
}
return length;
}
/// <summary>
/// Convert internal buffer to byte array.
/// Buffer is empty on completion
/// </summary>
/// <returns>
/// The internal buffer contents converted to a byte array.
/// </returns>
public byte[] ToByteArray()
{
byte[] result = new byte[end - start];
System.Array.Copy(buffer_, start, result, 0, result.Length);
start = 0;
end = 0;
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ReverseQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// Reverse imposes ordinal order preservation. There are normally two phases to this
/// operator's execution. Each partition first builds a buffer containing all of its
/// elements, and then proceeds to yielding the elements in reverse. There is a
/// 'barrier' (but not a blocking barrier) in between these two steps, at which point the largest index becomes
/// known. This is necessary so that when elements from the buffer are yielded, the
/// CurrentIndex can be reported as the largest index minus the original index (thereby
/// reversing the indices as well as the elements themselves). If the largest index is
/// known a priori, because we have an array for example, we can avoid the barrier in
/// between the steps.
/// </summary>
/// <typeparam name="TSource"></typeparam>
internal sealed class ReverseQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource>
{
//---------------------------------------------------------------------------------------
// Initializes a new reverse operator.
//
// Arguments:
// child - the child whose data we will reverse
//
internal ReverseQueryOperator(IEnumerable<TSource> child)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
if (Child.OrdinalIndexState == OrdinalIndexState.Indexible)
{
SetOrdinalIndexState(OrdinalIndexState.Indexible);
}
else
{
SetOrdinalIndexState(OrdinalIndexState.Shuffled);
}
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings)
{
Debug.Assert(Child.OrdinalIndexState != OrdinalIndexState.Indexible, "Don't take this code path if the child is indexible.");
int partitionCount = inputStream.PartitionCount;
PartitionedStream<TSource, TKey> outputStream = new PartitionedStream<TSource, TKey>(
partitionCount, new ReverseComparer<TKey>(inputStream.KeyComparer), OrdinalIndexState.Shuffled);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new ReverseQueryOperatorEnumerator<TKey>(inputStream[i], settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping)
{
QueryResults<TSource> childQueryResults = Child.Open(settings, false);
return ReverseQueryOperatorResults.NewResults(childQueryResults, this, settings, preferStriping);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TSource> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
return wrappedChild.Reverse();
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for executing the reverse operation.
//
class ReverseQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TSource, TKey>
{
private readonly QueryOperatorEnumerator<TSource, TKey> _source; // The data source to reverse.
private readonly CancellationToken _cancellationToken;
private List<Pair<TSource, TKey>> _buffer; // Our buffer. [allocate in moveNext to avoid false-sharing]
private Shared<int> _bufferIndex; // Our current index within the buffer. [allocate in moveNext to avoid false-sharing]
//---------------------------------------------------------------------------------------
// Instantiates a new select enumerator.
//
internal ReverseQueryOperatorEnumerator(QueryOperatorEnumerator<TSource, TKey> source,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
_source = source;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Straightforward IEnumerator<T> methods.
//
internal override bool MoveNext(ref TSource currentElement, ref TKey currentKey)
{
// If the buffer has not been created, we will generate it lazily on demand.
if (_buffer == null)
{
_bufferIndex = new Shared<int>(0);
// Buffer all of our data.
_buffer = new List<Pair<TSource, TKey>>();
TSource current = default(TSource);
TKey key = default(TKey);
int i = 0;
while (_source.MoveNext(ref current, ref key))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
_buffer.Add(new Pair<TSource, TKey>(current, key));
_bufferIndex.Value++;
}
}
// Continue yielding elements from our buffer.
if (--_bufferIndex.Value >= 0)
{
currentElement = _buffer[_bufferIndex.Value].First;
currentKey = _buffer[_bufferIndex.Value].Second;
return true;
}
return false;
}
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
}
//-----------------------------------------------------------------------------------
// Query results for a Reverse operator. The results are indexible if the child
// results were indexible.
//
class ReverseQueryOperatorResults : UnaryQueryOperatorResults
{
private int _count; // The number of elements in child results
public static QueryResults<TSource> NewResults(
QueryResults<TSource> childQueryResults, ReverseQueryOperator<TSource> op,
QuerySettings settings, bool preferStriping)
{
if (childQueryResults.IsIndexible)
{
return new ReverseQueryOperatorResults(
childQueryResults, op, settings, preferStriping);
}
else
{
return new UnaryQueryOperatorResults(
childQueryResults, op, settings, preferStriping);
}
}
private ReverseQueryOperatorResults(
QueryResults<TSource> childQueryResults, ReverseQueryOperator<TSource> op,
QuerySettings settings, bool preferStriping)
: base(childQueryResults, op, settings, preferStriping)
{
Debug.Assert(_childQueryResults.IsIndexible);
_count = _childQueryResults.ElementsCount;
}
internal override bool IsIndexible
{
get { return true; }
}
internal override int ElementsCount
{
get
{
Debug.Assert(_count >= 0);
return _count;
}
}
internal override TSource GetElement(int index)
{
Debug.Assert(_count >= 0);
Debug.Assert(index >= 0);
Debug.Assert(index < _count);
return _childQueryResults.GetElement(_count - index - 1);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Configuration
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using Microsoft.Xml;
using System.Linq;
public partial class SecurityElementBase : BindingElementExtensionElement
{
// if you add another variable, make sure to adjust: CopyFrom and UnMerge methods.
private SecurityBindingElement _failedSecurityBindingElement = null;
private bool _willX509IssuerReferenceAssertionBeWritten;
private SecurityKeyType _templateKeyType = IssuedSecurityTokenParameters.defaultKeyType;
internal SecurityElementBase()
{
}
internal bool HasImportFailed { get { return _failedSecurityBindingElement != null; } }
internal bool IsSecurityElementBootstrap { get; set; } // Used in serialization path to optimize Xml representation
public override Type BindingElementType
{
get { return typeof(SecurityBindingElement); }
}
protected internal override BindingElement CreateBindingElement()
{
throw new NotImplementedException();
}
private static bool AreTokenParametersMatching(SecurityTokenParameters p1, SecurityTokenParameters p2, bool skipRequireDerivedKeysComparison, bool exactMessageSecurityVersion)
{
if (p1 == null || p2 == null)
return false;
if (p1.GetType() != p2.GetType())
return false;
if (p1.InclusionMode != p2.InclusionMode)
return false;
if (skipRequireDerivedKeysComparison == false && p1.RequireDerivedKeys != p2.RequireDerivedKeys)
return false;
if (p1.ReferenceStyle != p2.ReferenceStyle)
return false;
// mutual ssl and anonymous ssl differ in the client cert requirement
if (p1 is SslSecurityTokenParameters)
{
if (((SslSecurityTokenParameters)p1).RequireClientCertificate != ((SslSecurityTokenParameters)p2).RequireClientCertificate)
return false;
}
else if (p1 is SecureConversationSecurityTokenParameters)
{
SecureConversationSecurityTokenParameters sc1 = (SecureConversationSecurityTokenParameters)p1;
SecureConversationSecurityTokenParameters sc2 = (SecureConversationSecurityTokenParameters)p2;
if (sc1.RequireCancellation != sc2.RequireCancellation)
return false;
if (sc1.CanRenewSession != sc2.CanRenewSession)
return false;
if (!AreBindingsMatching(sc1.BootstrapSecurityBindingElement, sc2.BootstrapSecurityBindingElement, exactMessageSecurityVersion))
return false;
}
else if (p1 is IssuedSecurityTokenParameters)
{
if (((IssuedSecurityTokenParameters)p1).KeyType != ((IssuedSecurityTokenParameters)p2).KeyType)
return false;
}
return true;
}
private static bool AreTokenParameterCollectionsMatching(Collection<SecurityTokenParameters> c1, Collection<SecurityTokenParameters> c2, bool exactMessageSecurityVersion)
{
if (c1.Count != c2.Count)
return false;
for (int i = 0; i < c1.Count; i++)
if (!AreTokenParametersMatching(c1[i], c2[i], true, exactMessageSecurityVersion))
return false;
return true;
}
internal static bool AreBindingsMatching(SecurityBindingElement b1, SecurityBindingElement b2)
{
return AreBindingsMatching(b1, b2, true);
}
internal static bool AreBindingsMatching(SecurityBindingElement b1, SecurityBindingElement b2, bool exactMessageSecurityVersion)
{
if (b1 == null || b2 == null)
return b1 == b2;
if (b1.GetType() != b2.GetType())
return false;
if (b1.MessageSecurityVersion != b2.MessageSecurityVersion)
{
// exactMessageSecurityVersion meant that BSP mismatch could be ignored
if (exactMessageSecurityVersion)
return false;
if (b1.MessageSecurityVersion.SecurityVersion != b2.MessageSecurityVersion.SecurityVersion
|| b1.MessageSecurityVersion.TrustVersion != b2.MessageSecurityVersion.TrustVersion
|| b1.MessageSecurityVersion.SecureConversationVersion != b2.MessageSecurityVersion.SecureConversationVersion
|| b1.MessageSecurityVersion.SecurityPolicyVersion != b2.MessageSecurityVersion.SecurityPolicyVersion)
{
return false;
}
}
if (b1.SecurityHeaderLayout != b2.SecurityHeaderLayout)
return false;
if (b1.DefaultAlgorithmSuite != b2.DefaultAlgorithmSuite)
return false;
if (b1.IncludeTimestamp != b2.IncludeTimestamp)
return false;
if (b1.SecurityHeaderLayout != b2.SecurityHeaderLayout)
return false;
if (b1.KeyEntropyMode != b2.KeyEntropyMode)
return false;
if (!AreTokenParameterCollectionsMatching(b1.EndpointSupportingTokenParameters.Endorsing, b2.EndpointSupportingTokenParameters.Endorsing, exactMessageSecurityVersion))
return false;
if (!AreTokenParameterCollectionsMatching(b1.EndpointSupportingTokenParameters.SignedEncrypted, b2.EndpointSupportingTokenParameters.SignedEncrypted, exactMessageSecurityVersion))
return false;
if (!AreTokenParameterCollectionsMatching(b1.EndpointSupportingTokenParameters.Signed, b2.EndpointSupportingTokenParameters.Signed, exactMessageSecurityVersion))
return false;
if (!AreTokenParameterCollectionsMatching(b1.EndpointSupportingTokenParameters.SignedEndorsing, b2.EndpointSupportingTokenParameters.SignedEndorsing, exactMessageSecurityVersion))
return false;
if (b1.OperationSupportingTokenParameters.Count != b2.OperationSupportingTokenParameters.Count)
return false;
foreach (KeyValuePair<string, SupportingTokenParameters> operation1 in b1.OperationSupportingTokenParameters)
{
if (!b2.OperationSupportingTokenParameters.ContainsKey(operation1.Key))
return false;
SupportingTokenParameters stp2 = b2.OperationSupportingTokenParameters[operation1.Key];
if (!AreTokenParameterCollectionsMatching(operation1.Value.Endorsing, stp2.Endorsing, exactMessageSecurityVersion))
return false;
if (!AreTokenParameterCollectionsMatching(operation1.Value.SignedEncrypted, stp2.SignedEncrypted, exactMessageSecurityVersion))
return false;
if (!AreTokenParameterCollectionsMatching(operation1.Value.Signed, stp2.Signed, exactMessageSecurityVersion))
return false;
if (!AreTokenParameterCollectionsMatching(operation1.Value.SignedEndorsing, stp2.SignedEndorsing, exactMessageSecurityVersion))
return false;
}
SymmetricSecurityBindingElement ssbe1 = b1 as SymmetricSecurityBindingElement;
if (ssbe1 != null)
{
SymmetricSecurityBindingElement ssbe2 = (SymmetricSecurityBindingElement)b2;
if (ssbe1.MessageProtectionOrder != ssbe2.MessageProtectionOrder)
return false;
if (!AreTokenParametersMatching(ssbe1.ProtectionTokenParameters, ssbe2.ProtectionTokenParameters, false, exactMessageSecurityVersion))
return false;
}
AsymmetricSecurityBindingElement asbe1 = b1 as AsymmetricSecurityBindingElement;
if (asbe1 != null)
{
AsymmetricSecurityBindingElement asbe2 = (AsymmetricSecurityBindingElement)b2;
if (asbe1.MessageProtectionOrder != asbe2.MessageProtectionOrder)
return false;
if (asbe1.RequireSignatureConfirmation != asbe2.RequireSignatureConfirmation)
return false;
if (!AreTokenParametersMatching(asbe1.InitiatorTokenParameters, asbe2.InitiatorTokenParameters, true, exactMessageSecurityVersion)
|| !AreTokenParametersMatching(asbe1.RecipientTokenParameters, asbe2.RecipientTokenParameters, true, exactMessageSecurityVersion))
return false;
}
return true;
}
}
}
| |
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.ComponentModel;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DUEMETRI.UI.Design.WebControls;
namespace DUEMETRI.UI.WebControls
{
/// <summary>
/// DesktopPanes class for supporting three pane browsing
/// </summary>
[
Designer("DUEMETRI.UI.Design.WebControls.DesktopPanesDesigner")
]
public class DesktopPanes : WebControl, INamingContainer
{
#region Member variables
bool _showFirstSeparator = true;
bool _showLastSeparator = true;
private ArrayList[] innerDataSource;
private TableItemStyle leftPaneStyle;
private TableItemStyle contentPaneStyle;
private TableItemStyle rightPaneStyle;
private Style horizontalSeparatorStyle;
private TableItemStyle verticalSeparatorStyle;
private ITemplate leftPaneTemplate;
private ITemplate contentPaneTemplate;
private ITemplate rightPaneTemplate;
private ITemplate horizontalSeparatorTemplate;
private ITemplate verticalSeparatorTemplate;
private System.Web.UI.Control leftPaneContainer;
private System.Web.UI.Control contentPaneContainer;
private System.Web.UI.Control rightPaneContainer;
private System.Web.UI.Control verticalSeparatorContainer;
private System.Web.UI.Control horizontalSeparatorContainer;
private System.Web.UI.WebControls.TableCell leftPane;
private System.Web.UI.WebControls.TableCell contentPane;
private System.Web.UI.WebControls.TableCell rightPane;
private const int IDX_CONTROL_STYLE = 0;
private const int IDX_LEFT_PANE_STYLE = 1;
private const int IDX_CONTENT_PANE_STYLE = 2;
private const int IDX_RIGHT_PANE_STYLE = 3;
private const int IDX_HORIZONTAL_SEPARATOR_STYLE = 4;
private const int IDX_VERTICAL_SEPARATOR_STYLE = 5;
/// <summary>
/// Left pane index
/// </summary>
protected const int IDX_LEFT_PANE_DATA = 0;
/// <summary>
/// Content pane index
/// </summary>
protected const int IDX_CONTENT_PANE_DATA = 1;
/// <summary>
/// Right pane index
/// </summary>
protected const int IDX_RIGHT_PANE_DATA = 2;
#endregion
/// <summary>
/// Show First Separator.
/// </summary>
[
Bindable(true),
Category("Appearance"),
DefaultValue(true),
Description("Show First Separator.")
]
public virtual bool ShowFirstSeparator
{
get
{
return _showFirstSeparator;
}
set
{
_showFirstSeparator = value;
}
}
/// <summary>
/// Show Last Separator.
/// </summary>
[
Bindable(true),
Category("Appearance"),
DefaultValue(true),
Description("Show Last Separator.")
]
public virtual bool ShowLastSeparator
{
get
{
return _showLastSeparator;
}
set
{
_showLastSeparator = value;
}
}
/// <summary>
/// The cell padding of the rendered table.
/// </summary>
[
Bindable(true),
Category("Appearance"),
DefaultValue(0),
Description("The cell padding of the rendered table.")
]
public virtual int CellPadding
{
get
{
if (ControlStyleCreated == false)
{
return 0;
}
return ((TableStyle)ControlStyle).CellPadding;
}
set
{
((TableStyle)ControlStyle).CellPadding = value;
}
}
/// <summary>
/// The cell spacing of the rendered table.
/// </summary>
[
Bindable(true),
Category("Appearance"),
DefaultValue(0),
Description("The cell spacing of the rendered table.")
]
public virtual int CellSpacing
{
get
{
if (ControlStyleCreated == false)
{
return 0;
}
return ((TableStyle)ControlStyle).CellSpacing;
}
set
{
((TableStyle)ControlStyle).CellSpacing = value;
}
}
/// <summary>
/// The width of the rendered table.
/// </summary>
[
Bindable(true),
Category("Appearance"),
DefaultValue("100%"),
Description("The width of the rendered table.")
]
public override Unit Width
{
get
{
if (ControlStyleCreated == false)
{
return 0;
}
return ((TableStyle)ControlStyle).Width;
}
set
{
((TableStyle)ControlStyle).Width = value;
}
}
/// <summary>
/// The height of the rendered table.
/// </summary>
[
Bindable(true),
Category("Appearance"),
DefaultValue(null),
Description("The height of the rendered table.")
]
public override Unit Height
{
get
{
if (ControlStyleCreated == false)
{
return 0;
}
return ((TableStyle)ControlStyle).Height;
}
set
{
((TableStyle)ControlStyle).Height = value;
}
}
/// <summary>
/// The grid lines to be shown in the rendered table.
/// </summary>
[
Bindable(true),
Category("Appearance"),
DefaultValue(GridLines.None),
Description("The grid lines to be shown in the rendered table.")
]
public virtual GridLines GridLines
{
get
{
if (ControlStyleCreated == false)
{
return GridLines.None;
}
return ((TableStyle)ControlStyle).GridLines;
}
set
{
((TableStyle)ControlStyle).GridLines = value;
}
}
/// <summary>
/// The style to be applied to LeftPane.
/// </summary>
[
Category("Style"),
Description("The style to be applied to LeftPane."),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual TableItemStyle LeftPaneStyle
{
get
{
if (leftPaneStyle == null)
{
leftPaneStyle = new TableItemStyle();
//Default
leftPaneStyle.Width = new Unit(170);
leftPaneStyle.VerticalAlign = VerticalAlign.Top;
if (IsTrackingViewState)
((IStateManager)leftPaneStyle).TrackViewState();
}
return leftPaneStyle;
}
}
/// <summary>
/// The style to be applied to RightPane.
/// </summary>
[
Category("Style"),
Description("The style to be applied to RightPane."),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual TableItemStyle RightPaneStyle
{
get
{
if (rightPaneStyle == null)
{
rightPaneStyle = new TableItemStyle();
//Default
rightPaneStyle.Width = new Unit(230);
rightPaneStyle.VerticalAlign = VerticalAlign.Top;
if (IsTrackingViewState)
((IStateManager)rightPaneStyle).TrackViewState();
}
return rightPaneStyle;
}
}
/// <summary>
/// The style to be applied to ContentPane.
/// </summary>
[
Category("Style"),
Description("The style to be applied to ContentPane."),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual TableItemStyle ContentPaneStyle
{
get
{
if (contentPaneStyle == null)
{
contentPaneStyle = new TableItemStyle();
//Default
contentPaneStyle.VerticalAlign = VerticalAlign.Top;
if (IsTrackingViewState)
((IStateManager)contentPaneStyle).TrackViewState();
}
return contentPaneStyle;
}
}
/// <summary>
/// The style to be applied to Horizontal Separator.
/// </summary>
[
Category("Style"),
Description(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual Style HorizontalSeparatorStyle
{
get
{
if (horizontalSeparatorStyle == null)
{
horizontalSeparatorStyle = new Style();
if (IsTrackingViewState)
((IStateManager)horizontalSeparatorStyle).TrackViewState();
}
return horizontalSeparatorStyle;
}
}
/// <summary>
/// The style to be applied to Horizontal Separator.
/// </summary>
[
Category("Style"),
Description("The style to be applied to Horizontal Separator."),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty)
]
public virtual TableItemStyle VerticalSeparatorStyle
{
get
{
if (verticalSeparatorStyle == null)
{
verticalSeparatorStyle = new TableItemStyle();
if (IsTrackingViewState)
((IStateManager)verticalSeparatorStyle).TrackViewState();
}
return verticalSeparatorStyle;
}
}
/// <summary>
/// The DataSource.
/// </summary>
[
Category("Data"),
Description("The DataSource.")
]
public ArrayList[] DataSource
{
get
{
if (innerDataSource == null)
{
InitializeDataSource();
}
return innerDataSource;
}
}
/// <summary>
/// Binds a data source to the invoked server control and all its child controls.
/// </summary>
public override void DataBind()
{
foreach(Control c in DataSource[IDX_LEFT_PANE_DATA])
{
LeftPane.Controls.Add(c);
LeftPane.Controls.Add(GetHorizontalSeparator());
}
foreach(Control c in DataSource[IDX_CONTENT_PANE_DATA])
{
ContentPane.Controls.Add(c);
ContentPane.Controls.Add(GetHorizontalSeparator());
}
foreach(Control c in DataSource[IDX_RIGHT_PANE_DATA])
{
RightPane.Controls.Add(c);
RightPane.Controls.Add(GetHorizontalSeparator());
}
}
/// <summary>
/// The Left Pane.
/// </summary>
[
Browsable(false),
DefaultValue(null),
Description("The Left Pane."),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(DesktopPanesTemplate))
]
public virtual ITemplate LeftPaneTemplate
{
get
{
return leftPaneTemplate;
}
set
{
leftPaneTemplate = value;
}
}
/// <summary>
/// The Content Pane.
/// </summary>
[
Browsable(false),
DefaultValue(null),
Description("The Content Pane."),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(DesktopPanesTemplate))
]
public virtual ITemplate ContentPaneTemplate
{
get
{
return contentPaneTemplate;
}
set
{
contentPaneTemplate = value;
}
}
/// <summary>
/// The Right Pane.
/// </summary>
[
Browsable(false),
DefaultValue(null),
Description("The Right Pane."),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(DesktopPanesTemplate))
]
public virtual ITemplate RightPaneTemplate
{
get
{
return rightPaneTemplate;
}
set
{
rightPaneTemplate = value;
}
}
/// <summary>
/// The HorizontalSeparator.
/// </summary>
[
Browsable(false),
DefaultValue(null),
Description("The HorizontalSeparator."),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(DesktopPanesTemplate))
]
public virtual ITemplate HorizontalSeparatorTemplate
{
get
{
return horizontalSeparatorTemplate;
}
set
{
horizontalSeparatorTemplate = value;
}
}
/// <summary>
/// The VerticalSeparator.
/// </summary>
[
Browsable(false),
DefaultValue(null),
Description("The VerticalSeparator."),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(DesktopPanesTemplate))
]
public virtual ITemplate VerticalSeparatorTemplate
{
get
{
return verticalSeparatorTemplate;
}
set
{
verticalSeparatorTemplate = value;
}
}
/// <summary>
/// LeftPane
/// </summary>
[
Browsable(false)
]
public TableCell LeftPane
{
get
{
if (leftPane == null)
{
leftPane = new TableCell();
}
return leftPane;
}
}
/// <summary>
/// ContentPane
/// </summary>
[
Browsable(false)
]
public TableCell ContentPane
{
get
{
if (contentPane == null)
{
contentPane = new TableCell();
}
return contentPane;
}
}
/// <summary>
/// RightPane
/// </summary>
[
Browsable(false)
]
public TableCell RightPane
{
get
{
if (rightPane == null)
{
rightPane = new TableCell();
}
return rightPane;
}
}
/// <summary>
/// This member overrides Control.LoadViewState
/// </summary>
/// <param name="savedState"></param>
protected override void LoadViewState(object savedState)
{
// Customize state management to handle saving state of contained objects.
if (savedState != null)
{
object[] myState = (object[])savedState;
if (myState[IDX_CONTROL_STYLE] != null)
base.LoadViewState(myState[IDX_CONTROL_STYLE]);
if (myState[IDX_LEFT_PANE_STYLE] != null)
((IStateManager)leftPaneStyle).LoadViewState(myState[IDX_LEFT_PANE_STYLE]);
if (myState[IDX_CONTENT_PANE_STYLE] != null)
((IStateManager)contentPaneStyle).LoadViewState(myState[IDX_CONTENT_PANE_STYLE]);
if (myState[IDX_RIGHT_PANE_STYLE] != null)
((IStateManager)rightPaneStyle).LoadViewState(myState[IDX_RIGHT_PANE_STYLE]);
if (myState[IDX_HORIZONTAL_SEPARATOR_STYLE] != null)
((IStateManager)horizontalSeparatorStyle).LoadViewState(myState[IDX_HORIZONTAL_SEPARATOR_STYLE]);
if (myState[IDX_VERTICAL_SEPARATOR_STYLE] != null)
((IStateManager)verticalSeparatorStyle).LoadViewState(myState[IDX_VERTICAL_SEPARATOR_STYLE]);
}
}
/// <summary>
/// This member overrides Control.SaveViewState
/// </summary>
/// <returns></returns>
protected override object SaveViewState()
{
// Customized state management to handle saving state of contained objects such as styles.
object baseState = base.SaveViewState();
object leftPaneStyleState = (leftPaneStyle != null) ? ((IStateManager)leftPaneStyle).SaveViewState() : null;
object contentPaneStyleState = (contentPaneStyle != null) ? ((IStateManager)contentPaneStyle).SaveViewState() : null;
object rightPaneStyleState = (rightPaneStyle != null) ? ((IStateManager)rightPaneStyle).SaveViewState() : null;
object horizontalSeparatorStyleState = (horizontalSeparatorStyle != null) ? ((IStateManager)horizontalSeparatorStyle).SaveViewState() : null;
object verticalSeparatorStyleState = (verticalSeparatorStyle != null) ? ((IStateManager)verticalSeparatorStyle).SaveViewState() : null;
object[] myState = new object[6];
myState[IDX_CONTROL_STYLE] = baseState;
myState[IDX_LEFT_PANE_STYLE] = leftPaneStyleState;
myState[IDX_CONTENT_PANE_STYLE] = contentPaneStyleState;
myState[IDX_RIGHT_PANE_STYLE] = rightPaneStyleState;
myState[IDX_HORIZONTAL_SEPARATOR_STYLE] = horizontalSeparatorStyleState;
myState[IDX_VERTICAL_SEPARATOR_STYLE] = verticalSeparatorStyleState;
return myState;
}
/// <summary>
/// This member overrides Control.TrackViewState.
/// </summary>
protected override void TrackViewState()
{
// Customized state management to handle saving state of contained objects such as styles.
base.TrackViewState();
if (leftPaneStyle != null)
((IStateManager)leftPaneStyle).TrackViewState();
if (contentPaneStyle != null)
((IStateManager)contentPaneStyle).TrackViewState();
if (rightPaneStyle != null)
((IStateManager)rightPaneStyle).TrackViewState();
if (horizontalSeparatorStyle != null)
((IStateManager)horizontalSeparatorStyle).TrackViewState();
if (verticalSeparatorStyle != null)
((IStateManager)verticalSeparatorStyle).TrackViewState();
}
/// <summary>
/// Web server control can set its control style to
/// any class that derives from Style by overriding
/// the WebControl.CreateControlStyle method
/// </summary>
/// <returns></returns>
protected override Style CreateControlStyle()
{
// Note that the constructor of Style takes
// ViewState as an argument.
TableStyle style = new TableStyle(ViewState);
// Set up default initial state.
style.CellSpacing = 0;
style.Width = new Unit("100%");
return style;
}
/// <summary>
/// Initialize internal data source
/// </summary>
protected virtual void InitializeDataSource()
{
innerDataSource = new ArrayList[3];
innerDataSource[IDX_LEFT_PANE_DATA] = new ArrayList();
innerDataSource[IDX_CONTENT_PANE_DATA] = new ArrayList();
innerDataSource[IDX_RIGHT_PANE_DATA] = new ArrayList();
}
/// <summary>
/// This member overrides Control.OnDataBinding
/// </summary>
/// <param name="e"></param>
protected override void OnDataBinding(EventArgs e)
{
EnsureChildControls();
base.OnDataBinding(e);
}
/// <summary>
/// This member overrides Control.CreateChildControls
/// </summary>
protected override void CreateChildControls()
{
Controls.Clear();
CreateControlHierarchy();
base.CreateChildControls();
}
/// <summary>
/// This member overrides Control.Render
/// </summary>
/// <param name="writer"></param>
protected override void Render(HtmlTextWriter writer)
{
// Apply styles to the control hierarchy
// and then render it out.
// Apply styles during render phase, so the user can change styles
// after calling DataBind without the property changes ending
// up in view state.
PrepareControlHierarchy();
RenderContents(writer);
// base.Render(writer);
}
/// <summary>
/// This member overrides Control.PrepareControlHierarchy
/// </summary>
private void PrepareControlHierarchy()
{
if (HasControls() == false)
return;
Debug.Assert(Controls[0] is Table);
Table table = (Table)Controls[0];
Debug.Assert(table.Rows.Count == 1);
TableCellCollection cells = table.Rows[0].Cells;
table.CopyBaseAttributes(this);
if (ControlStyleCreated)
table.ApplyStyle(ControlStyle);
Debug.Assert(cells.Count == 7);
TableCell firstSeparator = cells[0];
firstSeparator.Visible = ShowFirstSeparator;
firstSeparator.MergeStyle(this.VerticalSeparatorStyle);
TableCell leftCell = cells[1];
leftCell.MergeStyle(this.LeftPaneStyle);
TableCell leftToContentSeparator = cells[2];
leftToContentSeparator.MergeStyle(this.VerticalSeparatorStyle);
if (LeftPane.HasControls() || LeftPane.Text.Trim() != String.Empty)
{
LeftPane.Visible = true;
leftToContentSeparator.Visible = true;
}
else
{
LeftPane.Visible = false;
leftToContentSeparator.Visible = false;
}
TableCell contentCell = cells[3];
contentCell.MergeStyle(this.ContentPaneStyle);
TableCell contentToRightSeparator = cells[4];
contentToRightSeparator.MergeStyle(this.VerticalSeparatorStyle);
TableCell rightCell = cells[5];
rightCell.MergeStyle(this.RightPaneStyle);
TableCell lastSeparator = cells[6];
lastSeparator.Visible = ShowLastSeparator;
lastSeparator.MergeStyle(this.VerticalSeparatorStyle);
if (RightPane.HasControls() || RightPane.Text.Trim() != String.Empty)
{
contentToRightSeparator.Visible = true;
RightPane.Visible = true;
}
else
{
contentToRightSeparator.Visible = false;
RightPane.Visible = false;
}
}
/// <summary>
/// This member overrides Control.CreateControlHierarchy
/// </summary>
private void CreateControlHierarchy()
{
// NEVER hide controls on this routine
// some events WILL NOT FIRED
Controls.Clear();
Table table = new Table();
Controls.Add(table);
//Prepare Control Hierarchy
TableRow contentRow = new TableRow();
contentRow.Controls.Add(GetVerticalSeparator());
contentRow.Controls.Add(LeftPane);
TableCell leftToContentSeparator = GetVerticalSeparator();
contentRow.Controls.Add(leftToContentSeparator);
if (LeftPaneTemplate != null)
{
leftPaneContainer = new DesktopPanesTemplate(this);
LeftPaneTemplate.InstantiateIn(leftPaneContainer);
LeftPane.Controls.AddAt(0, leftPaneContainer);
LeftPane.Controls.AddAt(1, GetHorizontalSeparator());
}
if (ContentPaneTemplate != null)
{
contentPaneContainer = new DesktopPanesTemplate(this);
ContentPaneTemplate.InstantiateIn(contentPaneContainer);
ContentPane.Controls.AddAt(0, contentPaneContainer);
ContentPane.Controls.AddAt(1, GetHorizontalSeparator());
}
contentRow.Controls.Add(ContentPane);
TableCell contentToRightSeparator = GetVerticalSeparator();
contentRow.Controls.Add(contentToRightSeparator);
contentRow.Controls.Add(RightPane);
if (RightPaneTemplate != null)
{
rightPaneContainer = new DesktopPanesTemplate(this);
RightPaneTemplate.InstantiateIn(rightPaneContainer);
RightPane.Controls.AddAt(0, rightPaneContainer);
RightPane.Controls.AddAt(1, GetHorizontalSeparator());
}
contentRow.Controls.Add(GetVerticalSeparator());
table.Controls.Add(contentRow);
}
/// <summary>
/// Returns a reference to Horizontal separator
/// </summary>
/// <returns></returns>
protected Control GetHorizontalSeparator()
{
if (HorizontalSeparatorTemplate != null)
{
horizontalSeparatorContainer = new DesktopPanesTemplate(this);
HorizontalSeparatorTemplate.InstantiateIn(horizontalSeparatorContainer);
return horizontalSeparatorContainer;
}
else
return new Control();
}
/// <summary>
/// Returns a reference to Vertical separator
/// </summary>
/// <returns></returns>
protected TableCell GetVerticalSeparator()
{
TableCell tc = new TableCell();
if (VerticalSeparatorTemplate != null)
{
verticalSeparatorContainer = new DesktopPanesTemplate(this);
VerticalSeparatorTemplate.InstantiateIn(verticalSeparatorContainer);
tc.Controls.Add(verticalSeparatorContainer);
}
return tc;
}
}
}
| |
using HtmlAgilityPack;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace PurdueIo.Scraper.Connections
{
// Implementation of IMyPurdueConnection that fetches actual data from MyPurdue via HTTPS calls
public class MyPurdueConnection : IMyPurdueConnection
{
// Enum value of implemented HTTP request methods
private enum HttpMethod { GET, POST };
// Username used to authenticate with MyPurdue
private readonly string username;
// Password used to authenticate with MyPurdue
private readonly string password;
// Logger reference
private readonly ILogger<MyPurdueConnection> logger;
// Keeps track of cookies for all requests on this connection
private CookieContainer cookies = new CookieContainer();
// Keeps track of the last page requested, used in 'Referrer' HTTP header
private string referrer = "";
// HttpClient used by this connection to communicate with MyPurdue
private HttpClient httpClient;
// How many request attempts should be made before failure
private const int MAX_RETRIES = 5;
// Used to parse session timeout messages
private static Regex sessionTimeoutRegex = new Regex(@"Session timeout occurred",
RegexOptions.IgnoreCase);
// Attempts to open a new authenticated connection to MyPurdue,
// throws if authentication fails
public static async Task<MyPurdueConnection> CreateAndConnectAsync(string username,
string password, ILogger<MyPurdueConnection> logger)
{
var connection = new MyPurdueConnection(username, password, logger);
if (await connection.Authenticate())
{
return connection;
}
else
{
throw new ApplicationException(
"Could not authenticate to MyPurdue with supplied username and password.");
}
}
public async Task<string> GetTermListPageAsync()
{
for (int attempts = 0; attempts < MAX_RETRIES; ++attempts)
{
var result = await Request(HttpMethod.GET,
"https://selfservice.mypurdue.purdue.edu/prod/bwckschd.p_disp_dyn_sched");
var content = await result.Content.ReadAsStringAsync();
if (sessionTimeoutRegex.IsMatch(content))
{
// If we received a session timeout message, authenticate and then try again
await Authenticate();
}
else
{
return content;
}
}
throw new ApplicationException(
"Exceeded retries attempting to query MyPurdue term list");
}
public async Task<string> GetSubjectListPageAsync(string termCode)
{
for (int attempts = 0; attempts < MAX_RETRIES; ++attempts)
{
var request = await Request(HttpMethod.POST,
"https://selfservice.mypurdue.purdue.edu/prod/bwckgens.p_proc_term_date",
new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("p_calling_proc",
"bwckschd.p_disp_dyn_sched"),
new KeyValuePair<string, string>("p_term", termCode)
}),
true,
"https://selfservice.mypurdue.purdue.edu/prod/bwckschd.p_disp_dyn_sched");
var content = await request.Content.ReadAsStringAsync();
if (sessionTimeoutRegex.IsMatch(content))
{
// If we received a session timeout message, authenticate and then try again
await Authenticate();
}
else
{
return content;
}
}
throw new ApplicationException(
"Exceeded retries attempting to query MyPurdue subject list");
}
public async Task<string> GetSectionListPageAsync(string termCode, string subjectCode)
{
for (int attempts = 0; attempts < MAX_RETRIES; ++attempts)
{
var postBody = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("term_in", termCode),
new KeyValuePair<string, string>("sel_subj", "dummy"),
new KeyValuePair<string, string>("sel_day", "dummy"),
new KeyValuePair<string, string>("sel_schd", "dummy"),
new KeyValuePair<string, string>("sel_insm", "dummy"),
new KeyValuePair<string, string>("sel_camp", "dummy"),
new KeyValuePair<string, string>("sel_levl", "dummy"),
new KeyValuePair<string, string>("sel_sess", "dummy"),
new KeyValuePair<string, string>("sel_instr", "dummy"),
new KeyValuePair<string, string>("sel_ptrm", "dummy"),
new KeyValuePair<string, string>("sel_attr", "dummy"),
new KeyValuePair<string, string>("sel_subj", subjectCode),
new KeyValuePair<string, string>("sel_crse", "%"),
new KeyValuePair<string, string>("sel_title", ""),
new KeyValuePair<string, string>("sel_schd", "%"),
new KeyValuePair<string, string>("sel_from_cred", ""),
new KeyValuePair<string, string>("sel_to_cred", ""),
new KeyValuePair<string, string>("sel_camp", "%"),
new KeyValuePair<string, string>("sel_ptrm", "%"),
new KeyValuePair<string, string>("sel_instr", "%"),
new KeyValuePair<string, string>("sel_sess", "%"),
new KeyValuePair<string, string>("sel_attr", "%"),
new KeyValuePair<string, string>("begin_hh", "0"),
new KeyValuePair<string, string>("begin_mi", "0"),
new KeyValuePair<string, string>("begin_ap", "a"),
new KeyValuePair<string, string>("end_hh", "0"),
new KeyValuePair<string, string>("end_mi", "0"),
new KeyValuePair<string, string>("end_ap", "a"),
});
var request = await Request(HttpMethod.POST,
"https://selfservice.mypurdue.purdue.edu/prod/bwckschd.p_get_crse_unsec",
postBody);
var content = await request.Content.ReadAsStringAsync();
if (sessionTimeoutRegex.IsMatch(content))
{
// If we received a session timeout message, authenticate and then try again
await Authenticate();
}
else
{
return content;
}
}
throw new ApplicationException(
"Exceeded retries attempting to query MyPurdue section list");
}
public async Task<string> GetSectionDetailsPageAsync(string termCode, string subjectCode)
{
for (int attempts = 0; attempts < MAX_RETRIES; ++attempts)
{
var postBody = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("rsts", "dummy"),
new KeyValuePair<string, string>("crn", "dummy"),
new KeyValuePair<string, string>("term_in", termCode),
new KeyValuePair<string, string>("sel_subj", "dummy"),
new KeyValuePair<string, string>("sel_day", "dummy"),
new KeyValuePair<string, string>("sel_schd", "dummy"),
new KeyValuePair<string, string>("sel_insm", "dummy"),
new KeyValuePair<string, string>("sel_camp", "dummy"),
new KeyValuePair<string, string>("sel_levl", "dummy"),
new KeyValuePair<string, string>("sel_sess", "dummy"),
new KeyValuePair<string, string>("sel_instr", "dummy"),
new KeyValuePair<string, string>("sel_ptrm", "dummy"),
new KeyValuePair<string, string>("sel_attr", "dummy"),
new KeyValuePair<string, string>("sel_subj", subjectCode),
new KeyValuePair<string, string>("sel_crse", ""),
new KeyValuePair<string, string>("sel_title", ""),
new KeyValuePair<string, string>("sel_schd", "%"),
new KeyValuePair<string, string>("sel_insm", "%"),
new KeyValuePair<string, string>("sel_from_cred", ""),
new KeyValuePair<string, string>("sel_to_cred", ""),
new KeyValuePair<string, string>("sel_camp", "%"),
new KeyValuePair<string, string>("sel_ptrm", "%"),
new KeyValuePair<string, string>("sel_instr", "%"),
new KeyValuePair<string, string>("sel_sess", "%"),
new KeyValuePair<string, string>("sel_attr", "%"),
new KeyValuePair<string, string>("begin_hh", "0"),
new KeyValuePair<string, string>("begin_mi", "0"),
new KeyValuePair<string, string>("begin_ap", "a"),
new KeyValuePair<string, string>("end_hh", "0"),
new KeyValuePair<string, string>("end_mi", "0"),
new KeyValuePair<string, string>("end_ap", "a"),
new KeyValuePair<string, string>("SUB_BTN", "Section Search"),
new KeyValuePair<string, string>("path", "1"),
});
var request = await Request(HttpMethod.POST,
"https://selfservice.mypurdue.purdue.edu/prod/bwskfcls.P_GetCrse_Advanced",
postBody,
true,
"https://selfservice.mypurdue.purdue.edu/prod/bwskfcls.P_GetCrse");
var content = await request.Content.ReadAsStringAsync();
if (sessionTimeoutRegex.IsMatch(content))
{
// If we received a session timeout message, authenticate and then try again
await Authenticate();
}
else
{
return content;
}
}
throw new ApplicationException(
"Exceeded retries attempting to query MyPurdue section details");
}
private MyPurdueConnection(string username, string password,
ILogger<MyPurdueConnection> logger)
{
this.username = username;
this.password = password;
this.logger = logger;
var httpHandler = new HttpClientHandler()
{
CookieContainer = cookies, // MyPurdue stores a lot of state in cookies - we need
// to persist them to avoid upsetting it
AllowAutoRedirect = false, // We'll handle redirects by ourselves
};
httpClient = new HttpClient(httpHandler as HttpMessageHandler);
// Pretend we're Chrome
httpClient.DefaultRequestHeaders.Add("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.5");
httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
httpClient.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/45.0.2454.99 Safari/537.36");
}
private async Task<bool> Authenticate()
{
var loginForm = await Request(HttpMethod.GET,
"https://www.purdue.edu/apps/account/cas/login" +
"?service=https%3A%2F%2Fwl.mypurdue.purdue.edu%2Fc%2Fportal%2Flogin");
HtmlDocument document = new HtmlDocument();
document.LoadHtml(await loginForm.Content.ReadAsStringAsync());
HtmlNode docRoot = document.DocumentNode;
var ltValue = docRoot
.SelectSingleNode("//input[@name='lt']")
.GetAttributeValue("value", "");
FormUrlEncodedContent content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("lt", ltValue),
new KeyValuePair<string, string>("execution", "e1s1"),
new KeyValuePair<string, string>("_eventId", "submit"),
new KeyValuePair<string, string>("submit", "Login")
});
HttpResponseMessage r = await Request(HttpMethod.POST,
"https://www.purdue.edu/apps/account/cas/login" +
"?service=https%3A%2F%2Fwl.mypurdue.purdue.edu%2Fc%2Fportal%2Flogin", content);
string result = await r.Content.ReadAsStringAsync();
bool isAuthenticated = !result.Contains("Authentication failed.");
if (!isAuthenticated)
{
return false;
}
// Authenticate with MyPurdue self-service
var ssResult = await Request(HttpMethod.GET,
"https://wl.mypurdue.purdue.edu/static_resources/portal/jsp/ss_redir_lp5.jsp?pg=23",
null, true, "https://wl.mypurdue.purdue.edu/");
var ssResultContent = await ssResult.Content.ReadAsStringAsync();
// TODO: Verify self-service login
return isAuthenticated;
}
// Generates a basic request, providing POST body, following redirects, and storing cookies.
private async Task<HttpResponseMessage> Request(HttpMethod method, string url,
FormUrlEncodedContent postContent = null, bool followRedirect = true,
string requestReferrer = null)
{
logger.LogDebug($"{method.ToString()} Request: {url}");
if (requestReferrer != null)
{
referrer = requestReferrer;
}
logger.LogDebug($"Referrer: {referrer}");
if (referrer.Length > 0)
{
httpClient.DefaultRequestHeaders.Referrer = new Uri(referrer);
}
else
{
if (httpClient.DefaultRequestHeaders.Contains("Referrer"))
{
httpClient.DefaultRequestHeaders.Remove("Referrer");
}
}
// Print out our POST data
if (postContent != null)
{
var postString = await postContent.ReadAsStringAsync();
postString = postString.Replace("&", "\n\t\t");
logger.LogDebug($"POST data: \n{postString}");
}
// Print out all the cookies we're sending
var cookiesToSend = cookies.GetCookies(new Uri(url));
logger.LogDebug("Outgoing cookies: \n" +
$"{string.Join("\n", cookiesToSend.Select(c => c.ToString()))}");
HttpResponseMessage result = null;
for (int attempts = 0; attempts < MAX_RETRIES; ++attempts)
{
try
{
switch (method)
{
case HttpMethod.POST:
result = await httpClient.PostAsync(url, postContent);
break;
case HttpMethod.GET:
result = await httpClient.GetAsync(url);
break;
}
}
catch (Exception e)
{
logger.LogWarning("HTTP request exception, retrying " +
$"({attempts + 1} / {MAX_RETRIES})\n{e.ToString()}");
continue;
}
break;
}
if (result == null)
{
throw new InvalidOperationException(
"No request was made - most likely due to invalid HTTP method.");
}
IEnumerable<string> incomingCookies;
if (result.Headers.TryGetValues("set-cookie", out incomingCookies))
{
logger.LogDebug($"Incoming cookies:\n{string.Join("\n", incomingCookies)}");
foreach (var c in incomingCookies)
{
if (c.StartsWith("SESSID") && !c.Contains("expires"))
{
var sessidCookieValue = c.Substring((c.IndexOf('=') + 1),
(c.IndexOf(';') - c.IndexOf('=') - 1));
var sessidCookie = new Cookie("SESSID", sessidCookieValue);
sessidCookie.Domain = new Uri(url).Host;
sessidCookie.Path = "/";
cookies.Add(sessidCookie);
}
cookies.SetCookies(new Uri(url), c);
}
}
if (followRedirect && (result.Headers.Location != null))
{
logger.LogDebug($"Redirect to {result.Headers.Location.ToString()}");
// All redirects are converted to GET
result = await Request(HttpMethod.GET, result.Headers.Location.ToString(), null);
}
else
{
referrer = url;
}
return result;
}
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using Azure;
using DataLake;
using Management;
using Azure;
using Management;
using DataLake;
using Models;
using Newtonsoft.Json;
using Rest;
using Rest.Azure;
using Rest.Serialization;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Creates an Azure Data Lake Analytics account management client.
/// </summary>
public partial class DataLakeAnalyticsAccountManagementClient : ServiceClient<DataLakeAnalyticsAccountManagementClient>, IDataLakeAnalyticsAccountManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Get subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IStorageAccountsOperations.
/// </summary>
public virtual IStorageAccountsOperations StorageAccounts { get; private set; }
/// <summary>
/// Gets the IDataLakeStoreAccountsOperations.
/// </summary>
public virtual IDataLakeStoreAccountsOperations DataLakeStoreAccounts { get; private set; }
/// <summary>
/// Gets the IAccountOperations.
/// </summary>
public virtual IAccountOperations Account { get; private set; }
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeAnalyticsAccountManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeAnalyticsAccountManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected DataLakeAnalyticsAccountManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected DataLakeAnalyticsAccountManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
StorageAccounts = new StorageAccountsOperations(this);
DataLakeStoreAccounts = new DataLakeStoreAccountsOperations(this);
Account = new AccountOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2016-11-01";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
namespace HostingTest {
internal class PythonCodeSnippets : CodeSnippetCollection{
internal PythonCodeSnippets() {
AllSnippets = new CodeSnippet[]{
new CodeSnippet(
CodeType.Null, "Null Code",
null),
new CodeSnippet(
CodeType.Junk, "Junk Code",
"@@3skjdhfkshdfk"),
new CodeSnippet(
CodeType.Comment, "Comment only code",
"#this is a test comment"),
new CodeSnippet(
CodeType.WhiteSpace1, "WhiteSpace only",
" "),
new CodeSnippet(
CodeType.ValidExpressionWithMethodCalls, "Valid Expresion Using Method",
@"eval('eval(\'2+2\')')"),
new CodeSnippet(
CodeType.ValidStatement1, "Valid Statement",
@"if 1>0 :
print 1001"),
/// <summary>
/// Test Bug : this is not an expression - This is a statement!
/// </summary>
new CodeSnippet(
CodeType.InCompleteExpression1, "Incomplete expression",
"print("),
/// <summary>
/// Test Bug : this is not an expression - This is a statement!
/// </summary>
new CodeSnippet(
CodeType.InCompleteExpression2, "Incomplete expression",
"a = 2+"),
new CodeSnippet(
CodeType.InCompleteStatement1, "Incomplete statement",
"if"),
new CodeSnippet(
CodeType.Interactive1, "Interactive Code",
"<add valid interactive code>"),
new CodeSnippet(
CodeType.OneLineAssignmentStatement, "Interactive Code",
"x = 1+2"),
new CodeSnippet(
CodeType.LinefeedTerminatorRStatement, "Interactive Code",
"x = 1+2\ry= 3+4"),
/// <summary>
/// A python expression with classic functional language paradigms calling map with
/// a lambda function that multiplies the input value by -1.
/// </summary>
new CodeSnippet(
CodeType.CallingFuncWithLambdaArgsToMap, "A python expression with classic functional language paradigms using lambda and map",
@"map(lambda x: x * -1, range(0,-10, -1))"
),
new CodeSnippet(
CodeType.MethodWithThreeArgs,
"Simple method with three args",
@"def concat( a, b, c):
return str(a + b + c)"),
/// <summary>
/// Simple FooClass to test ScriptSource.Invocate(...)
/// </summary>
new CodeSnippet(
CodeType.SimpleFooClassDefinition, "Simple Foo class used to test calling member method after execution",
@"class FooClass:
'A simple test class'
def __init__(self):
self.someInstanceAttribute = 42
def f(self):return 'Hello World'
def concat(self, a, b, c):
return str(a + b + c)
def add(self, a, b):
return a + b
fooTest = FooClass()
def bar(): return fooTest.f()"),
/// <summary>
/// Rot13 function definition
/// </summary>
new CodeSnippet(
CodeType.Rot13Function, "Defined Rot13 function",
@"
def rot13(transstr):
chklst = list(transstr)
nlst = list()
lookup = list('NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')
for i in range(chklst.Length()):
rchr = 0
if(chklst[i].isalpha()):
if(chklst[i].isupper()):
rchr = lookup[ord(chklst[i]) % ord('A')]
else:
rchr = lookup[ord(chklst[i]) % ord('a') + 26]
else:
rchr = chklst[i];
nlst.append(rchr)
return ''.join(nlst)
"),
/// <summary>
/// Test Bug : this is not an expression - This is a statement!
/// </summary>
new CodeSnippet(
CodeType.ValidExpression1, "Interactive Code",
"x = 1+2"),
/// <summary>
/// Valid code snippet with both expressions and statements
/// </summary>
new CodeSnippet(
CodeType.ValidMultiLineMixedType, "Valid Code",
@"
def increment(arg):
local = arg + 1
local2 =local
del local2
return local
global1 = increment(3)
global2 = global1"),
new CodeSnippet(
CodeType.Valid1, "Valid Code",
@"
def increment(arg):
local = arg + 1
local2 =local
del local2
return local
global1 = increment(3)
global2 = global1"),
new CodeSnippet(
CodeType.BrokenString, "Broken String",
"a = \"a broken string'"),
new CodeSnippet(
CodeType.SimpleMethod, "Simple method",
"def pyf(): return 42"),
new CodeSnippet(
CodeType.FactorialFunc, "Factorial function",
@"def fact(x):
if (x == 1):
return 1
return x * fact(x - 1)"),
new CodeSnippet(
CodeType.ImportFutureDiv, "TrueDiv function",
@"from __future__ import division
r = 1/2"),
new CodeSnippet(
CodeType.ImportStandardDiv, "LegacyZeroResultFromOneHalfDiv function",
@"r = 1/2"),
new CodeSnippet(
CodeType.SevenLinesOfAssignemtStatements, "Very simple code example to be used for testing ScriptSource CodeReader method",
@"a1=1
a2=2
a3=3
a4=4
a5=5
a6=6
a7=7"),
new CodeSnippet(
CodeType.UpdateVarWithAbsValue, "Give a variable set to a negative number -1 and then re-assign abs value of itself",
@"
test1 = -10
test1 = abs(test1)"),
new CodeSnippet(
CodeType.SimpleExpressionOnePlusOne, "A very simple expression 1 + 1",
"1+1" ),
new CodeSnippet(
CodeType.IsEvenFunction, "A function that returns true or false depending on if a number is even or not",
"def iseven(n): return 1 != n % 2"),
new CodeSnippet(
CodeType.IsOddFunction, "A function that returns true or false depending on if a number is odd or not",
"def isodd(n): return 1 == n % 2;"),
new CodeSnippet(
CodeType.MethodWithDocumentationAttached, "A very simple method with docs attached",
@"def doc():
""""""This function does nothing""""""
return"),
new CodeSnippet(
CodeType.SmallDotNetObjectForDocTest, "A .Net Object to use to verify we can see attached documentation",
"from System.Runtime.Remoting import ObjectHandle"),
new CodeSnippet(
CodeType.TimeZoneDotNetObjectForDocTest, "Will this work",
"from System import TimeZone"),
new CodeSnippet(
CodeType.NegativeOneAssignedToX, "Interactive Code",
"x = 1"),
new CodeSnippet(
CodeType.ImportCPythonDateTimeModule, "Import a CPython DateTime Module",
"import datetime\ndate=datetime.datetime"),
new CodeSnippet(
CodeType.ImportDotNetAssemblyDateTimeModule, "Import .Net DateTime for an individual assembly",
"import clr\nfrom System import DateTime\nDotNetDate=DateTime")
};
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableListBuilderTest : ImmutableListTestBase
{
[Fact]
public void CreateBuilder()
{
ImmutableList<string>.Builder builder = ImmutableList.CreateBuilder<string>();
Assert.NotNull(builder);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableList<int>.Empty.ToBuilder();
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list = builder.ToImmutable();
Assert.Equal(builder.Count, list.Count);
builder.Add(8);
Assert.Equal(4, builder.Count);
Assert.Equal(3, list.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
}
[Fact]
public void BuilderFromList()
{
var list = ImmutableList<int>.Empty.Add(1);
var builder = list.ToBuilder();
Assert.True(builder.Contains(1));
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(4, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list2 = builder.ToImmutable();
Assert.Equal(builder.Count, list2.Count);
Assert.True(list2.Contains(1));
builder.Add(8);
Assert.Equal(5, builder.Count);
Assert.Equal(4, list2.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
Assert.False(list2.Contains(8));
}
[Fact]
public void SeveralChanges()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
var immutable1 = mutable.ToImmutable();
Assert.Same(immutable1, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
mutable.Add(1);
var immutable2 = mutable.ToImmutable();
Assert.NotSame(immutable1, immutable2); //, "Mutating the collection did not reset the Immutable property.");
Assert.Same(immutable2, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
Assert.Equal(1, immutable2.Count);
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 10)).ToBuilder();
Assert.Equal(Enumerable.Range(1, 10), builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
Assert.Equal(Enumerable.Range(1, 11), builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(Enumerable.Range(1, 11), builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableList<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void Insert()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.Insert(0, 1);
mutable.Insert(0, 0);
mutable.Insert(2, 3);
Assert.Equal(new[] { 0, 1, 3 }, mutable);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(-1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(4, 0));
}
[Fact]
public void InsertRange()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.InsertRange(0, new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.InsertRange(1, new[] { 2, 3 });
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, mutable);
mutable.InsertRange(5, new[] { 6 });
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
mutable.InsertRange(5, new int[0]);
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(-1, new int[0]));
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(mutable.Count + 1, new int[0]));
}
[Fact]
public void AddRange()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.AddRange(new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.AddRange(new[] { 2, 3 });
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
mutable.AddRange(new int[0]);
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
AssertExtensions.Throws<ArgumentNullException>("items", () => mutable.AddRange(null));
}
[Fact]
public void Remove()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
Assert.False(mutable.Remove(5));
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
Assert.True(mutable.Remove(2));
Assert.Equal(new[] { 1, 3 }, mutable);
Assert.True(mutable.Remove(1));
Assert.Equal(new[] { 3 }, mutable);
Assert.True(mutable.Remove(3));
Assert.Equal(new int[0], mutable);
Assert.False(mutable.Remove(5));
}
[Fact]
public void RemoveAllBugTest()
{
var builder = ImmutableList.CreateBuilder<int>();
var elemsToRemove = new[]{0, 1, 2, 3, 4, 5}.ToImmutableHashSet();
// NOTE: this uses Add instead of AddRange because AddRange doesn't exhibit the same issue due to a different order of tree building. Don't change it without testing with the bug repro from issue #20609
foreach(var elem in new[]{0, 1, 2, 3, 4, 5, 6})
builder.Add(elem);
builder.RemoveAll(elemsToRemove.Contains);
Assert.Equal(new[]{ 6 }, builder);
}
[Fact]
public void RemoveAt()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
mutable.RemoveAt(2);
Assert.Equal(new[] { 1, 2 }, mutable);
mutable.RemoveAt(0);
Assert.Equal(new[] { 2 }, mutable);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1));
mutable.RemoveAt(0);
Assert.Equal(new int[0], mutable);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1));
}
[Fact]
public void Reverse()
{
var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Reverse();
Assert.Equal(Enumerable.Range(1, 3).Reverse(), mutable);
}
[Fact]
public void Clear()
{
var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Clear();
Assert.Equal(0, mutable.Count);
// Do it again for good measure. :)
mutable.Clear();
Assert.Equal(0, mutable.Count);
}
[Fact]
public void IsReadOnly()
{
ICollection<int> builder = ImmutableList.Create<int>().ToBuilder();
Assert.False(builder.IsReadOnly);
}
[Fact]
public void Indexer()
{
var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Equal(2, mutable[1]);
mutable[1] = 5;
Assert.Equal(5, mutable[1]);
mutable[0] = -2;
mutable[2] = -3;
Assert.Equal(new[] { -2, 5, -3 }, mutable);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[3] = 4);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1] = 4);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[3]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableList.CreateRange(seq).ToBuilder(),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableList.CreateRange(seq).ToBuilder(),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void GetEnumeratorExplicit()
{
ICollection<int> builder = ImmutableList.Create<int>().ToBuilder();
var enumerator = builder.GetEnumerator();
Assert.NotNull(enumerator);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableList.Create<int>().ToBuilder();
Assert.False(collection.IsSynchronized);
}
[Fact]
public void IListMembers()
{
IList list = ImmutableList.Create<int>().ToBuilder();
Assert.False(list.IsReadOnly);
Assert.False(list.IsFixedSize);
Assert.Equal(0, list.Add(5));
Assert.Equal(1, list.Add(8));
Assert.True(list.Contains(5));
Assert.False(list.Contains(7));
list.Insert(1, 6);
Assert.Equal(6, list[1]);
list.Remove(5);
list[0] = 9;
Assert.Equal(new[] { 9, 8 }, list.Cast<int>().ToArray());
list.Clear();
Assert.Equal(0, list.Count);
}
[Fact]
public void IList_Remove_NullArgument()
{
this.AssertIListBaseline(RemoveFunc, 1, null);
this.AssertIListBaseline(RemoveFunc, "item", null);
this.AssertIListBaseline(RemoveFunc, new int?(1), null);
this.AssertIListBaseline(RemoveFunc, new int?(), null);
}
[Fact]
public void IList_Remove_ArgTypeMismatch()
{
this.AssertIListBaseline(RemoveFunc, "first item", new object());
this.AssertIListBaseline(RemoveFunc, 1, 1.0);
this.AssertIListBaseline(RemoveFunc, new int?(1), 1);
this.AssertIListBaseline(RemoveFunc, new int?(1), new int?(1));
this.AssertIListBaseline(RemoveFunc, new int?(1), string.Empty);
}
[Fact]
public void IList_Remove_EqualsOverride()
{
this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), "foo");
this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), 3);
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableList.CreateBuilder<int>());
ImmutableList<string>.Builder builder = ImmutableList.CreateBuilder<string>();
builder.Add("One");
builder.Add("Two");
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(builder);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
string[] items = itemProperty.GetValue(info.Instance) as string[];
Assert.Equal(builder, items);
}
[Fact]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableList.CreateBuilder<string>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void ItemRef()
{
var list = new[] { 1, 2, 3 }.ToImmutableList();
var builder = new ImmutableList<int>.Builder(list);
ref readonly var safeRef = ref builder.ItemRef(1);
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(2, builder.ItemRef(1));
unsafeRef = 4;
Assert.Equal(4, builder.ItemRef(1));
}
[Fact]
public void ItemRef_OutOfBounds()
{
var list = new[] { 1, 2, 3 }.ToImmutableList();
var builder = new ImmutableList<int>.Builder(list);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.ItemRef(5));
}
[Fact]
public void ToImmutableList()
{
ImmutableList<int>.Builder builder = ImmutableList.CreateBuilder<int>();
builder.Add(0);
builder.Add(1);
builder.Add(2);
var list = builder.ToImmutableList();
Assert.Equal(0, builder[0]);
Assert.Equal(1, builder[1]);
Assert.Equal(2, builder[2]);
builder[1] = 5;
Assert.Equal(5, builder[1]);
Assert.Equal(1, list[1]);
builder.Clear();
Assert.True(builder.ToImmutableList().IsEmpty);
Assert.False(list.IsEmpty);
ImmutableList<int>.Builder nullBuilder = null;
AssertExtensions.Throws<ArgumentNullException>("builder", () => nullBuilder.ToImmutableList());
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableList<T>.Empty.AddRange(contents).ToBuilder();
}
protected override void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test)
{
var builder = list.ToBuilder();
var bcl = list.ToList();
int expected = bcl.RemoveAll(test);
var actual = builder.RemoveAll(test);
Assert.Equal(expected, actual);
Assert.Equal<T>(bcl, builder.ToList());
}
protected override void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var builder = list.ToBuilder();
builder.Reverse(index, count);
Assert.Equal<T>(expected, builder.ToList());
}
internal override IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list)
{
return list.ToBuilder();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list)
{
var builder = list.ToBuilder();
builder.Sort();
return builder.ToImmutable().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison)
{
var builder = list.ToBuilder();
builder.Sort(comparison);
return builder.ToImmutable().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer)
{
var builder = list.ToBuilder();
builder.Sort(comparer);
return builder.ToImmutable().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer)
{
var builder = list.ToBuilder();
builder.Sort(index, count, comparer);
return builder.ToImmutable().ToList();
}
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using NDesk.Options;
namespace SteamBot
{
public class Program
{
private static OptionSet opts = new OptionSet()
{
{"bot=", "launch a configured bot given that bots index in the configuration array.",
b => botIndex = Convert.ToInt32(b) } ,
{ "help", "shows this help text", p => showHelp = (p != null) }
};
private static bool showHelp;
private static int botIndex = -1;
private static BotManager manager;
private static bool isclosing = false;
[STAThread]
public static void Main(string[] args)
{
opts.Parse(args);
if (showHelp)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("If no options are given SteamBot defaults to Bot Manager mode.");
opts.WriteOptionDescriptions(Console.Out);
Console.Write("Press Enter to exit...");
Console.ReadLine();
return;
}
if (args.Length == 0)
{
BotManagerMode();
}
else if (botIndex > -1)
{
BotMode(botIndex);
}
}
#region SteamBot Operational Modes
// This mode is to run a single Bot until it's terminated.
private static void BotMode(int botIndex)
{
if (!File.Exists("./settings.json"))
{
Console.WriteLine("No settings.json file found.");
return;
}
Configuration configObject;
try
{
configObject = Configuration.LoadConfiguration("./settings.json");
}
catch (Newtonsoft.Json.JsonReaderException)
{
// handle basic json formatting screwups
Console.WriteLine("settings.json file is corrupt or improperly formatted.");
return;
}
if (botIndex >= configObject.Bots.Length)
{
Console.WriteLine("Invalid bot index.");
return;
}
Bot b = new Bot(configObject.Bots[botIndex], configObject.ApiKey, BotManager.UserHandlerCreator, true, true);
Console.Title = "Bot Manager";
b.StartBot();
string AuthSet = "auth";
string ExecCommand = "exec";
string InputCommand = "input";
// this loop is needed to keep the botmode console alive.
// instead of just sleeping, this loop will handle console input
while (true)
{
string inputText = Console.ReadLine();
if (String.IsNullOrEmpty(inputText))
continue;
// Small parse for console input
var c = inputText.Trim();
var cs = c.Split(' ');
if (cs.Length > 1)
{
if (cs[0].Equals(AuthSet, StringComparison.CurrentCultureIgnoreCase))
{
b.AuthCode = cs[1].Trim();
}
else if (cs[0].Equals(ExecCommand, StringComparison.CurrentCultureIgnoreCase))
{
b.HandleBotCommand(c.Remove(0, cs[0].Length + 1));
}
else if (cs[0].Equals(InputCommand, StringComparison.CurrentCultureIgnoreCase))
{
b.HandleInput(c.Remove(0, cs[0].Length + 1));
}
}
}
}
// This mode is to manage child bot processes and take use command line inputs
private static void BotManagerMode()
{
Console.Title = "Bot Manager";
manager = new BotManager();
var loadedOk = manager.LoadConfiguration("settings.json");
if (!loadedOk)
{
Console.WriteLine(
"Configuration file Does not exist or is corrupt. Please rename 'settings-template.json' to 'settings.json' and modify the settings to match your environment");
Console.Write("Press Enter to exit...");
Console.ReadLine();
}
else
{
if (manager.ConfigObject.UseSeparateProcesses)
SetConsoleCtrlHandler(ConsoleCtrlCheck, true);
if (manager.ConfigObject.AutoStartAllBots)
{
var startedOk = manager.StartBots();
if (!startedOk)
{
Console.WriteLine(
"Error starting the bots because either the configuration was bad or because the log file was not opened.");
Console.Write("Press Enter to exit...");
Console.ReadLine();
}
}
else
{
foreach (var botInfo in manager.ConfigObject.Bots)
{
if (botInfo.AutoStart)
{
// auto start this particual bot...
manager.StartBot(botInfo.Username);
}
}
}
Console.WriteLine("Type help for bot manager commands. ");
Console.Write("botmgr > ");
var bmi = new BotManagerInterpreter(manager);
// command interpreter loop.
do
{
string inputText = Console.ReadLine();
if (String.IsNullOrEmpty(inputText))
continue;
bmi.CommandInterpreter(inputText);
Console.Write("botmgr > ");
} while (!isclosing);
}
}
#endregion Bot Modes
private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
// Put your own handler here
switch (ctrlType)
{
case CtrlTypes.CTRL_C_EVENT:
case CtrlTypes.CTRL_BREAK_EVENT:
case CtrlTypes.CTRL_CLOSE_EVENT:
case CtrlTypes.CTRL_LOGOFF_EVENT:
case CtrlTypes.CTRL_SHUTDOWN_EVENT:
if (manager != null)
{
manager.StopBots();
}
isclosing = true;
break;
}
return true;
}
#region Console Control Handler Imports
// Declare the SetConsoleCtrlHandler function
// as external and receiving a delegate.
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
#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.Text.RegularExpressions;
using Xunit;
public class CharacterClassSubtraction
{
// This tests CharacterClassSubtraction by specifying pattern, input and expected groups
[Fact]
public static void CharacterClassSubtractionTestCase()
{
//////////// Global Variables used for all tests
String strLoc = "Loc_000oo";
String strValue = String.Empty;
int iCountErrors = 0;
int iCountTestcases = 0;
try
{
///////////////////////// START TESTS ////////////////////////////
///////////////////////////////////////////////////////////////////
for (int i = 0; i < s_regexTests.Length; i++)
{
iCountTestcases++;
if (!s_regexTests[i].Run())
{
Console.WriteLine("Err_79872asnko! Test {0} FAILED Pattern={1}, Input={2}\n", i, s_regexTests[i].Pattern, s_regexTests[i].Input);
iCountErrors++;
}
}
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
Assert.Equal(0, iCountErrors);
}
private static RegexTestCase[] s_regexTests = new RegexTestCase[] {
/****************************************************************************
(A - B) B is a subset of A (ie B only contains chars that are in A)
*****************************************************************************/
new RegexTestCase(@"[abcd-[d]]+", "dddaabbccddd", "aabbcc"),
new RegexTestCase(@"[\d-[357]]+", "33312468955","124689"),
new RegexTestCase(@"[\d-[357]]+", "51246897","124689"),
new RegexTestCase(@"[\d-[357]]+", "3312468977","124689"),
new RegexTestCase(@"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy","aaaABCD09zzz"),
new RegexTestCase(@"[\w-[\d]]+", "0AZaz9","AZaz"),
new RegexTestCase(@"[\w-[\p{Ll}]]+", "a09AZz","09AZ"),
new RegexTestCase(@"[\d-[13579]]+", RegexOptions.ECMAScript, "1024689", "02468"),
new RegexTestCase(@"[\d-[13579]]+", RegexOptions.ECMAScript, "\x066102468\x0660", "02468"),
new RegexTestCase(@"[\d-[13579]]+", "\x066102468\x0660", "\x066102468\x0660"),
new RegexTestCase(@"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy","aaaABCD09zzz"),
new RegexTestCase(@"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy","aaaABCD09zzz"),
new RegexTestCase(@"[\w-[b-y]]+", "bbbaaaABCD09zzzyyy","aaaABCD09zzz"),
new RegexTestCase(@"[\p{Ll}-[ae-z]]+", "aaabbbcccdddeee","bbbcccddd"),
new RegexTestCase(@"[\p{Nd}-[2468]]+", "20135798","013579"),
new RegexTestCase(@"[\P{Lu}-[ae-z]]+", "aaabbbcccdddeee","bbbcccddd"),
new RegexTestCase(@"[\P{Nd}-[\p{Ll}]]+", "az09AZ'[]","AZ'[]"),
/****************************************************************************
(A - B) B is a superset of A (ie B contains chars that are in A plus other chars that are not in A)
*****************************************************************************/
new RegexTestCase(@"[abcd-[def]]+", "fedddaabbccddd", "aabbcc"),
new RegexTestCase(@"[\d-[357a-z]]+", "az33312468955","124689"),
new RegexTestCase(@"[\d-[de357fgA-Z]]+", "AZ51246897","124689"),
new RegexTestCase(@"[\d-[357\p{Ll}]]+", "az3312468977","124689"),
new RegexTestCase(@"[\w-[b-y\s]]+", " \tbbbaaaABCD09zzzyyy","aaaABCD09zzz"),
new RegexTestCase(@"[\w-[\d\p{Po}]]+", "!#0AZaz9","AZaz"),
new RegexTestCase(@"[\w-[\p{Ll}\s]]+", "a09AZz","09AZ"),
new RegexTestCase(@"[\d-[13579a-zA-Z]]+", RegexOptions.ECMAScript, "AZ1024689", "02468"),
new RegexTestCase(@"[\d-[13579abcd]]+", RegexOptions.ECMAScript, "abcd\x066102468\x0660", "02468"),
new RegexTestCase(@"[\d-[13579\s]]+", " \t\x066102468\x0660", "\x066102468\x0660"),
new RegexTestCase(@"[\w-[b-y\p{Po}]]+", "!#bbbaaaABCD09zzzyyy","aaaABCD09zzz"),
new RegexTestCase(@"[\w-[b-y!.,]]+", "!.,bbbaaaABCD09zzzyyy","aaaABCD09zzz"),
new RegexTestCase("[\\w-[b-y\x00-\x0F]]+", "\0bbbaaaABCD09zzzyyy","aaaABCD09zzz"),
new RegexTestCase(@"[\p{Ll}-[ae-z0-9]]+", "09aaabbbcccdddeee","bbbcccddd"),
new RegexTestCase(@"[\p{Nd}-[2468az]]+", "az20135798","013579"),
new RegexTestCase(@"[\P{Lu}-[ae-zA-Z]]+", "AZaaabbbcccdddeee","bbbcccddd"),
new RegexTestCase(@"[\P{Nd}-[\p{Ll}0123456789]]+", "09az09AZ'[]","AZ'[]"),
/****************************************************************************
(A - B) B only contains chars that are not in A
*****************************************************************************/
new RegexTestCase(@"[abc-[defg]]+", "dddaabbccddd", "aabbcc"),
new RegexTestCase(@"[\d-[abc]]+", "abc09abc","09"),
new RegexTestCase(@"[\d-[a-zA-Z]]+", "az09AZ","09"),
new RegexTestCase(@"[\d-[\p{Ll}]]+", "az09az","09"),
new RegexTestCase(@"[\w-[\x00-\x0F]]+", "bbbaaaABYZ09zzzyyy","bbbaaaABYZ09zzzyyy"),
new RegexTestCase(@"[\w-[\s]]+", "0AZaz9","0AZaz9"),
new RegexTestCase(@"[\w-[\W]]+", "0AZaz9","0AZaz9"),
new RegexTestCase(@"[\w-[\p{Po}]]+", "#a09AZz!","a09AZz"),
new RegexTestCase(@"[\d-[\D]]+", RegexOptions.ECMAScript, "azAZ1024689", "1024689"),
new RegexTestCase(@"[\d-[a-zA-Z]]+", RegexOptions.ECMAScript, "azAZ\x066102468\x0660", "02468"),
new RegexTestCase(@"[\d-[\p{Ll}]]+", "\x066102468\x0660", "\x066102468\x0660"),
new RegexTestCase(@"[a-zA-Z0-9-[\s]]+", " \tazAZ09","azAZ09"),
new RegexTestCase(@"[a-zA-Z0-9-[\W]]+", "bbbaaaABCD09zzzyyy","bbbaaaABCD09zzzyyy"),
new RegexTestCase(@"[a-zA-Z0-9-[^a-zA-Z0-9]]+", "bbbaaaABCD09zzzyyy","bbbaaaABCD09zzzyyy"),
new RegexTestCase(@"[\p{Ll}-[A-Z]]+", "AZaz09","az"),
new RegexTestCase(@"[\p{Nd}-[a-z]]+", "az09","09"),
new RegexTestCase(@"[\P{Lu}-[\p{Lu}]]+", "AZazAZ","az"),
new RegexTestCase(@"[\P{Lu}-[A-Z]]+", "AZazAZ","az"),
new RegexTestCase(@"[\P{Nd}-[\p{Nd}]]+", "azAZ09","azAZ"),
new RegexTestCase(@"[\P{Nd}-[2-8]]+", "1234567890azAZ1234567890","azAZ"),
/****************************************************************************
(A - B) A and B are the same sets
*****************************************************************************/
//No Negation
new RegexTestCase(@"[abcd-[abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[1234-[1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
//All Negation
new RegexTestCase(@"[^abcd-[^abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^1234-[^1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
//No Negation
new RegexTestCase(@"[a-z-[a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[0-9-[0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
//All Negation
new RegexTestCase(@"[^a-z-[^a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^0-9-[^0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
//No Negation
new RegexTestCase(@"[\w-[\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\W-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\s-[\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\S-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\d-[\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\D-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
//All Negation
new RegexTestCase(@"[^\w-[^\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\W-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\s-[^\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\S-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\d-[^\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\D-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
//MixedNegation
new RegexTestCase(@"[^\w-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\w-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\s-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\s-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\d-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\d-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
//No Negation
new RegexTestCase(@"[\p{Ll}-[\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\P{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\p{Lu}-[\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\P{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\p{Nd}-[\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\P{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
//All Negation
new RegexTestCase(@"[^\p{Ll}-[^\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\P{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\p{Lu}-[^\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\P{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\p{Nd}-[^\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\P{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
//MixedNegation
new RegexTestCase(@"[^\p{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\p{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\p{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\p{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[^\p{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
new RegexTestCase(@"[\p{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n"),
/****************************************************************************
Alternating construct
*****************************************************************************/
new RegexTestCase(@"([ ]|[\w-[0-9]])+", "09az AZ90", "az AZ", "Z"),
new RegexTestCase(@"([0-9-[02468]]|[0-9-[13579]])+", "az1234567890za", "1234567890", "0"),
new RegexTestCase(@"([^0-9-[a-zAE-Z]]|[\w-[a-zAF-Z]])+", "azBCDE1234567890BCDEFza", "BCDE1234567890BCDE", "E"),
new RegexTestCase("([\u0000-\uFFFF-[azAZ09]]|[\u0000-\uFFFF-[^azAZ09]])+", "azAZBCDE1234567890BCDEFAZza", "azAZBCDE1234567890BCDEFAZza", "a"),
new RegexTestCase(@"([\p{Ll}-[aeiou]]|[^\w-[\s]])+", "aeiobcdxyz!@#aeio", "bcdxyz!@#", "#"),
/****************************************************************************
Multiple characater classes using character class subtraction
*****************************************************************************/
new RegexTestCase(@"98[\d-[9]][\d-[8]][\d-[0]]", "98911 98881 98870 98871", "98871"),
new RegexTestCase(@"m[\w-[^aeiou]][\w-[^aeiou]]t", "mbbt mect meet", "meet"),
/****************************************************************************
Nested character class subtraction
*****************************************************************************/
new RegexTestCase("[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[a]]]]]]+",
"abcxyzABCXYZ123890", "bcxyzABCXYZ123890"),
new RegexTestCase("[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[\u0000-\uFFFF-[a]]]]]]]+",
"bcxyzABCXYZ123890a", "a"),
/****************************************************************************
Negation with character class subtraction
*****************************************************************************/
new RegexTestCase("[abcdef-[^bce]]+", "adfbcefda", "bce"),
new RegexTestCase("[^cde-[ag]]+", "agbfxyzga", "bfxyz"),
/****************************************************************************
Misc The idea here is come up with real world examples of char class subtraction. Things that
would be difficult to define without it
*****************************************************************************/
new RegexTestCase("[\u0000-\uFFFF-[\\p{P}\\p{S}\\p{C}]]+", "!@`';.,$+<>=\x0001\x001FazAZ09", "azAZ09"),
new RegexTestCase(@"[\p{L}-[^\p{Lu}]]+", "09',.abcxyzABCXYZ", "ABCXYZ"),
new RegexTestCase(@"[\p{IsGreek}-[\P{Lu}]]+", "\u0390\u03FE\u0386\u0388\u03EC\u03EE\u0400", "\u03FE\u0386\u0388\u03EC\u03EE"),
new RegexTestCase(@"[\p{IsBasicLatin}-[G-L]]+", "GAFMZL", "AFMZ"),
new RegexTestCase(@"[a-zA-Z-[aeiouAEIOU]]+", "aeiouAEIOUbcdfghjklmnpqrstvwxyz", "bcdfghjklmnpqrstvwxyz"),
//The following is an overly complex way of matching an ip address using char class subtraction
new RegexTestCase(@"^
(?<octet>^
(
(
(?<Octet2xx>[\d-[013-9]])
|
[\d-[2-9]]
)
(?(Octet2xx)
(
(?<Octet25x>[\d-[01-46-9]])
|
[\d-[5-9]]
)
(
(?(Octet25x)
[\d-[6-9]]
|
[\d]
)
)
|
[\d]{2}
)
)
|
([\d][\d])
|
[\d]
)$"
, RegexOptions.IgnorePatternWhitespace, "255", "255", "255", "2", "5", "5", "", "255", "2", "5"),
new RegexTestCase(@"^
(?<octet>
(
(
(?<Octet2xx>[\d-[013-9]])
|
[\d-[2-9]]
)
(?(Octet2xx)
(
(?<Octet25x>[\d-[01-46-9]])
|
[\d-[5-9]]
)
(
(?(Octet25x)
[\d-[6-9]]
|
[\d]
)
)
|
[\d]{2}
)
)
|
([\d][\d])
|
[\d]
)$"
, RegexOptions.IgnorePatternWhitespace, "256"),
new RegexTestCase(@"^
(?<octet>
(
(
(?<Octet2xx>[\d-[013-9]])
|
[\d-[2-9]]
)
(?(Octet2xx)
(
(?<Octet25x>[\d-[01-46-9]])
|
[\d-[5-9]]
)
(
(?(Octet25x)
[\d-[6-9]]
|
[\d]
)
)
|
[\d]{2}
)
)
|
([\d][\d])
|
[\d]
)$"
, RegexOptions.IgnorePatternWhitespace, "261"),
/****************************************************************************
Parser Correctness
*****************************************************************************/
//Character Class Substraction
new RegexTestCase(@"[abcd\-d-[bc]]+", "bbbaaa---dddccc", "aaa---ddd"),
new RegexTestCase(@"[abcd\-d-[bc]]+", "bbbaaa---dddccc", "aaa---ddd"),
new RegexTestCase(@"[^a-f-[\x00-\x60\u007B-\uFFFF]]+", "aaafffgggzzz{{{", "gggzzz"),
new RegexTestCase(@"[a-f-[]]+", typeof(ArgumentException)),
new RegexTestCase(@"[\[\]a-f-[[]]+", "gggaaafff]]][[[", "aaafff]]]"),
new RegexTestCase(@"[\[\]a-f-[]]]+", "gggaaafff[[[]]]", "aaafff[[["),
new RegexTestCase(@"[ab\-\[cd-[-[]]]]", "a]]", "a]]"),
new RegexTestCase(@"[ab\-\[cd-[-[]]]]", "b]]", "b]]"),
new RegexTestCase(@"[ab\-\[cd-[-[]]]]", "c]]", "c]]"),
new RegexTestCase(@"[ab\-\[cd-[-[]]]]", "d]]", "d]]"),
new RegexTestCase(@"[ab\-\[cd-[-[]]]]", "[]]"),
new RegexTestCase(@"[ab\-\[cd-[-[]]]]", "-]]"),
new RegexTestCase(@"[ab\-\[cd-[-[]]]]", "`]]"),
new RegexTestCase(@"[ab\-\[cd-[-[]]]]", "e]]"),
new RegexTestCase(@"[ab\-\[cd-[[]]]]", "a]]", "a]]"),
new RegexTestCase(@"[ab\-\[cd-[[]]]]", "b]]", "b]]"),
new RegexTestCase(@"[ab\-\[cd-[[]]]]", "c]]", "c]]"),
new RegexTestCase(@"[ab\-\[cd-[[]]]]", "d]]", "d]]"),
new RegexTestCase(@"[ab\-\[cd-[[]]]]", "-]]", "-]]"),
new RegexTestCase(@"[ab\-\[cd-[[]]]]", "']]"),
new RegexTestCase(@"[ab\-\[cd-[[]]]]", "e]]"),
new RegexTestCase(@"[a-[a-f]]", "abcdefghijklmnopqrstuvwxyz"),
new RegexTestCase(@"[a-[c-e]]+", "bbbaaaccc", "aaa"),
new RegexTestCase(@"[a-[c-e]]+", "```aaaccc", "aaa"),
new RegexTestCase(@"[a-d\--[bc]]+", "cccaaa--dddbbb", "aaa--ddd"),
//NOT Character Class Substraction
new RegexTestCase(@"[\0- [bc]+", "!!!\0\0\t\t [[[[bbbcccaaa", "\0\0\t\t [[[[bbbccc"),
new RegexTestCase(@"[[abcd]-[bc]]+", "a-b]", "a-b]"),
new RegexTestCase(@"[-[e-g]+", "ddd[[[---eeefffggghhh", "[[[---eeefffggg"),
new RegexTestCase(@"[-e-g]+", "ddd---eeefffggghhh", "---eeefffggg"),
new RegexTestCase(@"[-e-g]+", "ddd---eeefffggghhh", "---eeefffggg"),
new RegexTestCase(@"[a-e - m-p]+", "---a b c d e m n o p---", "a b c d e m n o p"),
new RegexTestCase(@"[^-[bc]]", "b] c] -] aaaddd]", "d]"),
new RegexTestCase(@"[^-[bc]]", "b] c] -] aaa]ddd]", "a]"),
new RegexTestCase(@"[A-[]+", typeof(ArgumentException)),
//Make sure we correctly handle \-
new RegexTestCase(@"[a\-[bc]+", "```bbbaaa---[[[cccddd", "bbbaaa---[[[ccc"),
new RegexTestCase(@"[a\-[\-\-bc]+", "```bbbaaa---[[[cccddd", "bbbaaa---[[[ccc"),
new RegexTestCase(@"[a\-\[\-\[\-bc]+", "```bbbaaa---[[[cccddd", "bbbaaa---[[[ccc"),
new RegexTestCase(@"[abc\--[b]]+", "[[[```bbbaaa---cccddd", "aaa---ccc"),
new RegexTestCase(@"[abc\-z-[b]]+", "```aaaccc---zzzbbb", "aaaccc---zzz"),
new RegexTestCase(@"[a-d\-[b]+", "```aaabbbcccddd----[[[[]]]", "aaabbbcccddd----[[[["),
new RegexTestCase(@"[abcd\-d\-[bc]+", "bbbaaa---[[[dddccc", "bbbaaa---[[[dddccc"),
//Everything works correctly with option RegexOptions.IgnorePatternWhitespace
new RegexTestCase(@"[a - c - [ b ] ]+", RegexOptions.IgnorePatternWhitespace, "dddaaa ccc [[[[ bbb ]]]", " ]]]"),
new RegexTestCase(@"[a - c - [ b ] +", RegexOptions.IgnorePatternWhitespace, "dddaaa ccc [[[[ bbb ]]]", "aaa ccc [[[[ bbb "),
};
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public static partial class Console
{
public static System.ConsoleColor BackgroundColor { get { throw null; } set { } }
public static void Beep() { }
public static void Beep(int frequency, int duration) { }
public static int BufferHeight { get { throw null; } set { } }
public static int BufferWidth { get { throw null; } set { } }
public static bool CapsLock { get { throw null; } }
public static event System.ConsoleCancelEventHandler CancelKeyPress { add { } remove { } }
public static void Clear() { }
public static int CursorLeft { get { throw null; } set { } }
public static int CursorSize { get { throw null; } set { } }
public static int CursorTop { get { throw null; } set { } }
public static bool CursorVisible { get { throw null; } set { } }
public static System.IO.TextWriter Error { get { throw null; } }
public static System.ConsoleColor ForegroundColor { get { throw null; } set { } }
public static System.Text.Encoding InputEncoding { get { throw null; } set { } }
public static bool IsErrorRedirected { get { throw null; } }
public static bool IsInputRedirected { get { throw null; } }
public static bool IsOutputRedirected { get { throw null; } }
public static System.IO.TextReader In { get { throw null; } }
public static bool KeyAvailable { get { throw null; }}
public static int LargestWindowWidth { get { throw null; } }
public static int LargestWindowHeight { get { throw null; }}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) { }
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { }
public static bool NumberLock { get { throw null; }}
public static System.IO.Stream OpenStandardError() { throw null; }
public static System.IO.Stream OpenStandardError(int bufferSize) { throw null; }
public static System.IO.Stream OpenStandardInput() { throw null; }
public static System.IO.Stream OpenStandardInput(int bufferSize) { throw null; }
public static System.IO.Stream OpenStandardOutput() { throw null; }
public static System.IO.Stream OpenStandardOutput(int bufferSize) { throw null; }
public static System.IO.TextWriter Out { get { throw null; } }
public static System.Text.Encoding OutputEncoding { get { throw null; } set { } }
public static int Read() { throw null; }
public static ConsoleKeyInfo ReadKey() { throw null; }
public static ConsoleKeyInfo ReadKey(bool intercept) { throw null; }
public static string ReadLine() { throw null; }
public static void ResetColor() { }
public static void SetBufferSize(int width, int height) { }
public static void SetCursorPosition(int left, int top) { }
public static void SetError(System.IO.TextWriter newError) { }
public static void SetIn(System.IO.TextReader newIn) { }
public static void SetOut(System.IO.TextWriter newOut) { }
public static void SetWindowPosition(int left, int top) { }
public static void SetWindowSize(int width, int height) { }
public static string Title { get { throw null; } set { } }
public static bool TreatControlCAsInput { get { throw null; } set { } }
public static int WindowHeight { get { throw null; } set { } }
public static int WindowWidth { get { throw null; } set { } }
public static int WindowLeft { get { throw null; } set { } }
public static int WindowTop { get { throw null; } set { } }
public static void Write(bool value) { }
public static void Write(char value) { }
public static void Write(char[] buffer) { }
public static void Write(char[] buffer, int index, int count) { }
public static void Write(decimal value) { }
public static void Write(double value) { }
public static void Write(int value) { }
public static void Write(long value) { }
public static void Write(object value) { }
public static void Write(float value) { }
public static void Write(string value) { }
public static void Write(string format, object arg0) { }
public static void Write(string format, object arg0, object arg1) { }
public static void Write(string format, object arg0, object arg1, object arg2) { }
public static void Write(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public static void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void Write(ulong value) { }
public static void WriteLine() { }
public static void WriteLine(bool value) { }
public static void WriteLine(char value) { }
public static void WriteLine(char[] buffer) { }
public static void WriteLine(char[] buffer, int index, int count) { }
public static void WriteLine(decimal value) { }
public static void WriteLine(double value) { }
public static void WriteLine(int value) { }
public static void WriteLine(long value) { }
public static void WriteLine(object value) { }
public static void WriteLine(float value) { }
public static void WriteLine(string value) { }
public static void WriteLine(string format, object arg0) { }
public static void WriteLine(string format, object arg0, object arg1) { }
public static void WriteLine(string format, object arg0, object arg1, object arg2) { }
public static void WriteLine(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(ulong value) { }
}
public sealed partial class ConsoleCancelEventArgs : System.EventArgs
{
internal ConsoleCancelEventArgs() { }
public bool Cancel { get { throw null; } set { } }
public System.ConsoleSpecialKey SpecialKey { get { throw null; } }
}
public delegate void ConsoleCancelEventHandler(object sender, System.ConsoleCancelEventArgs e);
public enum ConsoleColor
{
Black = 0,
Blue = 9,
Cyan = 11,
DarkBlue = 1,
DarkCyan = 3,
DarkGray = 8,
DarkGreen = 2,
DarkMagenta = 5,
DarkRed = 4,
DarkYellow = 6,
Gray = 7,
Green = 10,
Magenta = 13,
Red = 12,
White = 15,
Yellow = 14,
}
public partial struct ConsoleKeyInfo
{
public ConsoleKeyInfo(char keyChar, ConsoleKey key, bool shift, bool alt, bool control) { }
public char KeyChar { get { throw null; } }
public ConsoleKey Key { get { throw null; } }
public ConsoleModifiers Modifiers { get { throw null; } }
public bool Equals(ConsoleKeyInfo obj) { throw null; }
public override bool Equals(object value) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(ConsoleKeyInfo a, ConsoleKeyInfo b) { throw null; }
public static bool operator !=(ConsoleKeyInfo a, ConsoleKeyInfo b) { throw null; }
}
public enum ConsoleKey
{
Backspace = 0x8,
Tab = 0x9,
Clear = 0xC,
Enter = 0xD,
Pause = 0x13,
Escape = 0x1B,
Spacebar = 0x20,
PageUp = 0x21,
PageDown = 0x22,
End = 0x23,
Home = 0x24,
LeftArrow = 0x25,
UpArrow = 0x26,
RightArrow = 0x27,
DownArrow = 0x28,
Select = 0x29,
Print = 0x2A,
Execute = 0x2B,
PrintScreen = 0x2C,
Insert = 0x2D,
Delete = 0x2E,
Help = 0x2F,
D0 = 0x30, // 0 through 9
D1 = 0x31,
D2 = 0x32,
D3 = 0x33,
D4 = 0x34,
D5 = 0x35,
D6 = 0x36,
D7 = 0x37,
D8 = 0x38,
D9 = 0x39,
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4A,
K = 0x4B,
L = 0x4C,
M = 0x4D,
N = 0x4E,
O = 0x4F,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5A,
LeftWindows = 0x5B,
RightWindows = 0x5C,
Applications = 0x5D,
Sleep = 0x5F,
NumPad0 = 0x60,
NumPad1 = 0x61,
NumPad2 = 0x62,
NumPad3 = 0x63,
NumPad4 = 0x64,
NumPad5 = 0x65,
NumPad6 = 0x66,
NumPad7 = 0x67,
NumPad8 = 0x68,
NumPad9 = 0x69,
Multiply = 0x6A,
Add = 0x6B,
Separator = 0x6C,
Subtract = 0x6D,
Decimal = 0x6E,
Divide = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
F13 = 0x7C,
F14 = 0x7D,
F15 = 0x7E,
F16 = 0x7F,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
BrowserBack = 0xA6,
BrowserForward = 0xA7,
BrowserRefresh = 0xA8,
BrowserStop = 0xA9,
BrowserSearch = 0xAA,
BrowserFavorites = 0xAB,
BrowserHome = 0xAC,
VolumeMute = 0xAD,
VolumeDown = 0xAE,
VolumeUp = 0xAF,
MediaNext = 0xB0,
MediaPrevious = 0xB1,
MediaStop = 0xB2,
MediaPlay = 0xB3,
LaunchMail = 0xB4,
LaunchMediaSelect = 0xB5,
LaunchApp1 = 0xB6,
LaunchApp2 = 0xB7,
Oem1 = 0xBA,
OemPlus = 0xBB,
OemComma = 0xBC,
OemMinus = 0xBD,
OemPeriod = 0xBE,
Oem2 = 0xBF,
Oem3 = 0xC0,
Oem4 = 0xDB,
Oem5 = 0xDC,
Oem6 = 0xDD,
Oem7 = 0xDE,
Oem8 = 0xDF,
Oem102 = 0xE2,
Process = 0xE5,
Packet = 0xE7,
Attention = 0xF6,
CrSel = 0xF7,
ExSel = 0xF8,
EraseEndOfFile = 0xF9,
Play = 0xFA,
Zoom = 0xFB,
NoName = 0xFC,
Pa1 = 0xFD,
OemClear = 0xFE,
}
[Flags]
public enum ConsoleModifiers
{
Alt = 1,
Shift = 2,
Control = 4
}
public enum ConsoleSpecialKey
{
ControlBreak = 1,
ControlC = 0,
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading;
using Xunit;
public partial class ThreadPoolBoundHandleTests
{
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_NullAsCallback_ThrowsArgumentNullException()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
AssertExtensions.Throws<ArgumentNullException>("callback", () =>
{
handle.AllocateNativeOverlapped(null, new object(), new byte[256]);
});
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_PreAllocated_ThrowsArgumentNullException()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
AssertExtensions.Throws<ArgumentNullException>("preAllocated", () =>
{
handle.AllocateNativeOverlapped((PreAllocatedOverlapped)null);
});
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_NullAsContext_DoesNotThrow()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, (object)null, new byte[256]);
Assert.True(result != null);
handle.FreeNativeOverlapped(result);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_NullAsPinData_DoesNotThrow()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), (byte[])null);
Assert.True(result != null);
handle.FreeNativeOverlapped(result);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_EmptyArrayAsPinData_DoesNotThrow()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[0]);
Assert.True(result != null);
handle.FreeNativeOverlapped(result);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_NonBlittableTypeAsPinData_Throws()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
Assert.Throws<ArgumentException>(() => handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new NonBlittableType() { s = "foo" }));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_BlittableTypeAsPinData_DoesNotThrow()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new BlittableType() { i = 42 });
Assert.True(result != null);
handle.FreeNativeOverlapped(result);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_ObjectArrayAsPinData_DoesNotThrow()
{
object[] array = new object[]
{
new BlittableType() { i = 1 },
new byte[5],
};
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), array);
Assert.True(result != null);
handle.FreeNativeOverlapped(result);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_ObjectArrayWithNonBlittableTypeAsPinData_Throws()
{
object[] array = new object[]
{
new NonBlittableType() { s = "foo" },
new byte[5],
};
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
Assert.Throws<ArgumentException>(() => handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), array));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_ReturnedNativeOverlapped_AllFieldsZero()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
NativeOverlapped* overlapped = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[256]);
Assert.Equal(IntPtr.Zero, overlapped->InternalLow);
Assert.Equal(IntPtr.Zero, overlapped->InternalHigh);
Assert.Equal(0, overlapped->OffsetLow);
Assert.Equal(0, overlapped->OffsetHigh);
Assert.Equal(IntPtr.Zero, overlapped->EventHandle);
handle.FreeNativeOverlapped(overlapped);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_PreAllocated_ReturnedNativeOverlapped_AllFieldsZero()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
using(PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped((_, __, ___) => { }, new object(), new byte[256]))
{
NativeOverlapped* overlapped = handle.AllocateNativeOverlapped(preAlloc);
Assert.Equal(IntPtr.Zero, overlapped->InternalLow);
Assert.Equal(IntPtr.Zero, overlapped->InternalHigh);
Assert.Equal(0, overlapped->OffsetLow);
Assert.Equal(0, overlapped->OffsetHigh);
Assert.Equal(IntPtr.Zero, overlapped->EventHandle);
handle.FreeNativeOverlapped(overlapped);
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_PossibleReusedReturnedNativeOverlapped_OffsetLowAndOffsetHighSetToZero()
{ // The CLR reuses NativeOverlapped underneath, check to make sure that they reset fields back to zero
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
NativeOverlapped* overlapped = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[256]);
overlapped->OffsetHigh = 1;
overlapped->OffsetLow = 1;
handle.FreeNativeOverlapped(overlapped);
overlapped = handle.AllocateNativeOverlapped((errorCode, numBytes, overlap) => { }, new object(), new byte[256]);
Assert.Equal(IntPtr.Zero, overlapped->InternalLow);
Assert.Equal(IntPtr.Zero, overlapped->InternalHigh);
Assert.Equal(0, overlapped->OffsetLow);
Assert.Equal(0, overlapped->OffsetHigh);
Assert.Equal(IntPtr.Zero, overlapped->EventHandle);
handle.FreeNativeOverlapped(overlapped);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_PreAllocated_ReusedReturnedNativeOverlapped_OffsetLowAndOffsetHighSetToZero()
{ // The CLR reuses NativeOverlapped underneath, check to make sure that they reset fields back to zero
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped((_, __, ___) => { }, new object(), new byte[256]);
NativeOverlapped* overlapped = handle.AllocateNativeOverlapped(preAlloc);
overlapped->OffsetHigh = 1;
overlapped->OffsetLow = 1;
handle.FreeNativeOverlapped(overlapped);
overlapped = handle.AllocateNativeOverlapped(preAlloc);
Assert.Equal(IntPtr.Zero, overlapped->InternalLow);
Assert.Equal(IntPtr.Zero, overlapped->InternalHigh);
Assert.Equal(0, overlapped->OffsetLow);
Assert.Equal(0, overlapped->OffsetHigh);
Assert.Equal(IntPtr.Zero, overlapped->EventHandle);
handle.FreeNativeOverlapped(overlapped);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_WhenDisposed_ThrowsObjectDisposedException()
{
ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle();
handle.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
{
handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[256]);
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_PreAllocated_WhenDisposed_ThrowsObjectDisposedException()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped(delegate { }, null, null);
preAlloc.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
{
handle.AllocateNativeOverlapped(preAlloc);
});
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_PreAllocated_WhenHandleDisposed_ThrowsObjectDisposedException()
{
ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle();
handle.Dispose();
PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped(delegate { }, null, null);
Assert.Throws<ObjectDisposedException>(() =>
{
handle.AllocateNativeOverlapped(preAlloc);
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
public unsafe void AllocateNativeOverlapped_PreAllocated_WhenAlreadyAllocated_ThrowsArgumentException()
{
using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
{
using(PreAllocatedOverlapped preAlloc = new PreAllocatedOverlapped(delegate { }, null, null))
{
NativeOverlapped* overlapped = handle.AllocateNativeOverlapped(preAlloc);
Assert.Throws<ArgumentException>(() =>
{
handle.AllocateNativeOverlapped(preAlloc);
});
handle.FreeNativeOverlapped(overlapped);
}
}
}
}
| |
/* ====================================================================
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.HSSF.UserModel
{
using NPOI.Util;
using NPOI.DDF;
using NPOI.HSSF.Record;
/// <summary>
/// @author Glen Stampoultzis (glens at baselinksoftware.com)
/// </summary>
public class HSSFPolygon : HSSFSimpleShape
{
private static POILogger logger = POILogFactory.GetLogger(typeof(HSSFPolygon));
public new static short OBJECT_TYPE_MICROSOFT_OFFICE_DRAWING = 0x1E;
public HSSFPolygon(EscherContainerRecord spContainer, ObjRecord objRecord, TextObjectRecord _textObjectRecord)
: base(spContainer, objRecord, _textObjectRecord)
{
}
public HSSFPolygon(EscherContainerRecord spContainer, ObjRecord objRecord)
: base(spContainer, objRecord)
{
}
public HSSFPolygon(HSSFShape parent, HSSFAnchor anchor)
: base(parent, anchor)
{
}
protected override TextObjectRecord CreateTextObjRecord()
{
return null;
}
/**
* Generates the shape records for this shape.
*/
protected override EscherContainerRecord CreateSpContainer()
{
EscherContainerRecord spContainer = new EscherContainerRecord();
EscherSpRecord sp = new EscherSpRecord();
EscherOptRecord opt = new EscherOptRecord();
EscherClientDataRecord clientData = new EscherClientDataRecord();
spContainer.RecordId = (EscherContainerRecord.SP_CONTAINER);
spContainer.Options = ((short)0x000F);
sp.RecordId = (EscherSpRecord.RECORD_ID);
sp.Options = ((short)((EscherAggregate.ST_NOT_PRIMATIVE << 4) | 0x2));
if (Parent == null)
{
sp.Flags = (EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE);
}
else
{
sp.Flags = (EscherSpRecord.FLAG_CHILD | EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE);
}
opt.RecordId = (EscherOptRecord.RECORD_ID);
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.TRANSFORM__ROTATION, false, false, 0));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, false, false, 100));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, false, false, 100));
opt.SetEscherProperty(new EscherShapePathProperty(EscherProperties.GEOMETRY__SHAPEPATH, EscherShapePathProperty.COMPLEX));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__FILLOK, false, false, 0x00010001));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINESTARTARROWHEAD, false, false, 0x0));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEENDARROWHEAD, false, false, 0x0));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEENDCAPSTYLE, false, false, 0x0));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEDASHING, LINESTYLE_SOLID));
opt.SetEscherProperty(new EscherBoolProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x00080008));
opt.SetEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEWIDTH, LINEWIDTH_DEFAULT));
opt.SetEscherProperty(new EscherRGBProperty(EscherProperties.FILL__FILLCOLOR, FILL__FILLCOLOR_DEFAULT));
opt.SetEscherProperty(new EscherRGBProperty(EscherProperties.LINESTYLE__COLOR, LINESTYLE__COLOR_DEFAULT));
opt.SetEscherProperty(new EscherBoolProperty(EscherProperties.FILL__NOFILLHITTEST, 1));
opt.SetEscherProperty(new EscherBoolProperty(EscherProperties.GROUPSHAPE__PRINT, 0x080000));
EscherRecord anchor = Anchor.GetEscherAnchor();
clientData.RecordId = (EscherClientDataRecord.RECORD_ID);
clientData.Options = ((short)0x0000);
spContainer.AddChildRecord(sp);
spContainer.AddChildRecord(opt);
spContainer.AddChildRecord(anchor);
spContainer.AddChildRecord(clientData);
return spContainer;
}
/**
* Creates the low level OBJ record for this shape.
*/
protected override ObjRecord CreateObjRecord()
{
ObjRecord obj = new ObjRecord();
CommonObjectDataSubRecord c = new CommonObjectDataSubRecord();
c.ObjectType = CommonObjectType.MicrosoftOfficeDrawing;
c.IsLocked = (true);
c.IsPrintable = (true);
c.IsAutoFill = (true);
c.IsAutoline = (true);
EndSubRecord e = new EndSubRecord();
obj.AddSubRecord(c);
obj.AddSubRecord(e);
return obj;
}
internal override void AfterRemove(HSSFPatriarch patriarch)
{
patriarch.getBoundAggregate().RemoveShapeToObjRecord(GetEscherContainer().GetChildById(EscherClientDataRecord.RECORD_ID));
}
/**
* @return array of x coordinates
*/
public int[] XPoints
{
get
{
EscherArrayProperty verticesProp = (EscherArrayProperty)GetOptRecord().Lookup(EscherProperties.GEOMETRY__VERTICES);
if (null == verticesProp)
{
return new int[] { };
}
int[] array = new int[verticesProp.NumberOfElementsInArray - 1];
for (int i = 0; i < verticesProp.NumberOfElementsInArray - 1; i++)
{
byte[] property = verticesProp.GetElement(i);
short x = LittleEndian.GetShort(property, 0);
array[i] = x;
}
return array;
}
}
/**
* @return array of y coordinates
*/
public int[] YPoints
{
get
{
EscherArrayProperty verticesProp = (EscherArrayProperty)GetOptRecord().Lookup(EscherProperties.GEOMETRY__VERTICES);
if (null == verticesProp)
{
return new int[] { };
}
int[] array = new int[verticesProp.NumberOfElementsInArray - 1];
for (int i = 0; i < verticesProp.NumberOfElementsInArray - 1; i++)
{
byte[] property = verticesProp.GetElement(i);
short x = LittleEndian.GetShort(property, 2);
array[i] = x;
}
return array;
}
}
/**
* @param xPoints - array of x coordinates
* @param yPoints - array of y coordinates
*/
public void SetPoints(int[] xPoints, int[] yPoints)
{
if (xPoints.Length != yPoints.Length)
{
logger.Log(POILogger.ERROR, "xPoint.Length must be equal to yPoints.Length");
return;
}
if (xPoints.Length == 0)
{
logger.Log(POILogger.ERROR, "HSSFPolygon must have at least one point");
}
EscherArrayProperty verticesProp = new EscherArrayProperty(EscherProperties.GEOMETRY__VERTICES, false, new byte[0]);
verticesProp.NumberOfElementsInArray = (xPoints.Length + 1);
verticesProp.NumberOfElementsInMemory = (xPoints.Length + 1);
verticesProp.SizeOfElements = unchecked((short)(0xFFF0));
byte[] data;
for (int i = 0; i < xPoints.Length; i++)
{
data = new byte[4];
LittleEndian.PutShort(data, 0, (short)xPoints[i]);
LittleEndian.PutShort(data, 2, (short)yPoints[i]);
verticesProp.SetElement(i, data);
}
int point = xPoints.Length;
data = new byte[4];
LittleEndian.PutShort(data, 0, (short)xPoints[0]);
LittleEndian.PutShort(data, 2, (short)yPoints[0]);
verticesProp.SetElement(point, data);
SetPropertyValue(verticesProp);
EscherArrayProperty segmentsProp = new EscherArrayProperty(EscherProperties.GEOMETRY__SEGMENTINFO, false, null);
segmentsProp.SizeOfElements = (0x0002);
segmentsProp.NumberOfElementsInArray = (xPoints.Length * 2 + 4);
segmentsProp.NumberOfElementsInMemory = (xPoints.Length * 2 + 4);
segmentsProp.SetElement(0, new byte[] { (byte)0x00, (byte)0x40 });
segmentsProp.SetElement(1, new byte[] { (byte)0x00, (byte)0xAC });
for (int i = 0; i < xPoints.Length; i++)
{
segmentsProp.SetElement(2 + i * 2, new byte[] { (byte)0x01, (byte)0x00 });
segmentsProp.SetElement(3 + i * 2, new byte[] { (byte)0x00, (byte)0xAC });
}
segmentsProp.SetElement(segmentsProp.NumberOfElementsInArray - 2, new byte[] { (byte)0x01, (byte)0x60 });
segmentsProp.SetElement(segmentsProp.NumberOfElementsInArray - 1, new byte[] { (byte)0x00, (byte)0x80 });
SetPropertyValue(segmentsProp);
}
/**
* Defines the width and height of the points in the polygon
* @param width
* @param height
*/
public void SetPolygonDrawArea(int width, int height)
{
SetPropertyValue(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, width));
SetPropertyValue(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, height));
}
/**
* @return shape width
*/
public int DrawAreaWidth
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.GEOMETRY__RIGHT);
return property == null ? 100 : property.PropertyValue;
}
}
/**
* @return shape height
*/
public int DrawAreaHeight
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.GEOMETRY__BOTTOM);
return property == null ? 100 : property.PropertyValue;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Datastore.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedDatastoreClientTest
{
[xunit::FactAttribute]
public void LookupRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
LookupResponse expectedResponse = new LookupResponse
{
Found = { new EntityResult(), },
Missing = { new EntityResult(), },
Deferred = { new Key(), },
};
mockGrpcClient.Setup(x => x.Lookup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
LookupResponse response = client.Lookup(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task LookupRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
LookupResponse expectedResponse = new LookupResponse
{
Found = { new EntityResult(), },
Missing = { new EntityResult(), },
Deferred = { new Key(), },
};
mockGrpcClient.Setup(x => x.LookupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LookupResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
LookupResponse responseCallSettings = await client.LookupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LookupResponse responseCancellationToken = await client.LookupAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Lookup()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
LookupResponse expectedResponse = new LookupResponse
{
Found = { new EntityResult(), },
Missing = { new EntityResult(), },
Deferred = { new Key(), },
};
mockGrpcClient.Setup(x => x.Lookup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
LookupResponse response = client.Lookup(request.ProjectId, request.ReadOptions, request.Keys);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task LookupAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
LookupResponse expectedResponse = new LookupResponse
{
Found = { new EntityResult(), },
Missing = { new EntityResult(), },
Deferred = { new Key(), },
};
mockGrpcClient.Setup(x => x.LookupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LookupResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
LookupResponse responseCallSettings = await client.LookupAsync(request.ProjectId, request.ReadOptions, request.Keys, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LookupResponse responseCancellationToken = await client.LookupAsync(request.ProjectId, request.ReadOptions, request.Keys, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void RunQueryRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RunQueryRequest request = new RunQueryRequest
{
ReadOptions = new ReadOptions(),
PartitionId = new PartitionId(),
Query = new Query(),
GqlQuery = new GqlQuery(),
ProjectId = "project_id43ad98b0",
};
RunQueryResponse expectedResponse = new RunQueryResponse
{
Batch = new QueryResultBatch(),
Query = new Query(),
};
mockGrpcClient.Setup(x => x.RunQuery(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RunQueryResponse response = client.RunQuery(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RunQueryRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RunQueryRequest request = new RunQueryRequest
{
ReadOptions = new ReadOptions(),
PartitionId = new PartitionId(),
Query = new Query(),
GqlQuery = new GqlQuery(),
ProjectId = "project_id43ad98b0",
};
RunQueryResponse expectedResponse = new RunQueryResponse
{
Batch = new QueryResultBatch(),
Query = new Query(),
};
mockGrpcClient.Setup(x => x.RunQueryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RunQueryResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RunQueryResponse responseCallSettings = await client.RunQueryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RunQueryResponse responseCancellationToken = await client.RunQueryAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BeginTransactionRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "project_id43ad98b0",
TransactionOptions = new TransactionOptions(),
};
BeginTransactionResponse expectedResponse = new BeginTransactionResponse
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
};
mockGrpcClient.Setup(x => x.BeginTransaction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
BeginTransactionResponse response = client.BeginTransaction(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BeginTransactionRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "project_id43ad98b0",
TransactionOptions = new TransactionOptions(),
};
BeginTransactionResponse expectedResponse = new BeginTransactionResponse
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
};
mockGrpcClient.Setup(x => x.BeginTransactionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BeginTransactionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
BeginTransactionResponse responseCallSettings = await client.BeginTransactionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BeginTransactionResponse responseCancellationToken = await client.BeginTransactionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BeginTransaction()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "project_id43ad98b0",
};
BeginTransactionResponse expectedResponse = new BeginTransactionResponse
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
};
mockGrpcClient.Setup(x => x.BeginTransaction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
BeginTransactionResponse response = client.BeginTransaction(request.ProjectId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BeginTransactionAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "project_id43ad98b0",
};
BeginTransactionResponse expectedResponse = new BeginTransactionResponse
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
};
mockGrpcClient.Setup(x => x.BeginTransactionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BeginTransactionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
BeginTransactionResponse responseCallSettings = await client.BeginTransactionAsync(request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BeginTransactionResponse responseCancellationToken = await client.BeginTransactionAsync(request.ProjectId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CommitRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse response = client.Commit(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CommitRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse responseCallSettings = await client.CommitAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CommitResponse responseCancellationToken = await client.CommitAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Commit1()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse response = client.Commit(request.ProjectId, request.Mode, request.Transaction, request.Mutations);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task Commit1Async()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse responseCallSettings = await client.CommitAsync(request.ProjectId, request.Mode, request.Transaction, request.Mutations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CommitResponse responseCancellationToken = await client.CommitAsync(request.ProjectId, request.Mode, request.Transaction, request.Mutations, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Commit2()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.Commit(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse response = client.Commit(request.ProjectId, request.Mode, request.Mutations);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task Commit2Async()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
CommitRequest request = new CommitRequest
{
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "project_id43ad98b0",
};
CommitResponse expectedResponse = new CommitResponse
{
MutationResults =
{
new MutationResult(),
},
IndexUpdates = 1466771529,
};
mockGrpcClient.Setup(x => x.CommitAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CommitResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
CommitResponse responseCallSettings = await client.CommitAsync(request.ProjectId, request.Mode, request.Mutations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CommitResponse responseCancellationToken = await client.CommitAsync(request.ProjectId, request.Mode, request.Mutations, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void RollbackRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RollbackRequest request = new RollbackRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
ProjectId = "project_id43ad98b0",
};
RollbackResponse expectedResponse = new RollbackResponse { };
mockGrpcClient.Setup(x => x.Rollback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RollbackResponse response = client.Rollback(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RollbackRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RollbackRequest request = new RollbackRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
ProjectId = "project_id43ad98b0",
};
RollbackResponse expectedResponse = new RollbackResponse { };
mockGrpcClient.Setup(x => x.RollbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RollbackResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RollbackResponse responseCallSettings = await client.RollbackAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RollbackResponse responseCancellationToken = await client.RollbackAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Rollback()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RollbackRequest request = new RollbackRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
ProjectId = "project_id43ad98b0",
};
RollbackResponse expectedResponse = new RollbackResponse { };
mockGrpcClient.Setup(x => x.Rollback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RollbackResponse response = client.Rollback(request.ProjectId, request.Transaction);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RollbackAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
RollbackRequest request = new RollbackRequest
{
Transaction = proto::ByteString.CopyFromUtf8("transaction6ab7d5f4"),
ProjectId = "project_id43ad98b0",
};
RollbackResponse expectedResponse = new RollbackResponse { };
mockGrpcClient.Setup(x => x.RollbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RollbackResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
RollbackResponse responseCallSettings = await client.RollbackAsync(request.ProjectId, request.Transaction, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RollbackResponse responseCancellationToken = await client.RollbackAsync(request.ProjectId, request.Transaction, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AllocateIdsRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
AllocateIdsResponse expectedResponse = new AllocateIdsResponse { Keys = { new Key(), }, };
mockGrpcClient.Setup(x => x.AllocateIds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
AllocateIdsResponse response = client.AllocateIds(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AllocateIdsRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
AllocateIdsResponse expectedResponse = new AllocateIdsResponse { Keys = { new Key(), }, };
mockGrpcClient.Setup(x => x.AllocateIdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AllocateIdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
AllocateIdsResponse responseCallSettings = await client.AllocateIdsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AllocateIdsResponse responseCancellationToken = await client.AllocateIdsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AllocateIds()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
AllocateIdsResponse expectedResponse = new AllocateIdsResponse { Keys = { new Key(), }, };
mockGrpcClient.Setup(x => x.AllocateIds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
AllocateIdsResponse response = client.AllocateIds(request.ProjectId, request.Keys);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AllocateIdsAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
AllocateIdsResponse expectedResponse = new AllocateIdsResponse { Keys = { new Key(), }, };
mockGrpcClient.Setup(x => x.AllocateIdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AllocateIdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
AllocateIdsResponse responseCallSettings = await client.AllocateIdsAsync(request.ProjectId, request.Keys, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AllocateIdsResponse responseCancellationToken = await client.AllocateIdsAsync(request.ProjectId, request.Keys, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ReserveIdsRequestObject()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
DatabaseId = "database_idbff1efc9",
};
ReserveIdsResponse expectedResponse = new ReserveIdsResponse { };
mockGrpcClient.Setup(x => x.ReserveIds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
ReserveIdsResponse response = client.ReserveIds(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ReserveIdsRequestObjectAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
DatabaseId = "database_idbff1efc9",
};
ReserveIdsResponse expectedResponse = new ReserveIdsResponse { };
mockGrpcClient.Setup(x => x.ReserveIdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReserveIdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
ReserveIdsResponse responseCallSettings = await client.ReserveIdsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReserveIdsResponse responseCancellationToken = await client.ReserveIdsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ReserveIds()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
ReserveIdsResponse expectedResponse = new ReserveIdsResponse { };
mockGrpcClient.Setup(x => x.ReserveIds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
ReserveIdsResponse response = client.ReserveIds(request.ProjectId, request.Keys);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ReserveIdsAsync()
{
moq::Mock<Datastore.DatastoreClient> mockGrpcClient = new moq::Mock<Datastore.DatastoreClient>(moq::MockBehavior.Strict);
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "project_id43ad98b0",
};
ReserveIdsResponse expectedResponse = new ReserveIdsResponse { };
mockGrpcClient.Setup(x => x.ReserveIdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReserveIdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastoreClient client = new DatastoreClientImpl(mockGrpcClient.Object, null);
ReserveIdsResponse responseCallSettings = await client.ReserveIdsAsync(request.ProjectId, request.Keys, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReserveIdsResponse responseCancellationToken = await client.ReserveIdsAsync(request.ProjectId, request.Keys, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ODataBreeze.Areas.HelpPage.ModelDescriptions;
using ODataBreeze.Areas.HelpPage.Models;
namespace ODataBreeze.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
namespace SqlStreamStore
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// A delegating handler that handles HTTP redirects (301, 302, 303, 307, and 308).
/// https://gist.github.com/joelverhagen/3be85bc0d5733756befa#file-redirectinghandler-cs
/// </summary>
internal class RedirectingHandler : DelegatingHandler
{
/// <summary>
/// The property key used to access the list of responses.
/// </summary>
public const string HistoryPropertyKey = "Knapcode.Http.Handlers.RedirectingHandler.ResponseHistory";
private static readonly ISet<HttpStatusCode> s_redirectStatusCodes = new HashSet<HttpStatusCode>(new[]
{
HttpStatusCode.MovedPermanently,
HttpStatusCode.Found,
HttpStatusCode.SeeOther,
HttpStatusCode.PermanentRedirect,
});
private static readonly ISet<HttpStatusCode> s_keepRequestBodyRedirectStatusCodes = new HashSet<HttpStatusCode>(
new[]
{
HttpStatusCode.TemporaryRedirect,
HttpStatusCode.PermanentRedirect,
});
/// <summary>
/// Initializes a new instance of the <see cref="RedirectingHandler"/> class.
/// </summary>
public RedirectingHandler()
{
AllowAutoRedirect = true;
MaxAutomaticRedirections = 50;
DisableInnerAutoRedirect = true;
DownloadContentOnRedirect = true;
KeepResponseHistory = true;
}
/// <summary>
/// Gets or sets a value that indicates whether the handler should follow redirection responses.
/// </summary>
public bool AllowAutoRedirect { get; set; }
/// <summary>
/// Gets or sets the maximum number of redirects that the handler follows.
/// </summary>
public int MaxAutomaticRedirections { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the response body should be downloaded before each redirection.
/// </summary>
public bool DownloadContentOnRedirect { get; set; }
/// <summary>
/// Gets or sets a value indicating inner redirections on <see cref="HttpClientHandler"/> and <see cref="RedirectingHandler"/> should be disabled.
/// </summary>
public bool DisableInnerAutoRedirect { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the response history should be saved to the <see cref="HttpResponseMessage.RequestMessage"/> properties with the key of <see cref="HistoryPropertyKey"/>.
/// </summary>
public bool KeepResponseHistory { get; set; }
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if(DisableInnerAutoRedirect)
{
// find the inner-most handler
HttpMessageHandler innerHandler = InnerHandler;
while(innerHandler is DelegatingHandler)
{
if(innerHandler is RedirectingHandler redirectingHandler)
{
redirectingHandler.AllowAutoRedirect = false;
}
innerHandler = ((DelegatingHandler) innerHandler).InnerHandler;
}
if(innerHandler is HttpClientHandler httpClientHandler)
{
httpClientHandler.AllowAutoRedirect = false;
}
}
// buffer the request body, to allow re-use in redirects
HttpContent requestBody = null;
if(AllowAutoRedirect && request.Content != null)
{
var buffer = await request.Content.ReadAsByteArrayAsync();
requestBody = new ByteArrayContent(buffer);
foreach(var (key, value) in request.Content.Headers)
{
requestBody.Headers.Add(key, value);
}
}
// make a copy of the request headers
var requestHeaders = request
.Headers
.Select(p => new KeyValuePair<string, string[]>(p.Key, p.Value.ToArray()))
.ToArray();
// send the initial request
var response = await base.SendAsync(request, cancellationToken);
var responses = new List<HttpResponseMessage>();
var redirectCount = 0;
while(AllowAutoRedirect && redirectCount < MaxAutomaticRedirections
&& TryGetRedirectLocation(response, out var locationString))
{
if(DownloadContentOnRedirect && response.Content != null)
{
await response.Content.ReadAsByteArrayAsync();
}
Uri previousRequestUri = response.RequestMessage.RequestUri;
// Credit where credit is due: https://github.com/kennethreitz/requests/blob/master/requests/sessions.py
// allow redirection without a scheme
if(locationString.StartsWith("//"))
{
locationString = previousRequestUri.Scheme + ":" + locationString;
}
var nextRequestUri = new Uri(locationString, UriKind.RelativeOrAbsolute);
// allow relative redirects
if(!nextRequestUri.IsAbsoluteUri)
{
nextRequestUri = new Uri(previousRequestUri, nextRequestUri);
}
// override previous method
HttpMethod nextMethod = response.RequestMessage.Method;
if(response.StatusCode == HttpStatusCode.Moved && nextMethod == HttpMethod.Post
|| response.StatusCode == HttpStatusCode.Found && nextMethod != HttpMethod.Head
|| response.StatusCode == HttpStatusCode.SeeOther && nextMethod != HttpMethod.Head)
{
nextMethod = HttpMethod.Get;
requestBody = null;
}
if(!s_keepRequestBodyRedirectStatusCodes.Contains(response.StatusCode))
{
requestBody = null;
}
// build the next request
var nextRequest = new HttpRequestMessage(nextMethod, nextRequestUri)
{
Content = requestBody,
Version = request.Version
};
foreach(var header in requestHeaders)
{
nextRequest.Headers.Add(header.Key, header.Value);
}
foreach(var pair in request.Properties)
{
nextRequest.Properties.Add(pair.Key, pair.Value);
}
// keep a history all responses
if(KeepResponseHistory)
{
responses.Add(response);
}
// send the next request
response = await base.SendAsync(nextRequest, cancellationToken);
request = response.RequestMessage;
redirectCount++;
}
// save the history to the request message properties
if(KeepResponseHistory && response.RequestMessage != null)
{
responses.Add(response);
response.RequestMessage.Properties.Add(HistoryPropertyKey, responses);
}
return response;
}
private static bool TryGetRedirectLocation(HttpResponseMessage response, out string location)
{
if(s_redirectStatusCodes.Contains(response.StatusCode)
&& response.Headers.TryGetValues("Location", out var locations)
&& (locations = locations.ToArray()).Count() == 1
&& !string.IsNullOrWhiteSpace(locations.First()))
{
location = locations.First().Trim();
return true;
}
location = null;
return false;
}
}
}
| |
/**********************************************************************
* Copyright (c) 2010, j. montgomery *
* 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 j. montgomery's employer nor the names of *
* its contributors may be used to endorse or promote products *
* derived from this software without specific prior written *
* permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS*
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,*
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) *
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,*
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED*
* OF THE POSSIBILITY OF SUCH DAMAGE. *
**********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Diagnostics;
namespace DnDns.Records
{
/// <summary>
/// Handles a basic Dns record
///
/// From RFC 1035:
///
/// 3.2.1. Format
///
/// All RRs have the same top level format shown below:
///
/// 1 1 1 1 1 1
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
/// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// | |
/// / /
/// / NAME /
/// | |
/// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// | TYPE |
/// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// | CLASS |
/// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// | TTL |
/// | |
/// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// | RDLENGTH |
/// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
/// / RDATA /
/// / /
/// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///
/// where:
///
/// NAME an owner name, i.e., the name of the node to which this
/// resource record pertains.
///
/// TYPE two octets containing one of the RR TYPE codes.
///
/// CLASS two octets containing one of the RR CLASS codes.
///
/// TTL a 32 bit signed integer that specifies the time interval
/// that the resource record may be cached before the source
/// of the information should again be consulted. Zero
/// values are interpreted to mean that the RR can only be
/// used for the transaction in progress, and should not be
/// cached. For example, SOA records are always distributed
/// with a zero TTL to prohibit caching. Zero values can
/// also be used for extremely volatile data.
///
/// RDLENGTH an unsigned 16 bit integer that specifies the length in
/// octets of the RDATA field.
///
/// RDATA a variable length string of octets that describes the
/// resource. The format of this information varies
/// according to the TYPE and CLASS of the resource record.
/// </summary>
public abstract class DnsRecordBase : IDnsRecord
{
#region Fields
// NAME an owner name, i.e., the name of the node to which this
// resource record pertains.
//private string _name;
// TYPE two octets containing one of the RR TYPE codes.
//protected NsType _nsType;
// CLASS - two octets containing one of the RR CLASS codes.
//private NsClass _nsClass;
// TTL - a 32 bit signed integer that specifies the time interval
// that the resource record may be cached before the source
// of the information should again be consulted. Zero
// values are interpreted to mean that the RR can only be
// used for the transaction in progress, and should not be
// cached. For example, SOA records are always distributed
// with a zero TTL to prohibit caching. Zero values can
/// also be used for extremely volatile data.
//private int _timeToLive;
// RDLENGTH - an unsigned 16 bit integer that specifies the length in
// octets of the RDATA field.
//protected short _dataLength;
protected RecordHeader _dnsHeader;
protected string _answer;
protected string _errorMsg;
#endregion
#region Properties
/// <summary>
/// NAME - an owner name, i.e., the name of the node to which this
/// resource record pertains.
/// </summary>
//public string Name
//{
// get { return _name; }
//}
public RecordHeader DnsHeader
{
get { return _dnsHeader; }
protected set { _dnsHeader = value; }
}
public string Answer
{
get { return _answer; }
}
/// <summary>
/// TYPE two octets containing one of the RR TYPE codes.
/// </summary>
//public NsType NsType
//{
// get { return _nsType; }
//}
/// <summary>
/// CLASS - two octets containing one of the RR CLASS codes.
/// </summary>
//public NsClass NsClass
//{
// get { return _nsClass; }
//}
/// <summary>
/// TTL - a 32 bit signed integer that specifies the time interval
/// that the resource record may be cached before the source
/// of the information should again be consulted. Zero
/// values are interpreted to mean that the RR can only be
/// used for the transaction in progress, and should not be
/// cached. For example, SOA records are always distributed
/// with a zero TTL to prohibit caching. Zero values can
/// also be used for extremely volatile data.
/// </summary>
//public int TimeToLive
//{
// get { return _timeToLive; }
//}
/// <summary>
/// RDLENGTH - an unsigned 16 bit integer that specifies the length in
/// octets of the RDATA field.
/// </summary>
//public short DataLength
//{
// get { return _dataLength; }
//}
public string ErrorMsg
{
get { return _errorMsg; }
}
#endregion
internal DnsRecordBase()
{
}
public virtual void ParseRecord(ref MemoryStream ms)
{
// Default implementation - the most common.
_answer = DnsRecordBase.ParseName(ref ms);
}
internal DnsRecordBase(RecordHeader dnsHeader)
{
_dnsHeader = dnsHeader;
}
// RFC
// 4.1.4. Message compression
//
// In order to reduce the size of messages, the domain system utilizes a
// compression scheme which eliminates the repetition of domain names in a
// message. In this scheme, an entire domain name or a list of labels at
// the end of a domain name is replaced with a pointer to a prior occurance
// of the same name.
//
// The pointer takes the form of a two octet sequence:
//
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | 1 1| OFFSET |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
//
// The first two bits are ones. This allows a pointer to be distinguished
// from a label, since the label must begin with two zero bits because
// labels are restricted to 63 octets or less. (The 10 and 01 combinations
// are reserved for future use.) The OFFSET field specifies an offset from
// the start of the message (i.e., the first octet of the ID field in the
// domain header). A zero offset specifies the first byte of the ID field,
// etc.
//
// The compression scheme allows a domain name in a message to be
// represented as either:
//
// - a sequence of labels ending in a zero octet
// - a pointer
// - a sequence of labels ending with a pointer
//
internal static string ParseName(ref MemoryStream ms)
{
Trace.WriteLine("Reading Name...");
StringBuilder sb = new StringBuilder();
uint next = (uint)ms.ReadByte();
Trace.WriteLine("Next is 0x" + next.ToString("x2"));
int bPointer;
while ((next != 0x00))
{
// Isolate 2 most significat bits -> e.g. 11xx xxxx
// if it's 0xc0 (11000000b} then pointer
switch (0xc0 & next)
{
// 0xc0 -> Name is a pointer.
case 0xc0:
{
// Isolate Offset
int offsetMASK = ~0xc0;
// Example on how to calculate the offset
// e.g.
//
// So if given the following 2 bytes - 0xc1 0x1c (11000001 00011100)
//
// The pointer takes the form of a two octet sequence:
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | 1 1| OFFSET |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | 1 1| 0 0 0 0 0 1 0 0 0 1 1 1 0 0|
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
//
// A pointer is indicated by the a 1 in the two most significant bits
// The Offset is the remaining bits.
//
// The Pointer = 0xc0 (11000000 00000000)
// The offset = 0x11c (00000001 00011100)
// Move offset into the proper position
int offset = (int)(offsetMASK & next) << 8;
// extract the pointer to the data in the stream
bPointer = ms.ReadByte() + offset;
// store the position so we can resume later
long oldPtr = ms.Position;
// Move to the specified position in the stream and
// parse the name (recursive call)
ms.Position = bPointer;
sb.Append(DnsRecordBase.ParseName(ref ms));
Trace.WriteLine(sb.ToString());
// Move back to original position, and continue
ms.Position = oldPtr;
next = 0x00;
break;
}
case 0x00:
{
Debug.Assert(next < 0xc0, "Offset cannot be greater then 0xc0.");
byte[] buffer = new byte[next];
ms.Read(buffer, 0, (int)next);
sb.Append(Encoding.ASCII.GetString(buffer));
next = (uint)ms.ReadByte();
if (next != 0x00) {
sb.Append (".");
}
Trace.WriteLine("0x" + next.ToString("x2"));
break;
}
default:
throw new InvalidOperationException("There was a problem decompressing the DNS Message.");
}
}
return sb.ToString();
}
internal string ParseText(ref MemoryStream ms)
{
StringBuilder sb = new StringBuilder();
int len = ms.ReadByte();
byte[] buffer = new byte[len];
ms.Read(buffer, 0, len);
sb.Append(Encoding.ASCII.GetString(buffer));
return sb.ToString();
}
public override string ToString()
{
return _answer;
}
#region IDnsRecord Members
public virtual byte[] GetMessageBytes()
{
return new byte[]{};
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class FallbackGroupTargetTests : NLogTestBase
{
[Fact]
public void FirstTargetWorks_Write_AllEventsAreWrittenToFirstTarget()
{
var myTarget1 = new MyTarget();
var myTarget2 = new MyTarget();
var myTarget3 = new MyTarget();
var wrapper = CreateAndInitializeFallbackGroupTarget(false, myTarget1, myTarget2, myTarget3);
WriteAndAssertNoExceptions(wrapper);
Assert.Equal(10, myTarget1.WriteCount);
Assert.Equal(0, myTarget2.WriteCount);
Assert.Equal(0, myTarget3.WriteCount);
AssertNoFlushException(wrapper);
}
[Fact]
public void FirstTargetFails_Write_SecondTargetWritesAllEvents()
{
var myTarget1 = new MyTarget { FailCounter = 1 };
var myTarget2 = new MyTarget();
var myTarget3 = new MyTarget();
var wrapper = CreateAndInitializeFallbackGroupTarget(false, myTarget1, myTarget2, myTarget3);
WriteAndAssertNoExceptions(wrapper);
Assert.Equal(1, myTarget1.WriteCount);
Assert.Equal(10, myTarget2.WriteCount);
Assert.Equal(0, myTarget3.WriteCount);
AssertNoFlushException(wrapper);
}
[Fact]
public void FirstTwoTargetsFails_Write_ThirdTargetWritesAllEvents()
{
var myTarget1 = new MyTarget { FailCounter = 1 };
var myTarget2 = new MyTarget { FailCounter = 1 };
var myTarget3 = new MyTarget();
var wrapper = CreateAndInitializeFallbackGroupTarget(false, myTarget1, myTarget2, myTarget3);
WriteAndAssertNoExceptions(wrapper);
Assert.Equal(1, myTarget1.WriteCount);
Assert.Equal(1, myTarget2.WriteCount);
Assert.Equal(10, myTarget3.WriteCount);
AssertNoFlushException(wrapper);
}
[Fact]
public void ReturnToFirstOnSuccessAndSecondTargetSucceeds_Write_ReturnToFirstTargetOnSuccess()
{
var myTarget1 = new MyTarget { FailCounter = 1 };
var myTarget2 = new MyTarget();
var myTarget3 = new MyTarget();
var wrapper = CreateAndInitializeFallbackGroupTarget(true, myTarget1, myTarget2, myTarget3);
WriteAndAssertNoExceptions(wrapper);
Assert.Equal(10, myTarget1.WriteCount);
Assert.Equal(1, myTarget2.WriteCount);
Assert.Equal(0, myTarget3.WriteCount);
AssertNoFlushException(wrapper);
}
[Fact]
public void FallbackGroupTargetSyncTest5()
{
// fail once
var myTarget1 = new MyTarget { FailCounter = 3 };
var myTarget2 = new MyTarget { FailCounter = 3 };
var myTarget3 = new MyTarget { FailCounter = 3 };
var wrapper = CreateAndInitializeFallbackGroupTarget(true, myTarget1, myTarget2, myTarget3);
var exceptions = new List<Exception>();
// no exceptions
for (var i = 0; i < 10; ++i)
{
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
}
Assert.Equal(10, exceptions.Count);
for (var i = 0; i < 10; ++i)
{
if (i < 3)
{
Assert.NotNull(exceptions[i]);
}
else
{
Assert.Null(exceptions[i]);
}
}
Assert.Equal(10, myTarget1.WriteCount);
Assert.Equal(3, myTarget2.WriteCount);
Assert.Equal(3, myTarget3.WriteCount);
AssertNoFlushException(wrapper);
}
[Fact]
public void FallbackGroupTargetSyncTest6()
{
// fail once
var myTarget1 = new MyTarget { FailCounter = 10 };
var myTarget2 = new MyTarget { FailCounter = 3 };
var myTarget3 = new MyTarget { FailCounter = 3 };
var wrapper = CreateAndInitializeFallbackGroupTarget(true, myTarget1, myTarget2, myTarget3);
var exceptions = new List<Exception>();
// no exceptions
for (var i = 0; i < 10; ++i)
{
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
}
Assert.Equal(10, exceptions.Count);
for (var i = 0; i < 10; ++i)
{
if (i < 3)
{
// for the first 3 rounds, no target is available
Assert.NotNull(exceptions[i]);
Assert.IsType<InvalidOperationException>(exceptions[i]);
Assert.Equal("Some failure.", exceptions[i].Message);
}
else
{
Assert.Null(exceptions[i]);
}
}
Assert.Equal(10, myTarget1.WriteCount);
Assert.Equal(10, myTarget2.WriteCount);
Assert.Equal(3, myTarget3.WriteCount);
AssertNoFlushException(wrapper);
Assert.Equal(1, myTarget1.FlushCount);
Assert.Equal(1, myTarget2.FlushCount);
Assert.Equal(1, myTarget3.FlushCount);
}
[Fact]
public void FallbackGroupWithBufferingTargets_ReturnToFirstOnSuccess()
{
FallbackGroupWithBufferingTargets(true);
}
[Fact]
public void FallbackGroupWithBufferingTargets_DoNotReturnToFirstOnSuccess()
{
FallbackGroupWithBufferingTargets(false);
}
private void FallbackGroupWithBufferingTargets(bool returnToFirstOnSuccess)
{
const int totalEvents = 1000;
var myTarget1 = new MyTarget { FailCounter = int.MaxValue }; // Always failing.
var myTarget2 = new MyTarget();
var myTarget3 = new MyTarget();
var buffer1 = new BufferingTargetWrapper() { WrappedTarget = myTarget1, FlushTimeout = 100, SlidingTimeout = false };
var buffer2 = new BufferingTargetWrapper() { WrappedTarget = myTarget2, FlushTimeout = 100, SlidingTimeout = false };
var buffer3 = new BufferingTargetWrapper() { WrappedTarget = myTarget3, FlushTimeout = 100, SlidingTimeout = false };
var wrapper = CreateAndInitializeFallbackGroupTarget(returnToFirstOnSuccess, buffer1, buffer2, buffer3);
var allEventsDone = new ManualResetEvent(false);
var exceptions = new List<Exception>();
for (var i = 0; i < totalEvents; ++i)
{
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (exceptions.Count >= totalEvents)
allEventsDone.Set();
}
}));
}
allEventsDone.WaitOne(); // Wait for all events to be delivered.
Assert.True(totalEvents >= myTarget1.WriteCount, // Check events weren't delivered twice to myTarget1,
"Target 1 received " + myTarget1.WriteCount + " writes although only " + totalEvents + " events were written");
Assert.Equal(totalEvents, myTarget2.WriteCount); // were all delivered exactly once to myTarget2,
Assert.Equal(0, myTarget3.WriteCount); // with nothing delivered to myTarget3.
Assert.Equal(totalEvents, exceptions.Count);
foreach (var e in exceptions)
{
Assert.Null(e); // All events should have succeeded on myTarget2.
}
}
[Fact]
public void FallbackGroupTargetAsyncTest()
{
var myTarget1 = new MyTarget { FailCounter = int.MaxValue }; // Always failing.
var myTarget1Async = new AsyncTargetWrapper(myTarget1) { TimeToSleepBetweenBatches = 0 }; // Always failing.
var myTarget2 = new MyTarget() { Layout = "${ndlc}" };
var wrapper = CreateAndInitializeFallbackGroupTarget(true, myTarget1Async, myTarget2);
var exceptions = new List<Exception>();
// no exceptions
for (var i = 0; i < 10; ++i)
{
using (NestedDiagnosticsLogicalContext.Push("Hello World"))
{
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
}
}
ManualResetEvent resetEvent = new ManualResetEvent(false);
myTarget1Async.Flush((ex) => { Assert.Null(ex); resetEvent.Set(); });
resetEvent.WaitOne(1000);
Assert.Equal(10, exceptions.Count);
for (var i = 0; i < 10; ++i)
{
Assert.Null(exceptions[i]);
}
Assert.Equal(10, myTarget2.WriteCount);
AssertNoFlushException(wrapper);
}
private static FallbackGroupTarget CreateAndInitializeFallbackGroupTarget(bool returnToFirstOnSuccess, params Target[] targets)
{
var wrapper = new FallbackGroupTarget(targets)
{
ReturnToFirstOnSuccess = returnToFirstOnSuccess,
};
foreach (var target in targets)
{
WrapperTargetBase wrapperTarget = target as WrapperTargetBase;
if (wrapperTarget != null)
wrapperTarget.WrappedTarget.Initialize(null);
target.Initialize(null);
}
wrapper.Initialize(null);
return wrapper;
}
private static void WriteAndAssertNoExceptions(FallbackGroupTarget wrapper)
{
var exceptions = new List<Exception>();
for (var i = 0; i < 10; ++i)
{
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
}
Assert.Equal(10, exceptions.Count);
foreach (var e in exceptions)
{
Assert.Null(e);
}
}
private static void AssertNoFlushException(FallbackGroupTarget wrapper)
{
Exception flushException = null;
var flushHit = new ManualResetEvent(false);
wrapper.Flush(ex =>
{
flushException = ex;
flushHit.Set();
});
flushHit.WaitOne();
if (flushException != null)
Assert.True(false, flushException.ToString());
}
private class MyTarget : TargetWithLayout
{
public int FlushCount { get; set; }
public int WriteCount { get; set; }
public int FailCounter { get; set; }
protected override void Write(LogEventInfo logEvent)
{
if (Layout != null && string.IsNullOrEmpty(Layout.Render(logEvent)))
{
throw new InvalidOperationException("Empty LogEvent.");
}
Assert.True(FlushCount <= WriteCount);
WriteCount++;
if (FailCounter > 0)
{
FailCounter--;
throw new InvalidOperationException("Some failure.");
}
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
FlushCount++;
asyncContinuation(null);
}
}
}
}
| |
// 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 ILCompiler.DependencyAnalysisFramework;
using Internal.IL;
using Internal.Runtime;
using Internal.TypeSystem;
using System;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
/// <summary>
/// Given a type, EETypeNode writes an EEType data structure in the format expected by the runtime.
///
/// Format of an EEType:
///
/// Field Size | Contents
/// ----------------+-----------------------------------
/// UInt16 | Component Size. For arrays this is the element type size, for strings it is 2 (.NET uses
/// | UTF16 character encoding), and 0 for all other types.
/// |
/// UInt16 | EETypeKind (Normal, Array, Pointer type). Flags for: IsValueType, IsCrossModule, HasPointers,
/// | HasOptionalFields, IsInterface, IsGeneric. Top 5 bits are used for enum CorElementType to
/// | record whether it's back by an Int32, Int16 etc
/// |
/// Uint32 | Base size.
/// |
/// [Pointer Size] | Related type. Base type for regular types. Element type for arrays / pointer types.
/// |
/// UInt16 | Number of VTable slots (X)
/// |
/// UInt16 | Number of interfaces implemented by type (Y)
/// |
/// UInt32 | Hash code
/// |
/// [Pointer Size] | Pointer to containing Module indirection cell
/// |
/// X * [Ptr Size] | VTable entries (optional)
/// |
/// Y * [Ptr Size] | Pointers to interface map data structures (optional)
/// |
/// [Pointer Size] | Pointer to finalizer method (optional)
/// |
/// [Pointer Size] | Pointer to optional fields (optional)
/// |
/// [Pointer Size] | Pointer to the generic type argument of a Nullable<T> (optional)
/// |
/// [Pointer Size] | Pointer to the generic type definition EEType (optional)
/// |
/// [Pointer Size] | Pointer to the generic argument and variance info (optional)
/// </summary>
internal sealed partial class EETypeNode : ObjectNode, ISymbolNode, IEETypeNode
{
private TypeDesc _type;
private bool _constructed;
EETypeOptionalFieldsBuilder _optionalFieldsBuilder = new EETypeOptionalFieldsBuilder();
public EETypeNode(TypeDesc type, bool constructed)
{
_type = type;
_constructed = constructed;
}
public override string GetName()
{
if (_constructed)
{
return ((ISymbolNode)this).MangledName + " constructed";
}
else
{
return ((ISymbolNode)this).MangledName;
}
}
public override bool ShouldSkipEmittingObjectNode(NodeFactory factory)
{
if (!_constructed)
{
// If there is a constructed version of this node in the graph, emit that instead
if (((DependencyNode)factory.ConstructedTypeSymbol(_type)).Marked)
{
return true;
}
}
return false;
}
public TypeDesc Type
{
get { return _type; }
}
public bool Constructed
{
get { return _constructed; }
}
public override ObjectNodeSection Section
{
get
{
if (_type.Context.Target.IsWindows)
return ObjectNodeSection.ReadOnlyDataSection;
else
return ObjectNodeSection.DataSection;
}
}
public override bool ShouldShareNodeAcrossModules(NodeFactory factory)
{
return factory.CompilationModuleGroup.ShouldShareAcrossModules(_type);
}
public override bool StaticDependenciesAreComputed
{
get
{
return true;
}
}
public void SetDispatchMapIndex(int index)
{
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.DispatchMap, checked((uint)index));
}
int ISymbolNode.Offset
{
get
{
return GCDescSize;
}
}
string ISymbolNode.MangledName
{
get
{
return "__EEType_" + NodeFactory.NameMangler.GetMangledTypeName(_type);
}
}
public override ObjectData GetData(NodeFactory factory, bool relocsOnly)
{
ObjectDataBuilder objData = new ObjectDataBuilder(factory);
objData.Alignment = 16;
objData.DefinedSymbols.Add(this);
if (!_type.IsGenericDefinition)
ComputeOptionalEETypeFields(factory);
OutputGCDesc(ref objData);
OutputComponentSize(ref objData);
OutputFlags(factory, ref objData);
OutputBaseSize(ref objData);
OutputRelatedType(factory, ref objData);
// Avoid consulting VTable slots until they're guaranteed complete during final data emission
if (!relocsOnly)
{
OutputVirtualSlotAndInterfaceCount(factory, ref objData);
}
objData.EmitInt(_type.GetHashCode());
objData.EmitPointerReloc(factory.ModuleManagerIndirection);
if (_constructed)
{
Debug.Assert(!_type.IsGenericDefinition);
// Avoid consulting VTable slots until they're guaranteed complete during final data emission
if (!relocsOnly)
{
OutputVirtualSlots(factory, ref objData, _type, _type);
}
OutputInterfaceMap(factory, ref objData);
}
if (!_type.IsGenericDefinition)
{
OutputFinalizerMethod(factory, ref objData);
OutputOptionalFields(factory, ref objData);
OutputNullableTypeParameter(factory, ref objData);
OutputGenericInstantiationDetails(factory, ref objData);
}
return objData.ToObjectData();
}
protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory)
{
if (_constructed)
{
DependencyList dependencyList = new DependencyList();
if (_type.RuntimeInterfaces.Length > 0)
{
dependencyList.Add(factory.InterfaceDispatchMap(_type), "Interface dispatch map");
// If any of the implemented interfaces have variance, calls against compatible interface methods
// could result in interface methods of this type being used (e.g. IEnumberable<object>.GetEnumerator()
// can dispatch to an implementation of IEnumerable<string>.GetEnumerator()).
// For now, we will not try to optimize this and we will pretend all interface methods are necessary.
MetadataType mdType = _type.GetClosestMetadataType();
foreach (var implementedInterface in mdType.RuntimeInterfaces)
{
if (implementedInterface.HasVariance)
{
foreach (var interfaceMethod in implementedInterface.GetAllVirtualMethods())
{
MethodDesc implMethod = mdType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod);
if (implMethod != null)
{
dependencyList.Add(factory.VirtualMethodUse(interfaceMethod), "Variant interface method");
dependencyList.Add(factory.VirtualMethodUse(implMethod), "Variant interface method");
}
}
}
}
}
if (_type.IsArray)
{
// Array EEType depends on System.Array's virtuals. Array EETypes don't point to
// their base type (i.e. there's no reloc based dependency making this "just work").
dependencyList.Add(factory.ConstructedTypeSymbol(_type.BaseType), "Array base type");
}
dependencyList.Add(factory.VTable(_type), "VTable");
return dependencyList;
}
return null;
}
public override bool HasConditionalStaticDependencies
{
get
{
// non constructed types don't have vtables
if (!_constructed)
return false;
// Since the vtable is dependency driven, generate conditional static dependencies for
// all possible vtable entries
if (_type.GetClosestMetadataType().GetAllVirtualMethods().GetEnumerator().MoveNext())
{
return true;
}
// If the type implements at least one interface, calls against that interface could result in this type's
// implementation being used.
if (_type.RuntimeInterfaces.Length > 0)
return true;
return false;
}
}
public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory factory)
{
MetadataType mdType = _type.GetClosestMetadataType();
foreach (MethodDesc decl in mdType.EnumAllVirtualSlots())
{
MethodDesc impl = mdType.FindVirtualFunctionTargetMethodOnObjectType(decl);
if (impl.OwningType == mdType && !impl.IsAbstract)
{
yield return new DependencyNodeCore<NodeFactory>.CombinedDependencyListEntry(factory.MethodEntrypoint(impl, _type.IsValueType), factory.VirtualMethodUse(decl), "Virtual method");
}
}
Debug.Assert(
_type == mdType ||
((System.Collections.IStructuralEquatable)mdType.RuntimeInterfaces).Equals(_type.RuntimeInterfaces,
EqualityComparer<DefType>.Default));
// Add conditional dependencies for interface methods the type implements. For example, if the type T implements
// interface IFoo which has a method M1, add a dependency on T.M1 dependent on IFoo.M1 being called, since it's
// possible for any IFoo object to actually be an instance of T.
foreach (DefType interfaceType in mdType.RuntimeInterfaces)
{
Debug.Assert(interfaceType.IsInterface);
foreach (MethodDesc interfaceMethod in interfaceType.GetAllVirtualMethods())
{
MethodDesc implMethod = mdType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod);
if (implMethod != null)
{
yield return new CombinedDependencyListEntry(factory.VirtualMethodUse(implMethod), factory.ReadyToRunHelper(ReadyToRunHelperId.InterfaceDispatch, interfaceMethod), "Interface method");
yield return new CombinedDependencyListEntry(factory.VirtualMethodUse(implMethod), factory.ReadyToRunHelper(ReadyToRunHelperId.ResolveVirtualFunction, interfaceMethod), "Interface method address");
}
}
}
}
/// <summary>
/// Returns the offset within an EEType of the beginning of VTable entries
/// </summary>
/// <param name="pointerSize">The size of a pointer in bytes in the target architecture</param>
public static int GetVTableOffset(int pointerSize)
{
return 16 + 2 * pointerSize;
}
private int GCDescSize
{
get
{
if (!_constructed || _type.IsGenericDefinition)
return 0;
return GCDescEncoder.GetGCDescSize(_type);
}
}
private void OutputGCDesc(ref ObjectDataBuilder builder)
{
if (!_constructed || _type.IsGenericDefinition)
{
Debug.Assert(GCDescSize == 0);
return;
}
GCDescEncoder.EncodeGCDesc(ref builder, _type);
}
private void OutputComponentSize(ref ObjectDataBuilder objData)
{
if (_type.IsArray)
{
int elementSize = ((ArrayType)_type).ElementType.GetElementSize();
if (elementSize >= 64 * 1024)
{
// TODO: Array of type 'X' cannot be created because base value type is too large.
throw new TypeLoadException();
}
objData.EmitShort((short)elementSize);
}
else if (_type.IsString)
{
objData.EmitShort(2);
}
else
{
objData.EmitShort(0);
}
}
private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData)
{
UInt16 flags = EETypeBuilderHelpers.ComputeFlags(_type);
if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType)
{
// Generic array enumerators use special variance rules recognized by the runtime
flags |= (UInt16)EETypeFlags.GenericVarianceFlag;
}
// Todo: RelatedTypeViaIATFlag when we support cross-module EETypes
// Todo: Generic Type Definition EETypes
if (_optionalFieldsBuilder.IsAtLeastOneFieldUsed())
{
flags |= (UInt16)EETypeFlags.OptionalFieldsFlag;
}
objData.EmitShort((short)flags);
}
private void OutputBaseSize(ref ObjectDataBuilder objData)
{
if (_type.IsGenericDefinition)
{
objData.EmitInt(0);
return;
}
int pointerSize = _type.Context.Target.PointerSize;
int minimumObjectSize = pointerSize * 3;
int objectSize;
if (_type.IsDefType)
{
objectSize = pointerSize +
((DefType)_type).InstanceByteCount; // +pointerSize for SyncBlock
if (_type.IsValueType)
objectSize += pointerSize; // + EETypePtr field inherited from System.Object
}
else if (_type.IsArray)
{
objectSize = 3 * pointerSize; // SyncBlock + EETypePtr + Length
if (!_type.IsSzArray)
objectSize +=
2 * _type.Context.GetWellKnownType(WellKnownType.Int32).GetElementSize() * ((ArrayType)_type).Rank;
}
else if (_type.IsPointer)
{
// Object size 0 is a sentinel value in the runtime for parameterized types that means "Pointer Type"
objData.EmitInt(0);
return;
}
else
throw new NotImplementedException();
objectSize = AlignmentHelper.AlignUp(objectSize, pointerSize);
objectSize = Math.Max(minimumObjectSize, objectSize);
if (_type.IsString)
{
// If this is a string, throw away objectSize we computed so far. Strings are special.
// SyncBlock + EETypePtr + length + firstChar
objectSize = 2 * pointerSize +
_type.Context.GetWellKnownType(WellKnownType.Int32).GetElementSize() +
_type.Context.GetWellKnownType(WellKnownType.Char).GetElementSize();
}
objData.EmitInt(objectSize);
}
private void OutputRelatedType(NodeFactory factory, ref ObjectDataBuilder objData)
{
ISymbolNode relatedTypeNode = null;
if (_type.IsArray || _type.IsPointer)
{
var parameterType = ((ParameterizedType)_type).ParameterType;
relatedTypeNode = factory.NecessaryTypeSymbol(parameterType);
}
else if (_type.IsGenericDefinition)
{
// Related type is not set for generic definitions
}
else
{
TypeDesc baseType = _type.BaseType;
if (baseType != null)
{
if (_constructed)
{
relatedTypeNode = factory.ConstructedTypeSymbol(baseType);
}
else
{
relatedTypeNode = factory.NecessaryTypeSymbol(baseType);
}
}
}
if (relatedTypeNode != null)
{
objData.EmitPointerReloc(relatedTypeNode);
}
else
{
objData.EmitZeroPointer();
}
}
private void OutputVirtualSlotAndInterfaceCount(NodeFactory factory, ref ObjectDataBuilder objData)
{
if (!_constructed)
{
objData.EmitShort(0);
objData.EmitShort(0);
return;
}
Debug.Assert(!_type.IsGenericDefinition);
int virtualSlotCount = 0;
TypeDesc currentTypeSlice = _type.GetClosestMetadataType();
while (currentTypeSlice != null)
{
virtualSlotCount += factory.VTable(currentTypeSlice).Slots.Count;
currentTypeSlice = currentTypeSlice.BaseType;
}
objData.EmitShort(checked((short)virtualSlotCount));
objData.EmitShort(checked((short)_type.RuntimeInterfaces.Length));
}
private void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType)
{
declType = declType.GetClosestMetadataType();
var baseType = declType.BaseType;
if (baseType != null)
OutputVirtualSlots(factory, ref objData, implType, baseType);
IReadOnlyList<MethodDesc> virtualSlots = factory.VTable(declType).Slots;
for (int i = 0; i < virtualSlots.Count; i++)
{
MethodDesc declMethod = virtualSlots[i];
MethodDesc implMethod = implType.GetClosestMetadataType().FindVirtualFunctionTargetMethodOnObjectType(declMethod);
if (declMethod.HasInstantiation)
{
// Generic virtual methods will "compile", but will fail to link. Check for it here.
throw new NotImplementedException("VTable for " + _type + " has generic virtual methods.");
}
if (!implMethod.IsAbstract)
objData.EmitPointerReloc(factory.MethodEntrypoint(implMethod, implMethod.OwningType.IsValueType));
else
objData.EmitZeroPointer();
}
}
private void OutputInterfaceMap(NodeFactory factory, ref ObjectDataBuilder objData)
{
foreach (var itf in _type.RuntimeInterfaces)
{
objData.EmitPointerReloc(factory.NecessaryTypeSymbol(itf));
}
}
private void OutputFinalizerMethod(NodeFactory factory, ref ObjectDataBuilder objData)
{
MethodDesc finalizerMethod = _type.GetFinalizer();
if (finalizerMethod != null)
{
objData.EmitPointerReloc(factory.MethodEntrypoint(finalizerMethod));
}
}
private void OutputOptionalFields(NodeFactory factory, ref ObjectDataBuilder objData)
{
if(_optionalFieldsBuilder.IsAtLeastOneFieldUsed())
{
objData.EmitPointerReloc(factory.EETypeOptionalFields(_optionalFieldsBuilder));
}
}
private void OutputNullableTypeParameter(NodeFactory factory, ref ObjectDataBuilder objData)
{
if (_type.IsNullable)
{
objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type.Instantiation[0]));
}
}
private void OutputGenericInstantiationDetails(NodeFactory factory, ref ObjectDataBuilder objData)
{
if (_type.HasInstantiation && !_type.IsTypeDefinition)
{
objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type.GetTypeDefinition()));
GenericCompositionDetails details;
if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType)
{
// Generic array enumerators use special variance rules recognized by the runtime
details = new GenericCompositionDetails(_type.Instantiation, new[] { (GenericVariance)0x20 });
}
else
details = new GenericCompositionDetails(_type);
objData.EmitPointerReloc(factory.GenericComposition(details));
}
}
/// <summary>
/// Populate the OptionalFieldsRuntimeBuilder if any optional fields are required.
/// </summary>
private void ComputeOptionalEETypeFields(NodeFactory factory)
{
ComputeRareFlags(factory);
ComputeNullableValueOffset();
ComputeICastableVirtualMethodSlots(factory);
ComputeValueTypeFieldPadding();
}
void ComputeRareFlags(NodeFactory factory)
{
uint flags = 0;
if (_type.IsNullable)
{
flags |= (uint)EETypeRareFlags.IsNullableFlag;
}
if (factory.TypeInitializationManager.HasLazyStaticConstructor(_type))
{
flags |= (uint)EETypeRareFlags.HasCctorFlag;
}
if (EETypeBuilderHelpers.ComputeRequiresAlign8(_type))
{
flags |= (uint)EETypeRareFlags.RequiresAlign8Flag;
}
if (_type.IsDefType && ((DefType)_type).IsHfa)
{
flags |= (uint)EETypeRareFlags.IsHFAFlag;
}
if (flags != 0)
{
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.RareFlags, flags);
}
}
/// <summary>
/// To support boxing / unboxing, the offset of the value field of a Nullable type is recorded on the EEType.
/// This is variable according to the alignment requirements of the Nullable<T> type parameter.
/// </summary>
void ComputeNullableValueOffset()
{
if (!_type.IsNullable)
return;
var field = _type.GetKnownField("value");
// In the definition of Nullable<T>, the first field should be the boolean representing "hasValue"
Debug.Assert(field.Offset > 0);
// The contract with the runtime states the Nullable value offset is stored with the boolean "hasValue" size subtracted
// to get a small encoding size win.
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.NullableValueOffset, (uint)field.Offset - 1);
}
/// <summary>
/// ICastable is a special interface whose two methods are not invoked using regular interface dispatch.
/// Instead, their VTable slots are recorded on the EEType of an object implementing ICastable and are
/// called directly.
/// </summary>
void ComputeICastableVirtualMethodSlots(NodeFactory factory)
{
// TODO: This method is untested (we don't support interfaces yet)
if (_type.IsInterface)
return;
foreach (DefType itf in _type.RuntimeInterfaces)
{
if (itf == factory.ICastableInterface)
{
var isInstMethod = itf.GetKnownMethod("IsInstanceOfInterface", null);
var getImplTypeMethod = itf.GetKnownMethod("GetImplType", null);
int isInstMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, isInstMethod);
int getImplTypeMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, getImplTypeMethod);
if (isInstMethodSlot != -1 || getImplTypeMethodSlot != -1)
{
var rareFlags = _optionalFieldsBuilder.GetFieldValue(EETypeOptionalFieldsElement.RareFlags, 0);
rareFlags |= (uint)EETypeRareFlags.ICastableFlag;
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.RareFlags, rareFlags);
}
if (isInstMethodSlot != -1)
{
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.ICastableIsInstSlot, (uint)isInstMethodSlot);
}
if (getImplTypeMethodSlot != -1)
{
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.ICastableGetImplTypeSlot, (uint)getImplTypeMethodSlot);
}
}
}
}
void ComputeValueTypeFieldPadding()
{
if (!_type.IsValueType)
return;
DefType defType = _type as DefType;
Debug.Assert(defType != null);
uint valueTypeFieldPadding = checked((uint)(defType.InstanceByteCount - defType.InstanceByteCountUnaligned));
uint valueTypeFieldPaddingEncoded = EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue(valueTypeFieldPadding, (uint)defType.InstanceFieldAlignment);
if (valueTypeFieldPaddingEncoded != 0)
{
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.ValueTypeFieldPadding, valueTypeFieldPaddingEncoded);
}
}
public override bool HasDynamicDependencies
{
get
{
// This node's EETypeOptionalFields node may change if this EEType implements interfaces
// that are used since the dispatch map table index is computed once we know the interface
// layout later on in compilation.
return _type.RuntimeInterfaces.Length > 0 && _constructed;
}
}
public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<NodeFactory>> markedNodes, int firstNode, NodeFactory factory)
{
List<CombinedDependencyListEntry> dynamicNodes = new List<DependencyNodeCore<NodeFactory>.CombinedDependencyListEntry>();
dynamicNodes.Add(new CombinedDependencyListEntry(factory.EETypeOptionalFields(_optionalFieldsBuilder), null, "EEType optional fields"));
return dynamicNodes;
}
protected override void OnMarked(NodeFactory context)
{
Debug.Assert(_type.IsTypeDefinition || !_type.HasSameTypeDefinition(context.ArrayOfTClass), "Asking for Array<T> EEType");
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Product Groups.
/// </summary>
internal partial class ProductGroupsOperations : IServiceOperations<ApiManagementClient>, IProductGroupsOperations
{
/// <summary>
/// Initializes a new instance of the ProductGroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ProductGroupsOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Assigns group to product.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the Group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> AddAsync(string resourceGroupName, string serviceName, string pid, string gid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("gid", gid);
TracingAdapter.Enter(invocationId, this, "AddAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all Product Groups.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListAsync(string resourceGroupName, string serviceName, string pid, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
url = url + "/groups";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all Product Groups.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Removes group assignement from product.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the Group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> RemoveAsync(string resourceGroupName, string serviceName, string pid, string gid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("gid", gid);
TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using ASC.Collections;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.Core.Tenants;
using ASC.CRM.Core.Entities;
using ASC.ElasticSearch;
using ASC.Files.Core;
using ASC.Web.CRM;
using ASC.Web.CRM.Classes;
using ASC.Web.CRM.Core.Search;
using ASC.Web.Files.Api;
using ASC.Web.Studio.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using File = ASC.Files.Core.File;
using OrderBy = ASC.CRM.Core.Entities.OrderBy;
namespace ASC.CRM.Core.Dao
{
public class CachedRelationshipEventDao : RelationshipEventDao
{
#region Import
private readonly HttpRequestDictionary<RelationshipEvent> _contactCache = new HttpRequestDictionary<RelationshipEvent>("crm_relationshipEvent");
#endregion
#region Constructor
public CachedRelationshipEventDao(int tenantID)
: base(tenantID)
{
}
#endregion
#region Methods
public override RelationshipEvent GetByID(int eventID)
{
return _contactCache.Get(eventID.ToString(), () => GetByIDBase(eventID));
}
private RelationshipEvent GetByIDBase(int eventID)
{
return base.GetByID(eventID);
}
private void ResetCache(int dealID)
{
_contactCache.Reset(dealID.ToString());
}
#endregion
}
public class RelationshipEventDao : AbstractDao
{
#region Members
#endregion
#region Constructor
public RelationshipEventDao(int tenantID)
: base(tenantID)
{
}
#endregion
#region Methods
public RelationshipEvent AttachFiles(int contactID, EntityType entityType, int entityID, int[] fileIDs)
{
if (entityID > 0 && !_supportedEntityType.Contains(entityType))
throw new ArgumentException();
var relationshipEvent = new RelationshipEvent
{
CategoryID = (int)HistoryCategorySystem.FilesUpload,
ContactID = contactID,
EntityType = entityType,
EntityID = entityID,
Content = HistoryCategorySystem.FilesUpload.ToLocalizedString()
};
relationshipEvent = CreateItem(relationshipEvent);
AttachFiles(relationshipEvent.ID, fileIDs);
return relationshipEvent;
}
public void AttachFiles(int eventID, int[] fileIDs)
{
if (fileIDs.Length == 0) return;
using (var dao = FilesIntegration.GetTagDao())
{
var tags = fileIDs.ToList().ConvertAll(fileID => new Tag("RelationshipEvent_" + eventID, TagType.System, Guid.Empty) { EntryType = FileEntryType.File, EntryId = fileID });
dao.SaveTags(tags);
}
if (fileIDs.Length > 0)
Db.ExecuteNonQuery(Update("crm_relationship_event").Set("have_files", true).Where("id", eventID));
}
public int GetFilesCount(int[] contactID, EntityType entityType, int entityID)
{
return GetFilesIDs(contactID, entityType, entityID).Count;
}
private List<object> GetFilesIDs(int[] contactID, EntityType entityType, int entityID)
{
if (entityID > 0 && entityType != EntityType.Opportunity && entityType != EntityType.Case)
throw new ArgumentException();
var sqlQuery = Query("crm_relationship_event").Select("id");
if (contactID != null && contactID.Length > 0)
sqlQuery.Where(Exp.In("contact_id", contactID));
if (entityID > 0)
sqlQuery.Where(Exp.Eq("entity_id", entityID) & Exp.Eq("entity_type", (int)entityType));
sqlQuery.Where(Exp.Eq("have_files", true));
var tagNames = Db.ExecuteList(sqlQuery).ConvertAll(row => String.Format("RelationshipEvent_{0}", row[0]));
using (var tagdao = FilesIntegration.GetTagDao())
{
return tagdao.GetTags(tagNames.ToArray(), TagType.System)
.Where(t => t.EntryType == FileEntryType.File)
.Select(t => t.EntryId)
.ToList();
}
}
public List<File> GetAllFiles(int[] contactID, EntityType entityType, int entityID)
{
using (var filedao = FilesIntegration.GetFileDao())
{
var ids = GetFilesIDs(contactID, entityType, entityID);
var files = 0 < ids.Count ? filedao.GetFiles(ids) : new List<File>();
files.ForEach(CRMSecurity.SetAccessTo);
return files.ToList();
}
}
public Dictionary<int, List<File>> GetFiles(int[] eventID)
{
if (eventID == null || eventID.Length == 0)
throw new ArgumentException("eventID");
using (var tagdao = FilesIntegration.GetTagDao())
using (var filedao = FilesIntegration.GetFileDao())
{
var findedTags = tagdao.GetTags(eventID.Select(item => String.Concat("RelationshipEvent_", item)).ToArray(),
TagType.System).Where(t => t.EntryType == FileEntryType.File);
var filesID = findedTags.Select(t => t.EntryId).ToList();
var files = 0 < filesID.Count ? filedao.GetFiles(filesID) : new List<File>();
var filesTemp = new Dictionary<object, File>();
files.ForEach(item =>
{
if (!filesTemp.ContainsKey(item.ID))
filesTemp.Add(item.ID, item);
});
return findedTags.Where(x => filesTemp.ContainsKey(x.EntryId)).GroupBy(x => x.TagName).ToDictionary(x => Convert.ToInt32(x.Key.Split(new[] { '_' })[1]),
x => x.Select(item => filesTemp[item.EntryId]).ToList());
}
}
public List<File> GetFiles(int eventID)
{
if (eventID == 0)
throw new ArgumentException("eventID");
using (var tagdao = FilesIntegration.GetTagDao())
using (var filedao = FilesIntegration.GetFileDao())
{
var ids = tagdao.GetTags(String.Concat("RelationshipEvent_", eventID), TagType.System)
.Where(t => t.EntryType == FileEntryType.File)
.Select(t => t.EntryId)
.ToList();
var files = 0 < ids.Count ? filedao.GetFiles(ids) : new List<File>();
files.ForEach(CRMSecurity.SetAccessTo);
return files.ToList();
}
}
private void RemoveAllFiles(int[] contactID, EntityType entityType, int entityID)
{
if (entityID > 0 && entityType != EntityType.Opportunity && entityType != EntityType.Case)
{
throw new ArgumentException();
}
var files = GetAllFiles(contactID, entityType, entityID);
using (var dao = FilesIntegration.GetFileDao())
{
foreach (var file in files)
{
dao.DeleteFile(file.ID);
}
}
}
public List<int> RemoveFile(File file)
{
CRMSecurity.DemandDelete(file);
List<int> eventIDs;
using (var tagdao = FilesIntegration.GetTagDao())
{
var tags = tagdao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList().FindAll(tag => tag.TagName.StartsWith("RelationshipEvent_"));
eventIDs = tags.Select(item => Convert.ToInt32(item.TagName.Split(new[] { '_' })[1])).ToList();
}
using (var dao = FilesIntegration.GetFileDao())
{
dao.DeleteFile(file.ID);
}
foreach (var eventID in eventIDs)
{
if (GetFiles(eventID).Count == 0)
{
Db.ExecuteNonQuery(Update("crm_relationship_event").Set("have_files", false).Where("id", eventID));
}
}
Db.ExecuteNonQuery(Update("crm_invoice").Set("file_id", 0).Where("file_id", file.ID));
return eventIDs;
}
public int GetCount(int[] contactID, EntityType entityType, int entityID)
{
if (entityID > 0 && entityType != EntityType.Opportunity && entityType != EntityType.Case)
throw new ArgumentException();
var sqlQuery = Query("crm_relationship_event").SelectCount();
contactID = contactID.Where(item => item != 0).ToArray();
if (contactID.Length > 0)
sqlQuery.Where(Exp.In("contact_id", contactID));
if (entityID > 0)
sqlQuery.Where(Exp.Eq("entity_id", entityID) & Exp.Eq("entity_type", (int)entityType));
return Db.ExecuteScalar<int>(sqlQuery);
}
public RelationshipEvent CreateItem(RelationshipEvent item)
{
CRMSecurity.DemandCreateOrUpdate(item);
var htmlBody = String.Empty;
if (item.CreateOn == DateTime.MinValue)
item.CreateOn = TenantUtil.DateTimeNow();
item.CreateBy = ASC.Core.SecurityContext.CurrentAccount.ID;
item.LastModifedBy = ASC.Core.SecurityContext.CurrentAccount.ID;
if (item.CategoryID == (int)HistoryCategorySystem.MailMessage)
{
var jsonObj = JObject.Parse(item.Content);
var messageId = jsonObj.Value<Int32>("message_id");
var apiServer = new Api.ApiServer();
var msg = apiServer.GetApiResponse(
String.Format("{0}mail/messages/{1}.json?id={1}&loadImages=true&needSanitize=true", SetupInfo.WebApiBaseUrl, messageId), "GET");
if (msg == null)
throw new ArgumentException("Mail message cannot be found");
var msgResponseWrapper = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(msg)));
var msgRequestObj = msgResponseWrapper.Value<JObject>("response");
string messageUrl;
htmlBody = msgRequestObj.Value<String>("htmlBody");
using (var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlBody)))
{
var filePath = String.Format("folder_{0}/message_{1}.html", (messageId / 1000 + 1) * 1000, messageId);
Global.GetStore().Save("mail_messages", filePath, fileStream);
messageUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=mailmessage&message_id={1}", PathProvider.BaseAbsolutePath, messageId);
}
var msg_date_created = msgRequestObj.Value<String>("date");
var message_id = msgRequestObj.Value<Int32>("id");
item.Content = JsonConvert.SerializeObject(new
{
@from = msgRequestObj.Value<String>("from"),
to = msgRequestObj.Value<String>("to"),
cc = msgRequestObj.Value<String>("cc"),
bcc = msgRequestObj.Value<String>("bcc"),
subject = msgRequestObj.Value<String>("subject"),
important = msgRequestObj.Value<Boolean>("important"),
chain_id = msgRequestObj.Value<String>("chainId"),
is_sended = msgRequestObj.Value<Int32>("folder") != 1,
date_created = msg_date_created,
introduction = msgRequestObj.Value<String>("introduction"),
message_id = message_id,
message_url = messageUrl
});
item.CreateOn = DateTime.Parse(msg_date_created, CultureInfo.InvariantCulture);
var sqlQueryFindMailsAlready = Query("crm_relationship_event")
.SelectCount()
.Where("contact_id", item.ContactID)
.Where(Exp.Like("content", string.Format("\"message_id\":{0},", message_id)))
.Where("entity_type", (int)item.EntityType)
.Where("entity_id", item.EntityID)
.Where("category_id", item.CategoryID);
if (Db.ExecuteScalar<int>(sqlQueryFindMailsAlready) > 0)
throw new Exception("Already exists");
}
item.ID = Db.ExecuteScalar<int>(
Insert("crm_relationship_event")
.InColumnValue("id", 0)
.InColumnValue("contact_id", item.ContactID)
.InColumnValue("content", item.Content)
.InColumnValue("create_on", TenantUtil.DateTimeToUtc(item.CreateOn))
.InColumnValue("create_by", item.CreateBy)
.InColumnValue("entity_type", (int)item.EntityType)
.InColumnValue("entity_id", item.EntityID)
.InColumnValue("category_id", item.CategoryID)
.InColumnValue("last_modifed_on", DateTime.UtcNow)
.InColumnValue("last_modifed_by", item.LastModifedBy)
.InColumnValue("have_files", false)
.Identity(1, 0, true));
if (item.CreateOn.Kind == DateTimeKind.Utc)
item.CreateOn = TenantUtil.DateTimeFromUtc(item.CreateOn);
FactoryIndexer<EventsWrapper>.IndexAsync(item);
return item;
}
public virtual RelationshipEvent GetByID(int eventID)
{
return Db.ExecuteList(GetRelationshipEventQuery(Exp.Eq("id", eventID)))
.ConvertAll(ToRelationshipEvent).FirstOrDefault();
}
public int GetAllItemsCount()
{
return Db.ExecuteScalar<int>(Query("crm_relationship_event").SelectCount());
}
public List<RelationshipEvent> GetAllItems()
{
return GetItems(String.Empty,
EntityType.Any,
0,
Guid.Empty,
0,
DateTime.MinValue,
DateTime.MinValue,
0,
0, null);
}
public List<RelationshipEvent> GetItems(
String searchText,
EntityType entityType,
int entityID,
Guid createBy,
int categoryID,
DateTime fromDate,
DateTime toDate,
int from,
int count,
OrderBy orderBy)
{
var sqlQuery = GetRelationshipEventQuery(null);
if (entityID > 0)
switch (entityType)
{
case EntityType.Contact:
var isCompany = false;
isCompany = Db.ExecuteScalar<bool>(Query("crm_contact").Select("is_company").Where(Exp.Eq("id", entityID)));
if (isCompany)
return GetItems(searchText, EntityType.Company, entityID, createBy, categoryID, fromDate, toDate, from, count, orderBy);
else
return GetItems(searchText, EntityType.Person, entityID, createBy, categoryID, fromDate, toDate, from, count, orderBy);
case EntityType.Person:
sqlQuery.Where(Exp.Eq("contact_id", entityID));
break;
case EntityType.Company:
var personIDs = GetRelativeToEntity(entityID, EntityType.Person, null).ToList();
if (personIDs.Count == 0)
sqlQuery.Where(Exp.Eq("contact_id", entityID));
else
{
personIDs.Add(entityID);
sqlQuery.Where(Exp.In("contact_id", personIDs));
}
break;
case EntityType.Case:
case EntityType.Opportunity:
sqlQuery.Where(Exp.Eq("entity_id", entityID) &
Exp.Eq("entity_type", (int)entityType));
break;
}
if (fromDate != DateTime.MinValue && toDate != DateTime.MinValue)
sqlQuery.Where(Exp.Between("create_on", TenantUtil.DateTimeToUtc(fromDate), TenantUtil.DateTimeToUtc(toDate.AddDays(1).AddMinutes(-1))));
else if (fromDate != DateTime.MinValue)
sqlQuery.Where(Exp.Ge("create_on", TenantUtil.DateTimeToUtc(fromDate)));
else if (toDate != DateTime.MinValue)
sqlQuery.Where(Exp.Le("create_on", TenantUtil.DateTimeToUtc(toDate).AddDays(1).AddMinutes(-1)));
if (createBy != Guid.Empty)
sqlQuery.Where(Exp.Eq("create_by", createBy));
if (categoryID != 0)
sqlQuery.Where(Exp.Eq("category_id", categoryID));
if (!String.IsNullOrEmpty(searchText))
{
searchText = searchText.Trim();
var keywords = searchText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
List<int> eventsIds;
if (!FactoryIndexer<EventsWrapper>.TrySelectIds(s => s.MatchAll(searchText), out eventsIds))
{
if (keywords.Length > 0)
sqlQuery.Where(BuildLike(new[] { "content" }, keywords));
}
else
{
if (eventsIds.Count == 0) return new List<RelationshipEvent>();
sqlQuery.Where(Exp.In("id", eventsIds));
}
}
if (0 < from && from < int.MaxValue)
sqlQuery.SetFirstResult(from);
if (0 < count && count < int.MaxValue)
sqlQuery.SetMaxResults(count);
if (orderBy != null && Enum.IsDefined(typeof(RelationshipEventByType), orderBy.SortedBy))
switch ((RelationshipEventByType)orderBy.SortedBy)
{
case RelationshipEventByType.Category:
sqlQuery.OrderBy("category_id", orderBy.IsAsc);
break;
case RelationshipEventByType.Content:
sqlQuery.OrderBy("content", orderBy.IsAsc);
break;
case RelationshipEventByType.CreateBy:
sqlQuery.OrderBy("create_by", orderBy.IsAsc);
break;
case RelationshipEventByType.Created:
sqlQuery.OrderBy("create_on", orderBy.IsAsc);
break;
}
else
sqlQuery.OrderBy("create_on", false);
return Db.ExecuteList(sqlQuery)
.ConvertAll(row => ToRelationshipEvent(row));
}
private static RelationshipEvent ToRelationshipEvent(object[] row)
{
return new RelationshipEvent
{
ID = Convert.ToInt32(row[0]),
ContactID = Convert.ToInt32(row[1]),
Content = Convert.ToString(row[2]),
EntityID = Convert.ToInt32(row[3]),
EntityType = (EntityType)Convert.ToInt32(row[4]),
CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[5])),
CreateBy = ToGuid(row[6]),
CategoryID = Convert.ToInt32(row[7])
};
}
private SqlQuery GetRelationshipEventQuery(Exp where)
{
SqlQuery sqlQuery = Query("crm_relationship_event")
.Select("id",
"contact_id",
"content",
"entity_id",
"entity_type",
"create_on",
"create_by",
"category_id"
);
if (where != null)
sqlQuery.Where(where);
return sqlQuery;
}
public void DeleteItem(int id)
{
var item = GetByID(id);
if (item == null) throw new ArgumentException();
DeleteItem(item);
}
public void DeleteItem(RelationshipEvent item)
{
CRMSecurity.DemandDelete(item);
var relativeFiles = GetFiles(item.ID);
var nowFilesEditing = relativeFiles.Where(file => (file.FileStatus & FileStatus.IsEditing) == FileStatus.IsEditing);
if (nowFilesEditing.Count() != 0)
throw new ArgumentException();
relativeFiles.ForEach(f => RemoveFile(f));
Db.ExecuteNonQuery(Delete("crm_relationship_event").Where(Exp.Eq("id", item.ID)));
FactoryIndexer<EventsWrapper>.DeleteAsync(item);
}
#endregion
[DataContract]
internal class CrmHistoryContent
{
[DataMember]
public string to;
[DataMember]
public string from;
[DataMember]
public string cc;
[DataMember]
public string bcc;
[DataMember]
public string subject;
[DataMember]
public bool important;
[DataMember]
public string chain_id;
[DataMember]
public bool is_sended;
[DataMember]
public string date_created;
[DataMember]
public string introduction;
[DataMember]
public long message_id;
}
private static string GetHistoryContentJson(JObject apiResponse)
{
var content_struct = new CrmHistoryContent
{
@from = apiResponse.Value<String>("from"),
to = apiResponse.Value<String>("to"),
cc = apiResponse.Value<String>("cc"),
bcc = apiResponse.Value<String>("bcc"),
subject = apiResponse.Value<String>("subject"),
important = apiResponse.Value<Boolean>("important"),
chain_id = apiResponse.Value<String>("chainId"),
is_sended = apiResponse.Value<Int32>("folder") == 1,
date_created = apiResponse.Value<String>("date"),
introduction = apiResponse.Value<String>("introduction"),
message_id = apiResponse.Value<Int32>("id")
};
var serializer = new DataContractJsonSerializer(typeof(CrmHistoryContent));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, content_struct);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
}
}
| |
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 frmStockValSelect
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmStockValSelect() : base()
{
FormClosed += frmStockValSelect_FormClosed;
Load += frmStockValSelect_Load;
//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;
public System.Windows.Forms.CheckedListBox lstFilter;
private System.Windows.Forms.CheckBox withEventsField_ckbGrp;
public System.Windows.Forms.CheckBox ckbGrp {
get { return withEventsField_ckbGrp; }
set {
if (withEventsField_ckbGrp != null) {
withEventsField_ckbGrp.CheckStateChanged -= ckbGrp_CheckStateChanged;
}
withEventsField_ckbGrp = value;
if (withEventsField_ckbGrp != null) {
withEventsField_ckbGrp.CheckStateChanged += ckbGrp_CheckStateChanged;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdShow;
public System.Windows.Forms.Button cmdShow {
get { return withEventsField_cmdShow; }
set {
if (withEventsField_cmdShow != null) {
withEventsField_cmdShow.Click -= cmdShow_Click;
}
withEventsField_cmdShow = value;
if (withEventsField_cmdShow != null) {
withEventsField_cmdShow.Click += cmdShow_Click;
}
}
}
public System.Windows.Forms.RadioButton optSum;
public System.Windows.Forms.RadioButton optDel;
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.Label lblHeading;
public System.Windows.Forms.Panel picButtons;
private myDataGridView withEventsField_DataList1;
public myDataGridView DataList1 {
get { return withEventsField_DataList1; }
set {
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.Click -= DataList1_ClickEvent;
}
withEventsField_DataList1 = value;
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.Click += DataList1_ClickEvent;
}
}
}
public System.Windows.Forms.Label lbl;
//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(frmStockValSelect));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.lstFilter = new System.Windows.Forms.CheckedListBox();
this.ckbGrp = new System.Windows.Forms.CheckBox();
this.txtSearch = new System.Windows.Forms.TextBox();
this.cmdShow = new System.Windows.Forms.Button();
this.optSum = new System.Windows.Forms.RadioButton();
this.optDel = new System.Windows.Forms.RadioButton();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdClose = new System.Windows.Forms.Button();
this.lblHeading = new System.Windows.Forms.Label();
this.DataList1 = new myDataGridView();
this.lbl = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Stock Value Report";
this.ClientSize = new System.Drawing.Size(354, 159);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmStockValSelect";
this.lstFilter.Size = new System.Drawing.Size(247, 79);
this.lstFilter.Location = new System.Drawing.Point(8, 72);
this.lstFilter.TabIndex = 10;
this.lstFilter.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lstFilter.BackColor = System.Drawing.SystemColors.Window;
this.lstFilter.CausesValidation = true;
this.lstFilter.Enabled = true;
this.lstFilter.ForeColor = System.Drawing.SystemColors.WindowText;
this.lstFilter.IntegralHeight = true;
this.lstFilter.Cursor = System.Windows.Forms.Cursors.Default;
this.lstFilter.SelectionMode = System.Windows.Forms.SelectionMode.One;
this.lstFilter.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lstFilter.Sorted = false;
this.lstFilter.TabStop = true;
this.lstFilter.Visible = true;
this.lstFilter.MultiColumn = false;
this.lstFilter.Name = "lstFilter";
this.ckbGrp.Text = "Select Group ?";
this.ckbGrp.Size = new System.Drawing.Size(97, 17);
this.ckbGrp.Location = new System.Drawing.Point(160, 48);
this.ckbGrp.TabIndex = 9;
this.ckbGrp.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.ckbGrp.FlatStyle = System.Windows.Forms.FlatStyle.Standard;
this.ckbGrp.BackColor = System.Drawing.SystemColors.Control;
this.ckbGrp.CausesValidation = true;
this.ckbGrp.Enabled = true;
this.ckbGrp.ForeColor = System.Drawing.SystemColors.ControlText;
this.ckbGrp.Cursor = System.Windows.Forms.Cursors.Default;
this.ckbGrp.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ckbGrp.Appearance = System.Windows.Forms.Appearance.Normal;
this.ckbGrp.TabStop = true;
this.ckbGrp.CheckState = System.Windows.Forms.CheckState.Unchecked;
this.ckbGrp.Visible = true;
this.ckbGrp.Name = "ckbGrp";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(94, 19);
this.txtSearch.Location = new System.Drawing.Point(51, 46);
this.txtSearch.TabIndex = 7;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtSearch.Name = "txtSearch";
this.cmdShow.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdShow.Text = "&Print";
this.cmdShow.Size = new System.Drawing.Size(73, 29);
this.cmdShow.Location = new System.Drawing.Point(272, 124);
this.cmdShow.TabIndex = 5;
this.cmdShow.TabStop = false;
this.cmdShow.BackColor = System.Drawing.SystemColors.Control;
this.cmdShow.CausesValidation = true;
this.cmdShow.Enabled = true;
this.cmdShow.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdShow.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdShow.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdShow.Name = "cmdShow";
this.optSum.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.optSum.Text = "Summary";
this.optSum.Font = new System.Drawing.Font("Verdana", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
this.optSum.Size = new System.Drawing.Size(96, 23);
this.optSum.Location = new System.Drawing.Point(266, 86);
this.optSum.TabIndex = 4;
this.optSum.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.optSum.BackColor = System.Drawing.SystemColors.Control;
this.optSum.CausesValidation = true;
this.optSum.Enabled = true;
this.optSum.ForeColor = System.Drawing.SystemColors.ControlText;
this.optSum.Cursor = System.Windows.Forms.Cursors.Default;
this.optSum.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.optSum.Appearance = System.Windows.Forms.Appearance.Normal;
this.optSum.TabStop = true;
this.optSum.Checked = false;
this.optSum.Visible = true;
this.optSum.Name = "optSum";
this.optDel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.optDel.Text = "Detail";
this.optDel.Font = new System.Drawing.Font("Verdana", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
this.optDel.Size = new System.Drawing.Size(72, 23);
this.optDel.Location = new System.Drawing.Point(266, 46);
this.optDel.TabIndex = 3;
this.optDel.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.optDel.BackColor = System.Drawing.SystemColors.Control;
this.optDel.CausesValidation = true;
this.optDel.Enabled = true;
this.optDel.ForeColor = System.Drawing.SystemColors.ControlText;
this.optDel.Cursor = System.Windows.Forms.Cursors.Default;
this.optDel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.optDel.Appearance = System.Windows.Forms.Appearance.Normal;
this.optDel.TabStop = true;
this.optDel.Checked = false;
this.optDel.Visible = true;
this.optDel.Name = "optDel";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(354, 38);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 0;
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.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(272, 2);
this.cmdClose.TabIndex = 1;
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.lblHeading.Text = "Select option for Detail / Summary";
this.lblHeading.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblHeading.ForeColor = System.Drawing.Color.White;
this.lblHeading.Size = new System.Drawing.Size(273, 21);
this.lblHeading.Location = new System.Drawing.Point(2, 8);
this.lblHeading.TabIndex = 2;
this.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblHeading.BackColor = System.Drawing.Color.Transparent;
this.lblHeading.Enabled = true;
this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default;
this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblHeading.UseMnemonic = true;
this.lblHeading.Visible = true;
this.lblHeading.AutoSize = false;
this.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblHeading.Name = "lblHeading";
//DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State)
this.DataList1.Size = new System.Drawing.Size(244, 82);
this.DataList1.Location = new System.Drawing.Point(8, 168);
this.DataList1.TabIndex = 6;
this.DataList1.Name = "DataList1";
this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl.Text = "&Search :";
this.lbl.Size = new System.Drawing.Size(40, 13);
this.lbl.Location = new System.Drawing.Point(8, 49);
this.lbl.TabIndex = 8;
this.lbl.BackColor = System.Drawing.Color.Transparent;
this.lbl.Enabled = true;
this.lbl.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl.UseMnemonic = true;
this.lbl.Visible = true;
this.lbl.AutoSize = true;
this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl.Name = "lbl";
this.Controls.Add(lstFilter);
this.Controls.Add(ckbGrp);
this.Controls.Add(txtSearch);
this.Controls.Add(cmdShow);
this.Controls.Add(optSum);
this.Controls.Add(optDel);
this.Controls.Add(picButtons);
this.Controls.Add(DataList1);
this.Controls.Add(lbl);
this.picButtons.Controls.Add(cmdClose);
this.picButtons.Controls.Add(lblHeading);
((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit();
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#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.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using NPOI.Util;
/**
* Title: Unknown Record (for debugging)
* Description: Unknown record just tells you the sid so you can figure out
* what records you are missing. Also helps us Read/modify sheets we
* don't know all the records to. (HSSF leaves these alone!)
* Company: SuperLink Software, Inc.
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Jason Height (jheight at chariot dot net dot au)
* @author Glen Stampoultzis (glens at apache.org)
*/
internal class UnknownRecord : StandardRecord
{
public const int PRINTSIZE_0033 = 0x0033;
/*
* Some Record IDs used by POI as 'milestones' in the record stream
*/
public const int PLS_004D = 0x004D;
public const int SHEETPR_0081 = 0x0081;
public const int SORT_0090 = 0x0090;
public const int STANDARDWIDTH_0099 = 0x0099;
public const int SCL_00A0 = 0x00A0;
public const int BITMAP_00E9 = 0x00E9;
public const int PHONETICPR_00EF = 0x00EF;
public const int LABELRANGES_015F = 0x015F;
//public const int USERSVIEWBEGIN_01AA = 0x01AA;
//public const int USERSVIEWEND_01AB = 0x01AB;
public const int QUICKTIP_0800 = 0x0800;
//public const int SHEETEXT_0862 = 0x0862; // OOO calls this SHEETLAYOUT
public const int SHEETPROTECTION_0867 = 0x0867;
//public const int RANGEPROTECTION_0868 = 0x0868;
public const int HEADER_FOOTER_089C = 0x089C;
public const int CODENAME_1BA = 0x01BA;
private int _sid = 0;
private byte[] _rawData = null;
//public UnknownRecord()
//{
//}
/**
* @param id id of the record -not Validated, just stored for serialization
* @param data the data
*/
public UnknownRecord(int id, byte[] data)
{
_sid = id & 0xFFFF;
_rawData = data;
}
/**
* construct an Unknown record. No fields are interperated and the record will
* be Serialized in its original form more or less
* @param in the RecordInputstream to Read the record from
*/
public UnknownRecord(RecordInputStream in1)
{
_sid = in1.Sid;
_rawData = in1.ReadRemainder();
//if (false && GetBiffName(_sid) == null)
//{
// // unknown sids in the range 0x0004-0x0013 are probably 'sub-records' of ObjectRecord
// // those sids are in a different number space.
// // TODO - put unknown OBJ sub-records in a different class
// System.Console.WriteLine("Unknown record 0x" + _sid.ToString("X"));
//}
}
/**
* spit the record out AS IS. no interpretation or identification
*/
public override void Serialize(ILittleEndianOutput out1)
{
out1.Write(_rawData);
}
protected override int DataSize
{
get
{
return _rawData.Length;
}
}
/**
* print a sort of string representation ([UNKNOWN RECORD] id = x [/UNKNOWN RECORD])
*/
public override String ToString()
{
String biffName = GetBiffName(_sid);
if (biffName == null)
{
biffName = "UNKNOWNRECORD";
}
StringBuilder sb = new StringBuilder();
sb.Append("[").Append(biffName).Append("] (0x");
sb.Append(StringUtil.ToHexString(_sid).ToUpper() + ")\n");
if (_rawData.Length > 0)
{
sb.Append(" rawData=").Append(HexDump.ToHex(_rawData)).Append("\n");
}
sb.Append("[/").Append(biffName).Append("]\n");
return sb.ToString();
}
/**
* These BIFF record types are known but still uninterpreted by POI
*
* @return the documented name of this BIFF record type, <code>null</code> if unknown to POI
*/
public static String GetBiffName(int sid)
{
// Note to POI developers:
// Make sure you delete the corresponding entry from
// this method any time a new Record subclass is created.
switch (sid)
{
case PRINTSIZE_0033: return "PRINTSIZE";
case PLS_004D: return "PLS";
case 0x0050: return "DCON"; // Data Consolidation Information
case 0x007F: return "IMDATA";
case SHEETPR_0081: return "SHEETPR";
case SORT_0090: return "SORT"; // Sorting Options
case 0x0094: return "LHRECORD"; // .WK? File Conversion Information
case STANDARDWIDTH_0099: return "STANDARDWIDTH"; //Standard Column Width
case 0x009D: return "AUTOFILTERINFO"; // Drop-Down Arrow Count
case SCL_00A0: return "SCL"; // Window Zoom Magnification
case 0x00AE: return "SCENMAN"; // Scenario Output Data
case 0x00B2: return "SXVI"; // (pivot table) View Item
case 0x00B4: return "SXIVD"; // (pivot table) Row/Column Field IDs
case 0x00B5: return "SXLI"; // (pivot table) Line Item Array
case 0x00D3: return "OBPROJ";
case 0x00DC: return "PARAMQRY";
case 0x00DE: return "OLESIZE";
case BITMAP_00E9: return "BITMAP";
case PHONETICPR_00EF: return "PHONETICPR";
case 0x00F1: return "SXEX"; // PivotTable View Extended Information
case LABELRANGES_015F: return "LABELRANGES";
case 0x01BA: return "CODENAME";
case 0x01A9: return "USERBVIEW";
case 0x01AD: return "QSI";
case 0x01C0: return "EXCEL9FILE";
case 0x0802: return "QSISXTAG"; // Pivot Table and Query Table Extensions
case 0x0803: return "DBQUERYEXT";
case 0x0805: return "TXTQUERY";
case 0x0810: return "SXVIEWEX9"; // Pivot Table Extensions
case 0x0812: return "CONTINUEFRT";
case QUICKTIP_0800: return "QUICKTIP";
//case SHEETEXT_0862: return "SHEETEXT";
case 0x0863: return "BOOKEXT";
case 0x0864: return "SXADDL"; // Pivot Table Additional Info
case SHEETPROTECTION_0867: return "SHEETPROTECTION";
//case RANGEPROTECTION_0868: return "RANGEPROTECTION";
case 0x086B: return "DATALABEXTCONTENTS";
case 0x086C: return "CELLWATCH";
case 0x0874: return "DROPDOWNOBJIDS";
case 0x0876: return "DCONN";
case 0x087B: return "CFEX";
case 0x087C: return "XFCRC";
case 0x087D: return "XFEXT";
case 0x087F: return "CONTINUEFRT12";
case 0x088B: return "PLV";
case 0x088C: return "COMPAT12";
case 0x088D: return "DXF";
case 0x0892: return "STYLEEXT";
case 0x0896: return "THEME";
case 0x0897: return "GUIDTYPELIB";
case 0x089A: return "MTRSETTINGS";
case 0x089B: return "COMPRESSPICTURES";
case HEADER_FOOTER_089C: return "HEADERFOOTER";
case 0x08A1: return "SHAPEPROPSSTREAM";
case 0x08A3: return "FORCEFULLCALCULATION";
case 0x08A4: return "SHAPEPROPSSTREAM";
case 0x08A5: return "TEXTPROPSSTREAM";
case 0x08A6: return "RICHTEXTSTREAM";
case 0x08C8: return "PLV{Mac Excel}";
}
if (IsObservedButUnknown(sid))
{
return "UNKNOWN-" + StringUtil.ToHexString(sid).ToUpper();
}
return null;
}
/**
* @return <c>true</c> if the unknown record id has been observed in POI unit tests
*/
private static bool IsObservedButUnknown(int sid)
{
switch (sid)
{
case 0x0033:
// contains 2 bytes of data: 0x0001 or 0x0003
case 0x0034:
// Seems to be written by MSAccess
// contains text "[Microsoft JET Created Table]0021010"
// appears after last cell value record and before WINDOW2
case 0x01BD:
case 0x01C2:
// Written by Excel 2007
// rawData is multiple of 12 bytes long
// appears after last cell value record and before WINDOW2 or drawing records
case 0x089D:
case 0x089E:
case 0x08A7:
case 0x1001:
case 0x1006:
case 0x1007:
case 0x1009:
case 0x100A:
case 0x100B:
case 0x100C:
case 0x1014:
case 0x1017:
case 0x1018:
case 0x1019:
case 0x101A:
case 0x101B:
case 0x101D:
case 0x101E:
case 0x101F:
case 0x1020:
case 0x1021:
case 0x1022:
case 0x1024:
case 0x1025:
case 0x1026:
case 0x1027:
case 0x1032:
case 0x1033:
case 0x1034:
case 0x1035:
case 0x103A:
case 0x1041:
case 0x1043:
case 0x1044:
case 0x1045:
case 0x1046:
case 0x104A:
case 0x104B:
case 0x104E:
case 0x104F:
case 0x1051:
case 0x105C:
case 0x105D:
case 0x105F:
case 0x1060:
case 0x1062:
case 0x1063:
case 0x1064:
case 0x1065:
case 0x1066:
return true;
}
return false;
}
public override short Sid
{
get { return (short)_sid; }
}
/** Unlike the other Record.Clone methods this Is a shallow Clone*/
public override Object Clone()
{
//UnknownRecord rec = new UnknownRecord();
//rec._sid= _sid;
//rec._rawData = _rawData;
//return rec;
// immutable - ok to return this
return this;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OmniSharp.Models.AutoComplete;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class SnippetFacts : AbstractAutoCompleteTestFixture
{
private readonly ILogger _logger;
public SnippetFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
this._logger = this.LoggerFactory.CreateLogger<SnippetFacts>();
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_template_generic_type_argument(string filename)
{
const string source =
@"public class Class1 {
public Class1()
{
var l = new System.Collections.Generic.Lis$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("List<${1:T}>()$0", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_return_method_type_arguments_snippets(string filename)
{
const string source =
@"using System.Collections.Generic;
public class Test {
public string Get<SomeType>()
{
}
}
public class Class1 {
public Class1()
{
var someObj = new Test();
someObj.G$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("Get<${1:SomeType}>()$0 : string", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Does_not_include_tsource_argument_type(string filename)
{
const string source =
@"using System.Collections.Generic;
using System.Linq;
public class Class1 {
public Class1()
{
var l = new List<string>();
l.Firs$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("First()$0 : string", completions);
ContainsSnippet("FirstOrDefault(${1:Func<string, bool> predicate})$0 : string", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Does_not_include_tresult_argument_type(string filename)
{
const string source =
@"using System.Collections.Generic;
using System.Linq;
public class Class1 {
public Class1()
{
var dict = new Dictionary<string, object>();
dict.Sel$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("Select(${1:Func<KeyValuePair<string, object>, TResult> selector})$0 : IEnumerable<TResult>", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_template_field(string filename)
{
const string source =
@"using System.Collections.Generic;
public class Class1 {
public int someField;
public Class1()
{
somef$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("someField$0 : int", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_return_all_constructors(string filename)
{
const string source =
@"public class MyClass {
public MyClass() {}
public MyClass(int param) {}
public MyClass(int param, string param) {}
}
public class Class2 {
public Class2()
{
var c = new My$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("MyClass()$0", completions);
ContainsSnippet("MyClass(${1:int param})$0", completions);
ContainsSnippet("MyClass(${1:int param}, ${2:string param})$0", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_template_generic_type_arguments(string filename)
{
const string source =
@"using System.Collections.Generic;
public class Class1 {
public Class1()
{
var l = new Dict$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("Dictionary<${1:TKey}, ${2:TValue}>()$0", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_template_parameter(string filename)
{
const string source =
@"using System.Collections.Generic;
public class Class1 {
public Class1()
{
var l = new Lis$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("List<${1:T}>(${2:IEnumerable<T> collection})$0", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_complete_namespace(string filename)
{
const string source = "using Sys$$";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("System$0", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_complete_variable(string filename)
{
const string source = @"
public class Class1
{
public Class1()
{
var aVariable = 1;
av$$
}
}
";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("aVariable$0 : int", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Void_methods_end_with_semicolons(string filename)
{
const string source = @"
using System;
public class Class1
{
public Class1()
{
Array.Sor$$
}
}
";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("Sort(${1:Array array});$0 : void", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Fuzzy_matches_are_returned_when_first_letters_match(string filename)
{
const string source = @"
using System;
public class Class1
{
public Class1()
{
Guid.nwg$$
}
}
";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("NewGuid()$0 : Guid", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Fuzzy_matches_are_not_returned_when_first_letters_do_not_match(string filename)
{
const string source = @"
using System;
public class Class1
{
public Class1()
{
Console.rl$$
}
}
";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
var snippetTexts = GetSnippetTexts(completions);
Assert.DoesNotContain("WriteLine();$0 : void", snippetTexts);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_complete_parameter(string filename)
{
const string source = @"
public class Class1
{
public Class1()
{
}
public Class2(Class1 class1)
{
clas$$
}
}
";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("class1$0 : Class1", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Can_return_keywords(string filename)
{
const string source = "usin$$";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("using", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_enums(string filename)
{
const string source =
@"public enum Colors { Red, Blue }
public class MyClass1
{
public MyClass1()
{
Col$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
Assert.Single(completions);
ContainsSnippet("Colors$0", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_event_without_event_keyword(string filename)
{
const string source =
@"
public class MyClass1 {
public event TickHandler TickChanged;
public MyClass1()
{
Tick$$
}
}";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
Assert.Single(completions);
ContainsSnippet("TickChanged$0 : TickHandler", completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_method_without_optional_params(string filename)
{
const string source = @"
public class Class1
{
public void OptionalParam(int i, string s = null)
{
}
public void DoSomething()
{
Opt$$
}
}
";
var completions = await FindCompletionsAsync(filename, source, wantSnippet: true);
ContainsSnippet("OptionalParam(${1:int i});$0 : void", completions);
ContainsSnippet("OptionalParam(${1:int i}, ${2:string s = null});$0 : void", completions);
}
[Fact]
public async Task Can_complete_global_variable_in_CSX()
{
const string source = @"
var aVariable = 1;
av$$
";
var completions = await FindCompletionsAsync("dummy.csx", source, wantSnippet: true);
ContainsSnippet("aVariable$0 : int", completions);
}
[Fact]
public async Task Can_return_global_method_type_arguments_snippets_in_CSX()
{
const string source =
@"using System.Collections.Generic;
public string Get<SomeType>()
{
}
G$$
";
var completions = await FindCompletionsAsync("dummy.csx", source, wantSnippet: true);
ContainsSnippet("Get<${1:SomeType}>()$0 : string", completions);
}
private static IEnumerable<string> GetSnippetTexts(IEnumerable<AutoCompleteResponse> responses)
{
return responses.Select(r =>
r.ReturnType != null
? r.Snippet + " : " + r.ReturnType
: r.Snippet);
}
private void ContainsSnippet(string expected, IEnumerable<AutoCompleteResponse> responses)
{
var snippetTexts = GetSnippetTexts(responses);
if (!snippetTexts.Contains(expected))
{
var builder = new StringBuilder();
builder.AppendLine("Did not find - " + expected);
foreach (var snippetText in snippetTexts)
{
builder.AppendLine(snippetText);
}
this._logger.LogError(builder.ToString());
}
Assert.Contains(expected, snippetTexts);
}
}
}
| |
//==============================================================================
// TorqueLab -> Fonts Setup
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
//"art/terrains/*.cs";
$TerrainMaterialFolders="art/Terrains/";
//TerrainMaterialDlg.refreshMaterialTree();
//TerrainMaterialDlg.setFilteredMaterialsSet();
//==============================================================================
function TerrainMaterialDlg::refreshMaterialTree( %this,%selected ) {
// Refresh the material list.
%matLibTree = %this-->matLibTree;
%matLibTree.clear();
%matLibTree.open( FilteredTerrainMaterialsSet, false );
%matLibTree.buildVisibleTree( true );
if (%selected !$= "") {
%item = %matLibTree.findItemByObjectId( %newMat );
}
if (%item $= "-1" || %item $= "")
%item = %matLibTree.getFirstRootItem();
%matLibTree.selectItem( %item );
%matLibTree.expandItem( %item );
%this.activateMaterialCtrls( true );
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::selectObjectInTree( %this,%matObjectId,%selectFirstIfInvalid ) {
%matLibTree = %this-->matLibTree;
%matLibTree.clearSelection();
%item = %matLibTree.findItemByObjectId( %matObjectId );
if ( %item != -1 ) {
%matLibTree.selectItem( %item );
%matLibTree.scrollVisible( %item );
} else if (%selectFirstIfInvalid) {
for( %i = 1; %i < %matLibTree.getItemCount(); %i++ ) {
%terrMat = TerrainMaterialDlg-->matLibTree.getItemValue(%i);
if( %terrMat.getClassName() $= "TerrainMaterial" ) {
%matLibTree.selectItem( %i, true );
%matLibTree.scrollVisible( %i );
break;
}
}
}
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialTreeCtrl::onSelect( %this, %item ) {
TerrainMaterialDlg.setActiveMaterial( %item );
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialTreeCtrl::onUnSelect( %this, %item ) {
if ($TerrainMatDlg_SaveWhenUnselected)
TerrainMaterialDlg.checkMaterialDirty( %item );
else
warnLog("Saving when unselect material is disabled");
TerrainMaterialDlg.setActiveMaterial( 0 );
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::initFiltersData( %this ) {
%folderMenu = %this-->menuFolders;
%folderMenu.clear();
%folderMenu.add("All",0);
%menuId = 1;
for(%j=0; %j<getFieldCount($TerrainMaterialFolders); %j++) {
%pathBase = getField($TerrainMaterialFolders,%j);
%filePathScript = %pathBase@"*.cs";
for(%file = findFirstFile(%filePathScript); %file !$= ""; %file = findNextFile(%filePathScript)) {
//get folder
%folder = filePath(%file);
%folderStr = strreplace(%folder,"/","\t");
%folderCount = getFieldCount(%folderStr);
%themeId = "";
for(%i = 0; %i<%folderCount; %i++) {
%currentFolder = getField(%folderStr,%i);
if (%currentFolder $= "terrains") {
%themeId = %i+1;
%themeFolder = getField(%folderStr,%themeId);
}
if (!%added[%themeFolder] && %themeFolder !$= "") {
%folderMenu.add( %themeFolder,%menuId);
%added[%themeFolder] = true;
%menuId++;
}
}
}
}
%folderMenu.setSelected(0,false);
%surfaceMenu = %this-->menuSurfaces;
%surfaceMenu.clear();
%surfaceMenu.add("All",0);
%surfaceMenu.add("Grass",1);
%surfaceMenu.add("Ground",2);
%surfaceMenu.add("Rock",3);
%surfaceMenu.setSelected(0,false);
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::changeFolderFilter( %this ) {
%this.canSaveDirty = false;
%folderMenu = %this-->menuFolders;
%id = %folderMenu.getSelected();
%folder = %folderMenu.getTextById(%id);
TerrainMaterialDlg.folderFilter = %folder;
%this.setFilteredMaterialsSet();
%matLibTree = %this-->matLibTree;
%matLibTree.clearSelection();
%item = %matLibTree.findItemByObjectId( %this.activeMat );
if ( %item $= "-1" ) {
%item = FilteredTerrainMaterialsSet.getObject(0);
%matLibTree.selectItem( %item );
%matLibTree.scrollVisible( %item );
}
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::changeSurfaceFilter( %this ) {
%surfaceMenu = %this-->menuSurfaces;
%id = %surfaceMenu.getSelected();
%surface = %surfaceMenu.getTextById(%id);
TerrainMaterialDlg.surfaceFilter = %surface;
%this.setFilteredMaterialsSet();
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::applyMaterialFilters( %this ) {
%matLibTree = %this-->matLibTree;
%matLibTree.clear();
%matLibTree.open( TerrainMaterialSet, false );
%currentSelection = %matLibTree.getSelectedItemList();
%matLibTree.clearSelection();
%count = %matLibTree.getItemCount();
%hideMe = false;
foreach(%mat in TerrainMaterialSet) {
%item = %matLibTree.findItemByObjectId(%mat.getId());
if (%this.folderFilter !$= "All") {
%folderFound = strstr(%mat.getFilename(),%this.folderFilter);
if (%folderFound $= "-1") {
//Hide this material
%hideMe = true;
}
}
if (%this.surfaceFilter !$= "All") {
%folderFound = strstr(%mat.getFilename(),%this.surfaceFilter);
%nameFound = strstr(%mat.getName(),%this.surfaceFilter);
%intnameFound = strstr(%mat.internalName,%this.surfaceFilter);
if (%folderFound $= "-1" && %nameFound $= "-1" && %intnameFound $= "-1") {
//Hide this material
%hideMe = true;
}
}
if (!$Cfg_MaterialEditor_ShowGroundCoverMaterial && (%mat.isGroundCoverMat || %mat.isGroundCoverMat $= "1") )
%hideMe = true;
if (%hideMe) {
%matLibTree.removeItem(%item);
%matLibTree.hideSelection();
%matLibTree.clearSelection();
}
}
%matLibTree.clearSelection();
foreach$(%itemId in %currentSelection)
%matLibTree.selectItem(%itemId);
%matLibTree.setFilterText(%this-->materialFilter.getValue());
%matLibTree.buildVisibleTree( true );
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::setFilteredMaterialsSet( %this,%reset,%selectMat ) {
FilteredTerrainMaterialsSet.clear();
if (%reset) {
%this.folderFilter = "All";
%this.surfaceFilter = "All";
}
%folderFilter = %this.folderFilter;
%surfaceFilter = %this.surfaceFilter;
foreach(%mat in TerrainMaterialSet) {
%hideMe = false;
if (%this.folderFilter !$= "All") {
%folderFound = strstr(%mat.getFilename(),%folderFilter);
if (%folderFound $= "-1") {
//Hide this material
%hideMe = true;
}
}
if (%this.surfaceFilter !$= "All") {
%folderFound = strstr(%mat.getFilename(),%surfaceFilter);
%nameFound = strstr(%mat.getName(),%surfaceFilter);
%intnameFound = strstr(%mat.internalName,%surfaceFilter);
if (%folderFound $= "-1" && %nameFound $= "-1" && %intnameFound $= "-1") {
//Hide this material
%hideMe = true;
}
}
if (!$Cfg_MaterialEditor_ShowGroundCoverMaterial && (%mat.isGroundCoverMat || %mat.isGroundCoverMat $="1") )
%hideMe = true;
if (!%hideMe) {
FilteredTerrainMaterialsSet.add(%mat);
}
}
%this.refreshMaterialTree(%selectMat);
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::updateFilterText( %this ) {
%matLibTree = %this-->matLibTree;
%matLibTree.setFilterText(%this-->materialFilter.getValue());
%this.refreshMaterialTree();
}
| |
//-----------------------------------------------------------------------
// <copyright file="ARCoreSession.cs" company="Google LLC">
//
// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore
{
using System.Collections.Generic;
using GoogleARCoreInternal;
using UnityEngine;
/// <summary>
/// A component that manages the ARCore Session in a Unity scene.
/// </summary>
[HelpURL("https://developers.google.com/ar/reference/unity/class/GoogleARCore/ARCoreSession")]
public class ARCoreSession : MonoBehaviour
{
/// <summary>
/// The direction of the device camera used by the session.
/// </summary>
/// <remarks>
/// Note that changing this value will trigger a re-initialization of session. ARCore
/// tracking data (e.g. Trackables) are not shared between cameras.
/// </remarks>
[Tooltip("The direction of the device camera used by the session.")]
public DeviceCameraDirection DeviceCameraDirection = DeviceCameraDirection.BackFacing;
/// <summary>
/// A scriptable object specifying the ARCore session configuration.
/// </summary>
[Tooltip("A scriptable object specifying the ARCore session configuration.")]
public ARCoreSessionConfig SessionConfig;
/// <summary>
/// The camera configuration filter object that defines the set of
/// properties desired or required by the app to run.
/// </summary>
[Tooltip("Configuration options to select the camera mode and features.")]
public ARCoreCameraConfigFilter CameraConfigFilter;
private OnChooseCameraConfigurationDelegate m_OnChooseCameraConfiguration;
/// <summary>
/// Selects a camera configuration for the ARCore session being resumed.
/// </summary>
/// <param name="supportedConfigurations">
/// A list of supported camera configurations. The size is dependent on
/// <see cref="ARCoreSession.CameraConfigFilter"/> settings.
/// The GPU texture resolutions are the same in all configs.
/// Currently, most devices provide GPU texture resolution of 1920 x 1080,
/// but devices might provide higher or lower resolution textures, depending
/// on device capabilities.
/// The CPU image resolutions returned are VGA, 720p, and a resolution matching the GPU
/// texture, typically the native resolution of the device.</param>
/// <returns>The index of the camera configuration in <c>supportedConfigurations</c> to be
/// used for the ARCore session. If the return value is not a valid index (e.g. the value
/// -1), then no camera configuration will be set and the ARCore session will use the
/// previously selected camera configuration or a default configuration if no previous
/// selection exists.</returns>
public delegate int OnChooseCameraConfigurationDelegate(
List<CameraConfig> supportedConfigurations);
/// <summary>
/// Unity Awake.
/// </summary>
[SuppressMemoryAllocationError(Reason = "Could create new LifecycleManager")]
public virtual void Awake()
{
if (SessionConfig != null &&
SessionConfig.LightEstimationMode != LightEstimationMode.Disabled &&
Object.FindObjectsOfType<EnvironmentalLight>().Length == 0)
{
Debug.Log("Light Estimation may not work properly when EnvironmentalLight is not" +
" attached to the scene.");
}
LifecycleManager.Instance.CreateSession(this);
}
/// <summary>
/// Unity OnDestroy.
/// </summary>
[SuppressMemoryAllocationError(
IsWarning = true, Reason = "Requires further investigation.")]
public virtual void OnDestroy()
{
LifecycleManager.Instance.ResetSession();
}
/// <summary>
/// Unity OnEnable.
/// </summary>
[SuppressMemoryAllocationError(
Reason = "Enabling session creates a new ARSessionConfiguration")]
public void OnEnable()
{
LifecycleManager.Instance.EnableSession();
}
/// <summary>
/// Unity OnDisable.
/// </summary>
[SuppressMemoryAllocationError(
IsWarning = true, Reason = "Requires further investigation.")]
public void OnDisable()
{
LifecycleManager.Instance.DisableSession();
}
/// <summary>
/// Unity OnValidate.
/// </summary>
public void OnValidate()
{
if (DeviceCameraDirection == DeviceCameraDirection.FrontFacing && SessionConfig != null)
{
if (SessionConfig.PlaneFindingMode != DetectedPlaneFindingMode.Disabled)
{
Debug.LogErrorFormat("Plane Finding requires back-facing camera.");
}
if (SessionConfig.LightEstimationMode ==
LightEstimationMode.EnvironmentalHDRWithoutReflections ||
SessionConfig.LightEstimationMode ==
LightEstimationMode.EnvironmentalHDRWithReflections)
{
Debug.LogErrorFormat("LightEstimationMode.{0} is incompatible with" +
"front-facing (selfie) camera.", SessionConfig.LightEstimationMode);
}
if (SessionConfig.CloudAnchorMode != CloudAnchorMode.Disabled)
{
Debug.LogErrorFormat("Cloud Anchors require back-facing camera.");
}
if (SessionConfig.AugmentedImageDatabase != null)
{
Debug.LogErrorFormat("Augmented Images require back-facing camera.");
}
}
if (DeviceCameraDirection == DeviceCameraDirection.BackFacing &&
SessionConfig != null && SessionConfig.AugmentedFaceMode ==
AugmentedFaceMode.Mesh)
{
Debug.LogErrorFormat("AugmentedFaceMode.{0} requires front-facing (selfie) camera.",
SessionConfig.AugmentedFaceMode);
}
if (SessionConfig == null)
{
Debug.LogError("SessionConfig is required by ARCoreSession.");
}
if (CameraConfigFilter == null)
{
Debug.LogError("CameraConfigFilter is required by ARCoreSession. " +
"To get all available configurations, set CameraConfigFilter to " +
"a filter with all options selected.");
}
}
/// <summary>
/// Registers a callback that allows a camera configuration to be selected from a list of
/// valid configurations.
/// The callback should be registered before the ARCore session is enabled
/// to ensure it is triggered on the first frame update.
/// The callback will then be invoked each time the ARCore session is resumed,
/// which can happen when the <see cref="ARCoreSession"/> component is enabled or the
/// Android app moves from a state of 'paused' to 'resumed' state.
///
/// Note: Starting in ARCore 1.12, changing the active camera config will make existing
/// anchors and trackables fail to regain tracking.
/// </summary>
/// <param name="onChooseCameraConfiguration">The callback to register for selecting a
/// camera configuration.</param>
public void RegisterChooseCameraConfigurationCallback(
OnChooseCameraConfigurationDelegate onChooseCameraConfiguration)
{
m_OnChooseCameraConfiguration = onChooseCameraConfiguration;
}
internal OnChooseCameraConfigurationDelegate GetChooseCameraConfigurationCallback()
{
return m_OnChooseCameraConfiguration;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.GrainReferences;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime
{
/// <summary>
/// Maintains additional per-activation state that is required for Orleans internal operations.
/// MUST lock this object for any concurrent access
/// Consider: compartmentalize by usage, e.g., using separate interfaces for data for catalog, etc.
/// </summary>
internal class ActivationData : IActivationData, IGrainExtensionBinder, IAsyncDisposable
{
// This is the maximum amount of time we expect a request to continue processing
private readonly TimeSpan maxRequestProcessingTime;
private readonly TimeSpan maxWarningRequestProcessingTime;
private readonly SiloMessagingOptions messagingOptions;
private readonly ILogger logger;
private readonly IServiceScope serviceScope;
public readonly TimeSpan CollectionAgeLimit;
private readonly GrainTypeComponents _shared;
private HashSet<IGrainTimer> timers;
private Dictionary<Type, object> _components;
public ActivationData(
ActivationAddress addr,
PlacementStrategy placedUsing,
IActivationCollector collector,
TimeSpan ageLimit,
IOptions<SiloMessagingOptions> messagingOptions,
TimeSpan maxWarningRequestProcessingTime,
TimeSpan maxRequestProcessingTime,
ILoggerFactory loggerFactory,
IServiceProvider applicationServices,
IGrainRuntime grainRuntime,
GrainReferenceActivator referenceActivator,
GrainTypeComponents sharedComponents)
{
if (null == addr) throw new ArgumentNullException(nameof(addr));
if (null == placedUsing) throw new ArgumentNullException(nameof(placedUsing));
if (null == collector) throw new ArgumentNullException(nameof(collector));
_shared = sharedComponents;
logger = loggerFactory.CreateLogger<ActivationData>();
this.lifecycle = new GrainLifecycle(loggerFactory.CreateLogger<LifecycleSubject>());
this.maxRequestProcessingTime = maxRequestProcessingTime;
this.maxWarningRequestProcessingTime = maxWarningRequestProcessingTime;
this.messagingOptions = messagingOptions.Value;
ResetKeepAliveRequest();
Address = addr;
State = ActivationState.Create;
PlacedUsing = placedUsing;
if (!this.GrainId.IsSystemTarget())
{
this.collector = collector;
}
CollectionAgeLimit = ageLimit;
this.GrainReference = referenceActivator.CreateReference(addr.Grain, default);
this.serviceScope = applicationServices.CreateScope();
this.Runtime = grainRuntime;
}
public IGrainRuntime Runtime { get; }
public IServiceProvider ActivationServices => this.serviceScope.ServiceProvider;
internal WorkItemGroup WorkItemGroup { get; set; }
public TComponent GetComponent<TComponent>()
{
TComponent result;
if (this.GrainInstance is TComponent grainResult)
{
result = grainResult;
}
else if (this is TComponent contextResult)
{
result = contextResult;
}
else if (_components is object && _components.TryGetValue(typeof(TComponent), out var resultObj))
{
result = (TComponent)resultObj;
}
else
{
result = _shared.GetComponent<TComponent>();
}
return result;
}
public void SetComponent<TComponent>(TComponent instance)
{
if (this.GrainInstance is TComponent)
{
throw new ArgumentException("Cannot override a component which is implemented by this grain");
}
if (this is TComponent)
{
throw new ArgumentException("Cannot override a component which is implemented by this grain context");
}
if (instance == null)
{
_components?.Remove(typeof(TComponent));
return;
}
if (_components is null) _components = new Dictionary<Type, object>();
_components[typeof(TComponent)] = instance;
}
public HashSet<ActivationId> RunningRequestsSenders { get; } = new HashSet<ActivationId>();
internal void SetGrainInstance(Grain grainInstance)
{
GrainInstance = grainInstance;
}
private Streams.StreamDirectory streamDirectory;
internal Streams.StreamDirectory GetStreamDirectory()
{
return streamDirectory ?? (streamDirectory = new Streams.StreamDirectory());
}
internal bool IsUsingStreams
{
get { return streamDirectory != null; }
}
internal async Task DeactivateStreamResources()
{
if (streamDirectory == null) return; // No streams - Nothing to do.
if (_components == null) return; // No installed extensions - Nothing to do.
if (StreamResourceTestControl.TestOnlySuppressStreamCleanupOnDeactivate)
{
logger.Warn(0, "Suppressing cleanup of stream resources during tests for {0}", this);
return;
}
await streamDirectory.Cleanup(true, false);
}
public IAddressable GrainInstance { get; private set; }
public ActivationId ActivationId { get { return Address.Activation; } }
public ActivationAddress Address { get; private set; }
public IServiceProvider ServiceProvider => this.serviceScope?.ServiceProvider;
private readonly GrainLifecycle lifecycle;
public IGrainLifecycle ObservableLifecycle => lifecycle;
internal ILifecycleObserver Lifecycle => lifecycle;
public void OnTimerCreated(IGrainTimer timer)
{
AddTimer(timer);
}
public GrainReference GrainReference { get; }
public SiloAddress Silo { get { return Address.Silo; } }
public GrainId GrainId { get { return Address.Grain; } }
public ActivationState State { get; private set; }
public void SetState(ActivationState state)
{
State = state;
}
// Don't accept any new messages and stop all timers.
public void PrepareForDeactivation()
{
SetState(ActivationState.Deactivating);
deactivationStartTime = DateTime.UtcNow;
if (!IsCurrentlyExecuting)
StopAllTimers();
}
/// <summary>
/// If State == Invalid, this may contain a forwarding address for incoming messages
/// </summary>
public ActivationAddress ForwardingAddress { get; set; }
private IActivationCollector collector;
internal bool IsExemptFromCollection
{
get { return collector == null; }
}
public DateTime CollectionTicket { get; private set; }
private bool collectionCancelledFlag;
public bool TrySetCollectionCancelledFlag()
{
lock (this)
{
if (default(DateTime) == CollectionTicket || collectionCancelledFlag) return false;
collectionCancelledFlag = true;
return true;
}
}
public void ResetCollectionCancelledFlag()
{
lock (this)
{
collectionCancelledFlag = false;
}
}
public void ResetCollectionTicket()
{
CollectionTicket = default(DateTime);
}
public void SetCollectionTicket(DateTime ticket)
{
if (ticket == default(DateTime)) throw new ArgumentException("default(DateTime) is disallowed", "ticket");
if (CollectionTicket != default(DateTime))
{
throw new InvalidOperationException("call ResetCollectionTicket before calling SetCollectionTicket.");
}
CollectionTicket = ticket;
}
public PlacementStrategy PlacedUsing { get; private set; }
// Currently, the only supported multi-activation grain is one using the StatelessWorkerPlacement strategy.
internal bool IsStatelessWorker => this.PlacedUsing is StatelessWorkerPlacement;
/// <summary>
/// Returns a value indicating whether or not this placement strategy requires activations to be registered in
/// the grain directory.
/// </summary>
internal bool IsUsingGrainDirectory => this.PlacedUsing.IsUsingGrainDirectory;
public Message Blocking { get; private set; }
// the number of requests that are currently executing on this activation.
// includes reentrant and non-reentrant requests.
private int numRunning;
private DateTime currentRequestStartTime;
private DateTime becameIdle;
private DateTime deactivationStartTime;
public void RecordRunning(Message message, bool isInterleavable)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning++;
if (message.Direction != Message.Directions.OneWay
&& !(message.SendingActivation is null)
&& !message.SendingGrain.IsClient())
{
RunningRequestsSenders.Add(message.SendingActivation);
}
if (this.Blocking != null || isInterleavable) return;
// This logic only works for non-reentrant activations
// Consider: Handle long request detection for reentrant activations.
this.Blocking = message;
currentRequestStartTime = DateTime.UtcNow;
}
public void ResetRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning--;
RunningRequestsSenders.Remove(message.SendingActivation);
if (numRunning == 0)
{
becameIdle = DateTime.UtcNow;
if (!IsExemptFromCollection)
{
collector.TryRescheduleCollection(this);
}
}
// The below logic only works for non-reentrant activations.
if (this.Blocking != null && !message.Equals(this.Blocking)) return;
this.Blocking = null;
currentRequestStartTime = DateTime.MinValue;
}
private long inFlightCount;
private long enqueuedOnDispatcherCount;
/// <summary>
/// Number of messages that are actively being processed [as opposed to being in the Waiting queue].
/// In most cases this will be 0 or 1, but for Reentrant grains can be >1.
/// </summary>
public long InFlightCount { get { return Interlocked.Read(ref inFlightCount); } }
/// <summary>
/// Number of messages that are being received [as opposed to being in the scheduler queue or actively processed].
/// </summary>
public long EnqueuedOnDispatcherCount { get { return Interlocked.Read(ref enqueuedOnDispatcherCount); } }
/// <summary>Increment the number of in-flight messages currently being processed.</summary>
public void IncrementInFlightCount() { Interlocked.Increment(ref inFlightCount); }
/// <summary>Decrement the number of in-flight messages currently being processed.</summary>
public void DecrementInFlightCount() { Interlocked.Decrement(ref inFlightCount); }
/// <summary>Increment the number of messages currently in the process of being received.</summary>
public void IncrementEnqueuedOnDispatcherCount() { Interlocked.Increment(ref enqueuedOnDispatcherCount); }
/// <summary>Decrement the number of messages currently in the process of being received.</summary>
public void DecrementEnqueuedOnDispatcherCount() { Interlocked.Decrement(ref enqueuedOnDispatcherCount); }
/// <summary>
/// grouped by sending activation: responses first, then sorted by id
/// </summary>
private List<Message> waiting;
public int WaitingCount
{
get
{
return waiting == null ? 0 : waiting.Count;
}
}
public enum EnqueueMessageResult
{
Success,
ErrorInvalidActivation,
ErrorStuckActivation,
ErrorActivateFailed,
}
/// <summary>
/// Insert in a FIFO order
/// </summary>
/// <param name="message"></param>
public EnqueueMessageResult EnqueueMessage(Message message)
{
lock (this)
{
if (State == ActivationState.Invalid)
{
logger.Warn(ErrorCode.Dispatcher_InvalidActivation,
"Cannot enqueue message to invalid activation {0} : {1}", this.ToDetailedString(), message);
return EnqueueMessageResult.ErrorInvalidActivation;
}
if (State == ActivationState.FailedToActivate)
{
logger.Warn(ErrorCode.Dispatcher_InvalidActivation,
"Cannot enqueue message to activation that failed in OnActivate {0} : {1}", this.ToDetailedString(), message);
return EnqueueMessageResult.ErrorActivateFailed;
}
if (State == ActivationState.Deactivating)
{
var deactivatingTime = DateTime.UtcNow - deactivationStartTime;
if (deactivatingTime > maxRequestProcessingTime)
{
logger.Error(ErrorCode.Dispatcher_StuckActivation,
$"Current activation {ToDetailedString()} marked as Deactivating for {deactivatingTime}. Trying to enqueue {message}.");
return EnqueueMessageResult.ErrorStuckActivation;
}
}
if (this.Blocking != null)
{
var currentRequestActiveTime = DateTime.UtcNow - currentRequestStartTime;
if (currentRequestActiveTime > maxRequestProcessingTime)
{
logger.Error(ErrorCode.Dispatcher_StuckActivation,
$"Current request has been active for {currentRequestActiveTime} for activation {ToDetailedString()}. Currently executing {this.Blocking}. Trying to enqueue {message}.");
return EnqueueMessageResult.ErrorStuckActivation;
}
// Consider: Handle long request detection for reentrant activations -- this logic only works for non-reentrant activations
else if (currentRequestActiveTime > maxWarningRequestProcessingTime)
{
logger.Warn(ErrorCode.Dispatcher_ExtendedMessageProcessing,
"Current request has been active for {0} for activation {1}. Currently executing {2}. Trying to enqueue {3}.",
currentRequestActiveTime, this.ToDetailedString(), this.Blocking, message);
}
}
waiting = waiting ?? new List<Message>();
waiting.Add(message);
return EnqueueMessageResult.Success;
}
}
/// <summary>
/// Check whether this activation is overloaded.
/// Returns LimitExceededException if overloaded, otherwise <c>null</c>c>
/// </summary>
/// <param name="log">Logger to use for reporting any overflow condition</param>
/// <returns>Returns LimitExceededException if overloaded, otherwise <c>null</c>c></returns>
public LimitExceededException CheckOverloaded(ILogger log)
{
string limitName = LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS;
int maxRequestsHardLimit = this.messagingOptions.MaxEnqueuedRequestsHardLimit;
int maxRequestsSoftLimit = this.messagingOptions.MaxEnqueuedRequestsSoftLimit;
if (IsStatelessWorker)
{
limitName = LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER;
maxRequestsHardLimit = this.messagingOptions.MaxEnqueuedRequestsHardLimit_StatelessWorker;
maxRequestsSoftLimit = this.messagingOptions.MaxEnqueuedRequestsSoftLimit_StatelessWorker;
}
if (maxRequestsHardLimit <= 0 && maxRequestsSoftLimit <= 0) return null; // No limits are set
int count = GetRequestCount();
if (maxRequestsHardLimit > 0 && count > maxRequestsHardLimit) // Hard limit
{
log.Warn(ErrorCode.Catalog_Reject_ActivationTooManyRequests,
String.Format("Overload - {0} enqueued requests for activation {1}, exceeding hard limit rejection threshold of {2}",
count, this, maxRequestsHardLimit));
return new LimitExceededException(limitName, count, maxRequestsHardLimit, this.ToString());
}
if (maxRequestsSoftLimit > 0 && count > maxRequestsSoftLimit) // Soft limit
{
log.Warn(ErrorCode.Catalog_Warn_ActivationTooManyRequests,
String.Format("Hot - {0} enqueued requests for activation {1}, exceeding soft limit warning threshold of {2}",
count, this, maxRequestsSoftLimit));
return null;
}
return null;
}
internal int GetRequestCount()
{
lock (this)
{
long numInDispatcher = EnqueuedOnDispatcherCount;
long numActive = InFlightCount;
long numWaiting = WaitingCount;
return (int)(numInDispatcher + numActive + numWaiting);
}
}
public Message PeekNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0) return waiting[0];
return null;
}
public void DequeueNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0)
waiting.RemoveAt(0);
}
internal List<Message> DequeueAllWaitingMessages()
{
lock (this)
{
if (waiting == null) return null;
List<Message> tmp = waiting;
waiting = null;
return tmp;
}
}
public bool IsInactive
{
get
{
return !IsCurrentlyExecuting && (waiting == null || waiting.Count == 0);
}
}
public bool IsCurrentlyExecuting
{
get
{
return numRunning > 0 ;
}
}
/// <summary>
/// Returns how long this activation has been idle.
/// </summary>
public TimeSpan GetIdleness(DateTime now)
{
if (now == default(DateTime))
throw new ArgumentException("default(DateTime) is not allowed; Use DateTime.UtcNow instead.", "now");
return now - becameIdle;
}
/// <summary>
/// Returns whether this activation has been idle long enough to be collected.
/// </summary>
public bool IsStale(DateTime now)
{
return GetIdleness(now) >= CollectionAgeLimit;
}
private DateTime keepAliveUntil;
public bool ShouldBeKeptAlive { get { return keepAliveUntil >= DateTime.UtcNow; } }
public void DelayDeactivation(TimeSpan timespan)
{
if (timespan <= TimeSpan.Zero)
{
// reset any current keepAliveUntill
ResetKeepAliveRequest();
}
else if (timespan == TimeSpan.MaxValue)
{
// otherwise creates negative time.
keepAliveUntil = DateTime.MaxValue;
}
else
{
keepAliveUntil = DateTime.UtcNow + timespan;
}
}
public void ResetKeepAliveRequest()
{
keepAliveUntil = DateTime.MinValue;
}
public List<Action> OnInactive { get; set; } // ActivationData
public void AddOnInactive(Action action) // ActivationData
{
lock (this)
{
if (OnInactive == null)
{
OnInactive = new List<Action>();
}
OnInactive.Add(action);
if (!IsCurrentlyExecuting)
{
RunOnInactive();
}
}
}
public void RunOnInactive()
{
lock (this)
{
if (OnInactive == null) return;
var actions = OnInactive;
OnInactive = null;
foreach (var action in actions)
{
action();
}
}
}
internal void AddTimer(IGrainTimer timer)
{
lock(this)
{
if (timers == null)
{
timers = new HashSet<IGrainTimer>();
}
timers.Add(timer);
}
}
private void StopAllTimers()
{
lock (this)
{
if (timers == null) return;
foreach (var timer in timers)
{
timer.Stop();
}
}
}
public void OnTimerDisposed(IGrainTimer orleansTimerInsideGrain)
{
lock (this) // need to lock since dispose can be called on finalizer thread, outside grain context (not single threaded).
{
timers.Remove(orleansTimerInsideGrain);
}
}
internal Task WaitForAllTimersToFinish()
{
lock(this)
{
if (timers == null)
{
return Task.CompletedTask;
}
var tasks = new List<Task>();
var timerCopy = timers.ToList(); // need to copy since OnTimerDisposed will change the timers set.
foreach (var timer in timerCopy)
{
// first call dispose, then wait to finish.
Utils.SafeExecute(timer.Dispose, logger, "timer.Dispose has thrown");
tasks.Add(timer.GetCurrentlyExecutingTickTask());
}
return Task.WhenAll(tasks);
}
}
public string DumpStatus()
{
var sb = new StringBuilder();
lock (this)
{
sb.AppendFormat(" {0}", ToDetailedString());
if (this.Blocking != null)
{
sb.AppendFormat(" Processing message: {0}", this.Blocking);
}
if (waiting!=null && waiting.Count > 0)
{
sb.AppendFormat(" Messages queued within ActivationData: {0}", PrintWaitingQueue());
}
}
return sb.ToString();
}
public override string ToString()
{
return String.Format("[Activation: {0}{1}{2}{3} State={4}]",
Silo,
this.GrainId,
this.ActivationId,
GetActivationInfoString(),
State);
}
internal string ToDetailedString(bool includeExtraDetails = false)
{
return
String.Format(
"[Activation: {0}{1}{2} {3} State={4} NonReentrancyQueueSize={5} EnqueuedOnDispatcher={6} InFlightCount={7} NumRunning={8} IdlenessTimeSpan={9} CollectionAgeLimit={10}{11}]",
Silo.ToLongString(),
this.GrainId.ToString(),
this.ActivationId,
GetActivationInfoString(),
State, // 4
WaitingCount, // 5 NonReentrancyQueueSize
EnqueuedOnDispatcherCount, // 6 EnqueuedOnDispatcher
InFlightCount, // 7 InFlightCount
numRunning, // 8 NumRunning
GetIdleness(DateTime.UtcNow), // 9 IdlenessTimeSpan
CollectionAgeLimit, // 10 CollectionAgeLimit
(includeExtraDetails && this.Blocking != null) ? " CurrentlyExecuting=" + this.Blocking : ""); // 11: Running
}
public string Name
{
get
{
return String.Format("[Activation: {0}{1}{2}{3}]",
Silo,
this.GrainId,
this.ActivationId,
GetActivationInfoString());
}
}
/// <summary>
/// Return string containing dump of the queue of waiting work items
/// </summary>
/// <returns></returns>
/// <remarks>Note: Caller must be holding lock on this activation while calling this method.</remarks>
internal string PrintWaitingQueue()
{
return Utils.EnumerableToString(waiting);
}
private string GetActivationInfoString()
{
var placement = PlacedUsing != null ? PlacedUsing.GetType().Name : String.Empty;
return GrainInstance is null ? placement : $"#GrainType={GrainInstance.GetType().FullName} Placement={placement}";
}
public async ValueTask DisposeAsync()
{
var activator = this.GetComponent<IGrainActivator>();
if (activator != null)
{
await activator.DisposeInstance(this, this.GrainInstance);
}
switch (this.serviceScope)
{
case IAsyncDisposable asyncDisposable:
await asyncDisposable.DisposeAsync();
break;
case IDisposable disposable:
disposable.Dispose();
break;
}
}
bool IEquatable<IGrainContext>.Equals(IGrainContext other) => ReferenceEquals(this, other);
public (TExtension, TExtensionInterface) GetOrSetExtension<TExtension, TExtensionInterface>(Func<TExtension> newExtensionFunc)
where TExtension : TExtensionInterface
where TExtensionInterface : IGrainExtension
{
TExtension implementation;
if (this.GetComponent<TExtensionInterface>() is object existing)
{
if (existing is TExtension typedResult)
{
implementation = typedResult;
}
else
{
throw new InvalidCastException($"Cannot cast existing extension of type {existing.GetType()} to target type {typeof(TExtension)}");
}
}
else
{
implementation = newExtensionFunc();
this.SetComponent<TExtensionInterface>(implementation);
}
var reference = this.GrainReference.Cast<TExtensionInterface>();
return (implementation, reference);
}
public TExtensionInterface GetExtension<TExtensionInterface>()
where TExtensionInterface : IGrainExtension
{
if (this.GetComponent<TExtensionInterface>() is TExtensionInterface result)
{
return result;
}
var implementation = this.ActivationServices.GetServiceByKey<Type, IGrainExtension>(typeof(TExtensionInterface));
if (!(implementation is TExtensionInterface typedResult))
{
throw new GrainExtensionNotInstalledException($"No extension of type {typeof(TExtensionInterface)} is installed on this instance and no implementations are registered for automated install");
}
this.SetComponent<TExtensionInterface>(typedResult);
return typedResult;
}
}
internal static class StreamResourceTestControl
{
internal static bool TestOnlySuppressStreamCleanupOnDeactivate;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/bytestream/bytestream.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Bytestream {
/// <summary>Holder for reflection information generated from google/bytestream/bytestream.proto</summary>
public static partial class BytestreamReflection {
#region Descriptor
/// <summary>File descriptor for google/bytestream/bytestream.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static BytestreamReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiJnb29nbGUvYnl0ZXN0cmVhbS9ieXRlc3RyZWFtLnByb3RvEhFnb29nbGUu",
"Ynl0ZXN0cmVhbRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxoeZ29v",
"Z2xlL3Byb3RvYnVmL3dyYXBwZXJzLnByb3RvIk0KC1JlYWRSZXF1ZXN0EhUK",
"DXJlc291cmNlX25hbWUYASABKAkSEwoLcmVhZF9vZmZzZXQYAiABKAMSEgoK",
"cmVhZF9saW1pdBgDIAEoAyIcCgxSZWFkUmVzcG9uc2USDAoEZGF0YRgKIAEo",
"DCJfCgxXcml0ZVJlcXVlc3QSFQoNcmVzb3VyY2VfbmFtZRgBIAEoCRIUCgx3",
"cml0ZV9vZmZzZXQYAiABKAMSFAoMZmluaXNoX3dyaXRlGAMgASgIEgwKBGRh",
"dGEYCiABKAwiJwoNV3JpdGVSZXNwb25zZRIWCg5jb21taXR0ZWRfc2l6ZRgB",
"IAEoAyIwChdRdWVyeVdyaXRlU3RhdHVzUmVxdWVzdBIVCg1yZXNvdXJjZV9u",
"YW1lGAEgASgJIkQKGFF1ZXJ5V3JpdGVTdGF0dXNSZXNwb25zZRIWCg5jb21t",
"aXR0ZWRfc2l6ZRgBIAEoAxIQCghjb21wbGV0ZRgCIAEoCDKSAgoKQnl0ZVN0",
"cmVhbRJJCgRSZWFkEh4uZ29vZ2xlLmJ5dGVzdHJlYW0uUmVhZFJlcXVlc3Qa",
"Hy5nb29nbGUuYnl0ZXN0cmVhbS5SZWFkUmVzcG9uc2UwARJMCgVXcml0ZRIf",
"Lmdvb2dsZS5ieXRlc3RyZWFtLldyaXRlUmVxdWVzdBogLmdvb2dsZS5ieXRl",
"c3RyZWFtLldyaXRlUmVzcG9uc2UoARJrChBRdWVyeVdyaXRlU3RhdHVzEiou",
"Z29vZ2xlLmJ5dGVzdHJlYW0uUXVlcnlXcml0ZVN0YXR1c1JlcXVlc3QaKy5n",
"b29nbGUuYnl0ZXN0cmVhbS5RdWVyeVdyaXRlU3RhdHVzUmVzcG9uc2VCZQoV",
"Y29tLmdvb2dsZS5ieXRlc3RyZWFtQg9CeXRlU3RyZWFtUHJvdG9aO2dvb2ds",
"ZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvYnl0ZXN0cmVhbTti",
"eXRlc3RyZWFtYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bytestream.ReadRequest), global::Google.Bytestream.ReadRequest.Parser, new[]{ "ResourceName", "ReadOffset", "ReadLimit" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bytestream.ReadResponse), global::Google.Bytestream.ReadResponse.Parser, new[]{ "Data" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bytestream.WriteRequest), global::Google.Bytestream.WriteRequest.Parser, new[]{ "ResourceName", "WriteOffset", "FinishWrite", "Data" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bytestream.WriteResponse), global::Google.Bytestream.WriteResponse.Parser, new[]{ "CommittedSize" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bytestream.QueryWriteStatusRequest), global::Google.Bytestream.QueryWriteStatusRequest.Parser, new[]{ "ResourceName" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bytestream.QueryWriteStatusResponse), global::Google.Bytestream.QueryWriteStatusResponse.Parser, new[]{ "CommittedSize", "Complete" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Request object for ByteStream.Read.
/// </summary>
public sealed partial class ReadRequest : pb::IMessage<ReadRequest> {
private static readonly pb::MessageParser<ReadRequest> _parser = new pb::MessageParser<ReadRequest>(() => new ReadRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReadRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Bytestream.BytestreamReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadRequest(ReadRequest other) : this() {
resourceName_ = other.resourceName_;
readOffset_ = other.readOffset_;
readLimit_ = other.readLimit_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadRequest Clone() {
return new ReadRequest(this);
}
/// <summary>Field number for the "resource_name" field.</summary>
public const int ResourceNameFieldNumber = 1;
private string resourceName_ = "";
/// <summary>
/// The name of the resource to read.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ResourceName {
get { return resourceName_; }
set {
resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "read_offset" field.</summary>
public const int ReadOffsetFieldNumber = 2;
private long readOffset_;
/// <summary>
/// The offset for the first byte to return in the read, relative to the start
/// of the resource.
///
/// A `read_offset` that is negative or greater than the size of the resource
/// will cause an `OUT_OF_RANGE` error.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long ReadOffset {
get { return readOffset_; }
set {
readOffset_ = value;
}
}
/// <summary>Field number for the "read_limit" field.</summary>
public const int ReadLimitFieldNumber = 3;
private long readLimit_;
/// <summary>
/// The maximum number of `data` bytes the server is allowed to return in the
/// sum of all `ReadResponse` messages. A `read_limit` of zero indicates that
/// there is no limit, and a negative `read_limit` will cause an error.
///
/// If the stream returns fewer bytes than allowed by the `read_limit` and no
/// error occurred, the stream includes all data from the `read_offset` to the
/// end of the resource.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long ReadLimit {
get { return readLimit_; }
set {
readLimit_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReadRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReadRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ResourceName != other.ResourceName) return false;
if (ReadOffset != other.ReadOffset) return false;
if (ReadLimit != other.ReadLimit) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode();
if (ReadOffset != 0L) hash ^= ReadOffset.GetHashCode();
if (ReadLimit != 0L) hash ^= ReadLimit.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ResourceName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ResourceName);
}
if (ReadOffset != 0L) {
output.WriteRawTag(16);
output.WriteInt64(ReadOffset);
}
if (ReadLimit != 0L) {
output.WriteRawTag(24);
output.WriteInt64(ReadLimit);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ResourceName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName);
}
if (ReadOffset != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(ReadOffset);
}
if (ReadLimit != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(ReadLimit);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReadRequest other) {
if (other == null) {
return;
}
if (other.ResourceName.Length != 0) {
ResourceName = other.ResourceName;
}
if (other.ReadOffset != 0L) {
ReadOffset = other.ReadOffset;
}
if (other.ReadLimit != 0L) {
ReadLimit = other.ReadLimit;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ResourceName = input.ReadString();
break;
}
case 16: {
ReadOffset = input.ReadInt64();
break;
}
case 24: {
ReadLimit = input.ReadInt64();
break;
}
}
}
}
}
/// <summary>
/// Response object for ByteStream.Read.
/// </summary>
public sealed partial class ReadResponse : pb::IMessage<ReadResponse> {
private static readonly pb::MessageParser<ReadResponse> _parser = new pb::MessageParser<ReadResponse>(() => new ReadResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReadResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Bytestream.BytestreamReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadResponse(ReadResponse other) : this() {
data_ = other.data_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReadResponse Clone() {
return new ReadResponse(this);
}
/// <summary>Field number for the "data" field.</summary>
public const int DataFieldNumber = 10;
private pb::ByteString data_ = pb::ByteString.Empty;
/// <summary>
/// A portion of the data for the resource. The service **may** leave `data`
/// empty for any given `ReadResponse`. This enables the service to inform the
/// client that the request is still live while it is running an operation to
/// generate more data.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Data {
get { return data_; }
set {
data_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReadResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReadResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Data != other.Data) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Data.Length != 0) hash ^= Data.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Data.Length != 0) {
output.WriteRawTag(82);
output.WriteBytes(Data);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Data.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReadResponse other) {
if (other == null) {
return;
}
if (other.Data.Length != 0) {
Data = other.Data;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 82: {
Data = input.ReadBytes();
break;
}
}
}
}
}
/// <summary>
/// Request object for ByteStream.Write.
/// </summary>
public sealed partial class WriteRequest : pb::IMessage<WriteRequest> {
private static readonly pb::MessageParser<WriteRequest> _parser = new pb::MessageParser<WriteRequest>(() => new WriteRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<WriteRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Bytestream.BytestreamReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public WriteRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public WriteRequest(WriteRequest other) : this() {
resourceName_ = other.resourceName_;
writeOffset_ = other.writeOffset_;
finishWrite_ = other.finishWrite_;
data_ = other.data_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public WriteRequest Clone() {
return new WriteRequest(this);
}
/// <summary>Field number for the "resource_name" field.</summary>
public const int ResourceNameFieldNumber = 1;
private string resourceName_ = "";
/// <summary>
/// The name of the resource to write. This **must** be set on the first
/// `WriteRequest` of each `Write()` action. If it is set on subsequent calls,
/// it **must** match the value of the first request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ResourceName {
get { return resourceName_; }
set {
resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "write_offset" field.</summary>
public const int WriteOffsetFieldNumber = 2;
private long writeOffset_;
/// <summary>
/// The offset from the beginning of the resource at which the data should be
/// written. It is required on all `WriteRequest`s.
///
/// In the first `WriteRequest` of a `Write()` action, it indicates
/// the initial offset for the `Write()` call. The value **must** be equal to
/// the `committed_size` that a call to `QueryWriteStatus()` would return.
///
/// On subsequent calls, this value **must** be set and **must** be equal to
/// the sum of the first `write_offset` and the sizes of all `data` bundles
/// sent previously on this stream.
///
/// An incorrect value will cause an error.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long WriteOffset {
get { return writeOffset_; }
set {
writeOffset_ = value;
}
}
/// <summary>Field number for the "finish_write" field.</summary>
public const int FinishWriteFieldNumber = 3;
private bool finishWrite_;
/// <summary>
/// If `true`, this indicates that the write is complete. Sending any
/// `WriteRequest`s subsequent to one in which `finish_write` is `true` will
/// cause an error.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool FinishWrite {
get { return finishWrite_; }
set {
finishWrite_ = value;
}
}
/// <summary>Field number for the "data" field.</summary>
public const int DataFieldNumber = 10;
private pb::ByteString data_ = pb::ByteString.Empty;
/// <summary>
/// A portion of the data for the resource. The client **may** leave `data`
/// empty for any given `WriteRequest`. This enables the client to inform the
/// service that the request is still live while it is running an operation to
/// generate more data.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Data {
get { return data_; }
set {
data_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as WriteRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(WriteRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ResourceName != other.ResourceName) return false;
if (WriteOffset != other.WriteOffset) return false;
if (FinishWrite != other.FinishWrite) return false;
if (Data != other.Data) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode();
if (WriteOffset != 0L) hash ^= WriteOffset.GetHashCode();
if (FinishWrite != false) hash ^= FinishWrite.GetHashCode();
if (Data.Length != 0) hash ^= Data.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ResourceName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ResourceName);
}
if (WriteOffset != 0L) {
output.WriteRawTag(16);
output.WriteInt64(WriteOffset);
}
if (FinishWrite != false) {
output.WriteRawTag(24);
output.WriteBool(FinishWrite);
}
if (Data.Length != 0) {
output.WriteRawTag(82);
output.WriteBytes(Data);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ResourceName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName);
}
if (WriteOffset != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(WriteOffset);
}
if (FinishWrite != false) {
size += 1 + 1;
}
if (Data.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(WriteRequest other) {
if (other == null) {
return;
}
if (other.ResourceName.Length != 0) {
ResourceName = other.ResourceName;
}
if (other.WriteOffset != 0L) {
WriteOffset = other.WriteOffset;
}
if (other.FinishWrite != false) {
FinishWrite = other.FinishWrite;
}
if (other.Data.Length != 0) {
Data = other.Data;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ResourceName = input.ReadString();
break;
}
case 16: {
WriteOffset = input.ReadInt64();
break;
}
case 24: {
FinishWrite = input.ReadBool();
break;
}
case 82: {
Data = input.ReadBytes();
break;
}
}
}
}
}
/// <summary>
/// Response object for ByteStream.Write.
/// </summary>
public sealed partial class WriteResponse : pb::IMessage<WriteResponse> {
private static readonly pb::MessageParser<WriteResponse> _parser = new pb::MessageParser<WriteResponse>(() => new WriteResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<WriteResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Bytestream.BytestreamReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public WriteResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public WriteResponse(WriteResponse other) : this() {
committedSize_ = other.committedSize_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public WriteResponse Clone() {
return new WriteResponse(this);
}
/// <summary>Field number for the "committed_size" field.</summary>
public const int CommittedSizeFieldNumber = 1;
private long committedSize_;
/// <summary>
/// The number of bytes that have been processed for the given resource.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long CommittedSize {
get { return committedSize_; }
set {
committedSize_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as WriteResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(WriteResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (CommittedSize != other.CommittedSize) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (CommittedSize != 0L) hash ^= CommittedSize.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (CommittedSize != 0L) {
output.WriteRawTag(8);
output.WriteInt64(CommittedSize);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (CommittedSize != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(CommittedSize);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(WriteResponse other) {
if (other == null) {
return;
}
if (other.CommittedSize != 0L) {
CommittedSize = other.CommittedSize;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
CommittedSize = input.ReadInt64();
break;
}
}
}
}
}
/// <summary>
/// Request object for ByteStream.QueryWriteStatus.
/// </summary>
public sealed partial class QueryWriteStatusRequest : pb::IMessage<QueryWriteStatusRequest> {
private static readonly pb::MessageParser<QueryWriteStatusRequest> _parser = new pb::MessageParser<QueryWriteStatusRequest>(() => new QueryWriteStatusRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<QueryWriteStatusRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Bytestream.BytestreamReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryWriteStatusRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryWriteStatusRequest(QueryWriteStatusRequest other) : this() {
resourceName_ = other.resourceName_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryWriteStatusRequest Clone() {
return new QueryWriteStatusRequest(this);
}
/// <summary>Field number for the "resource_name" field.</summary>
public const int ResourceNameFieldNumber = 1;
private string resourceName_ = "";
/// <summary>
/// The name of the resource whose write status is being requested.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ResourceName {
get { return resourceName_; }
set {
resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as QueryWriteStatusRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(QueryWriteStatusRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ResourceName != other.ResourceName) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ResourceName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ResourceName);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ResourceName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(QueryWriteStatusRequest other) {
if (other == null) {
return;
}
if (other.ResourceName.Length != 0) {
ResourceName = other.ResourceName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ResourceName = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Response object for ByteStream.QueryWriteStatus.
/// </summary>
public sealed partial class QueryWriteStatusResponse : pb::IMessage<QueryWriteStatusResponse> {
private static readonly pb::MessageParser<QueryWriteStatusResponse> _parser = new pb::MessageParser<QueryWriteStatusResponse>(() => new QueryWriteStatusResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<QueryWriteStatusResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Bytestream.BytestreamReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryWriteStatusResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryWriteStatusResponse(QueryWriteStatusResponse other) : this() {
committedSize_ = other.committedSize_;
complete_ = other.complete_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryWriteStatusResponse Clone() {
return new QueryWriteStatusResponse(this);
}
/// <summary>Field number for the "committed_size" field.</summary>
public const int CommittedSizeFieldNumber = 1;
private long committedSize_;
/// <summary>
/// The number of bytes that have been processed for the given resource.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long CommittedSize {
get { return committedSize_; }
set {
committedSize_ = value;
}
}
/// <summary>Field number for the "complete" field.</summary>
public const int CompleteFieldNumber = 2;
private bool complete_;
/// <summary>
/// `complete` is `true` only if the client has sent a `WriteRequest` with
/// `finish_write` set to true, and the server has processed that request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Complete {
get { return complete_; }
set {
complete_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as QueryWriteStatusResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(QueryWriteStatusResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (CommittedSize != other.CommittedSize) return false;
if (Complete != other.Complete) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (CommittedSize != 0L) hash ^= CommittedSize.GetHashCode();
if (Complete != false) hash ^= Complete.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (CommittedSize != 0L) {
output.WriteRawTag(8);
output.WriteInt64(CommittedSize);
}
if (Complete != false) {
output.WriteRawTag(16);
output.WriteBool(Complete);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (CommittedSize != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(CommittedSize);
}
if (Complete != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(QueryWriteStatusResponse other) {
if (other == null) {
return;
}
if (other.CommittedSize != 0L) {
CommittedSize = other.CommittedSize;
}
if (other.Complete != false) {
Complete = other.Complete;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
CommittedSize = input.ReadInt64();
break;
}
case 16: {
Complete = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Abstract;
using System.Globalization;
using Microsoft.Practices.SharePoint.Common.Logging;
using Microsoft.SharePoint.Administration;
namespace Contoso.Abstract
{
/// <summary>
/// ISPDeveloperServiceLog
/// </summary>
public interface ISPDeveloperServiceLog : IServiceLog
{
/// <summary>
/// Gets the log.
/// </summary>
ILogger Log { get; }
/// <summary>
/// Gets the event ID.
/// </summary>
int EventID { get; }
/// <summary>
/// Gets the name of the area.
/// </summary>
/// <value>
/// The name of the area.
/// </value>
string AreaName { get; }
/// <summary>
/// Gets the category.
/// </summary>
string Category { get; }
}
/// <summary>
/// SPDeveloperServiceLog
/// </summary>
public class SPDeveloperServiceLog : ISPDeveloperServiceLog, ServiceLogManager.ISetupRegistration
{
static SPDeveloperServiceLog() { ServiceLogManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
public SPDeveloperServiceLog()
: this(new SharePointLogger(), 0, "SharePoint Foundation", "General") { }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
/// <param name="areaName">Name of the area.</param>
/// <param name="category">The category.</param>
public SPDeveloperServiceLog(string areaName, string category)
: this(new SharePointLogger(), 0, areaName, category) { }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
/// <param name="eventID">The event ID.</param>
public SPDeveloperServiceLog(int eventID)
: this(new SharePointLogger(), eventID, "SharePoint Foundation", "General") { }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
/// <param name="eventID">The event ID.</param>
/// <param name="areaName">Name of the area.</param>
/// <param name="category">The category.</param>
public SPDeveloperServiceLog(int eventID, string areaName, string category)
: this(new SharePointLogger(), eventID, areaName, category) { }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
/// <param name="log">The log.</param>
/// <param name="eventID">The event ID.</param>
/// <param name="areaName">Name of the area.</param>
/// <param name="category">The category.</param>
public SPDeveloperServiceLog(ILogger log, int eventID, string areaName, string category)
{
if (log == null)
throw new ArgumentNullException("log");
if (string.IsNullOrEmpty(areaName))
throw new ArgumentNullException("areaName");
if (string.IsNullOrEmpty(category))
throw new ArgumentNullException("category");
Log = log;
EventID = eventID;
AreaName = areaName;
Category = category;
}
Action<IServiceLocator, string> ServiceLogManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceLogManager.RegisterInstance<ISPDeveloperServiceLog>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.
/// -or-
/// null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { throw new NotImplementedException(); }
// get
/// <summary>
/// Gets the name.
/// </summary>
public string Name
{
get { return AreaName + "/" + Category; }
}
/// <summary>
/// Gets the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public IServiceLog Get(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
return new SPServiceLog(Log, EventID, AreaName, Name);
}
/// <summary>
/// Gets the specified name.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public IServiceLog Get(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return new SPServiceLog(Log, EventID, AreaName, type.Name);
}
// log
/// <summary>
/// Writes the specified level.
/// </summary>
/// <param name="level">The level.</param>
/// <param name="ex">The ex.</param>
/// <param name="s">The s.</param>
public void Write(ServiceLogLevel level, Exception ex, string s)
{
if (Log == null)
throw new NullReferenceException("Log");
if (ex == null)
switch (level)
{
case ServiceLogLevel.Fatal: Log.TraceToDeveloper(s, EventID, TraceSeverity.Unexpected, Name); return;
case ServiceLogLevel.Error: Log.TraceToDeveloper(s, EventID, TraceSeverity.High, Name); return;
case ServiceLogLevel.Warning: Log.TraceToDeveloper(s, EventID, TraceSeverity.Medium, Name); return;
case ServiceLogLevel.Information: Log.TraceToDeveloper(s, EventID, TraceSeverity.Monitorable, Name); return;
case ServiceLogLevel.Debug: Log.TraceToDeveloper(s, EventID, TraceSeverity.Verbose, Name); return;
default: return;
}
else
switch (level)
{
case ServiceLogLevel.Fatal: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.Unexpected, Name); return;
case ServiceLogLevel.Error: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.High, Name); return;
case ServiceLogLevel.Warning: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.Medium, Name); return;
case ServiceLogLevel.Information: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.Monitorable, Name); return;
case ServiceLogLevel.Debug: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.Verbose, Name); return;
default: return;
}
}
#region Domain-specific
/// <summary>
/// Gets the log.
/// </summary>
public ILogger Log { get; private set; }
/// <summary>
/// Gets the event ID.
/// </summary>
public int EventID { get; private set; }
/// <summary>
/// Gets the name of the area.
/// </summary>
/// <value>
/// The name of the area.
/// </value>
public string AreaName { get; private set; }
/// <summary>
/// Gets the category.
/// </summary>
public string Category { get; private set; }
#endregion
}
}
| |
namespace Pantry
{
partial class ThePantryView
{
/// <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()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.treeResources = new System.Windows.Forms.TreeView();
this.comboPackage = new System.Windows.Forms.ComboBox();
this.gridItem = new System.Windows.Forms.PropertyGrid();
this.glToolStrip = new System.Windows.Forms.ToolStripContainer();
this.gCenter = new System.Windows.Forms.CheckBox();
this.trackGridV = new System.Windows.Forms.TrackBar();
this.trackGridH = new System.Windows.Forms.TrackBar();
this.opMode = new System.Windows.Forms.ComboBox();
this.scaleBar = new System.Windows.Forms.TrackBar();
this.glView = new Pantry.OpenGLView();
this.flowPanel = new System.Windows.Forms.FlowLayoutPanel();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.importToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.milkshape3DStaticToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newShaderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newProgramShaderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.stripifyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.findTexturesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dOpenFile = new System.Windows.Forms.OpenFileDialog();
this.milkshape3DAnimatedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.glToolStrip.ContentPanel.SuspendLayout();
this.glToolStrip.TopToolStripPanel.SuspendLayout();
this.glToolStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trackGridV)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackGridH)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.scaleBar)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 20;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// treeResources
//
this.treeResources.Location = new System.Drawing.Point(12, 30);
this.treeResources.Name = "treeResources";
this.treeResources.Size = new System.Drawing.Size(342, 223);
this.treeResources.TabIndex = 2;
this.treeResources.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeResources_AfterSelect);
this.treeResources.KeyDown += new System.Windows.Forms.KeyEventHandler(this.treeResources_KeyDown);
//
// comboPackage
//
this.comboPackage.FormattingEnabled = true;
this.comboPackage.Location = new System.Drawing.Point(12, 3);
this.comboPackage.Name = "comboPackage";
this.comboPackage.Size = new System.Drawing.Size(342, 21);
this.comboPackage.TabIndex = 3;
this.comboPackage.SelectedIndexChanged += new System.EventHandler(this.comboPackage_SelectedIndexChanged);
//
// gridItem
//
this.gridItem.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.gridItem.Location = new System.Drawing.Point(12, 259);
this.gridItem.Name = "gridItem";
this.gridItem.PropertySort = System.Windows.Forms.PropertySort.Alphabetical;
this.gridItem.Size = new System.Drawing.Size(342, 264);
this.gridItem.TabIndex = 4;
this.gridItem.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.gridItem_PropertyValueChanged);
//
// glToolStrip
//
//
// glToolStrip.ContentPanel
//
this.glToolStrip.ContentPanel.Controls.Add(this.gCenter);
this.glToolStrip.ContentPanel.Controls.Add(this.trackGridV);
this.glToolStrip.ContentPanel.Controls.Add(this.trackGridH);
this.glToolStrip.ContentPanel.Controls.Add(this.opMode);
this.glToolStrip.ContentPanel.Controls.Add(this.scaleBar);
this.glToolStrip.ContentPanel.Controls.Add(this.glView);
this.glToolStrip.ContentPanel.Controls.Add(this.flowPanel);
this.glToolStrip.ContentPanel.Controls.Add(this.gridItem);
this.glToolStrip.ContentPanel.Controls.Add(this.comboPackage);
this.glToolStrip.ContentPanel.Controls.Add(this.treeResources);
this.glToolStrip.ContentPanel.Size = new System.Drawing.Size(863, 593);
this.glToolStrip.Dock = System.Windows.Forms.DockStyle.Fill;
this.glToolStrip.Location = new System.Drawing.Point(0, 0);
this.glToolStrip.Name = "glToolStrip";
this.glToolStrip.Size = new System.Drawing.Size(863, 617);
this.glToolStrip.TabIndex = 5;
this.glToolStrip.Text = "toolStripContainer1";
//
// glToolStrip.TopToolStripPanel
//
this.glToolStrip.TopToolStripPanel.Controls.Add(this.menuStrip1);
//
// gCenter
//
this.gCenter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.gCenter.AutoSize = true;
this.gCenter.Checked = true;
this.gCenter.CheckState = System.Windows.Forms.CheckState.Checked;
this.gCenter.Location = new System.Drawing.Point(12, 564);
this.gCenter.Name = "gCenter";
this.gCenter.Size = new System.Drawing.Size(57, 17);
this.gCenter.TabIndex = 11;
this.gCenter.Text = "Center";
this.gCenter.UseVisualStyleBackColor = true;
this.gCenter.CheckedChanged += new System.EventHandler(this.gCenter_CheckedChanged);
//
// trackGridV
//
this.trackGridV.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.trackGridV.Location = new System.Drawing.Point(204, 536);
this.trackGridV.Name = "trackGridV";
this.trackGridV.Size = new System.Drawing.Size(150, 45);
this.trackGridV.TabIndex = 10;
this.trackGridV.Value = 1;
this.trackGridV.ValueChanged += new System.EventHandler(this.trackGridV_ValueChanged);
this.trackGridV.Scroll += new System.EventHandler(this.trackGridV_Scroll);
//
// trackGridH
//
this.trackGridH.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.trackGridH.Location = new System.Drawing.Point(48, 536);
this.trackGridH.Name = "trackGridH";
this.trackGridH.Size = new System.Drawing.Size(150, 45);
this.trackGridH.TabIndex = 9;
this.trackGridH.Value = 1;
this.trackGridH.ValueChanged += new System.EventHandler(this.trackGridH_ValueChanged);
this.trackGridH.Scroll += new System.EventHandler(this.trackGridH_Scroll);
//
// opMode
//
this.opMode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.opMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.opMode.FormattingEnabled = true;
this.opMode.Items.AddRange(new object[] {
"Scale",
"TranslateX",
"TranslateY",
"TranslateZ"});
this.opMode.Location = new System.Drawing.Point(361, 536);
this.opMode.Name = "opMode";
this.opMode.Size = new System.Drawing.Size(75, 21);
this.opMode.TabIndex = 8;
this.opMode.SelectedIndexChanged += new System.EventHandler(this.opMode_SelectedIndexChanged);
//
// scaleBar
//
this.scaleBar.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.scaleBar.Location = new System.Drawing.Point(442, 536);
this.scaleBar.Maximum = 100;
this.scaleBar.Name = "scaleBar";
this.scaleBar.Size = new System.Drawing.Size(409, 45);
this.scaleBar.TabIndex = 7;
this.scaleBar.Value = 50;
this.scaleBar.ValueChanged += new System.EventHandler(this.scaleBar_ValueChanged);
this.scaleBar.Scroll += new System.EventHandler(this.scaleBar_Scroll);
//
// glView
//
this.glView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.glView.Location = new System.Drawing.Point(360, 130);
this.glView.Name = "glView";
this.glView.Size = new System.Drawing.Size(500, 393);
this.glView.TabIndex = 6;
this.glView.Text = "openGLView1";
//
// flowPanel
//
this.flowPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.flowPanel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.flowPanel.Location = new System.Drawing.Point(360, 30);
this.flowPanel.Name = "flowPanel";
this.flowPanel.Size = new System.Drawing.Size(500, 94);
this.flowPanel.TabIndex = 5;
//
// menuStrip1
//
this.menuStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.importToolStripMenuItem,
this.newShaderToolStripMenuItem,
this.newProgramShaderToolStripMenuItem,
this.saveToolStripMenuItem,
this.stripifyToolStripMenuItem,
this.findTexturesToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.menuStrip1.Size = new System.Drawing.Size(863, 24);
this.menuStrip1.TabIndex = 5;
this.menuStrip1.Text = "menuStrip1";
//
// importToolStripMenuItem
//
this.importToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.milkshape3DStaticToolStripMenuItem,
this.milkshape3DAnimatedToolStripMenuItem});
this.importToolStripMenuItem.Name = "importToolStripMenuItem";
this.importToolStripMenuItem.Size = new System.Drawing.Size(51, 20);
this.importToolStripMenuItem.Text = "Import";
//
// milkshape3DStaticToolStripMenuItem
//
this.milkshape3DStaticToolStripMenuItem.Name = "milkshape3DStaticToolStripMenuItem";
this.milkshape3DStaticToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.milkshape3DStaticToolStripMenuItem.Text = "Milkshape3D Static";
this.milkshape3DStaticToolStripMenuItem.Click += new System.EventHandler(this.milkshape3DStaticToolStripMenuItem_Click);
//
// newShaderToolStripMenuItem
//
this.newShaderToolStripMenuItem.Name = "newShaderToolStripMenuItem";
this.newShaderToolStripMenuItem.Size = new System.Drawing.Size(77, 20);
this.newShaderToolStripMenuItem.Text = "New Shader";
this.newShaderToolStripMenuItem.Click += new System.EventHandler(this.newShaderToolStripMenuItem_Click);
//
// newProgramShaderToolStripMenuItem
//
this.newProgramShaderToolStripMenuItem.Name = "newProgramShaderToolStripMenuItem";
this.newProgramShaderToolStripMenuItem.Size = new System.Drawing.Size(120, 20);
this.newProgramShaderToolStripMenuItem.Text = "New Program Shader";
this.newProgramShaderToolStripMenuItem.Click += new System.EventHandler(this.newProgramShaderToolStripMenuItem_Click);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(43, 20);
this.saveToolStripMenuItem.Text = "Save";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// stripifyToolStripMenuItem
//
this.stripifyToolStripMenuItem.Name = "stripifyToolStripMenuItem";
this.stripifyToolStripMenuItem.Size = new System.Drawing.Size(53, 20);
this.stripifyToolStripMenuItem.Text = "Stripify";
this.stripifyToolStripMenuItem.Click += new System.EventHandler(this.stripifyToolStripMenuItem_Click);
//
// findTexturesToolStripMenuItem
//
this.findTexturesToolStripMenuItem.Name = "findTexturesToolStripMenuItem";
this.findTexturesToolStripMenuItem.Size = new System.Drawing.Size(85, 20);
this.findTexturesToolStripMenuItem.Text = "Find Textures";
this.findTexturesToolStripMenuItem.Click += new System.EventHandler(this.findTexturesToolStripMenuItem_Click);
//
// milkshape3DAnimatedToolStripMenuItem
//
this.milkshape3DAnimatedToolStripMenuItem.Name = "milkshape3DAnimatedToolStripMenuItem";
this.milkshape3DAnimatedToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.milkshape3DAnimatedToolStripMenuItem.Text = "Milkshape3D Animated";
this.milkshape3DAnimatedToolStripMenuItem.Click += new System.EventHandler(this.milkshape3DAnimatedToolStripMenuItem_Click);
//
// ThePantryView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(863, 617);
this.Controls.Add(this.glToolStrip);
this.MainMenuStrip = this.menuStrip1;
this.Name = "ThePantryView";
this.Text = "OpenGL Slug Fest";
this.glToolStrip.ContentPanel.ResumeLayout(false);
this.glToolStrip.ContentPanel.PerformLayout();
this.glToolStrip.TopToolStripPanel.ResumeLayout(false);
this.glToolStrip.TopToolStripPanel.PerformLayout();
this.glToolStrip.ResumeLayout(false);
this.glToolStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.trackGridV)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackGridH)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.scaleBar)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.TreeView treeResources;
private System.Windows.Forms.ComboBox comboPackage;
private System.Windows.Forms.PropertyGrid gridItem;
private System.Windows.Forms.ToolStripContainer glToolStrip;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem importToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem milkshape3DStaticToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog dOpenFile;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem stripifyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem findTexturesToolStripMenuItem;
private System.Windows.Forms.FlowLayoutPanel flowPanel;
private OpenGLView glView;
private System.Windows.Forms.TrackBar scaleBar;
private System.Windows.Forms.ComboBox opMode;
private System.Windows.Forms.TrackBar trackGridV;
private System.Windows.Forms.TrackBar trackGridH;
private System.Windows.Forms.CheckBox gCenter;
private System.Windows.Forms.ToolStripMenuItem newShaderToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newProgramShaderToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem milkshape3DAnimatedToolStripMenuItem;
}
}
| |
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace Facebook.CSSLayout
{
/**
* Should measure the given node and put the result in the given MeasureOutput.
*/
public delegate MeasureOutput MeasureFunction(CSSNode node, float width, float height);
/**
* A CSS Node. It has a style object you can manipulate at {@link #style}. After calling
* {@link #calculateLayout()}, {@link #layout} will be filled with the results of the layout.
*/
public class CSSNode
{
const int POSITION_LEFT = CSSLayout.POSITION_LEFT;
const int POSITION_TOP = CSSLayout.POSITION_TOP;
const int POSITION_RIGHT = CSSLayout.POSITION_RIGHT;
const int POSITION_BOTTOM = CSSLayout.POSITION_BOTTOM;
const int DIMENSION_WIDTH = CSSLayout.DIMENSION_WIDTH;
const int DIMENSION_HEIGHT = CSSLayout.DIMENSION_HEIGHT;
enum LayoutState
{
/**
* Some property of this node or its children has changes and the current values in
* {@link #layout} are not valid.
*/
DIRTY,
/**
* This node has a new layout relative to the last time {@link #MarkLayoutSeen()} was called.
*/
HAS_NEW_LAYOUT,
/**
* {@link #layout} is valid for the node's properties and this layout has been marked as
* having been seen.
*/
UP_TO_DATE,
}
internal readonly CSSStyle style = new CSSStyle();
internal readonly CSSLayout layout = new CSSLayout();
internal readonly CachedCSSLayout lastLayout = new CachedCSSLayout();
internal int lineIndex = 0;
internal /*package*/ CSSNode nextAbsoluteChild;
internal /*package*/ CSSNode nextFlexChild;
// 4 is kinda arbitrary, but the default of 10 seems really high for an average View.
readonly List<CSSNode> mChildren = new List<CSSNode>(4);
[Nullable] CSSNode mParent;
[Nullable] MeasureFunction mMeasureFunction = null;
LayoutState mLayoutState = LayoutState.DIRTY;
public int ChildCount
{
get { return mChildren.Count; }
}
public CSSNode this[int i]
{
get { return mChildren[i]; }
}
public IEnumerable<CSSNode> Children
{
get { return mChildren; }
}
public void AddChild(CSSNode child)
{
InsertChild(ChildCount, child);
}
public void InsertChild(int i, CSSNode child)
{
if (child.mParent != null)
{
throw new InvalidOperationException("Child already has a parent, it must be removed first.");
}
mChildren.Insert(i, child);
child.mParent = this;
dirty();
}
public void RemoveChildAt(int i)
{
mChildren[i].mParent = null;
mChildren.RemoveAt(i);
dirty();
}
public CSSNode Parent
{
[return: Nullable]
get
{ return mParent; }
}
/**
* @return the index of the given child, or -1 if the child doesn't exist in this node.
*/
public int IndexOf(CSSNode child)
{
return mChildren.IndexOf(child);
}
public MeasureFunction MeasureFunction
{
get { return mMeasureFunction; }
set
{
if (!valuesEqual(mMeasureFunction, value))
{
mMeasureFunction = value;
dirty();
}
}
}
public bool IsMeasureDefined
{
get { return mMeasureFunction != null; }
}
internal MeasureOutput measure(MeasureOutput measureOutput, float width, float height)
{
if (!IsMeasureDefined)
{
throw new Exception("Measure function isn't defined!");
}
return Assertions.assertNotNull(mMeasureFunction)(this, width, height);
}
/**
* Performs the actual layout and saves the results in {@link #layout}
*/
public void CalculateLayout()
{
layout.resetResult();
LayoutEngine.layoutNode(DummyLayoutContext, this, CSSConstants.Undefined, CSSConstants.Undefined, null);
}
static readonly CSSLayoutContext DummyLayoutContext = new CSSLayoutContext();
/**
* See {@link LayoutState#DIRTY}.
*/
public bool IsDirty
{
get { return mLayoutState == LayoutState.DIRTY; }
}
/**
* See {@link LayoutState#HAS_NEW_LAYOUT}.
*/
public bool HasNewLayout
{
get { return mLayoutState == LayoutState.HAS_NEW_LAYOUT; }
}
internal protected virtual void dirty()
{
if (mLayoutState == LayoutState.DIRTY)
{
return;
}
else if (mLayoutState == LayoutState.HAS_NEW_LAYOUT)
{
throw new InvalidOperationException("Previous layout was ignored! MarkLayoutSeen() never called");
}
mLayoutState = LayoutState.DIRTY;
if (mParent != null)
{
mParent.dirty();
}
}
internal void markHasNewLayout()
{
mLayoutState = LayoutState.HAS_NEW_LAYOUT;
}
/**
* Tells the node that the current values in {@link #layout} have been seen. Subsequent calls
* to {@link #hasNewLayout()} will return false until this node is laid out with new parameters.
* You must call this each time the layout is generated if the node has a new layout.
*/
public void MarkLayoutSeen()
{
if (!HasNewLayout)
{
throw new InvalidOperationException("Expected node to have a new layout to be seen!");
}
mLayoutState = LayoutState.UP_TO_DATE;
}
void toStringWithIndentation(StringBuilder result, int level)
{
// Spaces and tabs are dropped by IntelliJ logcat integration, so rely on __ instead.
StringBuilder indentation = new StringBuilder();
for (int i = 0; i < level; ++i)
{
indentation.Append("__");
}
result.Append(indentation.ToString());
result.Append(layout.ToString());
if (ChildCount == 0)
{
return;
}
result.Append(", children: [\n");
for (var i = 0; i < ChildCount; i++)
{
this[i].toStringWithIndentation(result, level + 1);
result.Append("\n");
}
result.Append(indentation + "]");
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
this.toStringWithIndentation(sb, 0);
return sb.ToString();
}
protected bool valuesEqual(float f1, float f2)
{
return FloatUtil.floatsEqual(f1, f2);
}
protected bool valuesEqual<T>([Nullable] T o1, [Nullable] T o2)
{
if (o1 == null)
{
return o2 == null;
}
return o1.Equals(o2);
}
public CSSDirection Direction
{
get { return style.direction; }
set { updateDiscreteValue(ref style.direction, value); }
}
public CSSFlexDirection FlexDirection
{
get { return style.flexDirection; }
set { updateDiscreteValue(ref style.flexDirection, value); }
}
public CSSJustify JustifyContent
{
get { return style.justifyContent; }
set { updateDiscreteValue(ref style.justifyContent, value); }
}
public CSSAlign AlignContent
{
get { return style.alignContent; }
set { updateDiscreteValue(ref style.alignContent, value); }
}
public CSSAlign AlignItems
{
get { return style.alignItems; }
set { updateDiscreteValue(ref style.alignItems, value); }
}
public CSSAlign AlignSelf
{
get { return style.alignSelf; }
set { updateDiscreteValue(ref style.alignSelf, value); }
}
public CSSPositionType PositionType
{
get { return style.positionType; }
set { updateDiscreteValue(ref style.positionType, value); }
}
public CSSWrap Wrap
{
get { return style.flexWrap; }
set { updateDiscreteValue(ref style.flexWrap, value); }
}
public float Flex
{
get { return style.flex; }
set { updateFloatValue(ref style.flex, value); }
}
public void SetMargin(CSSSpacingType spacingType, float margin)
{
if (style.margin.set((int)spacingType, margin))
dirty();
}
public float GetMargin(CSSSpacingType spacingType)
{
return style.margin.getRaw((int)spacingType);
}
public void SetPadding(CSSSpacingType spacingType, float padding)
{
if (style.padding.set((int)spacingType, padding))
dirty();
}
public float GetPadding(CSSSpacingType spacingType)
{
return style.padding.getRaw((int)spacingType);
}
public void SetBorder(CSSSpacingType spacingType, float border)
{
if (style.border.set((int)spacingType, border))
dirty();
}
public float GetBorder(CSSSpacingType spacingType)
{
return style.border.getRaw((int)spacingType);
}
public float PositionTop
{
get { return style.position[POSITION_TOP]; }
set { updateFloatValue(ref style.position[POSITION_TOP], value); }
}
public float PositionBottom
{
get { return style.position[POSITION_BOTTOM]; }
set { updateFloatValue(ref style.position[POSITION_BOTTOM], value); }
}
public float PositionLeft
{
get { return style.position[POSITION_LEFT]; }
set { updateFloatValue(ref style.position[POSITION_LEFT], value); }
}
public float PositionRight
{
get { return style.position[POSITION_RIGHT]; }
set { updateFloatValue(ref style.position[POSITION_RIGHT], value); }
}
public float Width
{
get { return style.dimensions[DIMENSION_WIDTH]; }
set { updateFloatValue(ref style.dimensions[DIMENSION_WIDTH], value); }
}
public float Height
{
get { return style.dimensions[DIMENSION_HEIGHT]; }
set { updateFloatValue(ref style.dimensions[DIMENSION_HEIGHT], value); }
}
public float MinWidth
{
get { return style.minWidth; }
set { updateFloatValue(ref style.minWidth, value); }
}
public float MinHeight
{
get { return style.minHeight; }
set { updateFloatValue(ref style.minHeight, value); }
}
public float MaxWidth
{
get { return style.maxWidth; }
set { updateFloatValue(ref style.maxWidth, value); }
}
public float MaxHeight
{
get { return style.maxHeight; }
set { updateFloatValue(ref style.maxHeight, value); }
}
public float LayoutX
{
get { return layout.position[POSITION_LEFT]; }
}
public float LayoutY
{
get { return layout.position[POSITION_TOP]; }
}
public float LayoutWidth
{
get { return layout.dimensions[DIMENSION_WIDTH]; }
}
public float LayoutHeight
{
get { return layout.dimensions[DIMENSION_HEIGHT]; }
}
public CSSDirection LayoutDirection
{
get { return layout.direction; }
}
/**
* Set a default padding (left/top/right/bottom) for this node.
*/
public void SetDefaultPadding(CSSSpacingType spacingType, float padding)
{
if (style.padding.setDefault((int)spacingType, padding))
dirty();
}
void updateDiscreteValue<ValueT>(ref ValueT valueRef, ValueT newValue)
{
if (valuesEqual(valueRef, newValue))
return;
valueRef = newValue;
dirty();
}
void updateFloatValue(ref float valueRef, float newValue)
{
if (valuesEqual(valueRef, newValue))
return;
valueRef = newValue;
dirty();
}
}
public static class CSSNodeExtensions
{
/*
Explicitly mark this node as dirty.
Calling this function is required when the measure function points to the same instance,
but changes its behavior.
For all other property changes, the node is automatically marked dirty.
*/
public static void MarkDirty(this CSSNode node)
{
node.dirty();
}
}
internal static class CSSNodeExtensionsInternal
{
public static CSSNode getParent(this CSSNode node)
{
return node.Parent;
}
public static int getChildCount(this CSSNode node)
{
return node.ChildCount;
}
public static CSSNode getChildAt(this CSSNode node, int i)
{
return node[i];
}
public static void addChildAt(this CSSNode node, CSSNode child, int i)
{
node.InsertChild(i, child);
}
public static void removeChildAt(this CSSNode node, int i)
{
node.RemoveChildAt(i);
}
public static void setMeasureFunction(this CSSNode node, MeasureFunction measureFunction)
{
node.MeasureFunction = measureFunction;
}
public static void calculateLayout(this CSSNode node)
{
node.CalculateLayout();
}
public static bool isDirty(this CSSNode node)
{
return node.IsDirty;
}
public static void setMargin(this CSSNode node, int spacingType, float margin)
{
node.SetMargin((CSSSpacingType)spacingType, margin);
}
public static void setPadding(this CSSNode node, int spacingType, float padding)
{
node.SetPadding((CSSSpacingType)spacingType, padding);
}
public static void setBorder(this CSSNode node, int spacingType, float border)
{
node.SetBorder((CSSSpacingType)spacingType, border);
}
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
#region Includes
using System;
using System.Collections;
using System.Drawing;
using IronScheme.Editor.ComponentModel;
using System.Windows.Forms;
#endregion
namespace IronScheme.Editor.Controls
{
class AutoCompleteForm : Form
{
internal ListBox choices = new PictureListBox();
internal string lasthint = string.Empty;
internal Type[] filters;
internal string lastguess = string.Empty;
static string Join(Type[] t)
{
string[] s = new string[t.Length];
for (int i = 0; i < s.Length; i++)
{
s[i] = t[i].Name;
}
return string.Join(", ", s);
}
class CodeElementComparer: IComparer
{
public int Compare(object x, object y)
{
CodeModel.CodeElement a = x as CodeModel.CodeElement;
CodeModel.CodeElement b = y as CodeModel.CodeElement;
return a.Name.CompareTo(b.Name);
}
}
static IComparer CODEELEMCOMPARER = new CodeElementComparer();
public bool Show(Point location, string hint, CodeModel.ICodeElement[] hints, int fontheight, Type[] filters)
{
SuspendLayout();
if (this.filters == null)
{
this.filters = filters;
}
DialogResult = DialogResult.Cancel;
choices.Items.Clear();
lasthint = hint;
//System.Diagnostics.Trace.WriteLine(Join(this.filters), "Filters ");
IImageListProviderService ims = ServiceHost.ImageListProvider;
ArrayList all = new ArrayList();
foreach (CodeModel.ICodeElement s in hints)
{
if (Languages.Language.FilterType(this.filters, s))
{
all.Add(s);
}
}
all.Sort(CODEELEMCOMPARER);
choices.Items.AddRange(all.ToArray());
if (choices.Items.Count == 0)
{
ResumeLayout();
if (Visible)
{
Hide();
return true;
}
else
{
DialogResult = DialogResult.No;
return false;
}
}
choices.SelectedIndex = 0;
if (choices.Items.Count == 1)
{
if (this.filters == filters || lastguess == ((CodeModel.ICodeElement) (choices.SelectedItem)).Fullname)
{
ResumeLayout();
DialogResult = DialogResult.OK;
if (Visible)
{
Hide();
return true;
}
else
{
return false;
}
}
lastguess = ((CodeModel.ICodeElement) (choices.SelectedItem)).Fullname;
}
int diff = Height - ClientSize.Height;
if (choices.Items.Count < 12)
{
Height = choices.ItemHeight * choices.Items.Count + diff + 2;
}
else
{
Height = choices.ItemHeight * 12 + diff + 2;
}
Screen ss = Screen.FromPoint(location);
//x
if (location.X + Width > ss.WorkingArea.Width)
{
location.X = ss.WorkingArea.Width - Width;
}
//y
if (location.Y + Height > ss.WorkingArea.Bottom)
{
location.Y = location.Y - fontheight - Height;
}
Location = location;
ResumeLayout();
if (!Visible)
{
Show();
}
return true;
}
public AutoCompleteForm(AdvancedTextBox parent)
{
Opacity = .9;
DoubleBuffered = true;
FormBorderStyle = FormBorderStyle.SizableToolWindow;
this.ControlBox = false;
choices.BorderStyle = BorderStyle.FixedSingle;
choices.KeyDown += new KeyEventHandler(choices_KeyDown);
choices.DoubleClick +=new EventHandler(choices_DoubleClick);
choices.Font = SystemInformation.MenuFont;
choices.Dock = DockStyle.Fill;
choices.IntegralHeight = false;
Controls.Add(choices);
Width = 250;
this.ShowInTaskbar = false;
this.SizeGripStyle = SizeGripStyle.Hide;
this.StartPosition = FormStartPosition.Manual;
}
void choices_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
DialogResult = DialogResult.OK;
Hide();
break;
case Keys.Escape:
DialogResult = DialogResult.Cancel;
Hide();
break;
}
}
void choices_DoubleClick(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Hide();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using CoffLib.Binary;
namespace CoffLib.X86
{
public partial class I386
{
public static void Test2_32()
{
// Mov, Add, Or, Adc, Sbb, And, Sub, Xor, Cmp, Test, Xchg
// Mov
Mov(Reg32.EAX, 4)
.Test("mov eax, 4", "B8-04-00-00-00");
Mov(Reg32.ESP, 4)
.Test("mov esp, 4", "BC-04-00-00-00");
Mov(Reg32.EAX, Reg32.EBX)
.Test("mov eax, ebx", "89-D8");
Mov(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("mov eax, [edx]", "8B-02");
Mov(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("mov ebx, [eax]", "8B-18");
Mov(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("mov ecx, [esp]", "8B-0C-24");
Mov(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("mov ebp, [eax+0x1000]", "8B-A8-00-10-00-00");
Mov(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("mov [edx], eax", "89-02");
Mov(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("mov [eax], ebx", "89-18");
Mov(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("mov [esp], ecx", "89-0C-24");
Mov(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("mov [eax+0x1000], ebp", "89-A8-00-10-00-00");
Mov(new Addr32(Reg32.EAX), (Val32)1)
.Test("mov dword [eax], 1", "C7-00-01-00-00-00");
Mov(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("mov dword [ebp-4], 8", "C7-45-FC-08-00-00-00");
Mov(Reg32.EAX, new Addr32(0x12345678))
.Test("mov eax, [0x12345678]", "A1-78-56-34-12");
Mov(new Addr32(0x12345678), Reg32.EAX)
.Test("mov [0x12345678], eax", "A3-78-56-34-12");
// Add
Add(Reg32.EAX, 4)
.Test("add eax, 4", "05-04-00-00-00");
Add(Reg32.ESP, 4)
.Test("add esp, 4", "81-C4-04-00-00-00");
Add(Reg32.EAX, Reg32.EBX)
.Test("add eax, ebx", "01-D8");
Add(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("add eax, [edx]", "03-02");
Add(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("add ebx, [eax]", "03-18");
Add(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("add ecx, [esp]", "03-0C-24");
Add(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("add ebp, [eax+0x1000]", "03-A8-00-10-00-00");
Add(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("add [edx], eax", "01-02");
Add(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("add [eax], ebx", "01-18");
Add(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("add [esp], ecx", "01-0C-24");
Add(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("add [eax+0x1000], ebp", "01-A8-00-10-00-00");
Add(new Addr32(Reg32.EAX), (Val32)1)
.Test("add dword [eax], 1", "81-00-01-00-00-00");
Add(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("add dword [ebp-4], 8", "81-45-FC-08-00-00-00");
// Or
Or(Reg32.EAX, 4)
.Test("or eax, 4", "0D-04-00-00-00");
Or(Reg32.ESP, 4)
.Test("or esp, 4", "81-CC-04-00-00-00");
Or(Reg32.EAX, Reg32.EBX)
.Test("or eax, ebx", "09-D8");
Or(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("or eax, [edx]", "0B-02");
Or(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("or ebx, [eax]", "0B-18");
Or(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("or ecx, [esp]", "0B-0C-24");
Or(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("or ebp, [eax+0x1000]", "0B-A8-00-10-00-00");
Or(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("or [edx], eax", "09-02");
Or(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("or [eax], ebx", "09-18");
Or(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("or [esp], ecx", "09-0C-24");
Or(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("or [eax+0x1000], ebp", "09-A8-00-10-00-00");
Or(new Addr32(Reg32.EAX), (Val32)1)
.Test("or dword [eax], 1", "81-08-01-00-00-00");
Or(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("or dword [ebp-4], 8", "81-4D-FC-08-00-00-00");
// Adc
Adc(Reg32.EAX, 4)
.Test("adc eax, 4", "15-04-00-00-00");
Adc(Reg32.ESP, 4)
.Test("adc esp, 4", "81-D4-04-00-00-00");
Adc(Reg32.EAX, Reg32.EBX)
.Test("adc eax, ebx", "11-D8");
Adc(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("adc eax, [edx]", "13-02");
Adc(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("adc ebx, [eax]", "13-18");
Adc(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("adc ecx, [esp]", "13-0C-24");
Adc(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("adc ebp, [eax+0x1000]", "13-A8-00-10-00-00");
Adc(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("adc [edx], eax", "11-02");
Adc(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("adc [eax], ebx", "11-18");
Adc(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("adc [esp], ecx", "11-0C-24");
Adc(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("adc [eax+0x1000], ebp", "11-A8-00-10-00-00");
Adc(new Addr32(Reg32.EAX), (Val32)1)
.Test("adc dword [eax], 1", "81-10-01-00-00-00");
Adc(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("adc dword [ebp-4], 8", "81-55-FC-08-00-00-00");
// Sbb
Sbb(Reg32.EAX, 4)
.Test("sbb eax, 4", "1D-04-00-00-00");
Sbb(Reg32.ESP, 4)
.Test("sbb esp, 4", "81-DC-04-00-00-00");
Sbb(Reg32.EAX, Reg32.EBX)
.Test("sbb eax, ebx", "19-D8");
Sbb(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("sbb eax, [edx]", "1B-02");
Sbb(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("sbb ebx, [eax]", "1B-18");
Sbb(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("sbb ecx, [esp]", "1B-0C-24");
Sbb(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("sbb ebp, [eax+0x1000]", "1B-A8-00-10-00-00");
Sbb(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("sbb [edx], eax", "19-02");
Sbb(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("sbb [eax], ebx", "19-18");
Sbb(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("sbb [esp], ecx", "19-0C-24");
Sbb(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("sbb [eax+0x1000], ebp", "19-A8-00-10-00-00");
Sbb(new Addr32(Reg32.EAX), (Val32)1)
.Test("sbb dword [eax], 1", "81-18-01-00-00-00");
Sbb(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("sbb dword [ebp-4], 8", "81-5D-FC-08-00-00-00");
// And
And(Reg32.EAX, 4)
.Test("and eax, 4", "25-04-00-00-00");
And(Reg32.ESP, 4)
.Test("and esp, 4", "81-E4-04-00-00-00");
And(Reg32.EAX, Reg32.EBX)
.Test("and eax, ebx", "21-D8");
And(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("and eax, [edx]", "23-02");
And(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("and ebx, [eax]", "23-18");
And(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("and ecx, [esp]", "23-0C-24");
And(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("and ebp, [eax+0x1000]", "23-A8-00-10-00-00");
And(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("and [edx], eax", "21-02");
And(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("and [eax], ebx", "21-18");
And(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("and [esp], ecx", "21-0C-24");
And(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("and [eax+0x1000], ebp", "21-A8-00-10-00-00");
And(new Addr32(Reg32.EAX), (Val32)1)
.Test("and dword [eax], 1", "81-20-01-00-00-00");
And(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("and dword [ebp-4], 8", "81-65-FC-08-00-00-00");
// Sub
Sub(Reg32.EAX, 4)
.Test("sub eax, 4", "2D-04-00-00-00");
Sub(Reg32.ESP, 4)
.Test("sub esp, 4", "81-EC-04-00-00-00");
Sub(Reg32.EAX, Reg32.EBX)
.Test("sub eax, ebx", "29-D8");
Sub(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("sub eax, [edx]", "2B-02");
Sub(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("sub ebx, [eax]", "2B-18");
Sub(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("sub ecx, [esp]", "2B-0C-24");
Sub(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("sub ebp, [eax+0x1000]", "2B-A8-00-10-00-00");
Sub(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("sub [edx], eax", "29-02");
Sub(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("sub [eax], ebx", "29-18");
Sub(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("sub [esp], ecx", "29-0C-24");
Sub(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("sub [eax+0x1000], ebp", "29-A8-00-10-00-00");
Sub(new Addr32(Reg32.EAX), (Val32)1)
.Test("sub dword [eax], 1", "81-28-01-00-00-00");
Sub(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("sub dword [ebp-4], 8", "81-6D-FC-08-00-00-00");
// Xor
Xor(Reg32.EAX, 4)
.Test("xor eax, 4", "35-04-00-00-00");
Xor(Reg32.ESP, 4)
.Test("xor esp, 4", "81-F4-04-00-00-00");
Xor(Reg32.EAX, Reg32.EBX)
.Test("xor eax, ebx", "31-D8");
Xor(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("xor eax, [edx]", "33-02");
Xor(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("xor ebx, [eax]", "33-18");
Xor(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("xor ecx, [esp]", "33-0C-24");
Xor(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("xor ebp, [eax+0x1000]", "33-A8-00-10-00-00");
Xor(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("xor [edx], eax", "31-02");
Xor(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("xor [eax], ebx", "31-18");
Xor(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("xor [esp], ecx", "31-0C-24");
Xor(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("xor [eax+0x1000], ebp", "31-A8-00-10-00-00");
Xor(new Addr32(Reg32.EAX), (Val32)1)
.Test("xor dword [eax], 1", "81-30-01-00-00-00");
Xor(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("xor dword [ebp-4], 8", "81-75-FC-08-00-00-00");
// Cmp
Cmp(Reg32.EAX, 4)
.Test("cmp eax, 4", "3D-04-00-00-00");
Cmp(Reg32.ESP, 4)
.Test("cmp esp, 4", "81-FC-04-00-00-00");
Cmp(Reg32.EAX, Reg32.EBX)
.Test("cmp eax, ebx", "39-D8");
Cmp(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("cmp eax, [edx]", "3B-02");
Cmp(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("cmp ebx, [eax]", "3B-18");
Cmp(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("cmp ecx, [esp]", "3B-0C-24");
Cmp(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("cmp ebp, [eax+0x1000]", "3B-A8-00-10-00-00");
Cmp(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("cmp [edx], eax", "39-02");
Cmp(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("cmp [eax], ebx", "39-18");
Cmp(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("cmp [esp], ecx", "39-0C-24");
Cmp(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("cmp [eax+0x1000], ebp", "39-A8-00-10-00-00");
Cmp(new Addr32(Reg32.EAX), (Val32)1)
.Test("cmp dword [eax], 1", "81-38-01-00-00-00");
Cmp(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("cmp dword [ebp-4], 8", "81-7D-FC-08-00-00-00");
// Test
Test(Reg32.EAX, 4)
.Test("test eax, 4", "A9-04-00-00-00");
Test(Reg32.ESP, 4)
.Test("test esp, 4", "F7-C4-04-00-00-00");
Test(Reg32.EAX, Reg32.EBX)
.Test("test eax, ebx", "85-D8");
Test(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("test [edx], eax", "85-02");
Test(new Addr32(Reg32.EAX), Reg32.EBX)
.Test("test [eax], ebx", "85-18");
Test(new Addr32(Reg32.ESP), Reg32.ECX)
.Test("test [esp], ecx", "85-0C-24");
Test(new Addr32(Reg32.EAX, 0x1000), Reg32.EBP)
.Test("test [eax+0x1000], ebp", "85-A8-00-10-00-00");
Test(new Addr32(Reg32.EAX), (Val32)1)
.Test("test dword [eax], 1", "F7-00-01-00-00-00");
Test(new Addr32(Reg32.EBP, -4), (Val32)8)
.Test("test dword [ebp-4], 8", "F7-45-FC-08-00-00-00");
// Xchg
Xchg(Reg32.EAX, Reg32.EAX)
.Test("xchg eax, eax", "90");
Xchg(Reg32.EAX, Reg32.EBX)
.Test("xchg eax, ebx", "93");
Xchg(Reg32.EBX, Reg32.EAX)
.Test("xchg ebx, eax", "93");
Xchg(Reg32.EAX, new Addr32(Reg32.EDX))
.Test("xchg eax, [edx]", "87-02");
Xchg(Reg32.EBX, new Addr32(Reg32.EAX))
.Test("xchg ebx, [eax]", "87-18");
Xchg(Reg32.ECX, new Addr32(Reg32.ESP))
.Test("xchg ecx, [esp]", "87-0C-24");
Xchg(Reg32.EBP, new Addr32(Reg32.EAX, 0x1000))
.Test("xchg ebp, [eax+0x1000]", "87-A8-00-10-00-00");
Xchg(new Addr32(Reg32.EDX), Reg32.EAX)
.Test("xchg [edx], eax", "87-02");
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Conversations.V1.Service.Conversation
{
/// <summary>
/// Add a new message to the conversation in a specific service
/// </summary>
public class CreateMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Conversation Service that the resource is associated with.
/// </summary>
public string PathChatServiceSid { get; }
/// <summary>
/// The unique ID of the Conversation for this message.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// The channel specific identifier of the message's author.
/// </summary>
public string Author { get; set; }
/// <summary>
/// The content of the message.
/// </summary>
public string Body { get; set; }
/// <summary>
/// The date that this resource was created.
/// </summary>
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date that this resource was last updated.
/// </summary>
public DateTime? DateUpdated { get; set; }
/// <summary>
/// A string metadata field you can use to store any data you wish.
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// The Media SID to be attached to the new Message.
/// </summary>
public string MediaSid { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public MessageResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new CreateMessageOptions
/// </summary>
/// <param name="pathChatServiceSid"> The SID of the Conversation Service that the resource is associated with. </param>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this message. </param>
public CreateMessageOptions(string pathChatServiceSid, string pathConversationSid)
{
PathChatServiceSid = pathChatServiceSid;
PathConversationSid = pathConversationSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Author != null)
{
p.Add(new KeyValuePair<string, string>("Author", Author));
}
if (Body != null)
{
p.Add(new KeyValuePair<string, string>("Body", Body));
}
if (DateCreated != null)
{
p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated)));
}
if (DateUpdated != null)
{
p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated)));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
if (MediaSid != null)
{
p.Add(new KeyValuePair<string, string>("MediaSid", MediaSid.ToString()));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Update an existing message in the conversation
/// </summary>
public class UpdateMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Conversation Service that the resource is associated with.
/// </summary>
public string PathChatServiceSid { get; }
/// <summary>
/// The unique ID of the Conversation for this message.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// The channel specific identifier of the message's author.
/// </summary>
public string Author { get; set; }
/// <summary>
/// The content of the message.
/// </summary>
public string Body { get; set; }
/// <summary>
/// The date that this resource was created.
/// </summary>
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date that this resource was last updated.
/// </summary>
public DateTime? DateUpdated { get; set; }
/// <summary>
/// A string metadata field you can use to store any data you wish.
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public MessageResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new UpdateMessageOptions
/// </summary>
/// <param name="pathChatServiceSid"> The SID of the Conversation Service that the resource is associated with. </param>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this message. </param>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public UpdateMessageOptions(string pathChatServiceSid, string pathConversationSid, string pathSid)
{
PathChatServiceSid = pathChatServiceSid;
PathConversationSid = pathConversationSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Author != null)
{
p.Add(new KeyValuePair<string, string>("Author", Author));
}
if (Body != null)
{
p.Add(new KeyValuePair<string, string>("Body", Body));
}
if (DateCreated != null)
{
p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated)));
}
if (DateUpdated != null)
{
p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated)));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Remove a message from the conversation
/// </summary>
public class DeleteMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Conversation Service that the resource is associated with.
/// </summary>
public string PathChatServiceSid { get; }
/// <summary>
/// The unique ID of the Conversation for this message.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public MessageResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new DeleteMessageOptions
/// </summary>
/// <param name="pathChatServiceSid"> The SID of the Conversation Service that the resource is associated with. </param>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this message. </param>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public DeleteMessageOptions(string pathChatServiceSid, string pathConversationSid, string pathSid)
{
PathChatServiceSid = pathChatServiceSid;
PathConversationSid = pathConversationSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Fetch a message from the conversation
/// </summary>
public class FetchMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The SID of the Conversation Service that the resource is associated with.
/// </summary>
public string PathChatServiceSid { get; }
/// <summary>
/// The unique ID of the Conversation for this message.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchMessageOptions
/// </summary>
/// <param name="pathChatServiceSid"> The SID of the Conversation Service that the resource is associated with. </param>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this message. </param>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public FetchMessageOptions(string pathChatServiceSid, string pathConversationSid, string pathSid)
{
PathChatServiceSid = pathChatServiceSid;
PathConversationSid = pathConversationSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Retrieve a list of all messages in the conversation
/// </summary>
public class ReadMessageOptions : ReadOptions<MessageResource>
{
/// <summary>
/// The SID of the Conversation Service that the resource is associated with.
/// </summary>
public string PathChatServiceSid { get; }
/// <summary>
/// The unique ID of the Conversation for messages.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// The sort order of the returned messages
/// </summary>
public MessageResource.OrderTypeEnum Order { get; set; }
/// <summary>
/// Construct a new ReadMessageOptions
/// </summary>
/// <param name="pathChatServiceSid"> The SID of the Conversation Service that the resource is associated with. </param>
/// <param name="pathConversationSid"> The unique ID of the Conversation for messages. </param>
public ReadMessageOptions(string pathChatServiceSid, string pathConversationSid)
{
PathChatServiceSid = pathChatServiceSid;
PathConversationSid = pathConversationSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Order != null)
{
p.Add(new KeyValuePair<string, string>("Order", Order.ToString()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL 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.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Drawing.Printing;
using fyiReporting.RdlDesign.Resources;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal partial class ReportCtl : System.Windows.Forms.UserControl, IProperty
{
internal ReportCtl(DesignXmlDraw dxDraw)
{
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
XmlNode rNode = _Draw.GetReportNode();
tbWidth.Text = _Draw.GetElementValue(rNode, "Width", "");
tbReportAuthor.Text = _Draw.GetElementValue(rNode, "Author", "");
tbReportDescription.Text = _Draw.GetElementValue(rNode, "Description", "");
tbPageWidth.Text = _Draw.GetElementValue(rNode, "PageWidth", "8.5in");
tbPageHeight.Text = _Draw.GetElementValue(rNode, "PageHeight", "11in");
tbMarginLeft.Text = _Draw.GetElementValue(rNode, "LeftMargin", "");
tbMarginRight.Text = _Draw.GetElementValue(rNode, "RightMargin", "");
tbMarginBottom.Text = _Draw.GetElementValue(rNode, "BottomMargin", "");
tbMarginTop.Text = _Draw.GetElementValue(rNode, "TopMargin", "");
// Page header settings
XmlNode phNode = _Draw.GetCreateNamedChildNode(rNode, "PageHeader");
this.chkPHFirst.Checked = _Draw.GetElementValue(phNode, "PrintOnFirstPage", "true").ToLower() == "true" ? true : false;
this.chkPHLast.Checked = _Draw.GetElementValue(phNode, "PrintOnLastPage", "true").ToLower() == "true" ? true : false;
// Page footer settings
XmlNode pfNode = _Draw.GetCreateNamedChildNode(rNode, "PageFooter");
this.chkPFFirst.Checked = _Draw.GetElementValue(pfNode, "PrintOnFirstPage", "true").ToLower() == "true" ? true : false;
this.chkPFLast.Checked = _Draw.GetElementValue(pfNode, "PrintOnLastPage", "true").ToLower() == "true" ? true : false;
PrinterSettings settings = new PrinterSettings();
cbPageSize.DisplayMember = "PaperName";
int width = Conversions.MeasurementTypeAsHundrethsOfAnInch(tbPageWidth.Text);
int height = Conversions.MeasurementTypeAsHundrethsOfAnInch(tbPageHeight.Text);
int pageCount = settings.PaperSizes.Count;
// This conversion may be better converted to mm instead of hundrethds of an inch
int count = 0;
bool sizeFound = false;
foreach (PaperSize psize in settings.PaperSizes)
{
cbPageSize.Items.Add(psize);
if ((psize.Width == width) &&
(psize.Height == height) &&
(sizeFound == false))
{
cbPageSize.SelectedIndex = count;
sizeFound = true;
}
count = count + 1;
}
}
private string GetPaperSizeAsInch(int paperSize)
{
// paperSize is in hundredths of an inch.
return (paperSize / 100.0).ToString() + "in";
}
private string GetPaperSizeAsMillimeter(int paperSize)
{
// paperSize is in hundredths of an inch.
return ((paperSize / 100.0) * 25.4).ToString() + "mm";
}
public bool IsValid()
{
return true;
}
public void Apply()
{
XmlNode rNode = _Draw.GetReportNode();
_Draw.SetElement(rNode, "Width", DesignerUtility.MakeValidSize(tbWidth.Text, false));
_Draw.SetElement(rNode, "Author", tbReportAuthor.Text);
_Draw.SetElement(rNode, "Description", tbReportDescription.Text);
_Draw.SetElement(rNode, "PageWidth", tbPageWidth.Text);
_Draw.SetElement(rNode, "PageHeight", tbPageHeight.Text);
if (tbMarginLeft.Text.Trim().Length > 0)
_Draw.SetElement(rNode, "LeftMargin", tbMarginLeft.Text);
else
_Draw.RemoveElement(rNode, "LeftMargin");
if (tbMarginRight.Text.Trim().Length > 0)
_Draw.SetElement(rNode, "RightMargin", tbMarginRight.Text);
else
_Draw.RemoveElement(rNode, "RightMargin");
if (tbMarginBottom.Text.Trim().Length > 0)
_Draw.SetElement(rNode, "BottomMargin", tbMarginBottom.Text);
else
_Draw.RemoveElement(rNode, "BottomMargin");
if (tbMarginTop.Text.Trim().Length > 0)
_Draw.SetElement(rNode, "TopMargin", tbMarginTop.Text);
else
_Draw.RemoveElement(rNode, "TopMargin");
// Page header settings
XmlNode phNode = _Draw.GetCreateNamedChildNode(rNode, "PageHeader");
_Draw.SetElement(phNode, "PrintOnFirstPage", this.chkPHFirst.Checked ? "true" : "false");
_Draw.SetElement(phNode, "PrintOnLastPage", this.chkPHLast.Checked ? "true" : "false");
// Page footer settings
XmlNode pfNode = _Draw.GetCreateNamedChildNode(rNode, "PageFooter");
_Draw.SetElement(pfNode, "PrintOnFirstPage", this.chkPFFirst.Checked ? "true" : "false");
_Draw.SetElement(pfNode, "PrintOnLastPage", this.chkPFLast.Checked ? "true" : "false");
}
private void tbSize_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb == null)
return;
try { DesignerUtility.ValidateSize(tb.Text, false, false); }
catch (Exception ex)
{
e.Cancel = true;
MessageBox.Show(string.Format(Strings.ReportCtl_Show_SizeInvalid, tb.Text, ex.Message), tb.Tag + " " + Strings.ReportCtl_Show_Field_Invalid);
}
}
private void cbPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbPageSize.SelectedItem == null)
{
return;
}
if (cbPageSize.SelectedItem is PaperSize)
{
PaperSize size = (PaperSize)cbPageSize.SelectedItem;
// If the currnent size is in millimeter continue showing as millimeter when changing paper sizes
if (tbPageWidth.Text.Trim().ToLower().EndsWith("mm"))
{
tbPageWidth.Text = GetPaperSizeAsMillimeter(size.Width);
}
else
{
tbPageWidth.Text = GetPaperSizeAsInch(size.Width);
}
if (tbPageHeight.Text.Trim().ToLower().EndsWith("mm"))
{
tbPageHeight.Text = GetPaperSizeAsMillimeter(size.Height);
}
else
{
tbPageHeight.Text = GetPaperSizeAsInch(size.Height);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
{
/// <summary>
/// An <see cref="IModelBinder"/> which binds models from the request headers when a model
/// has the binding source <see cref="BindingSource.Header"/>.
/// </summary>
public class HeaderModelBinder : IModelBinder
{
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of <see cref="HeaderModelBinder"/>.
/// </summary>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
public HeaderModelBinder(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<HeaderModelBinder>();
}
/// <summary>
/// Initializes a new instance of <see cref="HeaderModelBinder"/>.
/// </summary>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
/// <param name="innerModelBinder">The <see cref="IModelBinder"/> which does the actual
/// binding of values.</param>
public HeaderModelBinder(ILoggerFactory loggerFactory, IModelBinder innerModelBinder)
{
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (innerModelBinder == null)
{
throw new ArgumentNullException(nameof(innerModelBinder));
}
_logger = loggerFactory.CreateLogger<HeaderModelBinder>();
InnerModelBinder = innerModelBinder;
}
// to enable unit testing
internal IModelBinder? InnerModelBinder { get; }
/// <inheritdoc />
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
_logger.AttemptingToBindModel(bindingContext);
// Property name can be null if the model metadata represents a type (rather than a property or parameter).
var headerName = bindingContext.FieldName;
// Do not set ModelBindingResult to Failed on not finding the value in the header as we want the inner
// ModelBinder to do that. This would give a chance to the inner binder to add more useful information.
// For example, SimpleTypeModelBinder adds a model error when binding to let's say an integer and the
// model is null.
var request = bindingContext.HttpContext.Request;
if (!request.Headers.ContainsKey(headerName))
{
_logger.FoundNoValueInRequest(bindingContext);
}
if (InnerModelBinder == null)
{
BindWithoutInnerBinder(bindingContext);
return;
}
var headerValueProvider = GetHeaderValueProvider(headerName, bindingContext);
// Capture the top level object here as entering nested scope would make it 'false'.
var isTopLevelObject = bindingContext.IsTopLevelObject;
// Create a new binding scope in order to supply the HeaderValueProvider so that the binders like
// SimpleTypeModelBinder can find values from header.
ModelBindingResult result;
using (bindingContext.EnterNestedScope(
bindingContext.ModelMetadata,
fieldName: bindingContext.FieldName,
modelName: bindingContext.ModelName,
model: bindingContext.Model))
{
bindingContext.IsTopLevelObject = isTopLevelObject;
bindingContext.ValueProvider = headerValueProvider;
await InnerModelBinder.BindModelAsync(bindingContext);
result = bindingContext.Result;
}
bindingContext.Result = result;
_logger.DoneAttemptingToBindModel(bindingContext);
}
private HeaderValueProvider GetHeaderValueProvider(string headerName, ModelBindingContext bindingContext)
{
var request = bindingContext.HttpContext.Request;
// Prevent breaking existing users in scenarios where they are binding to a 'string' property
// and expect the whole comma separated string, if any, as a single string and not as a string array.
var values = Array.Empty<string>();
if (request.Headers.ContainsKey(headerName))
{
if (bindingContext.ModelMetadata.IsEnumerableType)
{
values = request.Headers.GetCommaSeparatedValues(headerName);
}
else
{
values = new[] { request.Headers[headerName].ToString() };
}
}
return new HeaderValueProvider(values);
}
private void BindWithoutInnerBinder(ModelBindingContext bindingContext)
{
var headerName = bindingContext.FieldName;
var request = bindingContext.HttpContext.Request;
object? model;
if (bindingContext.ModelType == typeof(string))
{
var value = request.Headers[headerName];
model = value.ToString();
}
else if (ModelBindingHelper.CanGetCompatibleCollection<string>(bindingContext))
{
var values = request.Headers.GetCommaSeparatedValues(headerName);
model = GetCompatibleCollection(bindingContext, values);
}
else
{
// An unsupported datatype or a new collection is needed (perhaps because target type is an array) but
// can't assign it to the property.
model = null;
}
if (model == null)
{
// Silently fail if unable to create an instance or use the current instance. Also reach here in the
// typeof(string) case if the header does not exist in the request and in the
// typeof(IEnumerable<string>) case if the header does not exist and this is not a top-level object.
bindingContext.Result = ModelBindingResult.Failed();
}
else
{
bindingContext.ModelState.SetModelValue(
bindingContext.ModelName,
request.Headers.GetCommaSeparatedValues(headerName),
request.Headers[headerName]);
bindingContext.Result = ModelBindingResult.Success(model);
}
_logger.DoneAttemptingToBindModel(bindingContext);
}
private static object? GetCompatibleCollection(ModelBindingContext bindingContext, string[] values)
{
// Almost-always success if IsTopLevelObject.
if (!bindingContext.IsTopLevelObject && values.Length == 0)
{
return null;
}
if (bindingContext.ModelType.IsAssignableFrom(typeof(string[])))
{
// Array we already have is compatible.
return values;
}
var collection = ModelBindingHelper.GetCompatibleCollection<string>(bindingContext, values.Length);
for (var i = 0; i < values.Length; i++)
{
collection.Add(values[i]);
}
return collection;
}
private class HeaderValueProvider : IValueProvider
{
private readonly string[] _values;
public HeaderValueProvider(string[] values)
{
Debug.Assert(values != null);
_values = values;
}
public bool ContainsPrefix(string prefix)
{
return _values.Length != 0;
}
public ValueProviderResult GetValue(string key)
{
if (_values.Length == 0)
{
return ValueProviderResult.None;
}
else
{
return new ValueProviderResult(_values, CultureInfo.InvariantCulture);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using System.Numerics;
namespace NumericsTests
{
[TestClass()]
public class Matrix3x2Test
{
static Matrix3x2 GenerateMatrixNumberFrom1To6()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 1.0f; a.M12 = 2.0f;
a.M21 = 3.0f; a.M22 = 4.0f;
a.M31 = 5.0f; a.M32 = 6.0f;
return a;
}
static Matrix3x2 GenerateTestMatrix()
{
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.Translation = new Vector2(111.0f, 222.0f);
return m;
}
// A test for Identity
[TestMethod]
public void Matrix3x2IdentityTest()
{
Matrix3x2 val = new Matrix3x2();
val.M11 = val.M22 = 1.0f;
Assert.IsTrue(MathHelper.Equal(val, Matrix3x2.Identity), "Matrix3x2.Indentity was not set correctly.");
}
// A test for Determinant
[TestMethod]
public void Matrix3x2DeterminantTest()
{
Matrix3x2 target = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
float val = 1.0f;
float det = target.GetDeterminant();
Assert.IsTrue(MathHelper.Equal(val, det), "Matrix3x2.GetDeterminant was not set correctly.");
}
// A test for Determinant
// Determinant test |A| = 1 / |A'|
[TestMethod]
public void Matrix3x2DeterminantTest1()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 5.0f; a.M12 = 2.0f;
a.M21 = 12.0f; a.M22 = 6.8f;
a.M31 = 6.5f; a.M32 = 1.0f;
Matrix3x2 i;
Assert.IsTrue(Matrix3x2.Invert(a, out i));
float detA = a.GetDeterminant();
float detI = i.GetDeterminant();
float t = 1.0f / detI;
// only accurate to 3 precision
Assert.IsTrue(System.Math.Abs(detA - t) < 1e-3, "Matrix3x2.GetDeterminant was not set correctly.");
// sanity check against 4x4 version
Assert.AreEqual(new Matrix4x4(a).GetDeterminant(), detA);
Assert.AreEqual(new Matrix4x4(i).GetDeterminant(), detI);
}
// A test for Invert (Matrix3x2)
[TestMethod]
public void Matrix3x2InvertTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
Matrix3x2 expected = new Matrix3x2();
expected.M11 = 0.8660254f;
expected.M12 = -0.5f;
expected.M21 = 0.5f;
expected.M22 = 0.8660254f;
expected.M31 = 0;
expected.M32 = 0;
Matrix3x2 actual;
Assert.IsTrue(Matrix3x2.Invert(mtx, out actual));
Assert.IsTrue(MathHelper.Equal(expected, actual), "Matrix3x2.Invert did not return the expected value.");
Matrix3x2 i = mtx * actual;
Assert.IsTrue(MathHelper.Equal(i, Matrix3x2.Identity), "Matrix3x2.Invert did not return the expected value.");
}
// A test for Invert (Matrix3x2)
[TestMethod]
public void Matrix3x2InvertIdentityTest()
{
Matrix3x2 mtx = Matrix3x2.Identity;
Matrix3x2 actual;
Assert.IsTrue(Matrix3x2.Invert(mtx, out actual));
Assert.IsTrue(MathHelper.Equal(actual, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[TestMethod]
public void Matrix3x2InvertTranslationTest()
{
Matrix3x2 mtx = Matrix3x2.CreateTranslation(23, 42);
Matrix3x2 actual;
Assert.IsTrue(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.IsTrue(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[TestMethod]
public void Matrix3x2InvertRotationTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(2);
Matrix3x2 actual;
Assert.IsTrue(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.IsTrue(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[TestMethod]
public void Matrix3x2InvertScaleTest()
{
Matrix3x2 mtx = Matrix3x2.CreateScale(23, -42);
Matrix3x2 actual;
Assert.IsTrue(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.IsTrue(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[TestMethod]
public void Matrix3x2InvertAffineTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(2) *
Matrix3x2.CreateScale(23, -42) *
Matrix3x2.CreateTranslation(17, 53);
Matrix3x2 actual;
Assert.IsTrue(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.IsTrue(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for CreateRotation (float)
[TestMethod]
public void Matrix3x2CreateRotationTest()
{
float radians = MathHelper.ToRadians(50.0f);
Matrix3x2 expected = new Matrix3x2();
expected.M11 = 0.642787635f;
expected.M12 = 0.766044438f;
expected.M21 = -0.766044438f;
expected.M22 = 0.642787635f;
Matrix3x2 actual;
actual = Matrix3x2.CreateRotation(radians);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Matrix3x2.CreateRotation did not return the expected value.");
}
// A test for CreateRotation (float, Vector2)
[TestMethod]
public void Matrix3x2CreateRotationCenterTest()
{
float radians = MathHelper.ToRadians(30.0f);
Vector2 center = new Vector2(23, 42);
Matrix3x2 rotateAroundZero = Matrix3x2.CreateRotation(radians, Vector2.Zero);
Matrix3x2 rotateAroundZeroExpected = Matrix3x2.CreateRotation(radians);
Assert.IsTrue(MathHelper.Equal(rotateAroundZero, rotateAroundZeroExpected));
Matrix3x2 rotateAroundCenter = Matrix3x2.CreateRotation(radians, center);
Matrix3x2 rotateAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateRotation(radians) * Matrix3x2.CreateTranslation(center);
Assert.IsTrue(MathHelper.Equal(rotateAroundCenter, rotateAroundCenterExpected));
}
// A test for CreateRotation (float)
[TestMethod]
public void Matrix3x2CreateRotationRightAngleTest()
{
// 90 degree rotations must be exact!
Matrix3x2 actual = Matrix3x2.CreateRotation(0);
Assert.AreEqual(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2);
Assert.AreEqual(new Matrix3x2(0, 1, -1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi);
Assert.AreEqual(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2);
Assert.AreEqual(new Matrix3x2(0, -1, 1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2);
Assert.AreEqual(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2);
Assert.AreEqual(new Matrix3x2(0, 1, -1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2);
Assert.AreEqual(new Matrix3x2(0, -1, 1, 0, 0, 0), actual);
// But merely close-to-90 rotations should not be excessively clamped.
float delta = MathHelper.ToRadians(0.01f);
actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta);
Assert.IsFalse(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual));
actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta);
Assert.IsFalse(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual));
}
// A test for CreateRotation (float, Vector2)
[TestMethod]
public void Matrix3x2CreateRotationRightAngleCenterTest()
{
Vector2 center = new Vector2(3, 7);
// 90 degree rotations must be exact!
Matrix3x2 actual = Matrix3x2.CreateRotation(0, center);
Assert.AreEqual(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2, center);
Assert.AreEqual(new Matrix3x2(0, 1, -1, 0, 10, 4), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi, center);
Assert.AreEqual(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2, center);
Assert.AreEqual(new Matrix3x2(0, -1, 1, 0, -4, 10), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2, center);
Assert.AreEqual(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2, center);
Assert.AreEqual(new Matrix3x2(0, 1, -1, 0, 10, 4), actual);
actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2, center);
Assert.AreEqual(new Matrix3x2(0, -1, 1, 0, -4, 10), actual);
// But merely close-to-90 rotations should not be excessively clamped.
float delta = MathHelper.ToRadians(0.01f);
actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta, center);
Assert.IsFalse(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual));
actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta, center);
Assert.IsFalse(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual));
}
// A test for Invert (Matrix3x2)
// Non invertible matrix - determinant is zero - singular matrix
[TestMethod]
public void Matrix3x2InvertTest1()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 0.0f; a.M12 = 2.0f;
a.M21 = 0.0f; a.M22 = 4.0f;
a.M31 = 5.0f; a.M32 = 6.0f;
float detA = a.GetDeterminant();
Assert.IsTrue(MathHelper.Equal(detA, 0.0f), "Matrix3x2.Invert did not return the expected value.");
Matrix3x2 actual;
Assert.IsFalse(Matrix3x2.Invert(a, out actual));
// all the elements in Actual is NaN
Assert.IsTrue(
float.IsNaN(actual.M11) && float.IsNaN(actual.M12) &&
float.IsNaN(actual.M21) && float.IsNaN(actual.M22) &&
float.IsNaN(actual.M31) && float.IsNaN(actual.M32)
, "Matrix3x2.Invert did not return the expected value.");
}
// A test for Lerp (Matrix3x2, Matrix3x2, float)
[TestMethod]
public void Matrix3x2LerpTest()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 11.0f; a.M12 = 12.0f;
a.M21 = 21.0f; a.M22 = 22.0f;
a.M31 = 31.0f; a.M32 = 32.0f;
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
float t = 0.5f;
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + (b.M11 - a.M11) * t;
expected.M12 = a.M12 + (b.M12 - a.M12) * t;
expected.M21 = a.M21 + (b.M21 - a.M21) * t;
expected.M22 = a.M22 + (b.M22 - a.M22) * t;
expected.M31 = a.M31 + (b.M31 - a.M31) * t;
expected.M32 = a.M32 + (b.M32 - a.M32) * t;
Matrix3x2 actual;
actual = Matrix3x2.Lerp(a, b, t);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Matrix3x2.Lerp did not return the expected value.");
}
// A test for operator - (Matrix3x2)
[TestMethod]
public void Matrix3x2UnaryNegationTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = -1.0f; expected.M12 = -2.0f;
expected.M21 = -3.0f; expected.M22 = -4.0f;
expected.M31 = -5.0f; expected.M32 = -6.0f;
Matrix3x2 actual = -a;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value.");
}
// A test for operator - (Matrix3x2, Matrix3x2)
[TestMethod]
public void Matrix3x2SubtractionTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
Matrix3x2 actual = a - b;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value.");
}
// A test for operator * (Matrix3x2, Matrix3x2)
[TestMethod]
public void Matrix3x2MultiplyTest1()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 * b.M11 + a.M12 * b.M21;
expected.M12 = a.M11 * b.M12 + a.M12 * b.M22;
expected.M21 = a.M21 * b.M11 + a.M22 * b.M21;
expected.M22 = a.M21 * b.M12 + a.M22 * b.M22;
expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31;
expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32;
Matrix3x2 actual = a * b;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value.");
// Sanity check by comparison with 4x4 multiply.
a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42);
b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1);
actual = a * b;
Matrix4x4 a44 = new Matrix4x4(a);
Matrix4x4 b44 = new Matrix4x4(b);
Matrix4x4 expected44 = a44 * b44;
Matrix4x4 actual44 = new Matrix4x4(actual);
Assert.IsTrue(MathHelper.Equal(expected44, actual44), "Matrix3x2.operator * did not return the expected value.");
}
// A test for operator * (Matrix3x2, Matrix3x2)
// Multiply with identity matrix
[TestMethod]
public void Matrix3x2MultiplyTest4()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 1.0f; a.M12 = 2.0f;
a.M21 = 5.0f; a.M22 = -6.0f;
a.M31 = 9.0f; a.M32 = 10.0f;
Matrix3x2 b = new Matrix3x2();
b = Matrix3x2.Identity;
Matrix3x2 expected = a;
Matrix3x2 actual = a * b;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value.");
}
// A test for operator + (Matrix3x2, Matrix3x2)
[TestMethod]
public void Matrix3x2AdditionTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + b.M11; expected.M12 = a.M12 + b.M12;
expected.M21 = a.M21 + b.M21; expected.M22 = a.M22 + b.M22;
expected.M31 = a.M31 + b.M31; expected.M32 = a.M32 + b.M32;
Matrix3x2 actual;
actual = a + b;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Matrix3x2.operator + did not return the expected value.");
}
// A test for ToString ()
[TestMethod]
public void Matrix3x2ToStringTest()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 11.0f; a.M12 = -12.0f;
a.M21 = 21.0f; a.M22 = 22.0f;
a.M31 = 31.0f; a.M32 = 32.0f;
string expected = "{ {M11:11 M12:-12} " +
"{M21:21 M22:22} " +
"{M31:31 M32:32} }";
string actual;
actual = a.ToString();
Assert.AreEqual(expected, actual, "Matrix3x2.ToString did not return the expected value.");
}
// A test for Add (Matrix3x2, Matrix3x2)
[TestMethod]
public void Matrix3x2AddTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + b.M11; expected.M12 = a.M12 + b.M12;
expected.M21 = a.M21 + b.M21; expected.M22 = a.M22 + b.M22;
expected.M31 = a.M31 + b.M31; expected.M32 = a.M32 + b.M32;
Matrix3x2 actual;
actual = Matrix3x2.Add(a, b);
Assert.AreEqual(expected, actual, "Matrix3x2.Add did not return the expected value.");
}
// A test for Equals (object)
[TestMethod]
public void Matrix3x2EqualsTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.AreEqual(expected, actual, "Matrix3x2.Equals did not return the expected value.");
// case 2: compare between different values
b.M11 = 11.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.AreEqual(expected, actual, "Matrix3x2.Equals did not return the expected value.");
// case 3: compare between different types.
obj = new Vector4();
expected = false;
actual = a.Equals(obj);
Assert.AreEqual(expected, actual, "Matrix3x2.Equals did not return the expected value.");
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.AreEqual(expected, actual, "Matrix3x2.Equals did not return the expected value.");
}
// A test for GetHashCode ()
[TestMethod]
public void Matrix3x2GetHashCodeTest()
{
Matrix3x2 target = GenerateMatrixNumberFrom1To6();
int expected = target.M11.GetHashCode() + target.M12.GetHashCode() +
target.M21.GetHashCode() + target.M22.GetHashCode() +
target.M31.GetHashCode() + target.M32.GetHashCode();
int actual;
actual = target.GetHashCode();
Assert.AreEqual(expected, actual, "Matrix3x2.GetHashCode did not return the expected value.");
}
// A test for Multiply (Matrix3x2, Matrix3x2)
[TestMethod]
public void Matrix3x2MultiplyTest3()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 * b.M11 + a.M12 * b.M21;
expected.M12 = a.M11 * b.M12 + a.M12 * b.M22;
expected.M21 = a.M21 * b.M11 + a.M22 * b.M21;
expected.M22 = a.M21 * b.M12 + a.M22 * b.M22;
expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31;
expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32;
Matrix3x2 actual;
actual = Matrix3x2.Multiply(a, b);
Assert.AreEqual(expected, actual, "Matrix3x2.Multiply did not return the expected value.");
// Sanity check by comparison with 4x4 multiply.
a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42);
b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1);
actual = Matrix3x2.Multiply(a, b);
Matrix4x4 a44 = new Matrix4x4(a);
Matrix4x4 b44 = new Matrix4x4(b);
Matrix4x4 expected44 = Matrix4x4.Multiply(a44, b44);
Matrix4x4 actual44 = new Matrix4x4(actual);
Assert.IsTrue(MathHelper.Equal(expected44, actual44), "Matrix3x2.Multiply did not return the expected value.");
}
// A test for Multiply (Matrix3x2, float)
[TestMethod]
public void Matrix3x2MultiplyTest5()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18);
Matrix3x2 actual = Matrix3x2.Multiply(a, 3);
Assert.AreEqual(expected, actual, "Matrix3x2.Multiply did not return the expected value.");
}
// A test for Multiply (Matrix3x2, float)
[TestMethod]
public void Matrix3x2MultiplyTest6()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18);
Matrix3x2 actual = a * 3;
Assert.AreEqual(expected, actual, "Matrix3x2.operator * did not return the expected value.");
}
// A test for Negate (Matrix3x2)
[TestMethod]
public void Matrix3x2NegateTest()
{
Matrix3x2 m = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = -1.0f; expected.M12 = -2.0f;
expected.M21 = -3.0f; expected.M22 = -4.0f;
expected.M31 = -5.0f; expected.M32 = -6.0f;
Matrix3x2 actual;
actual = Matrix3x2.Negate(m);
Assert.AreEqual(expected, actual, "Matrix3x2.Negate did not return the expected value.");
}
// A test for operator != (Matrix3x2, Matrix3x2)
[TestMethod]
public void Matrix3x2InequalityTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.AreEqual(expected, actual, "Matrix3x2.operator != did not return the expected value.");
// case 2: compare between different values
b.M11 = 11.0f;
expected = true;
actual = a != b;
Assert.AreEqual(expected, actual, "Matrix3x2.operator != did not return the expected value.");
}
// A test for operator == (Matrix3x2, Matrix3x2)
[TestMethod]
public void Matrix3x2EqualityTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.AreEqual(expected, actual, "Matrix3x2.operator == did not return the expected value.");
// case 2: compare between different values
b.M11 = 11.0f;
expected = false;
actual = a == b;
Assert.AreEqual(expected, actual, "Matrix3x2.operator == did not return the expected value.");
}
// A test for Subtract (Matrix3x2, Matrix3x2)
[TestMethod]
public void Matrix3x2SubtractTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
Matrix3x2 actual;
actual = Matrix3x2.Subtract(a, b);
Assert.AreEqual(expected, actual, "Matrix3x2.Subtract did not return the expected value.");
}
// A test for CreateScale (Vector2)
[TestMethod]
public void Matrix3x2CreateScaleTest1()
{
Vector2 scales = new Vector2(2.0f, 3.0f);
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 3.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(scales);
Assert.AreEqual(expected, actual, "Matrix3x2.CreateScale did not return the expected value.");
}
// A test for CreateScale (Vector2, Vector2)
[TestMethod]
public void Matrix3x2CreateScaleCenterTest1()
{
Vector2 scale = new Vector2(3, 4);
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale);
Assert.IsTrue(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center);
Assert.IsTrue(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateScale (float)
[TestMethod]
public void Matrix3x2CreateScaleTest2()
{
float scale = 2.0f;
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 2.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(scale);
Assert.AreEqual(expected, actual, "Matrix3x2.CreateScale did not return the expected value.");
}
// A test for CreateScale (float, Vector2)
[TestMethod]
public void Matrix3x2CreateScaleCenterTest2()
{
float scale = 5;
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale);
Assert.IsTrue(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center);
Assert.IsTrue(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateScale (float, float)
[TestMethod]
public void Matrix3x2CreateScaleTest3()
{
float xScale = 2.0f;
float yScale = 3.0f;
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 3.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(xScale, yScale);
Assert.AreEqual(expected, actual, "Matrix3x2.CreateScale did not return the expected value.");
}
// A test for CreateScale (float, float, Vector2)
[TestMethod]
public void Matrix3x2CreateScaleCenterTest3()
{
Vector2 scale = new Vector2(3, 4);
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale.X, scale.Y, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale.X, scale.Y);
Assert.IsTrue(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale.X, scale.Y, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale.X, scale.Y) * Matrix3x2.CreateTranslation(center);
Assert.IsTrue(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateTranslation (Vector2)
[TestMethod]
public void Matrix3x2CreateTranslationTest1()
{
Vector2 position = new Vector2(2.0f, 3.0f);
Matrix3x2 expected = new Matrix3x2(
1.0f, 0.0f,
0.0f, 1.0f,
2.0f, 3.0f);
Matrix3x2 actual = Matrix3x2.CreateTranslation(position);
Assert.AreEqual(expected, actual, "Matrix3x2.CreateTranslation did not return the expected value.");
}
// A test for CreateTranslation (float, float)
[TestMethod]
public void Matrix3x2CreateTranslationTest2()
{
float xPosition = 2.0f;
float yPosition = 3.0f;
Matrix3x2 expected = new Matrix3x2(
1.0f, 0.0f,
0.0f, 1.0f,
2.0f, 3.0f);
Matrix3x2 actual = Matrix3x2.CreateTranslation(xPosition, yPosition);
Assert.AreEqual(expected, actual, "Matrix3x2.CreateTranslation did not return the expected value.");
}
// A test for Translation
[TestMethod]
public void Matrix3x2TranslationTest()
{
Matrix3x2 a = GenerateTestMatrix();
Matrix3x2 b = a;
// Transfomed vector that has same semantics of property must be same.
Vector2 val = new Vector2(a.M31, a.M32);
Assert.AreEqual(val, a.Translation, "Matrix3x2.Translation was not set correctly.");
// Set value and get value must be same.
val = new Vector2(1.0f, 2.0f);
a.Translation = val;
Assert.AreEqual(val, a.Translation, "Matrix3x2.Translation was not set correctly.");
// Make sure it only modifies expected value of matrix.
Assert.IsTrue(
a.M11 == b.M11 && a.M12 == b.M12 &&
a.M21 == b.M21 && a.M22 == b.M22 &&
a.M31 != b.M31 && a.M32 != b.M32,
"Matrix3x2.Translation modified unexpected value of matrix.");
}
// A test for Equals (Matrix3x2)
[TestMethod]
public void Matrix3x2EqualsTest1()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.AreEqual(expected, actual, "Matrix3x2.Equals did not return the expected value.");
// case 2: compare between different values
b.M11 = 11.0f;
expected = false;
actual = a.Equals(b);
Assert.AreEqual(expected, actual, "Matrix3x2.Equals did not return the expected value.");
}
// A test for CreateSkew (float, float)
[TestMethod]
public void Matrix3x2CreateSkewIdentityTest()
{
Matrix3x2 expected = Matrix3x2.Identity;
Matrix3x2 actual = Matrix3x2.CreateSkew(0, 0);
Assert.AreEqual(expected, actual, "Matrix3x2.CreateSkew did not return the expected value.");
}
// A test for CreateSkew (float, float)
[TestMethod]
public void Matrix3x2CreateSkewXTest()
{
Matrix3x2 expected = new Matrix3x2(1, 0, -0.414213562373095f, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(-MathHelper.Pi / 8, 0);
Assert.IsTrue(MathHelper.Equal(expected, actual));
expected = new Matrix3x2(1, 0, 0.414213562373095f, 1, 0, 0);
actual = Matrix3x2.CreateSkew(MathHelper.Pi / 8, 0);
Assert.IsTrue(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(0, 1), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(0.414213568f, 1), result));
result = Vector2.Transform(new Vector2(0, -1), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(-0.414213568f, -1), result));
result = Vector2.Transform(new Vector2(3, 10), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(7.14213568f, 10), result));
}
// A test for CreateSkew (float, float)
[TestMethod]
public void Matrix3x2CreateSkewYTest()
{
Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 0, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(0, -MathHelper.Pi / 8);
Assert.IsTrue(MathHelper.Equal(expected, actual));
expected = new Matrix3x2(1, 0.414213562373095f, 0, 1, 0, 0);
actual = Matrix3x2.CreateSkew(0, MathHelper.Pi / 8);
Assert.IsTrue(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(1, 0), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(1, 0.414213568f), result));
result = Vector2.Transform(new Vector2(-1, 0), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(-1, -0.414213568f), result));
result = Vector2.Transform(new Vector2(10, 3), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(10, 7.14213568f), result));
}
// A test for CreateSkew (float, float)
[TestMethod]
public void Matrix3x2CreateSkewXYTest()
{
Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 1, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(MathHelper.Pi / 4, -MathHelper.Pi / 8);
Assert.IsTrue(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(1, 0), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(1, -0.414213562373095f), result));
result = Vector2.Transform(new Vector2(0, 1), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(1, 1), result));
result = Vector2.Transform(new Vector2(1, 1), actual);
Assert.IsTrue(MathHelper.Equal(new Vector2(2, 0.585786437626905f), result));
}
// A test for CreateSkew (float, float, Vector2)
[TestMethod]
public void Matrix3x2CreateSkewCenterTest()
{
float skewX = 1, skewY = 2;
Vector2 center = new Vector2(23, 42);
Matrix3x2 skewAroundZero = Matrix3x2.CreateSkew(skewX, skewY, Vector2.Zero);
Matrix3x2 skewAroundZeroExpected = Matrix3x2.CreateSkew(skewX, skewY);
Assert.IsTrue(MathHelper.Equal(skewAroundZero, skewAroundZeroExpected));
Matrix3x2 skewAroundCenter = Matrix3x2.CreateSkew(skewX, skewY, center);
Matrix3x2 skewAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateSkew(skewX, skewY) * Matrix3x2.CreateTranslation(center);
Assert.IsTrue(MathHelper.Equal(skewAroundCenter, skewAroundCenterExpected));
}
// A test for IsIdentity
[TestMethod]
public void Matrix3x2IsIdentityTest()
{
Assert.IsTrue(Matrix3x2.Identity.IsIdentity);
Assert.IsTrue(new Matrix3x2(1, 0, 0, 1, 0, 0).IsIdentity);
Assert.IsFalse(new Matrix3x2(0, 0, 0, 1, 0, 0).IsIdentity);
Assert.IsFalse(new Matrix3x2(1, 1, 0, 1, 0, 0).IsIdentity);
Assert.IsFalse(new Matrix3x2(1, 0, 1, 1, 0, 0).IsIdentity);
Assert.IsFalse(new Matrix3x2(1, 0, 0, 0, 0, 0).IsIdentity);
Assert.IsFalse(new Matrix3x2(1, 0, 0, 1, 1, 0).IsIdentity);
Assert.IsFalse(new Matrix3x2(1, 0, 0, 1, 0, 1).IsIdentity);
}
// A test for Matrix3x2 comparison involving NaN values
[TestMethod]
public void Matrix3x2EqualsNanTest()
{
Matrix3x2 a = new Matrix3x2(float.NaN, 0, 0, 0, 0, 0);
Matrix3x2 b = new Matrix3x2(0, float.NaN, 0, 0, 0, 0);
Matrix3x2 c = new Matrix3x2(0, 0, float.NaN, 0, 0, 0);
Matrix3x2 d = new Matrix3x2(0, 0, 0, float.NaN, 0, 0);
Matrix3x2 e = new Matrix3x2(0, 0, 0, 0, float.NaN, 0);
Matrix3x2 f = new Matrix3x2(0, 0, 0, 0, 0, float.NaN);
Assert.IsFalse(a == new Matrix3x2());
Assert.IsFalse(b == new Matrix3x2());
Assert.IsFalse(c == new Matrix3x2());
Assert.IsFalse(d == new Matrix3x2());
Assert.IsFalse(e == new Matrix3x2());
Assert.IsFalse(f == new Matrix3x2());
Assert.IsTrue(a != new Matrix3x2());
Assert.IsTrue(b != new Matrix3x2());
Assert.IsTrue(c != new Matrix3x2());
Assert.IsTrue(d != new Matrix3x2());
Assert.IsTrue(e != new Matrix3x2());
Assert.IsTrue(f != new Matrix3x2());
Assert.IsFalse(a.Equals(new Matrix3x2()));
Assert.IsFalse(b.Equals(new Matrix3x2()));
Assert.IsFalse(c.Equals(new Matrix3x2()));
Assert.IsFalse(d.Equals(new Matrix3x2()));
Assert.IsFalse(e.Equals(new Matrix3x2()));
Assert.IsFalse(f.Equals(new Matrix3x2()));
Assert.IsFalse(a.IsIdentity);
Assert.IsFalse(b.IsIdentity);
Assert.IsFalse(c.IsIdentity);
Assert.IsFalse(d.IsIdentity);
Assert.IsFalse(e.IsIdentity);
Assert.IsFalse(f.IsIdentity);
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.IsFalse(a.Equals(a));
Assert.IsFalse(b.Equals(b));
Assert.IsFalse(c.Equals(c));
Assert.IsFalse(d.Equals(d));
Assert.IsFalse(e.Equals(e));
Assert.IsFalse(f.Equals(f));
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[TestMethod]
public unsafe void Matrix3x2SizeofTest()
{
Assert.AreEqual(24, sizeof(Matrix3x2));
Assert.AreEqual(48, sizeof(Matrix3x2_2x));
Assert.AreEqual(28, sizeof(Matrix3x2PlusFloat));
Assert.AreEqual(56, sizeof(Matrix3x2PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2_2x
{
Matrix3x2 a;
Matrix3x2 b;
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2PlusFloat
{
Matrix3x2 v;
float f;
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2PlusFloat_2x
{
Matrix3x2PlusFloat a;
Matrix3x2PlusFloat b;
}
// A test to make sure the fields are laid out how we expect
[TestMethod]
public unsafe void Matrix3x2FieldOffsetTest()
{
Matrix3x2 value;
Assert.AreEqual(0 + new IntPtr(&value).ToInt64(), new IntPtr(&value.M11).ToInt64());
Assert.AreEqual(4 + new IntPtr(&value).ToInt64(), new IntPtr(&value.M12).ToInt64());
Assert.AreEqual(8 + new IntPtr(&value).ToInt64(), new IntPtr(&value.M21).ToInt64());
Assert.AreEqual(12 + new IntPtr(&value).ToInt64(), new IntPtr(&value.M22).ToInt64());
Assert.AreEqual(16 + new IntPtr(&value).ToInt64(), new IntPtr(&value.M31).ToInt64());
Assert.AreEqual(20 + new IntPtr(&value).ToInt64(), new IntPtr(&value.M32).ToInt64());
}
// A test to validate interop between .NET (System.Numerics) and WinRT (Microsoft.Graphics.Canvas.Numerics)
[TestMethod]
public void Matrix3x2WinRTInteropTest()
{
Matrix3x2 a = new Matrix3x2(1, 2, 3, 4, 5, 6);
Microsoft.Graphics.Canvas.Numerics.Matrix3x2 b = a;
Assert.AreEqual(a.M11, b.M11);
Assert.AreEqual(a.M12, b.M12);
Assert.AreEqual(a.M21, b.M21);
Assert.AreEqual(a.M22, b.M22);
Assert.AreEqual(a.M31, b.M31);
Assert.AreEqual(a.M32, b.M32);
Matrix3x2 c = b;
Assert.AreEqual(a, c);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Diagnostics
{
public partial class CounterCreationData
{
public CounterCreationData() { }
public CounterCreationData(string counterName, string counterHelp, System.Diagnostics.PerformanceCounterType counterType) { }
public string CounterHelp { get { throw null; } set { } }
public string CounterName { get { throw null; } set { } }
public System.Diagnostics.PerformanceCounterType CounterType { get { throw null; } set { } }
}
public partial class CounterCreationDataCollection : System.Collections.CollectionBase
{
public CounterCreationDataCollection() { }
public CounterCreationDataCollection(System.Diagnostics.CounterCreationDataCollection value) { }
public CounterCreationDataCollection(System.Diagnostics.CounterCreationData[] value) { }
public System.Diagnostics.CounterCreationData this[int index] { get { throw null; } set { } }
public int Add(System.Diagnostics.CounterCreationData value) { throw null; }
public void AddRange(System.Diagnostics.CounterCreationDataCollection value) { }
public void AddRange(System.Diagnostics.CounterCreationData[] value) { }
public bool Contains(System.Diagnostics.CounterCreationData value) { throw null; }
public void CopyTo(System.Diagnostics.CounterCreationData[] array, int index) { }
public int IndexOf(System.Diagnostics.CounterCreationData value) { throw null; }
public void Insert(int index, System.Diagnostics.CounterCreationData value) { }
protected override void OnValidate(object value) { }
public virtual void Remove(System.Diagnostics.CounterCreationData value) { }
}
public readonly partial struct CounterSample
{
private readonly int _dummyPrimitive;
public static System.Diagnostics.CounterSample Empty;
public CounterSample(long rawValue, long baseValue, long counterFrequency, long systemFrequency, long timeStamp, long timeStamp100nSec, System.Diagnostics.PerformanceCounterType counterType) { throw null; }
public CounterSample(long rawValue, long baseValue, long counterFrequency, long systemFrequency, long timeStamp, long timeStamp100nSec, System.Diagnostics.PerformanceCounterType counterType, long counterTimeStamp) { throw null; }
public long BaseValue { get { throw null; } }
public long CounterFrequency { get { throw null; } }
public long CounterTimeStamp { get { throw null; } }
public System.Diagnostics.PerformanceCounterType CounterType { get { throw null; } }
public long RawValue { get { throw null; } }
public long SystemFrequency { get { throw null; } }
public long TimeStamp { get { throw null; } }
public long TimeStamp100nSec { get { throw null; } }
public static float Calculate(System.Diagnostics.CounterSample counterSample) { throw null; }
public static float Calculate(System.Diagnostics.CounterSample counterSample, System.Diagnostics.CounterSample nextCounterSample) { throw null; }
public bool Equals(System.Diagnostics.CounterSample sample) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Diagnostics.CounterSample a, System.Diagnostics.CounterSample b) { throw null; }
public static bool operator !=(System.Diagnostics.CounterSample a, System.Diagnostics.CounterSample b) { throw null; }
}
public static partial class CounterSampleCalculator
{
public static float ComputeCounterValue(System.Diagnostics.CounterSample newSample) { throw null; }
public static float ComputeCounterValue(System.Diagnostics.CounterSample oldSample, System.Diagnostics.CounterSample newSample) { throw null; }
}
public partial interface ICollectData
{
void CloseData();
void CollectData(int id, System.IntPtr valueName, System.IntPtr data, int totalBytes, out System.IntPtr res);
}
public partial class InstanceData
{
public InstanceData(string instanceName, System.Diagnostics.CounterSample sample) { }
public string InstanceName { get { throw null; } }
public long RawValue { get { throw null; } }
public System.Diagnostics.CounterSample Sample { get { throw null; } }
}
public partial class InstanceDataCollection : System.Collections.DictionaryBase
{
[System.ObsoleteAttribute("This constructor has been deprecated. Please use System.Diagnostics.InstanceDataCollectionCollection.get_Item to get an instance of this collection instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public InstanceDataCollection(string counterName) { }
public string CounterName { get { throw null; } }
public System.Diagnostics.InstanceData this[string instanceName] { get { throw null; } }
public System.Collections.ICollection Keys { get { throw null; } }
public System.Collections.ICollection Values { get { throw null; } }
public bool Contains(string instanceName) { throw null; }
public void CopyTo(System.Diagnostics.InstanceData[] instances, int index) { }
}
public partial class InstanceDataCollectionCollection : System.Collections.DictionaryBase
{
[System.ObsoleteAttribute("This constructor has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.ReadCategory() to get an instance of this collection instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public InstanceDataCollectionCollection() { }
public System.Diagnostics.InstanceDataCollection this[string counterName] { get { throw null; } }
public System.Collections.ICollection Keys { get { throw null; } }
public System.Collections.ICollection Values { get { throw null; } }
public bool Contains(string counterName) { throw null; }
public void CopyTo(System.Diagnostics.InstanceDataCollection[] counters, int index) { }
}
public sealed partial class PerformanceCounter : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
{
[System.ObsoleteAttribute("This field has been deprecated and is not used. Use machine.config or an application configuration file to set the size of the PerformanceCounter file mapping.")]
public static int DefaultFileMappingSize;
public PerformanceCounter() { }
public PerformanceCounter(string categoryName, string counterName) { }
public PerformanceCounter(string categoryName, string counterName, bool readOnly) { }
public PerformanceCounter(string categoryName, string counterName, string instanceName) { }
public PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly) { }
public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName) { }
public string CategoryName { get { throw null; } set { } }
public string CounterHelp { get { throw null; } }
public string CounterName { get { throw null; } set { } }
public System.Diagnostics.PerformanceCounterType CounterType { get { throw null; } }
public System.Diagnostics.PerformanceCounterInstanceLifetime InstanceLifetime { get { throw null; } set { } }
public string InstanceName { get { throw null; } set { } }
public string MachineName { get { throw null; } set { } }
public long RawValue { get { throw null; } set { } }
public bool ReadOnly { get { throw null; } set { } }
public void BeginInit() { }
public void Close() { }
public static void CloseSharedResources() { }
public long Decrement() { throw null; }
protected override void Dispose(bool disposing) { }
public void EndInit() { }
public long Increment() { throw null; }
public long IncrementBy(long value) { throw null; }
public System.Diagnostics.CounterSample NextSample() { throw null; }
public float NextValue() { throw null; }
public void RemoveInstance() { }
}
public sealed partial class PerformanceCounterCategory
{
public PerformanceCounterCategory() { }
public PerformanceCounterCategory(string categoryName) { }
public PerformanceCounterCategory(string categoryName, string machineName) { }
public string CategoryHelp { get { throw null; } }
public string CategoryName { get { throw null; } set { } }
public System.Diagnostics.PerformanceCounterCategoryType CategoryType { get { throw null; } }
public string MachineName { get { throw null; } set { } }
public bool CounterExists(string counterName) { throw null; }
public static bool CounterExists(string counterName, string categoryName) { throw null; }
public static bool CounterExists(string counterName, string categoryName, string machineName) { throw null; }
[System.ObsoleteAttribute("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Diagnostics.PerformanceCounterCategory Create(string categoryName, string categoryHelp, System.Diagnostics.CounterCreationDataCollection counterData) { throw null; }
public static System.Diagnostics.PerformanceCounterCategory Create(string categoryName, string categoryHelp, System.Diagnostics.PerformanceCounterCategoryType categoryType, System.Diagnostics.CounterCreationDataCollection counterData) { throw null; }
public static System.Diagnostics.PerformanceCounterCategory Create(string categoryName, string categoryHelp, System.Diagnostics.PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) { throw null; }
[System.ObsoleteAttribute("This method has been deprecated. Please use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Diagnostics.PerformanceCounterCategory Create(string categoryName, string categoryHelp, string counterName, string counterHelp) { throw null; }
public static void Delete(string categoryName) { }
public static bool Exists(string categoryName) { throw null; }
public static bool Exists(string categoryName, string machineName) { throw null; }
public static System.Diagnostics.PerformanceCounterCategory[] GetCategories() { throw null; }
public static System.Diagnostics.PerformanceCounterCategory[] GetCategories(string machineName) { throw null; }
public System.Diagnostics.PerformanceCounter[] GetCounters() { throw null; }
public System.Diagnostics.PerformanceCounter[] GetCounters(string instanceName) { throw null; }
public string[] GetInstanceNames() { throw null; }
public bool InstanceExists(string instanceName) { throw null; }
public static bool InstanceExists(string instanceName, string categoryName) { throw null; }
public static bool InstanceExists(string instanceName, string categoryName, string machineName) { throw null; }
public System.Diagnostics.InstanceDataCollectionCollection ReadCategory() { throw null; }
}
public enum PerformanceCounterCategoryType
{
MultiInstance = 1,
SingleInstance = 0,
Unknown = -1,
}
public enum PerformanceCounterInstanceLifetime
{
Global = 0,
Process = 1,
}
public sealed partial class PerformanceCounterManager : System.Diagnostics.ICollectData
{
[System.ObsoleteAttribute("This class has been deprecated. Use the PerformanceCounters through the System.Diagnostics.PerformanceCounter class instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public PerformanceCounterManager() { }
[System.ObsoleteAttribute("This class has been deprecated. Use the PerformanceCounters through the System.Diagnostics.PerformanceCounter class instead. https://go.microsoft.com/fwlink/?linkid=14202")]
void System.Diagnostics.ICollectData.CloseData() { }
[System.ObsoleteAttribute("This class has been deprecated. Use the PerformanceCounters through the System.Diagnostics.PerformanceCounter class instead. https://go.microsoft.com/fwlink/?linkid=14202")]
void System.Diagnostics.ICollectData.CollectData(int callIdx, System.IntPtr valueNamePtr, System.IntPtr dataPtr, int totalBytes, out System.IntPtr res) { throw null; }
}
public enum PerformanceCounterType
{
AverageBase = 1073939458,
AverageCount64 = 1073874176,
AverageTimer32 = 805438464,
CounterDelta32 = 4195328,
CounterDelta64 = 4195584,
CounterMultiBase = 1107494144,
CounterMultiTimer = 574686464,
CounterMultiTimer100Ns = 575735040,
CounterMultiTimer100NsInverse = 592512256,
CounterMultiTimerInverse = 591463680,
CounterTimer = 541132032,
CounterTimerInverse = 557909248,
CountPerTimeInterval32 = 4523008,
CountPerTimeInterval64 = 4523264,
ElapsedTime = 807666944,
NumberOfItems32 = 65536,
NumberOfItems64 = 65792,
NumberOfItemsHEX32 = 0,
NumberOfItemsHEX64 = 256,
RateOfCountsPerSecond32 = 272696320,
RateOfCountsPerSecond64 = 272696576,
RawBase = 1073939459,
RawFraction = 537003008,
SampleBase = 1073939457,
SampleCounter = 4260864,
SampleFraction = 549585920,
Timer100Ns = 542180608,
Timer100NsInverse = 558957824,
}
}
namespace System.Diagnostics.PerformanceData
{
public sealed partial class CounterData
{
internal CounterData() { }
public long RawValue { get { throw null; } set { } }
public long Value { get { throw null; } set { } }
public void Decrement() { }
public void Increment() { }
public void IncrementBy(long value) { }
}
public partial class CounterSet : System.IDisposable
{
public CounterSet(System.Guid providerGuid, System.Guid counterSetGuid, System.Diagnostics.PerformanceData.CounterSetInstanceType instanceType) { }
public void AddCounter(int counterId, System.Diagnostics.PerformanceData.CounterType counterType) { }
public void AddCounter(int counterId, System.Diagnostics.PerformanceData.CounterType counterType, string counterName) { }
public System.Diagnostics.PerformanceData.CounterSetInstance CreateCounterSetInstance(string instanceName) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~CounterSet() { }
}
public sealed partial class CounterSetInstance : System.IDisposable
{
internal CounterSetInstance() { }
public System.Diagnostics.PerformanceData.CounterSetInstanceCounterDataSet Counters { get { throw null; } }
public void Dispose() { }
~CounterSetInstance() { }
}
public sealed partial class CounterSetInstanceCounterDataSet : System.IDisposable
{
internal CounterSetInstanceCounterDataSet() { }
public System.Diagnostics.PerformanceData.CounterData this[int counterId] { get { throw null; } }
public System.Diagnostics.PerformanceData.CounterData this[string counterName] { get { throw null; } }
public void Dispose() { }
~CounterSetInstanceCounterDataSet() { }
}
public enum CounterSetInstanceType
{
GlobalAggregate = 4,
GlobalAggregateWithHistory = 11,
InstanceAggregate = 22,
Multiple = 2,
MultipleAggregate = 6,
Single = 0,
}
public enum CounterType
{
AverageBase = 1073939458,
AverageCount64 = 1073874176,
AverageTimer32 = 805438464,
Delta32 = 4195328,
Delta64 = 4195584,
ElapsedTime = 807666944,
LargeQueueLength = 4523264,
MultiTimerBase = 1107494144,
MultiTimerPercentageActive = 574686464,
MultiTimerPercentageActive100Ns = 575735040,
MultiTimerPercentageNotActive = 591463680,
MultiTimerPercentageNotActive100Ns = 592512256,
ObjectSpecificTimer = 543229184,
PercentageActive = 541132032,
PercentageActive100Ns = 542180608,
PercentageNotActive = 557909248,
PercentageNotActive100Ns = 558957824,
PrecisionObjectSpecificTimer = 543622400,
PrecisionSystemTimer = 541525248,
PrecisionTimer100Ns = 542573824,
QueueLength = 4523008,
QueueLength100Ns = 5571840,
QueueLengthObjectTime = 6620416,
RateOfCountPerSecond32 = 272696320,
RateOfCountPerSecond64 = 272696576,
RawBase32 = 1073939459,
RawBase64 = 1073939712,
RawData32 = 65536,
RawData64 = 65792,
RawDataHex32 = 0,
RawDataHex64 = 256,
RawFraction32 = 537003008,
RawFraction64 = 537003264,
SampleBase = 1073939457,
SampleCounter = 4260864,
SampleFraction = 549585920,
}
}
| |
//
// Copyright (c) Microsoft Corporation.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation.Language;
using System.Reflection;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
internal enum SettingsMode { None = 0, Auto, File, Hashtable, Preset };
/// <summary>
/// A class to represent the settings provided to ScriptAnalyzer class.
/// </summary>
public class Settings
{
private bool recurseCustomRulePath = false;
private bool includeDefaultRules = false;
private string filePath;
private List<string> includeRules;
private List<string> excludeRules;
private List<string> severities;
private List<string> customRulePath;
private Dictionary<string, Dictionary<string, object>> ruleArguments;
public bool RecurseCustomRulePath => recurseCustomRulePath;
public bool IncludeDefaultRules => includeDefaultRules;
public string FilePath => filePath;
public IEnumerable<string> IncludeRules => includeRules;
public IEnumerable<string> ExcludeRules => excludeRules;
public IEnumerable<string> Severities => severities;
public IEnumerable<string> CustomRulePath => customRulePath;
public Dictionary<string, Dictionary<string, object>> RuleArguments => ruleArguments;
/// <summary>
/// Create a settings object from the input object.
/// </summary>
/// <param name="settings">An input object of type Hashtable or string.</param>
/// <param name="presetResolver">A function that takes in a preset and resolves it to a path.</param>
public Settings(object settings, Func<string, string> presetResolver)
{
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
includeRules = new List<string>();
excludeRules = new List<string>();
severities = new List<string>();
ruleArguments = new Dictionary<string, Dictionary<string, object>>(StringComparer.OrdinalIgnoreCase);
var settingsFilePath = settings as string;
//it can either be a preset or path to a file or a hashtable
if (settingsFilePath != null)
{
if (presetResolver != null)
{
var resolvedFilePath = presetResolver(settingsFilePath);
if (resolvedFilePath != null)
{
settingsFilePath = resolvedFilePath;
}
}
if (File.Exists(settingsFilePath))
{
filePath = settingsFilePath;
parseSettingsFile(settingsFilePath);
}
else
{
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
Strings.InvalidPath,
settingsFilePath));
}
}
else
{
var settingsHashtable = settings as Hashtable;
if (settingsHashtable != null)
{
parseSettingsHashtable(settingsHashtable);
}
else
{
throw new ArgumentException(Strings.SettingsInvalidType);
}
}
}
/// <summary>
/// Create a Settings object from the input object.
/// </summary>
/// <param name="settings">An input object of type Hashtable or string.</param>
public Settings(object settings) : this(settings, null)
{
}
/// <summary>
/// Retrieves the Settings directory from the Module directory structure
/// </summary>
public static string GetShippedSettingsDirectory()
{
// Find the compatibility files in Settings folder
var path = typeof(Helper).GetTypeInfo().Assembly.Location;
if (String.IsNullOrWhiteSpace(path))
{
return null;
}
var settingsPath = Path.Combine(Path.GetDirectoryName(path), "Settings");
if (!Directory.Exists(settingsPath))
{
// try one level down as the PSScriptAnalyzer module structure is not consistent
// CORECLR binaries are in PSScriptAnalyzer/coreclr/, PowerShell v3 binaries are in PSScriptAnalyzer/PSv3/
// and PowerShell v5 binaries are in PSScriptAnalyzer/
settingsPath = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), "Settings");
if (!Directory.Exists(settingsPath))
{
return null;
}
}
return settingsPath;
}
/// <summary>
/// Returns the builtin setting presets
///
/// Looks for powershell data files (*.psd1) in the PSScriptAnalyzer module settings directory
/// and returns the names of the files without extension
/// </summary>
public static IEnumerable<string> GetSettingPresets()
{
var settingsPath = GetShippedSettingsDirectory();
if (settingsPath != null)
{
foreach (var filepath in System.IO.Directory.EnumerateFiles(settingsPath, "*.psd1"))
{
yield return System.IO.Path.GetFileNameWithoutExtension(filepath);
}
}
}
/// <summary>
/// Gets the path to the settings file corresponding to the given preset.
///
/// If the corresponding preset file is not found, the method returns null.
/// </summary>
public static string GetSettingPresetFilePath(string settingPreset)
{
var settingsPath = GetShippedSettingsDirectory();
if (settingsPath != null)
{
if (GetSettingPresets().Contains(settingPreset, StringComparer.OrdinalIgnoreCase))
{
return System.IO.Path.Combine(settingsPath, settingPreset + ".psd1");
}
}
return null;
}
/// <summary>
/// Create a settings object from an input object.
/// </summary>
/// <param name="settingsObj">An input object of type Hashtable or string.</param>
/// <param name="cwd">The path in which to search for a settings file.</param>
/// <param name="outputWriter">An output writer.</param>
/// <returns>An object of Settings type.</returns>
public static Settings Create(object settingsObj, string cwd, IOutputWriter outputWriter)
{
object settingsFound;
var settingsMode = FindSettingsMode(settingsObj, cwd, out settingsFound);
switch (settingsMode)
{
case SettingsMode.Auto:
outputWriter?.WriteVerbose(
String.Format(
CultureInfo.CurrentCulture,
Strings.SettingsNotProvided,
""));
outputWriter?.WriteVerbose(
String.Format(
CultureInfo.CurrentCulture,
Strings.SettingsAutoDiscovered,
(string)settingsFound));
break;
case SettingsMode.Preset:
case SettingsMode.File:
outputWriter?.WriteVerbose(
String.Format(
CultureInfo.CurrentCulture,
Strings.SettingsUsingFile,
(string)settingsFound));
break;
case SettingsMode.Hashtable:
outputWriter?.WriteVerbose(
String.Format(
CultureInfo.CurrentCulture,
Strings.SettingsUsingHashtable));
break;
default: // case SettingsMode.None
outputWriter?.WriteVerbose(
String.Format(
CultureInfo.CurrentCulture,
Strings.SettingsCannotFindFile));
break;
}
if (settingsMode != SettingsMode.None)
{
return new Settings(settingsFound);
}
return null;
}
/// <summary>
/// Recursively convert hashtable to dictionary
/// </summary>
/// <param name="hashtable"></param>
/// <returns>Dictionary that maps string to object</returns>
private Dictionary<string, object> GetDictionaryFromHashtable(Hashtable hashtable)
{
var dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var obj in hashtable.Keys)
{
string key = obj as string;
if (key == null)
{
throw new InvalidDataException(
string.Format(
CultureInfo.CurrentCulture,
Strings.KeyNotString,
key));
}
var valueHashtableObj = hashtable[obj];
if (valueHashtableObj == null)
{
throw new InvalidDataException(
string.Format(
CultureInfo.CurrentCulture,
Strings.WrongValueHashTable,
"",
key));
}
var valueHashtable = valueHashtableObj as Hashtable;
if (valueHashtable == null)
{
dictionary.Add(key, valueHashtableObj);
}
else
{
dictionary.Add(key, GetDictionaryFromHashtable(valueHashtable));
}
}
return dictionary;
}
private bool IsStringOrStringArray(object val)
{
if (val is string)
{
return true;
}
var valArr = val as object[];
return val == null ? false : valArr.All(x => x is string);
}
private List<string> GetData(object val, string key)
{
// value must be either string or or an array of strings
if (val == null)
{
throw new InvalidDataException(
string.Format(
CultureInfo.CurrentCulture,
Strings.WrongValueHashTable,
"",
key));
}
List<string> values = new List<string>();
var valueStr = val as string;
if (valueStr != null)
{
values.Add(valueStr);
}
else
{
var valueArr = val as object[];
if (valueArr == null)
{
// check if it is an array of strings
valueArr = val as string[];
}
if (valueArr != null)
{
foreach (var item in valueArr)
{
var itemStr = item as string;
if (itemStr != null)
{
values.Add(itemStr);
}
else
{
throw new InvalidDataException(
string.Format(
CultureInfo.CurrentCulture,
Strings.WrongValueHashTable,
val,
key));
}
}
}
else
{
throw new InvalidDataException(
string.Format(
CultureInfo.CurrentCulture,
Strings.WrongValueHashTable,
val,
key));
}
}
return values;
}
/// <summary>
/// Sets the arguments for consumption by rules
/// </summary>
/// <param name="ruleArgs">A hashtable with rule names as keys</param>
private Dictionary<string, Dictionary<string, object>> ConvertToRuleArgumentType(object ruleArguments)
{
var ruleArgs = ruleArguments as Dictionary<string, object>;
if (ruleArgs == null)
{
throw new ArgumentException(Strings.SettingsInputShouldBeDictionary, nameof(ruleArguments));
}
if (ruleArgs.Comparer != StringComparer.OrdinalIgnoreCase)
{
throw new ArgumentException(Strings.SettingsDictionaryShouldBeCaseInsesitive, nameof(ruleArguments));
}
var ruleArgsDict = new Dictionary<string, Dictionary<string, object>>(StringComparer.OrdinalIgnoreCase);
foreach (var rule in ruleArgs.Keys)
{
var argsDict = ruleArgs[rule] as Dictionary<string, object>;
if (argsDict == null)
{
throw new InvalidDataException(Strings.SettingsInputShouldBeDictionary);
}
ruleArgsDict[rule] = argsDict;
}
return ruleArgsDict;
}
private void parseSettingsHashtable(Hashtable settingsHashtable)
{
HashSet<string> validKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var settings = GetDictionaryFromHashtable(settingsHashtable);
foreach (var settingKey in settings.Keys)
{
var key = settingKey.ToLower();
object val = settings[key];
switch (key)
{
case "severity":
severities = GetData(val, key);
break;
case "includerules":
includeRules = GetData(val, key);
break;
case "excluderules":
excludeRules = GetData(val, key);
break;
case "customrulepath":
customRulePath = GetData(val, key);
break;
case "includedefaultrules":
case "recursecustomrulepath":
if (!(val is bool))
{
throw new InvalidDataException(string.Format(
CultureInfo.CurrentCulture,
Strings.SettingsValueTypeMustBeBool,
settingKey));
}
var booleanVal = (bool)val;
var field = this.GetType().GetField(
key,
BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.NonPublic);
field.SetValue(this, booleanVal);
break;
case "rules":
try
{
ruleArguments = ConvertToRuleArgumentType(val);
}
catch (ArgumentException argumentException)
{
throw new InvalidDataException(
string.Format(CultureInfo.CurrentCulture, Strings.WrongValueHashTable, "", key),
argumentException);
}
break;
default:
throw new InvalidDataException(
string.Format(
CultureInfo.CurrentCulture,
Strings.WrongKeyHashTable,
key));
}
}
}
private void parseSettingsFile(string settingsFilePath)
{
Token[] parserTokens = null;
ParseError[] parserErrors = null;
Ast profileAst = Parser.ParseFile(settingsFilePath, out parserTokens, out parserErrors);
IEnumerable<Ast> hashTableAsts = profileAst.FindAll(item => item is HashtableAst, false);
// no hashtable, raise warning
if (hashTableAsts.Count() == 0)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.InvalidProfile, settingsFilePath));
}
HashtableAst hashTableAst = hashTableAsts.First() as HashtableAst;
Hashtable hashtable;
try
{
// ideally we should use HashtableAst.SafeGetValue() but since
// it is not available on PSv3, we resort to our own narrow implementation.
hashtable = GetHashtableFromHashTableAst(hashTableAst);
}
catch (InvalidOperationException e)
{
throw new ArgumentException(Strings.InvalidProfile, e);
}
if (hashtable == null)
{
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
Strings.InvalidProfile,
settingsFilePath));
}
parseSettingsHashtable(hashtable);
}
private Hashtable GetHashtableFromHashTableAst(HashtableAst hashTableAst)
{
var output = new Hashtable();
foreach (var kvp in hashTableAst.KeyValuePairs)
{
var keyAst = kvp.Item1 as StringConstantExpressionAst;
if (keyAst == null)
{
// first item (the key) should be a string
ThrowInvalidDataException(kvp.Item1);
}
var key = keyAst.Value;
// parse the item2 as array
PipelineAst pipeAst = kvp.Item2 as PipelineAst;
List<string> rhsList = new List<string>();
if (pipeAst != null)
{
ExpressionAst pureExp = pipeAst.GetPureExpression();
var constExprAst = pureExp as ConstantExpressionAst;
if (constExprAst != null)
{
var strConstExprAst = constExprAst as StringConstantExpressionAst;
if (strConstExprAst != null)
{
// it is a string literal
output[key] = strConstExprAst.Value;
}
else
{
// it is either an integer or a float
output[key] = constExprAst.Value;
}
continue;
}
else if (pureExp is HashtableAst)
{
output[key] = GetHashtableFromHashTableAst((HashtableAst)pureExp);
continue;
}
else if (pureExp is VariableExpressionAst)
{
var varExprAst = (VariableExpressionAst)pureExp;
switch (varExprAst.VariablePath.UserPath.ToLower())
{
case "true":
output[key] = true;
break;
case "false":
output[key] = false;
break;
default:
ThrowInvalidDataException(varExprAst.Extent);
break;
}
continue;
}
else
{
rhsList = GetArrayFromAst(pureExp);
}
}
if (rhsList.Count == 0)
{
ThrowInvalidDataException(kvp.Item2);
}
output[key] = rhsList.ToArray();
}
return output;
}
private List<string> GetArrayFromAst(ExpressionAst exprAst)
{
ArrayLiteralAst arrayLitAst = exprAst as ArrayLiteralAst;
var result = new List<string>();
if (arrayLitAst == null && exprAst is ArrayExpressionAst)
{
ArrayExpressionAst arrayExp = (ArrayExpressionAst)exprAst;
return arrayExp == null ? null : GetArrayFromArrayExpressionAst(arrayExp);
}
if (arrayLitAst == null)
{
ThrowInvalidDataException(arrayLitAst);
}
foreach (var element in arrayLitAst.Elements)
{
var elementValue = element as StringConstantExpressionAst;
if (elementValue == null)
{
ThrowInvalidDataException(element);
}
result.Add(elementValue.Value);
}
return result;
}
private List<string> GetArrayFromArrayExpressionAst(ArrayExpressionAst arrayExp)
{
var result = new List<string>();
if (arrayExp.SubExpression != null)
{
StatementAst stateAst = arrayExp.SubExpression.Statements.FirstOrDefault();
if (stateAst != null && stateAst is PipelineAst)
{
CommandBaseAst cmdBaseAst = (stateAst as PipelineAst).PipelineElements.FirstOrDefault();
if (cmdBaseAst != null && cmdBaseAst is CommandExpressionAst)
{
CommandExpressionAst cmdExpAst = cmdBaseAst as CommandExpressionAst;
if (cmdExpAst.Expression is StringConstantExpressionAst)
{
return new List<string>()
{
(cmdExpAst.Expression as StringConstantExpressionAst).Value
};
}
else
{
// It should be an ArrayLiteralAst at this point
return GetArrayFromAst(cmdExpAst.Expression);
}
}
}
}
return null;
}
private void ThrowInvalidDataException(Ast ast)
{
ThrowInvalidDataException(ast.Extent);
}
private void ThrowInvalidDataException(IScriptExtent extent)
{
throw new InvalidDataException(string.Format(
CultureInfo.CurrentCulture,
Strings.WrongValueFormat,
extent.StartLineNumber,
extent.StartColumnNumber,
extent.File ?? ""));
}
private static bool IsBuiltinSettingPreset(object settingPreset)
{
var preset = settingPreset as string;
if (preset != null)
{
return GetSettingPresets().Contains(preset, StringComparer.OrdinalIgnoreCase);
}
return false;
}
internal static SettingsMode FindSettingsMode(object settings, string path, out object settingsFound)
{
var settingsMode = SettingsMode.None;
settingsFound = settings;
if (settingsFound == null)
{
if (path != null)
{
// add a directory separator character because if there is no trailing separator character, it will return the parent
var directory = path.TrimEnd(System.IO.Path.DirectorySeparatorChar);
if (File.Exists(directory))
{
// if given path is a file, get its directory
directory = Path.GetDirectoryName(directory);
}
if (Directory.Exists(directory))
{
// if settings are not provided explicitly, look for it in the given path
// check if pssasettings.psd1 exists
var settingsFilename = "PSScriptAnalyzerSettings.psd1";
var settingsFilePath = Path.Combine(directory, settingsFilename);
settingsFound = settingsFilePath;
if (File.Exists(settingsFilePath))
{
settingsMode = SettingsMode.Auto;
}
}
}
}
else
{
var settingsFilePath = settingsFound as String;
if (settingsFilePath != null)
{
if (IsBuiltinSettingPreset(settingsFilePath))
{
settingsMode = SettingsMode.Preset;
settingsFound = GetSettingPresetFilePath(settingsFilePath);
}
else
{
settingsMode = SettingsMode.File;
settingsFound = settingsFilePath;
}
}
else
{
if (settingsFound is Hashtable)
{
settingsMode = SettingsMode.Hashtable;
}
}
}
return settingsMode;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Runtime;
using System.Threading.Tasks;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Utilities class for handling configuration.
/// </summary>
public static class ConfigUtilities
{
internal static void ParseAdditionalAssemblyDirectories(IDictionary<string, SearchOption> directories, XmlElement root)
{
foreach(var node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if(grandchild == null)
{
continue;
}
else
{
if(!grandchild.HasAttribute("Path"))
throw new FormatException("Missing 'Path' attribute on Directory element.");
// default to recursive
var recursive = true;
if(grandchild.HasAttribute("IncludeSubFolders"))
{
if(!bool.TryParse(grandchild.Attributes["IncludeSubFolders"].Value, out recursive))
throw new FormatException("Attribute 'IncludeSubFolders' has invalid value.");
directories[grandchild.Attributes["Path"].Value] = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
}
}
}
}
internal static void ParseTelemetry(XmlElement root)
{
foreach (var node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (!grandchild.LocalName.Equals("TelemetryConsumer"))
{
continue;
}
else
{
if (!grandchild.HasAttribute("Type"))
throw new FormatException("Missing 'Type' attribute on TelemetryConsumer element.");
if (!grandchild.HasAttribute("Assembly"))
throw new FormatException("Missing 'Type' attribute on TelemetryConsumer element.");
var className = grandchild.Attributes["Type"].Value;
var assemblyName = new AssemblyName(grandchild.Attributes["Assembly"].Value);
Assembly assembly = null;
try
{
assembly = Assembly.Load(assemblyName);
var pluginType = assembly.GetType(className);
if (pluginType == null) throw new TypeLoadException("Cannot locate plugin class " + className + " in assembly " + assembly.FullName);
var args = grandchild.Attributes.Cast<XmlAttribute>().Where(a => a.LocalName != "Type" && a.LocalName != "Assembly").ToArray();
var plugin = Activator.CreateInstance(pluginType, args);
if (plugin is ITelemetryConsumer)
{
Logger.TelemetryConsumers.Add(plugin as ITelemetryConsumer);
}
else
{
throw new InvalidCastException("TelemetryConsumer class " + className + " must implement one of Orleans.Runtime.ITelemetryConsumer based interfaces");
}
}
catch (Exception exc)
{
throw new TypeLoadException("Cannot load TelemetryConsumer class " + className + " from assembly " + assembly + " - Error=" + exc);
}
}
}
}
internal static void ParseTracing(ITraceConfiguration config, XmlElement root, string nodeName)
{
if (root.HasAttribute("DefaultTraceLevel"))
{
config.DefaultTraceLevel = ParseSeverity(root.GetAttribute("DefaultTraceLevel"),
"Invalid trace level DefaultTraceLevel attribute value on Tracing element for " + nodeName);
}
if (root.HasAttribute("TraceToConsole"))
{
config.TraceToConsole = ParseBool(root.GetAttribute("TraceToConsole"),
"Invalid boolean value for TraceToConsole attribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("TraceToFile"))
{
config.TraceFilePattern = root.GetAttribute("TraceToFile");
}
if (root.HasAttribute("LargeMessageWarningThreshold"))
{
config.LargeMessageWarningThreshold = ParseInt(root.GetAttribute("LargeMessageWarningThreshold"),
"Invalid boolean value for LargeMessageWarningThresholdattribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("PropagateActivityId"))
{
config.PropagateActivityId = ParseBool(root.GetAttribute("PropagateActivityId"),
"Invalid boolean value for PropagateActivityId attribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("BulkMessageLimit"))
{
config.BulkMessageLimit = ParseInt(root.GetAttribute("BulkMessageLimit"),
"Invalid int value for BulkMessageLimit attribute on Tracing element for " + nodeName);
}
foreach (XmlNode node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (grandchild.LocalName.Equals("TraceLevelOverride") && grandchild.HasAttribute("TraceLevel") && grandchild.HasAttribute("LogPrefix"))
{
config.TraceLevelOverrides.Add(new Tuple<string, Severity>(grandchild.GetAttribute("LogPrefix"),
ParseSeverity(grandchild.GetAttribute("TraceLevel"),
"Invalid trace level TraceLevel attribute value on TraceLevelOverride element for " + nodeName + " prefix " +
grandchild.GetAttribute("LogPrefix"))));
}
else if (grandchild.LocalName.Equals("LogConsumer"))
{
var className = grandchild.InnerText;
Assembly assembly = null;
try
{
int pos = className.IndexOf(',');
if (pos > 0)
{
var assemblyName = className.Substring(pos + 1).Trim();
className = className.Substring(0, pos).Trim();
assembly = Assembly.Load(new AssemblyName(assemblyName));
}
else
{
assembly = typeof(ConfigUtilities).GetTypeInfo().Assembly;
}
var pluginType = assembly.GetType(className);
if (pluginType == null) throw new TypeLoadException("Cannot locate plugin class " + className + " in assembly " + assembly.FullName);
var plugin = Activator.CreateInstance(pluginType);
if (plugin is ILogConsumer)
{
TraceLogger.LogConsumers.Add(plugin as ILogConsumer);
}
else
{
throw new InvalidCastException("LogConsumer class " + className + " must implement Orleans.ILogConsumer interface");
}
}
catch (Exception exc)
{
throw new TypeLoadException("Cannot load LogConsumer class " + className + " from assembly " + assembly + " - Error=" + exc);
}
}
}
SetTraceFileName(config, nodeName, DateTime.UtcNow);
}
internal static void ParseStatistics(IStatisticsConfiguration config, XmlElement root, string nodeName)
{
if (root.HasAttribute("ProviderType"))
{
config.StatisticsProviderName = root.GetAttribute("ProviderType");
}
if (root.HasAttribute("MetricsTableWriteInterval"))
{
config.StatisticsMetricsTableWriteInterval = ParseTimeSpan(root.GetAttribute("MetricsTableWriteInterval"),
"Invalid TimeSpan value for Statistics.MetricsTableWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("PerfCounterWriteInterval"))
{
config.StatisticsPerfCountersWriteInterval = ParseTimeSpan(root.GetAttribute("PerfCounterWriteInterval"),
"Invalid TimeSpan value for Statistics.PerfCounterWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("LogWriteInterval"))
{
config.StatisticsLogWriteInterval = ParseTimeSpan(root.GetAttribute("LogWriteInterval"),
"Invalid TimeSpan value for Statistics.LogWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("WriteLogStatisticsToTable"))
{
config.StatisticsWriteLogStatisticsToTable = ParseBool(root.GetAttribute("WriteLogStatisticsToTable"),
"Invalid bool value for Statistics.WriteLogStatisticsToTable attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("StatisticsCollectionLevel"))
{
config.StatisticsCollectionLevel = ConfigUtilities.ParseEnum<StatisticsLevel>(root.GetAttribute("StatisticsCollectionLevel"),
"Invalid value of for Statistics.StatisticsCollectionLevel attribute on Statistics element for " + nodeName);
}
}
internal static void ParseLimitValues(LimitManager limitManager, XmlElement root, string nodeName)
{
foreach (XmlNode node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (grandchild.LocalName.Equals("Limit") && grandchild.HasAttribute("Name")
&& (grandchild.HasAttribute("SoftLimit") || grandchild.HasAttribute("HardLimit")))
{
var limitName = grandchild.GetAttribute("Name");
limitManager.AddLimitValue(limitName, new LimitValue
{
Name = limitName,
SoftLimitThreshold = ParseInt(grandchild.GetAttribute("SoftLimit"),
"Invalid integer value for the SoftLimit attribute on the Limit element"),
HardLimitThreshold = grandchild.HasAttribute("HardLimit") ? ParseInt(grandchild.GetAttribute("HardLimit"),
"Invalid integer value for the HardLimit attribute on the Limit element") : 0,
});
}
}
}
internal static void SetTraceFileName(ITraceConfiguration config, string nodeName, DateTime timestamp)
{
const string dateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ";
if (config == null) throw new ArgumentNullException("config");
if (config.TraceFilePattern == null
|| string.IsNullOrWhiteSpace(config.TraceFilePattern)
|| config.TraceFilePattern.Equals("false", StringComparison.OrdinalIgnoreCase)
|| config.TraceFilePattern.Equals("none", StringComparison.OrdinalIgnoreCase))
{
config.TraceFileName = null;
}
else if (string.Empty.Equals(config.TraceFileName))
{
config.TraceFileName = null; // normalize
}
else
{
string traceFileDir = Path.GetDirectoryName(config.TraceFilePattern);
if (!String.IsNullOrEmpty(traceFileDir) && !Directory.Exists(traceFileDir))
{
string traceFileName = Path.GetFileName(config.TraceFilePattern);
string[] alternateDirLocations = { "appdir", "." };
foreach (var d in alternateDirLocations)
{
if (Directory.Exists(d))
{
config.TraceFilePattern = Path.Combine(d, traceFileName);
break;
}
}
}
config.TraceFileName = String.Format(config.TraceFilePattern, nodeName, timestamp.ToUniversalTime().ToString(dateFormat), Dns.GetHostName());
}
}
internal static int ParseInt(string input, string errorMessage)
{
int p;
if (!Int32.TryParse(input, out p))
{
throw new FormatException(errorMessage);
}
return p;
}
internal static long ParseLong(string input, string errorMessage)
{
long p;
if (!Int64.TryParse(input, out p))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static bool ParseBool(string input, string errorMessage)
{
bool p;
if (Boolean.TryParse(input, out p)) return p;
switch (input)
{
case "0":
p = false;
break;
case "1":
p = true;
break;
default:
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static double ParseDouble(string input, string errorMessage)
{
double p;
if (!Double.TryParse(input, out p))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static Guid ParseGuid(string input, string errorMessage)
{
Guid p;
if (!Guid.TryParse(input, out p))
{
throw new FormatException(errorMessage);
}
return p;
}
internal static Type ParseFullyQualifiedType(string input, string errorMessage)
{
Type returnValue;
try
{
returnValue = Type.GetType(input);
}
catch(Exception e)
{
throw new FormatException(errorMessage, e);
}
if (returnValue == null)
{
throw new FormatException(errorMessage);
}
return returnValue;
}
internal static void ValidateSerializationProvider(Type type)
{
if (type.IsClass == false)
{
throw new FormatException(string.Format("The serialization provider type {0} was not a class", type.FullName));
}
if (type.IsAbstract)
{
throw new FormatException(string.Format("The serialization provider type {0} was an abstract class", type.FullName));
}
if (type.IsPublic == false)
{
throw new FormatException(string.Format("The serialization provider type {0} is not public", type.FullName));
}
if (type.IsGenericType && type.IsConstructedGenericType == false)
{
throw new FormatException(string.Format("The serialization provider type {0} is generic and has a missing type parameter specification", type.FullName));
}
var constructor = type.GetConstructor(Type.EmptyTypes);
if (constructor == null)
{
throw new FormatException(string.Format("The serialization provider type {0} does not have a parameterless constructor", type.FullName));
}
if (constructor.IsPublic == false)
{
throw new FormatException(string.Format("The serialization provider type {0} has a non-public parameterless constructor", type.FullName));
}
}
// Time spans are entered as a string of decimal digits, optionally followed by a unit string: "ms", "s", "m", "hr"
internal static TimeSpan ParseTimeSpan(string input, string errorMessage)
{
int unitSize;
string numberInput;
var trimmedInput = input.Trim().ToLowerInvariant();
if (trimmedInput.EndsWith("ms", StringComparison.Ordinal))
{
unitSize = 1;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else if (trimmedInput.EndsWith("s", StringComparison.Ordinal))
{
unitSize = 1000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("m", StringComparison.Ordinal))
{
unitSize = 60 * 1000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("hr", StringComparison.Ordinal))
{
unitSize = 60 * 60 * 1000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else
{
unitSize = 1000; // Default is seconds
numberInput = trimmedInput;
}
double rawTimeSpan;
if (!double.TryParse(numberInput, out rawTimeSpan))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return TimeSpan.FromMilliseconds(rawTimeSpan * unitSize);
}
internal static string ToParseableTimeSpan(TimeSpan input)
{
return $"{input.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)}ms";
}
internal static byte[] ParseSubnet(string input, string errorMessage)
{
return string.IsNullOrEmpty(input) ? null : input.Split('.').Select(s => (byte) ParseInt(s, errorMessage)).ToArray();
}
internal static T ParseEnum<T>(string input, string errorMessage)
where T : struct // really, where T : enum, but there's no way to require that in C#
{
T s;
if (!Enum.TryParse<T>(input, out s))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return s;
}
internal static Severity ParseSeverity(string input, string errorMessage)
{
Severity s;
if (!Enum.TryParse<Severity>(input, out s))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return s;
}
internal static async Task<IPEndPoint> ParseIPEndPoint(XmlElement root, byte[] subnet = null)
{
if (!root.HasAttribute("Address")) throw new FormatException("Missing Address attribute for " + root.LocalName + " element");
if (!root.HasAttribute("Port")) throw new FormatException("Missing Port attribute for " + root.LocalName + " element");
var family = AddressFamily.InterNetwork;
if (root.HasAttribute("Subnet"))
{
subnet = ParseSubnet(root.GetAttribute("Subnet"), "Invalid subnet");
}
if (root.HasAttribute("PreferredFamily"))
{
family = ParseEnum<AddressFamily>(root.GetAttribute("PreferredFamily"),
"Invalid preferred addressing family for " + root.LocalName + " element");
}
IPAddress addr = await ClusterConfiguration.ResolveIPAddress(root.GetAttribute("Address"), subnet, family);
int port = ParseInt(root.GetAttribute("Port"), "Invalid Port attribute for " + root.LocalName + " element");
return new IPEndPoint(addr, port);
}
internal static string TraceConfigurationToString(ITraceConfiguration config)
{
var sb = new StringBuilder();
sb.Append(" Tracing: ").AppendLine();
sb.Append(" Default Trace Level: ").Append(config.DefaultTraceLevel).AppendLine();
if (config.TraceLevelOverrides.Count > 0)
{
sb.Append(" TraceLevelOverrides:").AppendLine();
foreach (var over in config.TraceLevelOverrides)
{
sb.Append(" ").Append(over.Item1).Append(" ==> ").Append(over.Item2.ToString()).AppendLine();
}
}
else
{
sb.Append(" TraceLevelOverrides: None").AppendLine();
}
sb.Append(" Trace to Console: ").Append(config.TraceToConsole).AppendLine();
sb.Append(" Trace File Name: ").Append(string.IsNullOrWhiteSpace(config.TraceFileName) ? "" : Path.GetFullPath(config.TraceFileName)).AppendLine();
sb.Append(" LargeMessageWarningThreshold: ").Append(config.LargeMessageWarningThreshold).AppendLine();
sb.Append(" PropagateActivityId: ").Append(config.PropagateActivityId).AppendLine();
sb.Append(" BulkMessageLimit: ").Append(config.BulkMessageLimit).AppendLine();
return sb.ToString();
}
internal static string IStatisticsConfigurationToString(IStatisticsConfiguration config)
{
var sb = new StringBuilder();
sb.Append(" Statistics: ").AppendLine();
sb.Append(" MetricsTableWriteInterval: ").Append(config.StatisticsMetricsTableWriteInterval).AppendLine();
sb.Append(" PerfCounterWriteInterval: ").Append(config.StatisticsPerfCountersWriteInterval).AppendLine();
sb.Append(" LogWriteInterval: ").Append(config.StatisticsLogWriteInterval).AppendLine();
sb.Append(" WriteLogStatisticsToTable: ").Append(config.StatisticsWriteLogStatisticsToTable).AppendLine();
sb.Append(" StatisticsCollectionLevel: ").Append(config.StatisticsCollectionLevel).AppendLine();
#if TRACK_DETAILED_STATS
sb.Append(" TRACK_DETAILED_STATS: true").AppendLine();
#endif
if (!string.IsNullOrEmpty(config.StatisticsProviderName))
sb.Append(" StatisticsProviderName:").Append(config.StatisticsProviderName).AppendLine();
return sb.ToString();
}
/// <summary>
/// Prints the the DataConnectionString,
/// without disclosing any credential info
/// such as the Azure Storage AccountKey or SqlServer password.
/// </summary>
/// <param name="dataConnectionString">The connection string to print.</param>
/// <returns>The string representation of the DataConnectionString with account credential info redacted.</returns>
public static string RedactConnectionStringInfo(string dataConnectionString)
{
return PrintSqlConnectionString(
PrintDataConnectionInfo(dataConnectionString));
}
public static string PrintDataConnectionInfo(string azureConnectionString)
{
if (String.IsNullOrEmpty(azureConnectionString)) return "null";
string azureConnectionInfo = azureConnectionString;
// Remove any Azure account keys from connection string info written to log files
int accountKeyPos = azureConnectionInfo.LastIndexOf("AccountKey=", StringComparison.Ordinal);
if (accountKeyPos > 0)
{
azureConnectionInfo = azureConnectionInfo.Remove(accountKeyPos) + "AccountKey=<--SNIP-->";
}
return azureConnectionInfo;
}
public static string PrintSqlConnectionString(string sqlConnectionString)
{
if (String.IsNullOrEmpty(sqlConnectionString))
{
return "null";
}
var sqlConnectionInfo = sqlConnectionString;
// Remove any Azure account keys from connection string info written to log files
int keyPos = sqlConnectionInfo.LastIndexOf("Password=", StringComparison.OrdinalIgnoreCase);
if (keyPos > 0)
{
sqlConnectionInfo = sqlConnectionInfo.Remove(keyPos) + "Password=<--SNIP-->";
}
return sqlConnectionInfo;
}
public static TimeSpan ParseCollectionAgeLimit(XmlElement xmlElement)
{
if (xmlElement.LocalName != "Deactivation")
throw new ArgumentException("The XML element must be a <Deactivate/> element.");
if (!xmlElement.HasAttribute("AgeLimit"))
throw new ArgumentException("The AgeLimit attribute is required for a <Deactivate/> element.");
return ParseTimeSpan(xmlElement.GetAttribute("AgeLimit"), "Invalid TimeSpan value for Deactivation.AgeLimit");
}
private static readonly string[] defaultClientConfigFileNames = { "ClientConfiguration.xml", "OrleansClientConfiguration.xml", "Client.config", "Client.xml" };
private static readonly string[] defaultSiloConfigFileNames = { "OrleansConfiguration.xml", "orleans.config", "config.xml", "orleans.config.xml" };
private static readonly string[] defaultConfigDirs =
{
null, // Will be filled in with directory location for this executing assembly
"approot", // Azure AppRoot directory
".", // Current directory
".." // Parent directory
};
public static string FindConfigFile(bool isSilo)
{
// Add directory containing Orleans binaries to the search locations for config files
defaultConfigDirs[0] = Path.GetDirectoryName(typeof(ConfigUtilities).GetTypeInfo().Assembly.Location);
var notFound = new List<string>();
foreach (string dir in defaultConfigDirs)
{
foreach (string file in isSilo ? defaultSiloConfigFileNames : defaultClientConfigFileNames)
{
var fileName = Path.GetFullPath(Path.Combine(dir, file));
if (File.Exists(fileName)) return fileName;
notFound.Add(fileName);
}
}
var whereWeLooked = new StringBuilder();
whereWeLooked.AppendFormat("Cannot locate Orleans {0} config file.", isSilo ? "silo" : "client").AppendLine();
whereWeLooked.AppendLine("Searched locations:");
foreach (var i in notFound)
{
whereWeLooked.AppendFormat("\t- {0}", i).AppendLine();
}
throw new FileNotFoundException(whereWeLooked.ToString());
}
/// <summary>
/// Returns the Runtime Version information.
/// </summary>
/// <returns>the Runtime Version information</returns>
public static string RuntimeVersionInfo()
{
var sb = new StringBuilder();
sb.Append(" .NET version: ").AppendLine(Environment.Version.ToString());
sb.Append(" Is .NET 4.5=").AppendLine(IsNet45OrNewer().ToString());
sb.Append(" OS version: ").AppendLine(Environment.OSVersion.ToString());
sb.AppendFormat(" GC Type={0} GCLatencyMode={1}",
GCSettings.IsServerGC ? "Server" : "Client",
Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode))
.AppendLine();
return sb.ToString();
}
internal static bool IsNet45OrNewer()
{
// From: http://stackoverflow.com/questions/8517159/how-to-detect-at-runtime-that-net-version-4-5-currently-running-your-code
// Class "ReflectionContext" exists from .NET 4.5 onwards.
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
}
}
| |
// Lucene version compatibility level 4.8.1
using J2N.Numerics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Analysis.Compound.Hyphenation
{
/*
* 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>
/// This tree structure stores the hyphenation patterns in an efficient way for
/// fast lookup. It provides the provides the method to hyphenate a word.
/// <para/>
/// This class has been taken from the Apache FOP project (http://xmlgraphics.apache.org/fop/). They have been slightly modified.
/// </summary>
public class HyphenationTree : TernaryTree, IPatternConsumer
{
/// <summary>
/// value space: stores the interletter values
/// </summary>
protected ByteVector m_vspace;
/// <summary>
/// This map stores hyphenation exceptions
/// </summary>
protected IDictionary<string, IList<object>> m_stoplist;
/// <summary>
/// This map stores the character classes
/// </summary>
protected TernaryTree m_classmap;
/// <summary>
/// Temporary map to store interletter values on pattern loading.
/// </summary>
#if FEATURE_SERIALIZABLE
[NonSerialized]
#endif
private TernaryTree ivalues;
public HyphenationTree()
{
m_stoplist = new JCG.Dictionary<string, IList<object>>(23); // usually a small table
m_classmap = new TernaryTree();
m_vspace = new ByteVector();
m_vspace.Alloc(1); // this reserves index 0, which we don't use
}
/// <summary>
/// Packs the values by storing them in 4 bits, two values into a byte Values
/// range is from 0 to 9. We use zero as terminator, so we'll add 1 to the
/// value.
/// </summary>
/// <param name="values"> a string of digits from '0' to '9' representing the
/// interletter values. </param>
/// <returns> the index into the vspace array where the packed values are stored. </returns>
protected virtual int PackValues(string values)
{
int i, n = values.Length;
int m = (n & 1) == 1 ? (n >> 1) + 2 : (n >> 1) + 1;
int offset = m_vspace.Alloc(m);
byte[] va = m_vspace.Array;
for (i = 0; i < n; i++)
{
int j = i >> 1;
byte v = (byte)((values[i] - '0' + 1) & 0x0f);
if ((i & 1) == 1)
{
va[j + offset] = (byte)(va[j + offset] | v);
}
else
{
va[j + offset] = (byte)(v << 4); // big endian
}
}
va[m - 1 + offset] = 0; // terminator
return offset;
}
protected virtual string UnpackValues(int k)
{
StringBuilder buf = new StringBuilder();
byte v = m_vspace[k++];
while (v != 0)
{
char c = (char)(v.TripleShift(4) - 1 + '0');;
buf.Append(c);
c = (char)(v & 0x0f);
if (c == 0)
{
break;
}
c = (char)(c - 1 + '0');
buf.Append(c);
v = m_vspace[k++];
}
return buf.ToString();
}
/// <summary>
/// Read hyphenation patterns from an XML file.
/// </summary>
/// <param name="filename"> the filename </param>
/// <exception cref="IOException"> In case the parsing fails </exception>
public virtual void LoadPatterns(string filename)
{
LoadPatterns(filename, Encoding.UTF8);
}
/// <summary>
/// Read hyphenation patterns from an XML file.
/// </summary>
/// <param name="filename"> the filename </param>
/// <param name="encoding">The character encoding to use</param>
/// <exception cref="IOException"> In case the parsing fails </exception>
public virtual void LoadPatterns(string filename, Encoding encoding)
{
var src = new FileStream(filename, FileMode.Open, FileAccess.Read);
LoadPatterns(src, encoding);
}
/// <summary>
/// Read hyphenation patterns from an XML file.
/// </summary>
/// <param name="f"> a <see cref="FileInfo"/> object representing the file </param>
/// <exception cref="IOException"> In case the parsing fails </exception>
public virtual void LoadPatterns(FileInfo f)
{
LoadPatterns(f, Encoding.UTF8);
}
/// <summary>
/// Read hyphenation patterns from an XML file.
/// </summary>
/// <param name="f"> a <see cref="FileInfo"/> object representing the file </param>
/// <param name="encoding">The character encoding to use</param>
/// <exception cref="IOException"> In case the parsing fails </exception>
public virtual void LoadPatterns(FileInfo f, Encoding encoding)
{
var src = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
LoadPatterns(src, encoding);
}
/// <summary>
/// Read hyphenation patterns from an XML file.
/// </summary>
/// <param name="source"> <see cref="Stream"/> input source for the file </param>
/// <exception cref="IOException"> In case the parsing fails </exception>
public virtual void LoadPatterns(Stream source)
{
LoadPatterns(source, Encoding.UTF8);
}
/// <summary>
/// Read hyphenation patterns from an XML file.
/// </summary>
/// <param name="source"> <see cref="Stream"/> input source for the file </param>
/// <param name="encoding">The character encoding to use</param>
/// <exception cref="IOException"> In case the parsing fails </exception>
public virtual void LoadPatterns(Stream source, Encoding encoding)
{
var xmlReaderSettings =
new XmlReaderSettings
{
// DTD Processing currently is
// not supported in .NET Standard but will come back in .NET Standard 2.0.
// https://github.com/dotnet/corefx/issues/4376.
#if FEATURE_DTD_PROCESSING
DtdProcessing = DtdProcessing.Parse,
XmlResolver = new PatternParser.DtdResolver()
#else
DtdProcessing = DtdProcessing.Ignore
#endif
};
using var reader = XmlReader.Create(new StreamReader(source, encoding), xmlReaderSettings);
LoadPatterns(reader);
}
/// <summary>
/// Read hyphenation patterns from an <see cref="XmlReader"/>.
/// </summary>
/// <param name="source"> <see cref="XmlReader"/> input source for the file </param>
/// <exception cref="IOException"> In case the parsing fails </exception>
public virtual void LoadPatterns(XmlReader source)
{
PatternParser pp = new PatternParser(this);
ivalues = new TernaryTree();
pp.Parse(source);
// patterns/values should be now in the tree
// let's optimize a bit
TrimToSize();
m_vspace.TrimToSize();
m_classmap.TrimToSize();
// get rid of the auxiliary map
ivalues = null;
}
public virtual string FindPattern(string pat)
{
int k = base.Find(pat);
if (k >= 0)
{
return UnpackValues(k);
}
return "";
}
/// <summary>
/// String compare, returns 0 if equal or t is a substring of s
/// </summary>
protected virtual int HStrCmp(char[] s, int si, char[] t, int ti)
{
for (; s[si] == t[ti]; si++, ti++)
{
if (s[si] == 0)
{
return 0;
}
}
if (t[ti] == 0)
{
return 0;
}
return s[si] - t[ti];
}
protected virtual byte[] GetValues(int k)
{
StringBuilder buf = new StringBuilder();
byte v = m_vspace[k++];
while (v != 0)
{
char c = (char)(v.TripleShift(4) - 1);
buf.Append(c);
c = (char)(v & 0x0f);
if (c == 0)
{
break;
}
c = (char)(c - 1);
buf.Append(c);
v = m_vspace[k++];
}
byte[] res = new byte[buf.Length];
for (int i = 0; i < res.Length; i++)
{
res[i] = (byte)buf[i];
}
return res;
}
/// <summary>
/// <para>
/// Search for all possible partial matches of word starting at index an update
/// interletter values. In other words, it does something like:
/// </para>
/// <code>
/// for (i=0; i<patterns.Length; i++)
/// {
/// if (word.Substring(index).StartsWith(patterns[i], StringComparison.Ordinal))
/// update_interletter_values(patterns[i]);
/// }
/// </code>
/// <para>
/// But it is done in an efficient way since the patterns are stored in a
/// ternary tree. In fact, this is the whole purpose of having the tree: doing
/// this search without having to test every single pattern. The number of
/// patterns for languages such as English range from 4000 to 10000. Thus,
/// doing thousands of string comparisons for each word to hyphenate would be
/// really slow without the tree. The tradeoff is memory, but using a ternary
/// tree instead of a trie, almost halves the the memory used by Lout or TeX.
/// It's also faster than using a hash table
/// </para>
/// </summary>
/// <param name="word"> null terminated word to match </param>
/// <param name="index"> start index from word </param>
/// <param name="il"> interletter values array to update </param>
protected virtual void SearchPatterns(char[] word, int index, byte[] il)
{
byte[] values;
int i = index;
char p, q;
char sp = word[i];
p = m_root;
while (p > 0 && p < m_sc.Length)
{
if (m_sc[p] == 0xFFFF)
{
if (HStrCmp(word, i, m_kv.Array, m_lo[p]) == 0)
{
values = GetValues(m_eq[p]); // data pointer is in eq[]
int j = index;
for (int k = 0; k < values.Length; k++)
{
if (j < il.Length && values[k] > il[j])
{
il[j] = values[k];
}
j++;
}
}
return;
}
int d = sp - m_sc[p];
if (d == 0)
{
if (sp == 0)
{
break;
}
sp = word[++i];
p = m_eq[p];
q = p;
// look for a pattern ending at this position by searching for
// the null char ( splitchar == 0 )
while (q > 0 && q < m_sc.Length)
{
if (m_sc[q] == 0xFFFF) // stop at compressed branch
{
break;
}
if (m_sc[q] == 0)
{
values = GetValues(m_eq[q]);
int j = index;
for (int k = 0; k < values.Length; k++)
{
if (j < il.Length && values[k] > il[j])
{
il[j] = values[k];
}
j++;
}
break;
}
else
{
q = m_lo[q];
// actually the code should be: q = sc[q] < 0 ? hi[q] : lo[q]; but
// java chars are unsigned
}
}
}
else
{
p = d < 0 ? m_lo[p] : m_hi[p];
}
}
}
/// <summary>
/// Hyphenate word and return a <see cref="Hyphenation"/> object.
/// </summary>
/// <param name="word"> the word to be hyphenated </param>
/// <param name="remainCharCount"> Minimum number of characters allowed before the
/// hyphenation point. </param>
/// <param name="pushCharCount"> Minimum number of characters allowed after the
/// hyphenation point. </param>
/// <returns> a <see cref="Hyphenation"/> object representing the
/// hyphenated word or null if word is not hyphenated. </returns>
public virtual Hyphenation Hyphenate(string word, int remainCharCount, int pushCharCount)
{
char[] w = word.ToCharArray();
return Hyphenate(w, 0, w.Length, remainCharCount, pushCharCount);
}
/// <summary>
/// Hyphenate word and return an array of hyphenation points.
/// </summary>
/// <remarks>
/// w = "****nnllllllnnn*****", where n is a non-letter, l is a letter, all n
/// may be absent, the first n is at offset, the first l is at offset +
/// iIgnoreAtBeginning; word = ".llllll.'\0'***", where all l in w are copied
/// into word. In the first part of the routine len = w.length, in the second
/// part of the routine len = word.length. Three indices are used: index(w),
/// the index in w, index(word), the index in word, letterindex(word), the
/// index in the letter part of word. The following relations exist: index(w) =
/// offset + i - 1 index(word) = i - iIgnoreAtBeginning letterindex(word) =
/// index(word) - 1 (see first loop). It follows that: index(w) - index(word) =
/// offset - 1 + iIgnoreAtBeginning index(w) = letterindex(word) + offset +
/// iIgnoreAtBeginning
/// </remarks>
/// <param name="w"> char array that contains the word </param>
/// <param name="offset"> Offset to first character in word </param>
/// <param name="len"> Length of word </param>
/// <param name="remainCharCount"> Minimum number of characters allowed before the
/// hyphenation point. </param>
/// <param name="pushCharCount"> Minimum number of characters allowed after the
/// hyphenation point. </param>
/// <returns> a <see cref="Hyphenation"/> object representing the
/// hyphenated word or null if word is not hyphenated. </returns>
public virtual Hyphenation Hyphenate(char[] w, int offset, int len, int remainCharCount, int pushCharCount)
{
int i;
char[] word = new char[len + 3];
// normalize word
char[] c = new char[2];
int iIgnoreAtBeginning = 0;
int iLength = len;
bool bEndOfLetters = false;
for (i = 1; i <= len; i++)
{
c[0] = w[offset + i - 1];
int nc = m_classmap.Find(c, 0);
if (nc < 0) // found a non-letter character ...
{
if (i == (1 + iIgnoreAtBeginning))
{
// ... before any letter character
iIgnoreAtBeginning++;
}
else
{
// ... after a letter character
bEndOfLetters = true;
}
iLength--;
}
else
{
if (!bEndOfLetters)
{
word[i - iIgnoreAtBeginning] = (char)nc;
}
else
{
return null;
}
}
}
len = iLength;
if (len < (remainCharCount + pushCharCount))
{
// word is too short to be hyphenated
return null;
}
int[] result = new int[len + 1];
int k = 0;
// check exception list first
string sw = new string(word, 1, len);
// LUCENENET: Eliminated extra lookup by using TryGetValue instead of ContainsKey
if (m_stoplist.TryGetValue(sw, out IList<object> hw))
{
// assume only simple hyphens (Hyphen.pre="-", Hyphen.post = Hyphen.no =
// null)
int j = 0;
for (i = 0; i < hw.Count; i++)
{
object o = hw[i];
// j = index(sw) = letterindex(word)?
// result[k] = corresponding index(w)
if (o is string)
{
j += ((string)o).Length;
if (j >= remainCharCount && j < (len - pushCharCount))
{
result[k++] = j + iIgnoreAtBeginning;
}
}
}
}
else
{
// use algorithm to get hyphenation points
word[0] = '.'; // word start marker
word[len + 1] = '.'; // word end marker
word[len + 2] = (char)0; // null terminated
byte[] il = new byte[len + 3]; // initialized to zero
for (i = 0; i < len + 1; i++)
{
SearchPatterns(word, i, il);
}
// hyphenation points are located where interletter value is odd
// i is letterindex(word),
// i + 1 is index(word),
// result[k] = corresponding index(w)
for (i = 0; i < len; i++)
{
if (((il[i + 1] & 1) == 1) && i >= remainCharCount && i <= (len - pushCharCount))
{
result[k++] = i + iIgnoreAtBeginning;
}
}
}
if (k > 0)
{
// trim result array
int[] res = new int[k + 2];
Array.Copy(result, 0, res, 1, k);
// We add the synthetical hyphenation points
// at the beginning and end of the word
res[0] = 0;
res[k + 1] = len;
return new Hyphenation(res);
}
else
{
return null;
}
}
/// <summary>
/// Add a character class to the tree. It is used by
/// <see cref="PatternParser"/> as callback to add character classes.
/// Character classes define the valid word characters for hyphenation. If a
/// word contains a character not defined in any of the classes, it is not
/// hyphenated. It also defines a way to normalize the characters in order to
/// compare them with the stored patterns. Usually pattern files use only lower
/// case characters, in this case a class for letter 'a', for example, should
/// be defined as "aA", the first character being the normalization char.
/// </summary>
public virtual void AddClass(string chargroup)
{
if (chargroup.Length > 0)
{
char equivChar = chargroup[0];
char[] key = new char[2];
key[1] = (char)0;
for (int i = 0; i < chargroup.Length; i++)
{
key[0] = chargroup[i];
m_classmap.Insert(key, 0, equivChar);
}
}
}
/// <summary>
/// Add an exception to the tree. It is used by
/// <see cref="PatternParser"/> class as callback to store the
/// hyphenation exceptions.
/// </summary>
/// <param name="word"> normalized word </param>
/// <param name="hyphenatedword"> a vector of alternating strings and
/// <see cref="Hyphen"/> objects. </param>
public virtual void AddException(string word, IList<object> hyphenatedword)
{
m_stoplist[word] = hyphenatedword;
}
/// <summary>
/// Add a pattern to the tree. Mainly, to be used by
/// <see cref="PatternParser"/> class as callback to add a pattern to
/// the tree.
/// </summary>
/// <param name="pattern"> the hyphenation pattern </param>
/// <param name="ivalue"> interletter weight values indicating the desirability and
/// priority of hyphenating at a given point within the pattern. It
/// should contain only digit characters. (i.e. '0' to '9'). </param>
public virtual void AddPattern(string pattern, string ivalue)
{
int k = ivalues.Find(ivalue);
if (k <= 0)
{
k = PackValues(ivalue);
ivalues.Insert(ivalue, (char)k);
}
Insert(pattern, (char)k);
}
// public override void printStats(PrintStream @out)
// {
//@out.println("Value space size = " + Convert.ToString(vspace.length(), CultureInfo.InvariantCulture));
//base.printStats(@out);
// }
}
}
| |
// Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
namespace DBus.Protocol
{
public class MessageReader
{
public class PaddingException : Exception
{
int position;
byte element;
internal PaddingException (int position, byte element)
: base ("Read non-zero byte at position " + position + " while expecting padding. Value given: " + element)
{
this.position = position;
this.element = element;
}
public int Position {
get {
return position;
}
}
public byte Byte {
get {
return element;
}
}
}
readonly EndianFlag endianness;
readonly byte[] data;
readonly Message message;
int pos = 0;
static Dictionary<Type, bool> isPrimitiveStruct = new Dictionary<Type, bool> ();
static readonly Encoding stringEncoding = Encoding.UTF8;
Dictionary<Type, Func<object>> readValueCache = new Dictionary<Type, Func<object>> ();
public MessageReader (EndianFlag endianness, byte[] data)
{
if (data == null)
data = new byte[0];
this.endianness = endianness;
this.data = data;
}
public MessageReader (Message message) : this (message.Header.Endianness, message.Body)
{
if (message == null)
throw new ArgumentNullException ("message");
this.message = message;
}
public bool DataAvailable {
get {
return pos < data.Length;
}
}
public object ReadValue (Type type)
{
if (type == typeof (void))
return null;
Func<object> fastAccess;
if (readValueCache.TryGetValue (type, out fastAccess))
return fastAccess ();
if (type.IsArray) {
readValueCache[type] = () => ReadArray (type.GetElementType ());
return ReadArray (type.GetElementType ());
} else if (type == typeof (ObjectPath)) {
readValueCache[type] = () => ReadObjectPath ();
return ReadObjectPath ();
} else if (type == typeof (Signature)) {
readValueCache[type] = () => ReadSignature ();
return ReadSignature ();
} else if (type == typeof (object)) {
readValueCache[type] = () => ReadVariant ();
return ReadVariant ();
} else if (type == typeof (string)) {
readValueCache[type] = () => ReadString ();
return ReadString ();
} else if (type == typeof (UnixFD)) {
readValueCache[type] = () => ReadUnixFD ();
return ReadUnixFD ();
} else if (type.IsGenericType && (type.GetGenericTypeDefinition () == typeof (Dictionary<,>) || type.GetGenericTypeDefinition() == typeof(IDictionary<,>))) {
Type[] genArgs = type.GetGenericArguments ();
readValueCache[type] = () => ReadDictionary (genArgs[0], genArgs[1]);
return ReadDictionary (genArgs[0], genArgs[1]);
} else if (Mapper.IsPublic (type)) {
readValueCache[type] = () => GetObject (type);
return GetObject (type);
} else if (!type.IsPrimitive && !type.IsEnum) {
readValueCache[type] = () => ReadStruct (type);
return ReadStruct (type);
} else {
object val;
DType dtype = Signature.TypeToDType (type);
val = ReadValue (dtype);
if (type.IsEnum)
val = Enum.ToObject (type, val);
return val;
}
}
public object ReadValue (DType dtype)
{
switch (dtype)
{
case DType.Byte:
return ReadByte ();
case DType.Boolean:
return ReadBoolean ();
case DType.Int16:
return ReadInt16 ();
case DType.UInt16:
return ReadUInt16 ();
case DType.Int32:
return ReadInt32 ();
case DType.UInt32:
return ReadUInt32 ();
case DType.Int64:
return ReadInt64 ();
case DType.UInt64:
return ReadUInt64 ();
#if !DISABLE_SINGLE
case DType.Single:
return ReadSingle ();
#endif
case DType.Double:
return ReadDouble ();
case DType.String:
return ReadString ();
case DType.ObjectPath:
return ReadObjectPath ();
case DType.Signature:
return ReadSignature ();
case DType.Variant:
return ReadVariant ();
default:
throw new Exception ("Unhandled D-Bus type: " + dtype);
}
}
public object PeekValue (DType sig)
{
int savedPos = pos;
object result = ReadValue (sig);
pos = savedPos;
return result;
}
public void Seek (int stride)
{
var check = pos + stride;
if (check < 0 || check > data.Length)
throw new ArgumentOutOfRangeException ("stride");
pos = check;
}
public object GetObject (Type type)
{
ObjectPath path = ReadObjectPath ();
return message.Connection.GetObject (type, (string)message.Header[FieldCode.Sender], path);
}
public byte ReadByte ()
{
return data[pos++];
}
public bool ReadBoolean ()
{
uint intval = ReadUInt32 ();
switch (intval) {
case 0:
return false;
case 1:
return true;
default:
throw new Exception ("Read value " + intval + " at position " + pos + " while expecting boolean (0/1)");
}
}
unsafe protected void MarshalUShort (void* dstPtr)
{
ReadPad (2);
if (data.Length < pos + 2)
throw new Exception ("Cannot read beyond end of data");
if (endianness == Connection.NativeEndianness) {
fixed (byte* p = &data[pos])
*((ushort*)dstPtr) = *((ushort*)p);
} else {
byte* dst = (byte*)dstPtr;
dst[0] = data[pos + 1];
dst[1] = data[pos + 0];
}
pos += 2;
}
unsafe public short ReadInt16 ()
{
short val;
MarshalUShort (&val);
return val;
}
unsafe public ushort ReadUInt16 ()
{
ushort val;
MarshalUShort (&val);
return val;
}
unsafe protected void MarshalUInt (void* dstPtr)
{
ReadPad (4);
if (data.Length < pos + 4)
throw new Exception ("Cannot read beyond end of data");
if (endianness == Connection.NativeEndianness) {
fixed (byte* p = &data[pos])
*((uint*)dstPtr) = *((uint*)p);
} else {
byte* dst = (byte*)dstPtr;
dst[0] = data[pos + 3];
dst[1] = data[pos + 2];
dst[2] = data[pos + 1];
dst[3] = data[pos + 0];
}
pos += 4;
}
unsafe public int ReadInt32 ()
{
int val;
MarshalUInt (&val);
return val;
}
unsafe public uint ReadUInt32 ()
{
uint val;
MarshalUInt (&val);
return val;
}
unsafe protected void MarshalULong (void* dstPtr)
{
ReadPad (8);
if (data.Length < pos + 8)
throw new Exception ("Cannot read beyond end of data");
if (endianness == Connection.NativeEndianness) {
fixed (byte* p = &data[pos])
*((ulong*)dstPtr) = *((ulong*)p);
} else {
byte* dst = (byte*)dstPtr;
for (int i = 0; i < 8; ++i)
dst[i] = data[pos + (7 - i)];
}
pos += 8;
}
unsafe public long ReadInt64 ()
{
long val;
MarshalULong (&val);
return val;
}
unsafe public ulong ReadUInt64 ()
{
ulong val;
MarshalULong (&val);
return val;
}
#if !DISABLE_SINGLE
unsafe public float ReadSingle ()
{
float val;
MarshalUInt (&val);
return val;
}
#endif
unsafe public double ReadDouble ()
{
double val;
MarshalULong (&val);
return val;
}
public string ReadString ()
{
uint ln = ReadUInt32 ();
string val = stringEncoding.GetString (data, pos, (int)ln);
pos += (int)ln;
ReadNull ();
return val;
}
public UnixFD ReadUnixFD ()
{
uint index = ReadUInt32 ();
if (message.UnixFDArray == null)
throw new Exception ("Trying to read a UnixFD value but unix fd transfer not supported");
if (index >= message.UnixFDArray.FDs.Count)
throw new Exception ("UnixFD index " + index + " out of range (got " + message.UnixFDArray.FDs.Count + " fds)");
return message.UnixFDArray.FDs[(int)index];
}
public ObjectPath ReadObjectPath ()
{
//exactly the same as string
return new ObjectPath (ReadString ());
}
public Signature ReadSignature ()
{
byte ln = ReadByte ();
// Avoid an array allocation for small signatures
if (ln == 1) {
DType dtype = (DType)ReadByte ();
ReadNull ();
return new Signature (dtype);
}
if (ln > ProtocolInformation.MaxSignatureLength)
throw new Exception ("Signature length " + ln + " exceeds maximum allowed " + ProtocolInformation.MaxSignatureLength + " bytes");
byte[] sigData = new byte[ln];
Array.Copy (data, pos, sigData, 0, (int)ln);
pos += (int)ln;
ReadNull ();
return Signature.Take (sigData);
}
public object ReadVariant ()
{
var sig = ReadSignature ();
if (!sig.IsSingleCompleteType)
throw new InvalidOperationException (string.Format ("ReadVariant need a single complete type signature, {0} was given", sig.ToString ()));
return ReadValue (sig);
}
// Used primarily for reading variant values
public object ReadValue (Signature sig)
{
if (!sig.IsSingleCompleteType)
throw new ArgumentException (string.Format ("ReadVariant need a single complete type signature, {0} was given", sig.ToString ()));
var val = ReadValue (sig.ToType ());
return val;
}
public IDictionary ReadDictionary (Type keyType, Type valType)
{
MethodInfo mi = this.GetType ().GetMethod ("ReadDictionary", Type.EmptyTypes).MakeGenericMethod (new [] { keyType, valType });
return (IDictionary)mi.Invoke (this, null);
}
public Dictionary<TKey, TValue> ReadDictionary<TKey, TValue> ()
{
uint ln = ReadUInt32 ();
if (ln > ProtocolInformation.MaxArrayLength)
throw new Exception ("Dict length " + ln + " exceeds maximum allowed " + ProtocolInformation.MaxArrayLength + " bytes");
var val = new Dictionary<TKey, TValue> ((int)(ln / 8));
ReadPad (8);
int endPos = pos + (int)ln;
while (pos < endPos) {
ReadPad (8);
TKey k = (TKey)ReadValue (typeof (TKey));
TValue v = (TValue)ReadValue (typeof (TValue));
val.Add (k, v);
}
if (pos != endPos)
throw new Exception ("Read pos " + pos + " != ep " + endPos);
return val;
}
public Array ReadArray (Type elemType)
{
MethodInfo mi = this.GetType ().GetMethod ("ReadArray", Type.EmptyTypes).MakeGenericMethod (new [] { elemType });
return (Array)mi.Invoke (this, null);
}
public TArray[] ReadArray<TArray> ()
{
uint ln = ReadUInt32 ();
Type elemType = typeof (TArray);
if (ln > ProtocolInformation.MaxArrayLength)
throw new Exception ("Array length " + ln + " exceeds maximum allowed " + ProtocolInformation.MaxArrayLength + " bytes");
//advance to the alignment of the element
ReadPad (ProtocolInformation.GetAlignment (Signature.TypeToDType (elemType)));
if (elemType.IsPrimitive) {
// Fast path for primitive types (except bool which isn't blittable and take another path)
if (elemType != typeof (bool))
return MarshalArray<TArray> (ln);
else
return (TArray[])(Array)MarshalBoolArray (ln);
}
var list = new List<TArray> ();
int endPos = pos + (int)ln;
while (pos < endPos)
list.Add ((TArray)ReadValue (elemType));
if (pos != endPos)
throw new Exception ("Read pos " + pos + " != ep " + endPos);
return list.ToArray ();
}
TArray[] MarshalArray<TArray> (uint length)
{
int sof = Marshal.SizeOf (typeof (TArray));
TArray[] array = new TArray[(int)(length / sof)];
if (endianness == Connection.NativeEndianness) {
Buffer.BlockCopy (data, pos, array, 0, (int)length);
} else {
GCHandle handle = GCHandle.Alloc (array, GCHandleType.Pinned);
DirectCopy (sof, length, handle);
handle.Free ();
}
pos += (int)length;
return array;
}
void DirectCopy (int sof, uint length, GCHandle handle)
{
DirectCopy (sof, length, handle.AddrOfPinnedObject ());
}
unsafe void DirectCopy (int sof, uint length, IntPtr handle)
{
if (endianness == Connection.NativeEndianness) {
Marshal.Copy (data, pos, handle, (int)length);
} else {
byte* ptr = (byte*)(void*)handle;
for (int i = pos; i < pos + length; i += sof)
for (int j = i; j < i + sof; j++)
ptr[2 * i - pos + (sof - 1) - j] = data[j];
}
}
bool[] MarshalBoolArray (uint length)
{
bool[] array = new bool [length];
for (int i = 0; i < length; i++)
array[i] = ReadBoolean ();
return array;
}
public object ReadStruct (Type type)
{
ReadPad (8);
FieldInfo[] fis = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// Empty struct? No need for processing
if (fis.Length == 0)
return Activator.CreateInstance (type);
if (IsEligibleStruct (type, fis))
return MarshalStruct (type, fis);
object val = Activator.CreateInstance (type);
foreach (System.Reflection.FieldInfo fi in fis)
fi.SetValue (val, ReadValue (fi.FieldType));
return val;
}
public T ReadStruct<T> () where T : struct
{
ReadPad (8);
FieldInfo[] fis = typeof (T).GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// Empty struct? No need for processing
if (fis.Length == 0)
return default (T);
if (IsEligibleStruct (typeof(T), fis))
return (T)MarshalStruct (typeof(T), fis);
object val = Activator.CreateInstance<T> ();
foreach (System.Reflection.FieldInfo fi in fis)
fi.SetValue (val, ReadValue (fi.FieldType));
return (T)val;
}
object MarshalStruct (Type structType, FieldInfo[] fis)
{
object strct = Activator.CreateInstance (structType);
int sof = Marshal.SizeOf (fis[0].FieldType);
GCHandle handle = GCHandle.Alloc (strct, GCHandleType.Pinned);
uint length = (uint)(fis.Length * sof);
DirectCopy (sof, length, handle);
pos += (int)length;
handle.Free ();
return strct;
}
// Unfortunately in newer Mono, the compiler is not able to infer
// that T is a structure for the purpose of acquiring a pointer
// causing a compilation error
/*T NewMarshalStruct<T> (FieldInfo[] fis) where T : struct
{
T val = default (T);
int sof = Marshal.SizeOf (fis[0].FieldType);
unsafe {
byte* pVal = (byte*)&val;
DirectCopy (sof, (uint)(fis.Length * sof), (IntPtr)pVal);
}
return val;
}*/
public void ReadNull ()
{
if (data[pos] != 0)
throw new Exception ("Read non-zero byte at position " + pos + " while expecting null terminator");
pos++;
}
public void ReadPad (int alignment)
{
for (int endPos = ProtocolInformation.Padded (pos, alignment) ; pos != endPos ; pos++)
if (data[pos] != 0)
throw new PaddingException (pos, data[pos]);
}
// Note: This method doesn't support aggregate signatures
public bool StepOver (Signature sig)
{
if (sig == Signature.VariantSig) {
Signature valueSig = ReadSignature ();
return StepOver (valueSig);
}
if (sig == Signature.StringSig) {
uint valueLength = ReadUInt32 ();
pos += (int)valueLength;
pos++;
return true;
}
if (sig == Signature.ObjectPathSig) {
uint valueLength = ReadUInt32 ();
pos += (int)valueLength;
pos++;
return true;
}
if (sig == Signature.SignatureSig) {
byte valueLength = ReadByte ();
pos += valueLength;
pos++;
return true;
}
// No need to handle dicts specially. IsArray does the job
if (sig.IsArray) {
Signature elemSig = sig.GetElementSignature ();
uint ln = ReadUInt32 ();
pos = ProtocolInformation.Padded (pos, elemSig.Alignment);
pos += (int)ln;
return true;
}
int endPos = pos;
if (sig.GetFixedSize (ref endPos)) {
pos = endPos;
return true;
}
if (sig.IsDictEntry) {
pos = ProtocolInformation.Padded (pos, sig.Alignment);
Signature sigKey, sigValue;
sig.GetDictEntrySignatures (out sigKey, out sigValue);
if (!StepOver (sigKey))
return false;
if (!StepOver (sigValue))
return false;
return true;
}
if (sig.IsStruct) {
pos = ProtocolInformation.Padded (pos, sig.Alignment);
foreach (Signature fieldSig in sig.GetFieldSignatures ())
if (!StepOver (fieldSig))
return false;
return true;
}
throw new Exception ("Can't step over '" + sig + "'");
}
public IEnumerable<Signature> StepInto (Signature sig)
{
if (sig == Signature.VariantSig) {
Signature valueSig = ReadSignature ();
yield return valueSig;
yield break;
}
// No need to handle dicts specially. IsArray does the job
if (sig.IsArray) {
Signature elemSig = sig.GetElementSignature ();
uint ln = ReadUInt32 ();
ReadPad (elemSig.Alignment);
int endPos = pos + (int)ln;
while (pos < endPos)
yield return elemSig;
yield break;
}
if (sig.IsDictEntry) {
pos = ProtocolInformation.Padded (pos, sig.Alignment);
Signature sigKey, sigValue;
sig.GetDictEntrySignatures (out sigKey, out sigValue);
yield return sigKey;
yield return sigValue;
yield break;
}
if (sig.IsStruct) {
pos = ProtocolInformation.Padded (pos, sig.Alignment);
foreach (Signature fieldSig in sig.GetFieldSignatures ())
yield return fieldSig;
yield break;
}
throw new Exception ("Can't step into '" + sig + "'");
}
// If a struct is only composed of primitive type fields (i.e. blittable types)
// then this method return true. Result is cached in isPrimitiveStruct dictionary.
internal static bool IsEligibleStruct (Type structType, FieldInfo[] fields)
{
bool result;
if (isPrimitiveStruct.TryGetValue (structType, out result))
return result;
if (!(isPrimitiveStruct[structType] = fields.All ((f) => f.FieldType.IsPrimitive && f.FieldType != typeof (bool))))
return false;
int alignement = GetAlignmentFromPrimitiveType (fields[0].FieldType);
return isPrimitiveStruct[structType] = !fields.Any ((f) => GetAlignmentFromPrimitiveType (f.FieldType) != alignement);
}
static int GetAlignmentFromPrimitiveType (Type type)
{
return ProtocolInformation.GetAlignment (Signature.TypeCodeToDType (Type.GetTypeCode (type)));
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using LumiSoft.Net;
namespace LumiSoft.Data.lsDB
{
/// <summary>
/// LumiSoft database file.
/// </summary>
public class DbFile : IDisposable
{
private LDB_DataColumnCollection m_pColumns = null;
private FileStream m_pDbFile = null;
private string m_DbFileName = "";
private long m_DatapagesStartOffset = -1;
private LDB_Record m_pCurrentRecord = null;
private bool m_TableLocked = false;
private int m_DataPageDataAreaSize = 1000;
private long m_FileLength = 0;
private long m_FilePosition = 0;
/// <summary>
/// Default constructor.
/// </summary>
public DbFile()
{
m_pColumns = new LDB_DataColumnCollection(this);
}
#region method Dispose
/// <summary>
/// Clean up any resources being used.
/// </summary>
public void Dispose()
{
Close();
}
#endregion
#region method Open
/// <summary>
/// Opens specified data file.
/// </summary>
/// <param name="fileName">File name.</param>
public void Open(string fileName)
{
Open(fileName,0);
}
/// <summary>
/// Opens specified data file.
/// </summary>
/// <param name="fileName">File name.</param>
/// <param name="waitTime">If data base file is exclusively locked, then how many seconds to wait file to unlock before raising a error.</param>
public void Open(string fileName,int waitTime)
{
DateTime lockExpireTime = DateTime.Now.AddSeconds(waitTime);
while(true){
try{
m_pDbFile = File.Open(fileName,FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite);
break;
}
catch(IOException x){
// Make this because to get rid of "The variable 'x' is declared but never used"
string dummy = x.Message;
System.Threading.Thread.Sleep(15);
// Lock wait time timed out
if(DateTime.Now > lockExpireTime){
throw new Exception("Database file is locked and lock wait time expired !");
}
}
}
/* Table structure:
50 bytes - version
2 bytes - CRLF
8 bytes - free datapages count
2 bytes - CRLF
4 bytes - datapage data area size
2 bytes - CRLF
100 x 500 bytes - 100 columns info store
2 bytes - CRLF
... data pages
*/
m_DbFileName = fileName;
StreamLineReader r = new StreamLineReader(m_pDbFile);
// TODO: check if LDB file
// Read version line (50 bytes + CRLF)
byte[] version = r.ReadLine();
// Skip free data pages count
byte[] freeDataPagesCount = new byte[10];
m_pDbFile.Read(freeDataPagesCount,0,freeDataPagesCount.Length);
// 4 bytes datapage data area size + CRLF
byte[] dataPageDataAreaSize = new byte[6];
m_pDbFile.Read(dataPageDataAreaSize,0,dataPageDataAreaSize.Length);
m_DataPageDataAreaSize = ldb_Utils.ByteToInt(dataPageDataAreaSize,0);
// Read 100 column lines (500 + CRLF bytes each)
for(int i=0;i<100;i++){
byte[] columnInfo = r.ReadLine();
if(columnInfo == null){
throw new Exception("Invalid columns data area length !");
}
if(columnInfo[0] != '\0'){
m_pColumns.Parse(columnInfo);
}
}
// Header terminator \0
m_pDbFile.Position++;
// No we have rows start offset
m_DatapagesStartOffset = m_pDbFile.Position;
// Store file length and position
m_FileLength = m_pDbFile.Length;
m_FilePosition = m_pDbFile.Position;
}
#endregion
#region method Close
/// <summary>
/// Closes database file.
/// </summary>
public void Close()
{
if(m_pDbFile != null){
m_pDbFile.Close();
m_pDbFile = null;
m_DbFileName = "";
m_FileLength = 0;
m_FilePosition = 0;
}
}
#endregion
#region method Create
/// <summary>
/// Creates new database file.
/// </summary>
/// <param name="fileName">File name.</param>
public void Create(string fileName)
{
Create(fileName,1000);
}
/// <summary>
/// Creates new database file.
/// </summary>
/// <param name="fileName">File name.</param>
/// <param name="dataPageDataAreaSize">Specifies how many data can data page store.</param>
public void Create(string fileName,int dataPageDataAreaSize)
{
m_pDbFile = new FileStream(fileName,FileMode.CreateNew,FileAccess.ReadWrite,FileShare.None);
/* Table structure:
50 bytes - version
2 bytes - CRLF
8 bytes - free datapages count
2 bytes - CRLF
4 bytes - datapage data area size
2 bytes - CRLF
100 x 500 bytes - 100 columns info store
2 bytes - CRLF
... data pages
*/
// Version 50 + CRLF bytes
byte[] versionData = new byte[52];
versionData[0] = (byte)'1';
versionData[1] = (byte)'.';
versionData[2] = (byte)'0';
versionData[50] = (byte)'\r';
versionData[51] = (byte)'\n';
m_pDbFile.Write(versionData,0,versionData.Length);
// 8 bytes free data pages count + CRLF
byte[] freeDataPagesCount = new byte[10];
freeDataPagesCount[8] = (byte)'\r';
freeDataPagesCount[9] = (byte)'\n';
m_pDbFile.Write(freeDataPagesCount,0,freeDataPagesCount.Length);
// 4 bytes datapage data area size + CRLF
byte[] dataPageDataAreaSizeB = new byte[6];
Array.Copy(ldb_Utils.IntToByte(dataPageDataAreaSize),0,dataPageDataAreaSizeB,0,4);
dataPageDataAreaSizeB[4] = (byte)'\r';
dataPageDataAreaSizeB[5] = (byte)'\n';
m_pDbFile.Write(dataPageDataAreaSizeB,0,dataPageDataAreaSizeB.Length);
// 100 x 100 + CRLF bytes header lines
for(int i=0;i<100;i++){
byte[] data = new byte[100];
m_pDbFile.Write(data,0,data.Length);
m_pDbFile.Write(new byte[]{(int)'\r',(int)'\n'},0,2);
}
// Headers terminator char(0)
m_pDbFile.WriteByte((int)'\0');
// Data pages start pointer
m_DatapagesStartOffset = m_pDbFile.Position - 1;
m_DbFileName = fileName;
m_DataPageDataAreaSize = dataPageDataAreaSize;
// Store file length and position
m_FileLength = m_pDbFile.Length;
m_FilePosition = m_pDbFile.Position;
}
#endregion
#region method LockTable
/// <summary>
/// Locks table.
/// </summary>
/// <param name="waitTime">If table is locked, then how many sconds to wait table to unlock, before teturning error.</param>
public void LockTable(int waitTime)
{
if(!this.IsDatabaseOpen){
throw new Exception("Database isn't open, please open database first !");
}
// Table is locked already, just skip locking
if(m_TableLocked){
return;
}
DateTime lockExpireTime = DateTime.Now.AddSeconds(waitTime);
while(true){
try{
// We just lock first byte
m_pDbFile.Lock(0,1);
m_TableLocked = true;
break;
}
// Catch the IOException generated if the
// specified part of the file is locked.
catch(IOException x){
// Make this because to get rid of "The variable 'x' is declared but never used"
string dummy = x.Message;
System.Threading.Thread.Sleep(15);
// Lock wait time timed out
if(DateTime.Now > lockExpireTime){
throw new Exception("Table is locked and lock wait time expired !");
}
}
}
}
#endregion
#region method UnlockTable
/// <summary>
/// Unlock table.
/// </summary>
public void UnlockTable()
{
if(!this.IsDatabaseOpen){
throw new Exception("Database isn't open, please open database first !");
}
if(m_TableLocked){
// We just unlock first byte
m_pDbFile.Unlock(0,1);
}
}
#endregion
#region method LockRecord
/*
/// <summary>
/// Locks current record.
/// </summary>
public void LockRecord()
{
if(!this.IsDatabaseOpen){
throw new Exception("Database isn't open, please open database first !");
}
}
*/
#endregion
#region method UnlockRecord
/*
/// <summary>
/// Unlocks current record.
/// </summary>
public void UnlockRecord()
{
if(!this.IsDatabaseOpen){
throw new Exception("Database isn't open, please open database first !");
}
}
*/
#endregion
#region method NextRecord
/// <summary>
/// Gets next record. Returns true if end of file reached and there are no more records.
/// </summary>
/// <returns>Returns true if end of file reached and there are no more records.</returns>
public bool NextRecord()
{
if(!this.IsDatabaseOpen){
throw new Exception("Database isn't open, please open database first !");
}
//--- Find next record ---------------------------------------------------//
long nextRowStartOffset = 0;
if(m_pCurrentRecord == null){
nextRowStartOffset = m_DatapagesStartOffset;
}
else{
nextRowStartOffset = m_pCurrentRecord.DataPage.Pointer + m_DataPageDataAreaSize + 33;
}
while(true){
if(m_FileLength > nextRowStartOffset){
DataPage dataPage = new DataPage(m_DataPageDataAreaSize,this,nextRowStartOffset);
// We want datapage with used space
if(dataPage.Used && dataPage.OwnerDataPagePointer < 1){
m_pCurrentRecord = new LDB_Record(this,dataPage);
break;
}
}
else{
return true;
}
nextRowStartOffset += m_DataPageDataAreaSize + 33;
}
//-------------------------------------------------------------------------//
return false;
}
#endregion
#region method AppendRecord
/// <summary>
/// Appends new record to table.
/// </summary>
public void AppendRecord(object[] values)
{
if(!this.IsDatabaseOpen){
throw new Exception("Database isn't open, please open database first !");
}
if(m_pColumns.Count != values.Length){
throw new Exception("Each column must have corresponding value !");
}
bool unlock = true;
// Table is already locked, don't lock it
if(this.TableLocked){
unlock = false;
}
else{
LockTable(15);
}
// Construct record data
byte[] record = LDB_Record.CreateRecord(this,values);
// Get free data pages
DataPage[] dataPages = GetDataPages(0,(int)Math.Ceiling(record.Length / (double)m_DataPageDataAreaSize));
DbFile.StoreDataToDataPages(m_DataPageDataAreaSize,record,dataPages);
if(unlock){
UnlockTable();
}
}
#endregion
#region method DeleteRecord
/// <summary>
/// Deletes current record.
/// </summary>
public void DeleteCurrentRecord()
{
if(!this.IsDatabaseOpen){
throw new Exception("Database isn't open, please open database first !");
}
if(m_pCurrentRecord == null){
throw new Exception("There is no current record !");
}
bool unlock = true;
// Table is already locked, don't lock it
if(this.TableLocked){
unlock = false;
}
else{
LockTable(15);
}
// Release all data pages hold by this row
DataPage[] dataPages = m_pCurrentRecord.DataPages;
for(int i=0;i<dataPages.Length;i++){
DataPage p = dataPages[i];
byte[] dataPage = DataPage.CreateDataPage(m_DataPageDataAreaSize,false,0,0,0,new byte[m_DataPageDataAreaSize]);
SetFilePosition(p.Pointer);
WriteToFile(dataPage,0,dataPage.Length);
}
// Increase free data pages count info in table header
byte[] freeDataPagesCount = new byte[8];
SetFilePosition(52);
ReadFromFile(freeDataPagesCount,0,freeDataPagesCount.Length);
freeDataPagesCount = ldb_Utils.LongToByte(ldb_Utils.ByteToLong(freeDataPagesCount,0) + dataPages.Length);
SetFilePosition(52);
WriteToFile(freeDataPagesCount,0,freeDataPagesCount.Length);
if(unlock){
UnlockTable();
}
// Activate next record **** Change it ???
NextRecord();
}
#endregion
#region static method StoreDataToDataPages
/// <summary>
/// Stores data to specified data pages.
/// </summary>
/// <param name="dataPageDataAreaSize">Data page data area size.</param>
/// <param name="data">Data to store.</param>
/// <param name="dataPages">Data pages where to store data.</param>
internal static void StoreDataToDataPages(int dataPageDataAreaSize,byte[] data,DataPage[] dataPages)
{
if((int)Math.Ceiling(data.Length / (double)dataPageDataAreaSize) > dataPages.Length){
throw new Exception("There isn't enough data pages to store data ! Data needs '" + (int)Math.Ceiling(data.Length / (double)dataPageDataAreaSize) + "' , but available '" + dataPages.Length + "'.");
}
//--- Store data to data page(s) -----------------------//
long position = 0;
for(int i=0;i<dataPages.Length;i++){
if((data.Length - position) > dataPageDataAreaSize){
byte[] d = new byte[dataPageDataAreaSize];
Array.Copy(data,position,d,0,d.Length);
dataPages[i].WriteData(d);
position += dataPageDataAreaSize;
}
else{
byte[] d = new byte[data.Length - position];
Array.Copy(data,position,d,0,d.Length);
dataPages[i].WriteData(d);
}
}
//------------------------------------------------------//
}
#endregion
#region method GetDataPages
/// <summary>
/// Gets specified number of free data pages. If free data pages won't exist, creates new ones.
/// Data pages are marked as used and OwnerDataPagePointer and NextDataPagePointer is set as needed.
/// </summary>
/// <param name="ownerDataPagePointer">Owner data page pointer that own first requested data page. If no owner then this value is 0.</param>
/// <param name="count">Number of data pages wanted.</param>
internal DataPage[] GetDataPages(long ownerDataPagePointer,int count)
{
if(!this.TableLocked){
throw new Exception("Table must be locked to acess GetDataPages() method !");
}
ArrayList freeDataPages = new ArrayList();
// Get free data pages count from table header
byte[] freeDataPagesCount = new byte[8];
SetFilePosition(52);
ReadFromFile(freeDataPagesCount,0,freeDataPagesCount.Length);
long nFreeDataPages = ldb_Utils.ByteToLong(freeDataPagesCount,0);
// We have plenty free data pages and enough for count requested, find requested count free data pages
if(nFreeDataPages > 1000 && nFreeDataPages > count){
long nextDataPagePointer = m_DatapagesStartOffset + 1;
while(freeDataPages.Count < count){
DataPage dataPage = new DataPage(m_DataPageDataAreaSize,this,nextDataPagePointer);
if(!dataPage.Used){
dataPage.Used = true;
freeDataPages.Add(dataPage);
}
nextDataPagePointer += m_DataPageDataAreaSize + 33;
}
// Decrease free data pages count in table header
SetFilePosition(52);
ReadFromFile(ldb_Utils.LongToByte(nFreeDataPages - count),0,8);
}
// Just create new data pages
else{
for(int i=0;i<count;i++){
byte[] dataPage = DataPage.CreateDataPage(m_DataPageDataAreaSize,true,0,0,0,new byte[m_DataPageDataAreaSize]);
GoToFileEnd();
long dataPageStartPointer = GetFilePosition();
WriteToFile(dataPage,0,dataPage.Length);
freeDataPages.Add(new DataPage(m_DataPageDataAreaSize,this,dataPageStartPointer));
}
}
// Relate data pages (chain)
for(int i=0;i<freeDataPages.Count;i++){
// First data page
if(i == 0){
// Owner data page poitner specified for first data page
if(ownerDataPagePointer > 0){
((DataPage)freeDataPages[i]).OwnerDataPagePointer = ownerDataPagePointer;
}
// There is continuing data page
if(freeDataPages.Count > 1){
((DataPage)freeDataPages[i]).NextDataPagePointer = ((DataPage)freeDataPages[i + 1]).Pointer;
}
}
// Last data page
else if(i == (freeDataPages.Count - 1)){
((DataPage)freeDataPages[i]).OwnerDataPagePointer = ((DataPage)freeDataPages[i - 1]).Pointer;
}
// Middle range data page
else{
((DataPage)freeDataPages[i]).OwnerDataPagePointer = ((DataPage)freeDataPages[i - 1]).Pointer;
((DataPage)freeDataPages[i]).NextDataPagePointer = ((DataPage)freeDataPages[i + 1]).Pointer;
}
}
DataPage[] retVal = new DataPage[freeDataPages.Count];
freeDataPages.CopyTo(retVal);
return retVal;
}
#endregion
#region method AddColumn
/// <summary>
/// Adds column to db file.
/// </summary>
/// <param name="column"></param>
internal void AddColumn(LDB_DataColumn column)
{
// Find free column data area
// Set position over version, free data pages count and data page data area size
m_pDbFile.Position = 68;
long freeColumnPosition = -1;
StreamLineReader r = new StreamLineReader(m_pDbFile);
// Loop all columns data areas, see it there any free left
for(int i=0;i<100;i++){
byte[] columnInfo = r.ReadLine();
if(columnInfo == null){
throw new Exception("Invalid columns data area length !");
}
// We found unused column data area
if(columnInfo[0] == '\0'){
freeColumnPosition = m_pDbFile.Position;
break;
}
}
m_FilePosition = m_pDbFile.Position;
if(freeColumnPosition != -1){
// TODO: If there is data ???
// Move to row start
SetFilePosition(GetFilePosition() - 102);
// Store column
byte[] columnData = column.ToColumnInfo();
WriteToFile(columnData,0,columnData.Length);
}
else{
throw new Exception("Couldn't find free column space ! ");
}
}
#endregion
#region method RemoveColumn
/// <summary>
/// Removes specified column from database file.
/// </summary>
/// <param name="column"></param>
internal void RemoveColumn(LDB_DataColumn column)
{
throw new Exception("TODO:");
}
#endregion
#region method ReadFromFile
/// <summary>
/// Reads data from file.
/// </summary>
/// <param name="data">Buffer where to store readed data..</param>
/// <param name="offset">Offset in array to where to start storing readed data.</param>
/// <param name="count">Number of bytes to read.</param>
/// <returns></returns>
internal int ReadFromFile(byte[] data,int offset,int count)
{
int readed = m_pDbFile.Read(data,offset,count);
m_FilePosition += readed;
return readed;
}
#endregion
#region method WriteToFile
/// <summary>
/// Writes data to file.
/// </summary>
/// <param name="data">Data to write.</param>
/// <param name="offset">Offset in array from where to start writing data.</param>
/// <param name="count">Number of bytes to write.</param>
/// <returns></returns>
internal void WriteToFile(byte[] data,int offset,int count)
{
m_pDbFile.Write(data,offset,count);
m_FilePosition += count;
}
#endregion
#region method GetFilePosition
/// <summary>
/// Gets current position in file.
/// </summary>
/// <returns></returns>
internal long GetFilePosition()
{
return m_FilePosition;
}
#endregion
#region method SetFilePosition
/// <summary>
/// Sets file position.
/// </summary>
/// <param name="position">Position in file.</param>
internal void SetFilePosition(long position)
{
if(m_FilePosition != position){
m_pDbFile.Position = position;
m_FilePosition = position;
}
}
#endregion
#region method GoToFileEnd
/// <summary>
/// Moves position to the end of file.
/// </summary>
private void GoToFileEnd()
{
m_pDbFile.Position = m_pDbFile.Length;
m_FileLength = m_pDbFile.Length;
m_FilePosition = m_FileLength;
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets if there is active database file.
/// </summary>
public bool IsDatabaseOpen
{
get{ return m_pDbFile != null; }
}
/// <summary>
/// Gets open database file name. Throws exception if database isn't open.
/// </summary>
public string FileName
{
get{
if(!this.IsDatabaseOpen){
throw new Exception("Database isn't open, please open database first !");
}
return m_DbFileName;
}
}
/// <summary>
/// Gets table columns. Throws exception if database isn't open.
/// </summary>
public LDB_DataColumnCollection Columns
{
get{
if(!this.IsDatabaseOpen){
throw new Exception("Database isn't open, please open database first !");
}
return m_pColumns;
}
}
/// <summary>
/// Gets current record. Returns null if there isn't current record.
/// </summary>
public LDB_Record CurrentRecord
{
get{ return m_pCurrentRecord; }
}
/// <summary>
/// Gets table is locked.
/// </summary>
public bool TableLocked
{
get{ return m_TableLocked; }
}
/// <summary>
/// Gets how much data data page can store.
/// </summary>
public int DataPageDataAreaSize
{
get{ return m_DataPageDataAreaSize; }
}
#endregion
}
}
| |
// <copyright file="BiCgStabTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// 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>
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double.Solvers.Iterative
{
/// <summary>
/// Tests of Bi-Conjugate Gradient stabilized iterative matrix solver.
/// </summary>
[TestFixture, Category("LASolver")]
public class BiCgStabTest
{
/// <summary>
/// Convergence boundary.
/// </summary>
const double ConvergenceBoundary = 1e-10;
/// <summary>
/// Maximum iterations.
/// </summary>
const int MaximumIterations = 1000;
/// <summary>
/// Solve wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveWideMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(2, 3);
var input = new DenseVector(2);
var solver = new BiCgStab();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve long matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveLongMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(3, 2);
var input = new DenseVector(3);
var solver = new BiCgStab();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve unit matrix and back multiply.
/// </summary>
[Test]
public void SolveUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = Matrix<double>.Build.SparseIdentity(100);
// Create the y vector
var y = Vector<double>.Build.Dense(matrix.RowCount, 1.0d);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(MaximumIterations),
new ResidualStopCriterion<double>(ConvergenceBoundary),
new DivergenceStopCriterion<double>(),
new FailureStopCriterion<double>());
var solver = new BiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, Math.Abs(y[i] - z[i]), "#05-" + i);
}
}
/// <summary>
/// Solve scaled unit matrix and back multiply.
/// </summary>
[Test]
public void SolveScaledUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = Matrix<double>.Build.SparseIdentity(100);
// Scale it with a funny number
matrix.Multiply(Math.PI, matrix);
// Create the y vector
var y = Vector<double>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(MaximumIterations),
new ResidualStopCriterion<double>(ConvergenceBoundary),
new DivergenceStopCriterion<double>(),
new FailureStopCriterion<double>());
var solver = new BiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, Math.Abs(y[i] - z[i]), "#05-" + i);
}
}
/// <summary>
/// Solve poisson matrix and back multiply.
/// </summary>
[Test]
public void SolvePoissonMatrixAndBackMultiply()
{
// Create the matrix
var matrix = Matrix<double>.Build.Sparse(100, 100);
// Assemble the matrix. We assume we're solving the Poisson equation
// on a rectangular 10 x 10 grid
const int GridSize = 10;
// The pattern is:
// 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
for (var i = 0; i < matrix.RowCount; i++)
{
// Insert the first set of -1's
if (i > (GridSize - 1))
{
matrix[i, i - GridSize] = -1;
}
// Insert the second set of -1's
if (i > 0)
{
matrix[i, i - 1] = -1;
}
// Insert the centerline values
matrix[i, i] = 4;
// Insert the first trailing set of -1's
if (i < matrix.RowCount - 1)
{
matrix[i, i + 1] = -1;
}
// Insert the second trailing set of -1's
if (i < matrix.RowCount - GridSize)
{
matrix[i, i + GridSize] = -1;
}
}
// Create the y vector
var y = Vector<double>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(MaximumIterations),
new ResidualStopCriterion<double>(ConvergenceBoundary),
new DivergenceStopCriterion<double>(),
new FailureStopCriterion<double>());
var solver = new BiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, Math.Abs(y[i] - z[i]), "#05-" + i);
}
}
/// <summary>
/// Can solve for a random vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<double>.Build.Random(order, order, 1);
var vectorb = Vector<double>.Build.Random(order, 1);
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(1000),
new ResidualStopCriterion<double>(1e-10));
var solver = new BiCgStab();
var resultx = matrixA.SolveIterative(vectorb, solver, monitor);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-7);
}
}
/// <summary>
/// Can solve for random matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<double>.Build.Random(order, order, 100);
var matrixB = Matrix<double>.Build.Random(order, order, 200);
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(1000),
new ResidualStopCriterion<double>(1e-10));
var solver = new BiCgStab();
var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-7);
}
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Networking/Requests/Messages/StartGymBattleMessage.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Networking.Requests.Messages {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Requests/Messages/StartGymBattleMessage.proto</summary>
public static partial class StartGymBattleMessageReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Requests/Messages/StartGymBattleMessage.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static StartGymBattleMessageReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkNQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVxdWVzdHMvTWVzc2FnZXMvU3Rh",
"cnRHeW1CYXR0bGVNZXNzYWdlLnByb3RvEidQT0dPUHJvdG9zLk5ldHdvcmtp",
"bmcuUmVxdWVzdHMuTWVzc2FnZXMilwEKFVN0YXJ0R3ltQmF0dGxlTWVzc2Fn",
"ZRIOCgZneW1faWQYASABKAkSHQoVYXR0YWNraW5nX3Bva2Vtb25faWRzGAIg",
"AygGEhwKFGRlZmVuZGluZ19wb2tlbW9uX2lkGAMgASgGEhcKD3BsYXllcl9s",
"YXRpdHVkZRgEIAEoARIYChBwbGF5ZXJfbG9uZ2l0dWRlGAUgASgBYgZwcm90",
"bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Requests.Messages.StartGymBattleMessage), global::POGOProtos.Networking.Requests.Messages.StartGymBattleMessage.Parser, new[]{ "GymId", "AttackingPokemonIds", "DefendingPokemonId", "PlayerLatitude", "PlayerLongitude" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class StartGymBattleMessage : pb::IMessage<StartGymBattleMessage> {
private static readonly pb::MessageParser<StartGymBattleMessage> _parser = new pb::MessageParser<StartGymBattleMessage>(() => new StartGymBattleMessage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<StartGymBattleMessage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Requests.Messages.StartGymBattleMessageReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StartGymBattleMessage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StartGymBattleMessage(StartGymBattleMessage other) : this() {
gymId_ = other.gymId_;
attackingPokemonIds_ = other.attackingPokemonIds_.Clone();
defendingPokemonId_ = other.defendingPokemonId_;
playerLatitude_ = other.playerLatitude_;
playerLongitude_ = other.playerLongitude_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StartGymBattleMessage Clone() {
return new StartGymBattleMessage(this);
}
/// <summary>Field number for the "gym_id" field.</summary>
public const int GymIdFieldNumber = 1;
private string gymId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GymId {
get { return gymId_; }
set {
gymId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "attacking_pokemon_ids" field.</summary>
public const int AttackingPokemonIdsFieldNumber = 2;
private static readonly pb::FieldCodec<ulong> _repeated_attackingPokemonIds_codec
= pb::FieldCodec.ForFixed64(18);
private readonly pbc::RepeatedField<ulong> attackingPokemonIds_ = new pbc::RepeatedField<ulong>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<ulong> AttackingPokemonIds {
get { return attackingPokemonIds_; }
}
/// <summary>Field number for the "defending_pokemon_id" field.</summary>
public const int DefendingPokemonIdFieldNumber = 3;
private ulong defendingPokemonId_;
/// <summary>
/// needs to be fixed64, tested by Grover
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong DefendingPokemonId {
get { return defendingPokemonId_; }
set {
defendingPokemonId_ = value;
}
}
/// <summary>Field number for the "player_latitude" field.</summary>
public const int PlayerLatitudeFieldNumber = 4;
private double playerLatitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PlayerLatitude {
get { return playerLatitude_; }
set {
playerLatitude_ = value;
}
}
/// <summary>Field number for the "player_longitude" field.</summary>
public const int PlayerLongitudeFieldNumber = 5;
private double playerLongitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PlayerLongitude {
get { return playerLongitude_; }
set {
playerLongitude_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as StartGymBattleMessage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(StartGymBattleMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (GymId != other.GymId) return false;
if(!attackingPokemonIds_.Equals(other.attackingPokemonIds_)) return false;
if (DefendingPokemonId != other.DefendingPokemonId) return false;
if (PlayerLatitude != other.PlayerLatitude) return false;
if (PlayerLongitude != other.PlayerLongitude) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (GymId.Length != 0) hash ^= GymId.GetHashCode();
hash ^= attackingPokemonIds_.GetHashCode();
if (DefendingPokemonId != 0UL) hash ^= DefendingPokemonId.GetHashCode();
if (PlayerLatitude != 0D) hash ^= PlayerLatitude.GetHashCode();
if (PlayerLongitude != 0D) hash ^= PlayerLongitude.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (GymId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(GymId);
}
attackingPokemonIds_.WriteTo(output, _repeated_attackingPokemonIds_codec);
if (DefendingPokemonId != 0UL) {
output.WriteRawTag(25);
output.WriteFixed64(DefendingPokemonId);
}
if (PlayerLatitude != 0D) {
output.WriteRawTag(33);
output.WriteDouble(PlayerLatitude);
}
if (PlayerLongitude != 0D) {
output.WriteRawTag(41);
output.WriteDouble(PlayerLongitude);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (GymId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GymId);
}
size += attackingPokemonIds_.CalculateSize(_repeated_attackingPokemonIds_codec);
if (DefendingPokemonId != 0UL) {
size += 1 + 8;
}
if (PlayerLatitude != 0D) {
size += 1 + 8;
}
if (PlayerLongitude != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(StartGymBattleMessage other) {
if (other == null) {
return;
}
if (other.GymId.Length != 0) {
GymId = other.GymId;
}
attackingPokemonIds_.Add(other.attackingPokemonIds_);
if (other.DefendingPokemonId != 0UL) {
DefendingPokemonId = other.DefendingPokemonId;
}
if (other.PlayerLatitude != 0D) {
PlayerLatitude = other.PlayerLatitude;
}
if (other.PlayerLongitude != 0D) {
PlayerLongitude = other.PlayerLongitude;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
GymId = input.ReadString();
break;
}
case 18:
case 17: {
attackingPokemonIds_.AddEntriesFrom(input, _repeated_attackingPokemonIds_codec);
break;
}
case 25: {
DefendingPokemonId = input.ReadFixed64();
break;
}
case 33: {
PlayerLatitude = input.ReadDouble();
break;
}
case 41: {
PlayerLongitude = input.ReadDouble();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace Settings.NET.Serialized
{
public class SerializableSettings<T> : ISettings<T> where T : new()
{
private T _current;
private bool _currentExist;
private Encoding _encoding;
private SettingsFile _file;
private string _name;
private string _path;
private ISerializeEx _serializer;
/// <summary>
/// Gets or sets the file.
/// </summary>
/// <value>
/// The file.
/// </value>
public SettingsFile SettingsFile
{
get { return _file ?? (_file = SettingsFile.XmlFile(typeof(T).Name, "Settings")); }
set { _file = value; }
}
/// <summary>
/// Gets or sets the serializer.
/// </summary>
/// <value>
/// The serializer.
/// </value>
public ISerializeEx Serializer
{
get
{
if (_serializer == null)
{
_serializer = new XmlSerializerEx();
SettingsFile.Extension = ".xml";
SettingsFile.SubDirectory = "XmlSettings";
}
return _serializer;
}
set { _serializer = value; }
}
/// <summary>
/// Gets or sets a value indicating whether [backup on save].
/// </summary>
/// <value>
/// <c>true</c> if [backup on save]; otherwise, <c>false</c>.
/// </value>
public bool BackupOnSave { get; set; } = true;
/// <summary>
/// Gets or sets the path.
/// </summary>
/// <value>
/// The path.
/// </value>
public string Path
{
get
{
if (string.IsNullOrEmpty(_path))
{
_path = SettingsFile.GetFullPath();
}
return _path;
}
protected set { _path = value; }
}
/// <summary>
/// Gets or sets the name of the settings.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name
{
get
{
if (string.IsNullOrEmpty(_name))
{
_name = typeof(T).Name;
}
return _name;
}
set { _name = value; }
}
/// <summary>
/// Gets or sets the encoding.
/// </summary>
/// <value>
/// The encoding.
/// </value>
public Encoding Encoding
{
get { return _encoding ?? (_encoding = Encoding.UTF8); }
set { _encoding = value; }
}
/// <summary>
/// Gets or sets the current settings instance.
/// </summary>
/// <value>
/// The current.
/// </value>
public T Current
{
get
{
if (!_currentExist)
{
_current = new T();
_currentExist = true;
}
return _current;
}
set
{
_current = value;
_currentExist = true;
}
}
/// <summary>
/// Saves the settings to the specified file.
/// </summary>
/// <param name="file">The file.</param>
public void Save(string file = "")
{
if (string.IsNullOrEmpty(file))
{
file = Path;
}
if (File.Exists(file) && BackupOnSave)
{
BackupSettings(file);
}
Serializer.ExportToFile(Current, file, Encoding.UTF8);
}
/// <summary>
/// Loads the settings from the specified location.
/// </summary>
/// <param name="location">
/// The location of the file.
/// </param>
/// <exception cref="System.ArgumentNullException"></exception>
public void Load(string location = "")
{
if (string.IsNullOrEmpty(location))
{
location = Path;
}
if (!File.Exists(location))
{
Save(location);
}
var settings = Serializer.ImportFromFile<T>(location, Encoding.UTF8);
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
Current = settings;
OnSettingsChanged(location);
}
/// <summary>
/// Backups the settings if one already exist.
/// </summary>
/// <param name="target">The target to back up settings to.</param>
/// <exception cref="System.ArgumentNullException"></exception>
protected void BackupSettings(string target = "")
{
if (string.IsNullOrEmpty(target))
{
target = Path;
}
var extension = System.IO.Path.GetExtension(target);
if (extension == null)
{
throw new ArgumentNullException(Path + " does not contain an extension.");
}
var time = DateTime.Now;
var backup = target.Replace(extension,
$"-{time.ToString("yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture)}{extension}");
Serializer.ExportToFile(Current, backup, Encoding);
}
/// <summary>
/// Occurs when [on settings changed].
/// </summary>
public event EventHandler<string> SettingsLoaded;
/// <summary>
/// Raises the on settings changed.
/// </summary>
/// <param name="target">The e.</param>
protected virtual void OnSettingsChanged(string target)
{
SettingsLoaded?.Invoke(this, target);
}
}
}
| |
#region Header
// --------------------------------------------------------------------------
// Tethys.Silverlight
// ==========================================================================
//
// This library contains common code for Windows Forms applications.
//
// ===========================================================================
//
// <copyright file="ColorUtil.cs" company="Tethys">
// Copyright 1998-2015 by Thomas Graf
// All rights reserved.
// Licensed under the Apache License, Version 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.
// </copyright>
//
// System ... Microsoft .Net Framework 4
// Tools .... Microsoft Visual Studio 2013
//
// ---------------------------------------------------------------------------
#endregion
namespace Tethys.Forms
{
using System;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
/// <summary>
/// The class <see cref="ColorUtil"/> implements support functions for
/// color conversion and color detection.
/// </summary>
public static class ColorUtil
{
#region PRIVATE PROPERTIES
/// <summary>
/// The system color names.
/// </summary>
private static ReadOnlyCollection<string> systemColorNames;
/// <summary>
/// The known color names.
/// </summary>
private static ReadOnlyCollection<string> knownColorNames;
#endregion // PRIVATE PROPERTIES
#region COLOR NAMES
/// <summary>
/// Gets the known color names.
/// </summary>
public static ReadOnlyCollection<string> KnownColorNames
{
get
{
if (knownColorNames == null)
{
knownColorNames = new ReadOnlyCollection<string>(new[]
{
"Transparent", "Black", "DimGray", "Gray", "DarkGray", "Silver",
"LightGray", "Gainsboro", "WhiteSmoke", "White", "RosyBrown", "IndianRed",
"Brown", "Firebrick", "LightCoral", "Maroon", "DarkRed", "Red", "Snow",
"MistyRose", "Salmon", "Tomato", "DarkSalmon", "Coral", "OrangeRed",
"LightSalmon", "Sienna", "SeaShell", "Chocalate", "SaddleBrown",
"SandyBrown", "PeachPuff", "Peru", "Linen", "Bisque", "DarkOrange",
"BurlyWood", "Tan", "AntiqueWhite", "NavajoWhite", "BlanchedAlmond",
"PapayaWhip", "Mocassin", "Orange", "Wheat", "OldLace", "FloralWhite",
"DarkGoldenrod", "Cornsilk", "Gold", "Khaki", "LemonChiffon",
"PaleGoldenrod", "DarkKhaki", "Beige", "LightGoldenrod", "Olive",
"Yellow", "LightYellow", "Ivory", "OliveDrab", "YellowGreen",
"DarkOliveGreen", "GreenYellow", "Chartreuse", "LawnGreen",
"DarkSeaGreen", "ForestGreen", "LimeGreen", "PaleGreen", "DarkGreen",
"Green", "Lime", "Honeydew", "SeaGreen", "MediumSeaGreen", "SpringGreen",
"MintCream", "MediumSpringGreen", "MediumAquaMarine", "YellowAquaMarine",
"Turquoise", "LightSeaGreen", "MediumTurquoise", "DarkSlateGray",
"PaleTurquoise", "Teal", "DarkCyan", "Aqua", "Cyan", "LightCyan", "Azure",
"DarkTurquoise", "CadetBlue", "PowderBlue", "LightBlue", "DeepSkyBlue",
"SkyBlue", "LightSkyBlue", "SteelBlue", "AliceBlue", "DodgerBlue",
"SlateGray", "LightSlateGray", "LightSteelBlue", "CornflowerBlue",
"RoyalBlue", "MidnightBlue", "Lavender", "Navy", "DarkBlue", "MediumBlue",
"Blue", "GhostWhite", "SlateBlue", "DarkSlateBlue", "MediumSlateBlue",
"MediumPurple", "BlueViolet", "Indigo", "DarkOrchid", "DarkViolet",
"MediumOrchid", "Thistle", "Plum", "Violet", "Purple", "DarkMagenta",
"Magenta", "Fuchsia", "Orchid", "MediumVioletRed", "DeepPink", "HotPink",
"LavenderBlush", "PaleVioletRed", "Crimson", "Pink", "LightPink"
});
} // if
return knownColorNames;
}
}
/// <summary>
/// Gets the system color names.
/// </summary>
public static ReadOnlyCollection<string> SystemColorNames
{
get
{
if (systemColorNames == null)
{
systemColorNames = new ReadOnlyCollection<string>(new[]
{
"ActiveBorder", "ActiveCaption", "ActiveCaptionText", "AppWorkspace",
"Control", "ControlDark", "ControlDarkDark", "ControlLight",
"ControlLightLight", "ControlText", "Desktop", "GrayText", "HighLight",
"HighLightText", "HotTrack", "InactiveBorder", "InactiveCaption",
"InactiveCaptionText", "Info", "InfoText", "Menu", "MenuText",
"ScrollBar", "Window", "WindowFrame", "WindowText"
});
} // if
return systemColorNames;
}
}
#endregion // COLOR NAMES
//// ---------------------------------------------------------------------
#region CONVERSION FUNCTIONS
// ------------------------------------------
// Conversion between RGB and Hue, Saturation
// and Luminosity function helpers
// ------------------------------------------
/// <summary>
/// Conversion HSL to RGB.
/// </summary>
/// <param name="h">The h.</param>
/// <param name="s">The s.</param>
/// <param name="l">The l.</param>
/// <param name="r">The r.</param>
/// <param name="g">The g.</param>
/// <param name="b">The b.</param>
[SuppressMessage("Microsoft.Design",
"CA1045:DoNotPassTypesByReference", MessageId = "3#",
Justification = "Best solution here")]
[SuppressMessage("Microsoft.Design",
"CA1045:DoNotPassTypesByReference", MessageId = "4#",
Justification = "Best solution here")]
[SuppressMessage("Microsoft.Design",
"CA1045:DoNotPassTypesByReference", MessageId = "5#",
Justification = "Best solution here")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "h",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "s",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "l",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "r",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "g",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b",
Justification = "This is here a proper name.")]
public static void HslToRgb(float h, float s, float l,
ref float r, ref float g, ref float b)
{
// given h,s,l,[240 and r,g,b [0-255]
// convert h [0-360], s,l,r,g,b [0-1]
h = (h / 240) * 360;
s /= 240;
l /= 240;
// Begin Foley
float m2;
// Calc m2
if (l <= 0.5f)
{
// m2=(l*(l+s)); seems to be typo in Foley??, replace l for 1
m2 = (l * (1 + s));
}
else
{
m2 = (l + s - (l * s));
} // if
// calc m1
float m1 = (2.0f * l) - m2;
// calc r,g,b in [0-1]
if (Math.Abs(s - 0.0f) < 0.01)
{
// Achromatic: There is no hue
// leave out the UNDEFINED part, h will always have value
r = g = b = l;
}
else
{
// Chromatic: There is a hue
r = GetRgbValue(m1, m2, h + 120.0f);
g = GetRgbValue(m1, m2, h);
b = GetRgbValue(m1, m2, h - 120.0f);
} // if
// End Foley
// convert to 0-255 ranges
r *= 255;
g *= 255;
b *= 255;
} // HslToRgb()
/// <summary>
/// Helper function for the HSLToRGB function above
/// </summary>
/// <param name="n1">The n1.</param>
/// <param name="n2">The n2.</param>
/// <param name="hue">The hue.</param>
/// <returns>An RGB value.</returns>
private static float GetRgbValue(float n1, float n2, float hue)
{
if (hue > 360.0f)
{
hue -= 360.0f;
}
else if (hue < 0.0f)
{
hue += 360.0f;
} // if
if (hue < 60.0)
{
return n1 + (((n2 - n1) * hue) / 60.0f);
}
if (hue < 180.0f)
{
return n2;
}
if (hue < 240.0f)
{
return n1 + ((n2 - n1) * (240.0f - hue) / 60.0f);
}
return n1;
} // GetRgbValue()
/// <summary>
/// Conversion RGB to HSL.
/// </summary>
/// <param name="r">The r.</param>
/// <param name="g">The g.</param>
/// <param name="b">The b.</param>
/// <param name="h">The h.</param>
/// <param name="s">The s.</param>
/// <param name="l">The l.</param>
[SuppressMessage("Microsoft.Design",
"CA1045:DoNotPassTypesByReference", MessageId = "3#",
Justification = "Best solution here")]
[SuppressMessage("Microsoft.Design",
"CA1045:DoNotPassTypesByReference", MessageId = "4#",
Justification = "Best solution here")]
[SuppressMessage("Microsoft.Design",
"CA1045:DoNotPassTypesByReference", MessageId = "5#",
Justification = "Best solution here")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "h",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "s",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "l",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "r",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "g",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b",
Justification = "This is here a proper name.")]
public static void RgbToHsl(int r, int g, int b,
ref float h, ref float s, ref float l)
{
// Computer Graphics - Foley p.595
float fr = (float)r / 255;
float fg = (float)g / 255;
float fb = (float)b / 255;
float max = Math.Max(fr, Math.Max(fg, fb));
float min = Math.Min(fr, Math.Min(fg, fb));
// calc the lightness
l = (max + min) / 2;
if (Math.Abs(max - min) < 0.001)
{
// should be undefined but this works for what we need
s = 0;
h = 240.0f;
}
else
{
var delta = max - min;
// calc the Saturation
if (l < 0.5)
{
s = delta / (max + min);
}
else
{
s = delta / (2.0f - (max + min));
} // if
// calc the hue
if (Math.Abs(fr - max) < 0.001)
{
h = (fg - fb) / delta;
}
else if (Math.Abs(fg - max) < 0.001)
{
h = 2.0f + ((fb - fr) / delta);
}
else if (Math.Abs(fb - max) < 0.001)
{
h = 4.0f + ((fr - fg) / delta);
} // if
// convert hue to degrees
h *= 60.0f;
if (h < 0.0f)
{
h += 360.0f;
} // if
} // if
// end foley
// convert to 0-255 ranges
// h [0-360], h,l [0-1]
l *= 240;
s *= 240;
h = (h / 360) * 240;
} // RgbToHsl()
#endregion // COMVERSION FUNCTIONS
//// ---------------------------------------------------------------------
#region VISUAL STUDIO .NET COLORS CALCULATION HELPERS
/// <summary>
/// Gets a Visual Studio .Net like menu item background color.
/// Also used as toolbar background color.
/// </summary>
[SuppressMessage("Microsoft.Naming",
"CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vs",
Justification = "Ok here.")]
public static Color VsNetBackgroundColor
{
get
{
return CalculateColor(SystemColors.Window, SystemColors.Control, 220);
}
} // VSNetBackgroundColor
/// <summary>
/// Gets a Visual Studio .Net like menu item selection color.
/// Also used as toolbar background color.
/// </summary>
[SuppressMessage("Microsoft.Naming",
"CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vs",
Justification = "Ok here.")]
public static Color VsNetSelectionColor
{
get
{
return CalculateColor(SystemColors.Highlight, SystemColors.Window, 180/*70*/);
}
} // VSNetSelectionColor
/// <summary>
/// Gets a Visual Studio .Net like menu item stripe color.
/// </summary>
[SuppressMessage("Microsoft.Naming",
"CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vs",
Justification = "Ok here.")]
public static Color VsNetStripeColor
{
get
{
return CalculateColor(SystemColors.Control,
VsNetBackgroundColor, 195);
}
} // VSNetStripeColor
/// <summary>
/// Gets a Visual Studio .Net like pressed menu item color.
/// </summary>
[SuppressMessage("Microsoft.Naming",
"CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vs",
Justification = "Ok here.")]
public static Color VsNetPressedColor
{
get
{
return CalculateColor(SystemColors.Highlight,
VsNetSelectionColor, 70);
}
} // VSNetPressedColor
/// <summary>
/// Gets a Visual Studio .Net like menu item toggle color.
/// </summary>
[SuppressMessage("Microsoft.Naming",
"CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vs",
Justification = "Ok here.")]
public static Color VsNetToggleColor
{
get
{
return CalculateColor(SystemColors.Highlight,
SystemColors.Window, 30);
}
} // VSNetToggleColor
/// <summary>
/// Gets a Visual Studio .Net like selection border color.
/// </summary>
[SuppressMessage("Microsoft.Naming",
"CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vs",
Justification = "Ok here.")]
public static Color VsNetSelectionBorderColor
{
get
{
return SystemColors.Highlight;
}
} // VSNetSelectionBorderColor
/// <summary>
/// Returns the color the is an alpha blending of the given front color
/// over the given background color with the given alpha blending level.
/// </summary>
/// <param name="front">The front.</param>
/// <param name="back">The back.</param>
/// <param name="alpha">The alpha.</param>
/// <returns>Alpha blend color.</returns>
public static Color CalculateColor(Color front, Color back, int alpha)
{
if ((alpha < 0) || (alpha > 255))
{
throw new ArgumentOutOfRangeException("alpha",
"range for alpha: 0 <= alpha <= 255");
} // if
// Use alpha blending to brigthen the colors but don't use it
// directly. Instead derive an opaque color that we can use.
// -- if we use a color with alpha blending directly we won't be
// able to paint over whatever color was in the background and there
// would be shadows of that color showing through
Color frontColor = Color.FromArgb(255, front);
Color backColor = Color.FromArgb(255, back);
float frontRed = frontColor.R;
float frontGreen = frontColor.G;
float frontBlue = frontColor.B;
float backRed = backColor.R;
float backGreen = backColor.G;
float backBlue = backColor.B;
float red = (frontRed * alpha / 255) + (backRed
* ((float)(255 - alpha) / 255));
var newRed = (byte)red;
float green = (frontGreen * alpha / 255) + (backGreen
* ((float)(255 - alpha) / 255));
var newGreen = (byte)green;
float blue = (frontBlue * alpha / 255) + (backBlue
* ((float)(255 - alpha) / 255));
var newBlue = (byte)blue;
return Color.FromArgb(255, newRed, newGreen, newBlue);
} // CalculateColor()
#endregion // VISUAL STUDIO .NET COLORS CALCULATION HELPERS
//// ---------------------------------------------------------------------
#region GENERAL FUNCTIONS
/// <summary>
/// Verifies whether the given color is a .Net 'known' color.
/// </summary>
/// <param name="color">The color.</param>
/// <param name="knownColor">Color of the known.</param>
/// <param name="useTransparent">if set to <c>true</c> [use transparent].</param>
/// <returns>
/// <c>true</c> if [is known color] [the specified color]; otherwise, <c>false</c>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference",
MessageId = "1#", Justification = "Ok here.")]
public static bool IsKnownColor(Color color, ref Color knownColor,
bool useTransparent)
{
// Using the Color structure "FromKnowColor" does not work if
// we did not create the color as a known color to begin with
// we need to compare the rgbs of both color
bool badColor = false;
for (KnownColor enumValue = 0; enumValue <= KnownColor.YellowGreen;
enumValue++)
{
Color currentColor = Color.FromKnownColor(enumValue);
string colorName = currentColor.Name;
if (!useTransparent)
{
badColor = (colorName == "Transparent");
} // if
if (color.A == currentColor.A && color.R == currentColor.R
&& color.G == currentColor.G
&& color.B == currentColor.B && !currentColor.IsSystemColor
&& !badColor)
{
knownColor = currentColor;
return true;
} // if
} // for
// unknown color
return false;
} // IsKnownColor()
/// <summary>
/// Verifies whether the given color is a system color.
/// </summary>
/// <param name="color">The color.</param>
/// <param name="knownColor">Color of the known.</param>
/// <returns>
/// <c>true</c> if [is system color] [the specified color];
/// otherwise, <c>false</c>.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference",
MessageId = "1#", Justification = "Ok here.")]
public static bool IsSystemColor(Color color, ref Color knownColor)
{
// Using the Color structrure "FromKnowColor" does not work if
// we did not create the color as a known color to begin with
// we need to compare the rgbs of both color
for (KnownColor enumValue = 0; enumValue <= KnownColor.YellowGreen;
enumValue++)
{
Color currentColor = Color.FromKnownColor(enumValue);
if (color.R == currentColor.R && color.G == currentColor.G
&& color.B == currentColor.B && currentColor.IsSystemColor)
{
knownColor = currentColor;
return true;
} // if
} // for
return false;
} // IsSystemColor()
/// <summary>
/// Return a 24-bit color value of the given color.
/// </summary>
/// <param name="color">The color.</param>
/// <returns>Color value.</returns>
public static uint GetColorRef(Color color)
{
return Rgb(color.R, color.G, color.B);
} // GetColorRef()
#endregion // GENERAL FUNCTIONS
//// ------------------------------------------------------------------
#region WINDOWS RGB RELATED MACROS
/// <summary>
/// Returns the red components of the given 24-bit RGB color value.
/// </summary>
/// <param name="color">The color.</param>
/// <returns>The red value.</returns>
public static byte GetRValue(uint color)
{
return (byte)color;
} // GetRValue()
/// <summary>
/// Returns the green components of the given 24-bit RGB color value.
/// </summary>
/// <param name="color">The color.</param>
/// <returns>The green value.</returns>
public static byte GetGValue(uint color)
{
return ((byte)(((short)(color)) >> 8));
} // GetGValue()
/// <summary>
/// Returns the blue components of the given 24-bit RGB color value.
/// </summary>
/// <param name="color">The color.</param>
/// <returns>The blue value.</returns>
public static byte GetBValue(uint color)
{
return ((byte)((color) >> 16));
} // GetBValue()
/// <summary>
/// Returns a 24 bit RGB value of the specified R, G, B colors.
/// </summary>
/// <param name="r">The r.</param>
/// <param name="g">The g.</param>
/// <param name="b">The b.</param>
/// <returns>A value.</returns>
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "r",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "g",
Justification = "This is here a proper name.")]
[SuppressMessage("Microsoft.Naming",
"CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b",
Justification = "This is here a proper name.")]
public static uint Rgb(int r, int g, int b)
{
return ((uint)(((byte)(r) | ((byte)(g) << 8)) | ((byte)(b) << 16)));
} // Rgb()
#endregion // WINDOWS RGB RELATED MACROS
} // ColorUtil
} // Tethys.Forms
// ==========================
// Tethys: end of ColorUtil.cs
// ==========================
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ContentPatcher.Framework.Lexing;
using ContentPatcher.Framework.Lexing.LexTokens;
using ContentPatcher.Framework.Tokens;
using Pathoschild.Stardew.Common.Utilities;
namespace ContentPatcher.Framework.Conditions
{
/// <summary>A string value optionally containing tokens.</summary>
internal class TokenString : IManagedTokenString
{
/*********
** Fields
*********/
/// <summary>Handles parsing raw strings into tokens.</summary>
private static readonly Lexer Lexer = Lexer.Instance;
/// <summary>The token names used in the string.</summary>
private readonly InvariantHashSet TokensUsed = new();
/// <summary>Diagnostic info about the contextual instance.</summary>
private readonly ContextualState State = new();
/// <summary>Metadata for each lexical token in the string.</summary>
private readonly TokenStringPart[] Parts;
/*********
** Accessors
*********/
/// <inheritdoc />
public string Raw { get; }
/// <inheritdoc />
public IEnumerable<ILexToken> LexTokens => this.Parts.Select(p => p.LexToken);
/// <inheritdoc />
public bool HasAnyTokens { get; }
/// <inheritdoc />
public bool IsMutable { get; }
/// <inheritdoc />
public bool IsSingleTokenOnly { get; }
/// <inheritdoc />
public string Value { get; private set; }
/// <inheritdoc />
public bool IsReady => this.State.IsReady;
/// <inheritdoc />
public string Path { get; }
/*********
** Public methods
*********/
/// <summary>Construct an instance from raw text. This constructor bypasses migrations, so it should not be used to parse any values from a content pack.</summary>
/// <param name="raw">The raw string before token substitution.</param>
/// <param name="context">The available token context.</param>
/// <param name="path">The path to the value from the root content file.</param>
public TokenString(string raw, IContext context, LogPathBuilder path)
: this(lexTokens: TokenString.Lexer.ParseBits(raw, impliedBraces: false).ToArray(), context: context, path: path) { }
/// <summary>Construct an instance.</summary>
/// <param name="inputArgs">The raw token input arguments.</param>
/// <param name="context">The available token context.</param>
/// <param name="path">The path to the value from the root content file.</param>
public TokenString(LexTokenInput inputArgs, IContext context, LogPathBuilder path)
: this(lexTokens: inputArgs?.Parts, context: context, path: path) { }
/// <summary>Construct an instance.</summary>
/// <param name="lexTokens">The lexical tokens parsed from the raw string.</param>
/// <param name="context">The available token context.</param>
/// <param name="path">The path to the value from the root content file.</param>
public TokenString(ILexToken[] lexTokens, IContext context, LogPathBuilder path)
{
// get lexical tokens
this.Parts =
(
from token in (lexTokens ?? Array.Empty<ILexToken>())
let input = token is LexTokenToken lexToken && lexToken.HasInputArgs()
? new TokenString(lexToken.InputArgs.Parts, context, path.With(lexToken.Name))
: null
select new TokenStringPart(token, input)
)
.ToArray();
// set raw value
this.Raw = string.Join("", this.Parts.Select(p => p.LexToken)).Trim();
if (string.IsNullOrWhiteSpace(this.Raw))
{
this.Value = this.Raw;
return;
}
// extract tokens
bool isMutable = false;
bool hasTokens = false;
foreach (LexTokenToken lexToken in this.GetTokenPlaceholders(this.LexTokens, recursive: true))
{
hasTokens = true;
IToken token = context.GetToken(lexToken.Name, enforceContext: false);
if (token != null)
{
this.TokensUsed.Add(token.Name);
isMutable = isMutable || token.IsMutable;
}
else
{
string requiredModId = lexToken.GetProviderModId();
if (!string.IsNullOrWhiteSpace(requiredModId) && !context.IsModInstalled(requiredModId))
this.State.AddUnavailableModTokens(requiredModId);
else
this.State.AddInvalidTokens(lexToken.Name);
isMutable = true; // can't optimize away the token value if it's invalid
}
}
// set metadata
this.IsMutable = isMutable;
this.HasAnyTokens = hasTokens;
this.IsSingleTokenOnly = TokenString.GetIsSingleTokenOnly(this.Parts);
this.Path = path.ToString();
// set initial context
if (this.State.IsReady)
this.UpdateContext(context, forceUpdate: true);
}
/// <inheritdoc />
public bool UpdateContext(IContext context)
{
return this.UpdateContext(context, forceUpdate: false);
}
/// <inheritdoc />
public IEnumerable<string> GetTokensUsed()
{
return this.TokensUsed;
}
/// <inheritdoc />
public IEnumerable<LexTokenToken> GetTokenPlaceholders(bool recursive)
{
return this.GetTokenPlaceholders(this.LexTokens, recursive);
}
/// <inheritdoc />
public bool UsesToken(ConditionType token)
{
return this.TokensUsed.Contains(token.ToString());
}
/// <inheritdoc />
public bool UsesTokens(IEnumerable<ConditionType> tokens)
{
return tokens.Any(this.UsesToken);
}
/// <inheritdoc />
public IContextualState GetDiagnosticState()
{
return this.State.Clone();
}
/// <inheritdoc />
public override string ToString()
{
return this.IsReady
? this.Value
: this.Raw;
}
/*********
** Private methods
*********/
/// <summary>Force a context update.</summary>
/// <param name="context">Provides access to contextual tokens.</param>
/// <param name="forceUpdate">Update even if the state hasn't changed.</param>
/// <returns>Returns whether the context changed.</returns>
private bool UpdateContext(IContext context, bool forceUpdate)
{
if (!forceUpdate && !this.ShouldUpdate())
return false;
// reset
string wasValue = this.Value;
bool wasReady = this.State.IsReady;
this.State.Reset();
// update value
{
StringBuilder str = new StringBuilder();
foreach (TokenStringPart part in this.Parts)
str.Append(this.TryGetTokenText(context, part, this.State, out string text) ? text : part.LexToken.ToString());
this.Value = this.State.IsReady
? str.ToString().Trim()
: null;
}
// sanity check (should never happen)
if (this.Value == null && this.State.IsReady)
throw new InvalidOperationException($"Could not apply tokens to string '{this.Raw}', but no invalid tokens or errors were reported.");
return
this.Value != wasValue
|| this.State.IsReady != wasReady;
}
/// <summary>Get whether the token string should be updated for the current state.</summary>
private bool ShouldUpdate()
{
// skip if immutable
if (!this.IsMutable)
return false;
// skip if we know it's still broken
if (this.State.InvalidTokens.Any() || this.State.UnavailableModTokens.Any())
return false;
// otherwise try to update
return true;
}
/// <summary>Recursively get the token placeholders from the given lexical tokens.</summary>
/// <param name="lexTokens">The lexical tokens to scan.</param>
/// <param name="recursive">Whether to scan recursively.</param>
private IEnumerable<LexTokenToken> GetTokenPlaceholders(IEnumerable<ILexToken> lexTokens, bool recursive)
{
lexTokens = lexTokens?.ToArray();
if (lexTokens?.Any() != true)
yield break;
foreach (LexTokenToken token in lexTokens.OfType<LexTokenToken>())
{
yield return token;
if (recursive && token.HasInputArgs())
{
foreach (LexTokenToken subtoken in this.GetTokenPlaceholders(token.InputArgs.Parts, recursive: true))
yield return subtoken;
}
}
}
/// <summary>Get the text representation of a token's values.</summary>
/// <param name="context">Provides access to contextual tokens.</param>
/// <param name="part">The token string part whose value to fetch.</param>
/// <param name="state">The context state to update with errors, unavailable tokens, etc.</param>
/// <param name="text">The text representation, if available.</param>
/// <returns>Returns true if the token is ready and <paramref name="text"/> was set, else false.</returns>
private bool TryGetTokenText(IContext context, TokenStringPart part, ContextualState state, out string text)
{
switch (part.LexToken)
{
case LexTokenToken lexToken:
{
// get token
IToken token = context.GetToken(lexToken.Name, enforceContext: false);
if (token == null)
{
state.AddInvalidTokens(lexToken.Name);
text = null;
return false;
}
if (!token.IsReady)
{
this.State.AddUnreadyTokens(lexToken.Name);
text = null;
return false;
}
// get token input
if (part.Input != null)
{
part.Input.UpdateContext(context);
if (!part.Input.IsReady)
{
state.MergeFrom(part.Input.GetDiagnosticState());
text = null;
return false;
}
}
// validate input
if (!token.TryValidateInput(part.InputArgs, out string error))
{
state.AddErrors(error);
text = null;
return false;
}
// get text representation
string[] values = token.GetValues(part.InputArgs).ToArray();
text = string.Join(", ", values);
return true;
}
default:
text = part.LexToken.ToString();
return true;
}
}
/// <summary>Get whether a string only contains a single root token, ignoring literal whitespace.</summary>
/// <param name="parts">The lexical string parts.</param>
private static bool GetIsSingleTokenOnly(TokenStringPart[] parts)
{
bool foundToken = false;
foreach (TokenStringPart part in parts)
{
// non-token content
if (part.LexToken is LexTokenLiteral literal)
{
if (!string.IsNullOrWhiteSpace(literal.Text))
return false;
}
// multiple tokens
else if (part.LexToken.Type == LexTokenType.Token)
{
if (foundToken)
return false;
foundToken = true;
}
// non-token content
else
return false;
}
return foundToken;
}
/// <summary>A lexical token component in the token string.</summary>
private class TokenStringPart
{
/*********
** Accessors
*********/
/// <summary>The underlying lex token.</summary>
public ILexToken LexToken { get; }
/// <summary>The input to the lex token, if it's a <see cref="LexTokenType.Token"/>.</summary>
public TokenString Input { get; }
/// <summary>The parsed version of <see cref="Input"/>.</summary>
public IInputArguments InputArgs { get; }
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="lexToken">The underlying lex token.</param>
/// <param name="input">The parsed version of <see cref="Input"/>.</param>
public TokenStringPart(ILexToken lexToken, TokenString input)
{
this.LexToken = lexToken;
this.Input = input;
this.InputArgs = new InputArguments(input);
}
}
}
}
| |
/*
* Author Luke Campbell <[email protected]>
* com.asascience.netcdf4.NcGroup
*/
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace ASA.NetCDF4 {
public enum GroupLocation {
ChildrenGrps,
ParentsGrps,
ChildrenOfChildrenGrps,
AllChildrenGrps,
ParentsAndCurrentGrps,
AllGrps
}
public enum Location {
Current,
Parents,
Children,
ParentsAndCurrent,
ChildrenAndCurrent,
All
}
public class NcGroup {
protected Int32 myId;
protected bool nullObject;
public NcGroup() {
nullObject = true;
}
public NcGroup(int groupId) {
myId = groupId;
}
public NcGroup(NcGroup rhs) {
nullObject = rhs.nullObject;
myId = rhs.myId;
}
~NcGroup() {
}
public string GetName(bool fullName=false) {
if(IsNull()) {
throw new exceptions.NcNullGrp("Attempt to invoke NcGroup.GetName on a Null group");
}
string groupName;
if(fullName) {
Int32 lenp = new Int32();
NcCheck.Check(NetCDF.nc_inq_grpname_len(myId, ref lenp));
StringBuilder name = new StringBuilder();
NcCheck.Check(NetCDF.nc_inq_grpname_full(myId, ref lenp, name));
groupName = name.ToString();
}
else {
StringBuilder name = new StringBuilder ();
NcCheck.Check(NetCDF.nc_inq_grpname(myId, name));
groupName = name.ToString();
}
return groupName;
}
public NcGroup GetParentGroup() {
if(IsNull()) throw new exceptions.NcNullGrp("Attempt to invoke NcGroup.GetParentGroup on a Null group");
try {
int parentId=0;
NcCheck.Check(NetCDF.nc_inq_grp_parent(myId, ref parentId));
NcGroup ncGroupParent = new NcGroup(parentId);
return ncGroupParent;
} catch (exceptions.NcEnoGrp) {
return new NcGroup();
}
}
public Int32 GetId() {
return myId;
}
protected void CheckNull() {
if(IsNull()) {
throw new exceptions.NcNullGrp("Attempt to invoke NcGroup method on a Null group");
}
}
public void CheckDefine() {
try {
NcCheck.Check(NetCDF.nc_redef(myId));
} catch (exceptions.NcInDefineMode) {
}
}
public void CheckData() {
try {
NcCheck.Check(NetCDF.nc_enddef(myId));
} catch (exceptions.NcNotInDefineMode) {
}
}
public int GetGroupCount(GroupLocation location=GroupLocation.ChildrenGrps) {
CheckNull();
int ngroups=0;
// record this group
if(location == GroupLocation.ParentsAndCurrentGrps || location == GroupLocation.AllGrps) {
ngroups++;
}
// search in current group
if(location == GroupLocation.ChildrenGrps || location == GroupLocation.AllChildrenGrps
|| location == GroupLocation.AllGrps) {
int numgrps=0;
int[] ncids=null;
NcCheck.Check(NetCDF.nc_inq_grps(myId, ref numgrps, ncids));
ngroups += numgrps;
}
// search in parent groups
if(location == GroupLocation.ParentsGrps || location == GroupLocation.ParentsAndCurrentGrps
|| location == GroupLocation.AllGrps) {
Dictionary<string,NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
ngroups += groups.Count;
}
// get the number of all children that are childreof children
if(location == GroupLocation.ChildrenOfChildrenGrps || location == GroupLocation.AllChildrenGrps
|| location == GroupLocation.AllGrps) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ChildrenOfChildrenGrps);
ngroups += groups.Count;
}
return ngroups;
}
public Dictionary<string, NcGroup> GetGroups(GroupLocation location=GroupLocation.ChildrenGrps) {
CheckNull();
Dictionary<string, NcGroup> ncGroups = new Dictionary<string, NcGroup>();
// Record this group
if(location == GroupLocation.ParentsAndCurrentGrps || location == GroupLocation.AllGrps) {
ncGroups.Add(GetName(), this);
}
// the child groups of the current group
if(location == GroupLocation.ChildrenGrps || location == GroupLocation.AllChildrenGrps
|| location == GroupLocation.AllGrps ) {
int groupCount = GetGroupCount();
int[] ncids = new int[groupCount];
int numgrps=0;
NcCheck.Check(NetCDF.nc_inq_grps(myId, ref numgrps, ncids));
for(int i=0; i<groupCount; i++) {
NcGroup tmpGroup = new NcGroup(ncids[i]);
ncGroups.Add(tmpGroup.GetName(), tmpGroup);
}
}
// search in parent groups.
if(location == GroupLocation.ParentsGrps || location == GroupLocation.ParentsAndCurrentGrps
|| location == GroupLocation.AllGrps) {
NcGroup tmpGroup = GetParentGroup();
while(tmpGroup != null && !tmpGroup.IsNull()) {
ncGroups.Add(tmpGroup.GetName(), tmpGroup);
tmpGroup = tmpGroup.GetParentGroup();
}
}
// search in child groups of the children
if(location == GroupLocation.ChildrenOfChildrenGrps || location == GroupLocation.AllChildrenGrps
|| location == GroupLocation.AllGrps) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ChildrenGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
foreach(KeyValuePair<string, NcGroup> kchild in k.Value.GetGroups(GroupLocation.AllChildrenGrps)) {
ncGroups.Add(kchild.Key, kchild.Value);
}
}
}
return ncGroups;
}
public HashSet<NcGroup> GetGroups(string name, GroupLocation location=GroupLocation.ChildrenGrps) {
CheckNull();
HashSet<NcGroup> retval = new HashSet<NcGroup>();
foreach(KeyValuePair<string, NcGroup> k in GetGroups(location)) {
if(name.Equals(k.Key))
retval.Add(k.Value);
}
return retval;
}
public NcGroup GetGroup(string name, GroupLocation location=GroupLocation.ChildrenGrps) {
CheckNull();
Dictionary<string, NcGroup> groups = GetGroups(location);
foreach(KeyValuePair<string, NcGroup> k in groups) {
if(k.Key.Equals(name))
return k.Value;
}
return new NcGroup(); // Null
}
public NcGroup AddGroup(string name) {
CheckNull();
CheckDefine();
int new_ncid=0;
NcCheck.Check(NetCDF.nc_def_grp(myId, name, ref new_ncid));
return new NcGroup(new_ncid);
}
public bool IsNull() {
return nullObject;
}
public bool IsRootGroup() {
if(GetName().Equals("/")) {
return true;
}
return false;
}
public int GetVarCount(Location location=Location.Current) {
int nvars=0;
if(LocationIsCurrentGroup(location)) {
NcCheck.Check(NetCDF.nc_inq_nvars(myId, ref nvars));
}
if(LocationIsParentGroup(location)) {
foreach(KeyValuePair<string,NcGroup> g in GetGroups(GroupLocation.ParentsGrps)) {
nvars += g.Value.GetVarCount();
}
}
if(LocationIsChildGroup(location)) {
foreach(KeyValuePair<string, NcGroup> g in GetGroups(GroupLocation.AllChildrenGrps)) {
nvars += g.Value.GetVarCount();
}
}
return nvars;
}
public Dictionary<string, NcVar> GetVars(Location location=Location.Current) {
Dictionary<string, NcVar> vars = new Dictionary<string, NcVar>();
if(LocationIsCurrentGroup(location)) {
int varCount = GetVarCount();
Int32[] varIds = new Int32[varCount];
NcCheck.Check(NetCDF.nc_inq_varids(myId, ref varCount, varIds));
foreach(Int32 varId in varIds) {
NcVar tmpVar = new NcVar(this, varId);
vars.Add(tmpVar.GetName(), tmpVar);
}
}
if(LocationIsParentGroup(location)) {
foreach(KeyValuePair<string, NcGroup> g in GetGroups(GroupLocation.ParentsGrps)) {
g.Value.GetVars().ToList().ForEach(x => vars[x.Key] = x.Value);
}
}
if(LocationIsChildGroup(location)) {
foreach(KeyValuePair<string, NcGroup> g in GetGroups(GroupLocation.AllChildrenGrps)) {
g.Value.GetVars().ToList().ForEach(x => vars[x.Key] = x.Value);
}
}
return vars;
}
public HashSet<NcVar> GetVars(string name, Location location=Location.Current) {
HashSet<NcVar> ncVars = new HashSet<NcVar>();
foreach(KeyValuePair<string, NcVar> k in GetVars(location)) {
if(k.Key == name)
ncVars.Add(k.Value);
}
return ncVars;
}
public NcVar GetVar(string name, Location location=Location.Current) {
foreach(KeyValuePair<string, NcVar> k in GetVars(location)) {
if(k.Key == name)
return k.Value;
}
return new NcVar(); // return null
}
// Add a scalar variable
public NcVar AddVar(string name, string typeName)
{
CheckNull();
CheckDefine();
NcType tmpType = GetType(typeName, Location.ParentsAndCurrent);
if(tmpType.IsNull())
throw new exceptions.NcNullType("Attempt to invoke NcGroup.AddVar failed: typeName must be defined in either the current group or a parent group");
Int32 varId = 0;
Int32[] dimIds = null;
NcCheck.Check(NetCDF.nc_def_var(myId, name, tmpType.GetId(), 0, dimIds, ref varId));
return new NcVar(this, varId);
}
// Add a scalar variable
public NcVar AddVar(string name, NcType type)
{
CheckNull();
CheckDefine();
if(type.IsNull())
throw new exceptions.NcNullType("Attempt to invoke NcGroup.AddVar failed: typeName must be defined in either the current group or a parent group");
Int32 varId = 0;
Int32[] dimIds = null;
NcCheck.Check(NetCDF.nc_def_var(myId, name, type.GetId(), 0, dimIds, ref varId));
return new NcVar(this, varId);
}
// Add a new netCDF variable
public NcVar AddVar(string name, string typeName, string dimName) {
CheckNull();
CheckDefine();
NcType tmpType = GetType(typeName, Location.ParentsAndCurrent);
if(tmpType.IsNull())
throw new exceptions.NcNullType("Attempt to invoke NcGroup.AddVar failed: typeName must be defined in either the current group or a parent group");
NcDim tmpDim = GetDim(dimName, Location.ParentsAndCurrent);
if(tmpDim.IsNull())
throw new exceptions.NcNullDim("Attempt to invoke NcGroup.AddVar failed: dimName must be defined in either the current group or a parent group");
Int32 varId=0;
Int32[] dimId = {tmpDim.GetId()};
NcCheck.Check(NetCDF.nc_def_var(myId, name, tmpType.GetId(), 1, dimId, ref varId));
return new NcVar(this, varId);
}
public NcVar AddVar(string name, NcType ncType, NcDim ncDim) {
CheckNull();
CheckDefine();
if(ncType.IsNull())
throw new exceptions.NcNullType("Attempt to invoke NcGroup.AddVar failed: NcType must be defined in either the current group or a parent group");
NcType tmpType = GetType(ncType.GetName(), Location.ParentsAndCurrent);
if(tmpType.IsNull())
throw new exceptions.NcNullType("Attempt to invoke NcGroup.AddVar failed: NcType must be defined in either the current group or a parent group");
if(ncDim.IsNull())
throw new exceptions.NcNullDim("Attempt to invoke NcGroup.AddVar failed: NcDim must be defined in either the current group or a parent group");
NcDim tmpDim = GetDim(ncDim.GetName(), Location.ParentsAndCurrent);
if(tmpDim.IsNull())
throw new exceptions.NcNullDim("Attempt to invoke NcGroup.AddVar failed: NcDim must be defined in either the current group or a parent group");
Int32 varId=0;
Int32[] dimId = {tmpDim.GetId()};
NcCheck.Check(NetCDF.nc_def_var(myId, name, tmpType.GetId(), 1, dimId, ref varId));
return new NcVar(this, varId);
}
public NcVar AddVar(string name, string typeName, List<string> dimNames) {
CheckNull();
CheckDefine();
NcType tmpType = GetType(typeName, Location.ParentsAndCurrent);
if(tmpType.IsNull())
throw new exceptions.NcNullType("Attempt to invoke NcGroup.AddVar failed: NcType must be defined in either the current group or a parent group");
Int32[] dimIds = new Int32[dimNames.Count];
for(int i=0;i<dimNames.Count;i++) {
NcDim tmpDim = GetDim(dimNames[i], Location.ParentsAndCurrent);
if(tmpDim.IsNull())
throw new exceptions.NcNullDim("Attempt to invoke NcGroup.AddVar failed: NcDim must be defined in either the current group or a parent group");
dimIds[i] = tmpDim.GetId();
}
Int32 varId=0;
NcCheck.Check(NetCDF.nc_def_var(myId, name, tmpType.GetId(), dimIds.Length, dimIds, ref varId));
return new NcVar(this, varId);
}
public NcVar AddVar(string name, NcType ncType, List<NcDim> ncDimVector) {
CheckNull();
CheckDefine();
NcType tmpType=null;
Int32 varId=0;
Int32[] dimIds = new Int32[ncDimVector.Count];
if(ncType.IsNull())
throw new exceptions.NcNullType("Attempt to invoke NcGroup.AddVar with a Null NcType object");
tmpType = GetType(ncType.GetName(), Location.ParentsAndCurrent);
if(tmpType.IsNull())
throw new exceptions.NcNullType("Attempt to invoke NcGroup.AddVar failed: NcType must be defined in either the current group or a parent group");
for(int i=0;i<ncDimVector.Count;i++) {
if(ncDimVector[i].IsNull())
throw new exceptions.NcNullDim("Attempt to invoke NcGroup.AddVar failed: NcType must be defined in either the current group or a parent group");
NcDim tmpDim = GetDim(ncDimVector[i].GetName(), Location.ParentsAndCurrent);
if(tmpDim.IsNull())
throw new exceptions.NcNullDim("Attempt to invoke NcGroup::addVar failed: NcDim must be defined in either the current group or a parent group");
dimIds[i] = ncDimVector[i].GetId();
}
NcCheck.Check(NetCDF.nc_def_var(myId, name, tmpType.GetId(), ncDimVector.Count, dimIds, ref varId));
return new NcVar(this, varId);
}
public int GetAttCount(Location location=Location.Current) {
CheckNull();
Int32 ngatts = 0;
if(LocationIsCurrentGroup(location)){
NcCheck.Check(NetCDF.nc_inq_natts(myId, ref ngatts));
}
if(LocationIsParentGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
foreach(KeyValuePair<string, NcGroup> g in groups) {
ngatts += g.Value.GetAttCount();
}
}
if(LocationIsChildGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.AllChildrenGrps);
foreach(KeyValuePair<string, NcGroup> g in groups) {
ngatts += g.Value.GetAttCount();
}
}
return ngatts;
}
public Dictionary<string, NcGroupAtt> GetAtts(Location location=Location.Current) {
CheckNull();
Dictionary<string, NcGroupAtt> ncAtts = new Dictionary<string, NcGroupAtt>();
if(LocationIsCurrentGroup(location)) {
int attCount = GetAttCount();
for(int i=0;i<attCount;i++) {
NcGroupAtt tmpGroupAtt = new NcGroupAtt(this, i);
ncAtts.Add(tmpGroupAtt.GetName(), tmpGroupAtt);
}
}
if(LocationIsParentGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
foreach(KeyValuePair<string, NcGroup> g in groups) {
g.Value.GetAtts().ToList().ForEach(x => ncAtts[x.Key] = x.Value);
}
}
if(LocationIsChildGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.AllChildrenGrps);
foreach(KeyValuePair<string, NcGroup> g in groups) {
g.Value.GetAtts().ToList().ForEach(x => ncAtts[x.Key] = x.Value);
}
}
return ncAtts;
}
public HashSet<NcGroupAtt> GetAtts(string name, Location location=Location.Current) {
CheckNull();
HashSet<NcGroupAtt> attSet = new HashSet<NcGroupAtt>();
Dictionary<string, NcGroupAtt> ncAtts = GetAtts(location);
foreach(KeyValuePair<string, NcGroupAtt> k in ncAtts) {
if(k.Key == name)
attSet.Add(k.Value);
}
return attSet;
}
public NcGroupAtt GetAtt(string name, Location location=Location.Current) {
CheckNull();
Dictionary<string, NcGroupAtt> ncAtts = GetAtts(location);
foreach(KeyValuePair<string, NcGroupAtt> k in ncAtts) {
if(k.Key == name) {
return k.Value;
}
}
return new NcGroupAtt(); // null
}
public NcGroupAtt PutAtt(NcAtt attr) {
CheckNull();
CheckDefine();
NcType t = attr.GetNcType();
if(NcByte.Instance.Equals(t)) {
sbyte[] buffer = new sbyte[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_schar(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcUbyte.Instance.Equals(t)) {
byte[] buffer = new byte[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_uchar(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcShort.Instance.Equals(t)) {
Int16[] buffer = new Int16[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_short(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcUshort.Instance.Equals(t)) {
UInt16[] buffer = new UInt16[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_ushort(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcInt.Instance.Equals(t)) {
Int32[] buffer = new Int32[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_int(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcUint.Instance.Equals(t)) {
UInt32[] buffer = new UInt32[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_uint(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcInt64.Instance.Equals(t)) {
Int64[] buffer = new Int64[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_longlong(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcUint64.Instance.Equals(t)) {
UInt64[] buffer = new UInt64[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_ulonglong(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcFloat.Instance.Equals(t)) {
float[] buffer = new float[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_float(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcDouble.Instance.Equals(t)) {
double[] buffer = new double[attr.GetAttLength()];
attr.GetValues(buffer);
NcCheck.Check(NetCDF.nc_put_att_double(myId, NcAtt.NC_GLOBAL, attr.GetName(), t.GetId(), attr.GetAttLength(), buffer));
return GetAtt(attr.GetName());
}
if(NcChar.Instance.Equals(t)) {
string sBuffer = attr.GetValues();
NcCheck.Check(NetCDF.nc_put_att_text(myId, NcAtt.NC_GLOBAL,attr.GetName(), sBuffer.Length, sBuffer));
return GetAtt(attr.GetName());
}
return new NcGroupAtt();
}
public NcGroupAtt PutAtt(string name, string dataValues) {
CheckNull();
CheckDefine();
NcCheck.Check(NetCDF.nc_put_att_text(myId, NcAtt.NC_GLOBAL, name, dataValues.Length, dataValues));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, sbyte datumValue) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_schar(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new sbyte[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, byte datumValue) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_uchar(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new byte[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, Int16 datumValue) {
CheckNull();
CheckDefine();
//TODO: Support for VLEN | OPAQUE | ENUM | COMPOUND
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_short(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new Int16[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, UInt16 datumValue) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_ushort(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new UInt16[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, Int32 datumValue) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_int(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new Int32[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, UInt32 datumValue) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_uint(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new UInt32[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, Int64 datumValue) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_longlong(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new Int64[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, UInt64 datumValue) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_ulonglong(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new UInt64[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, float datumValue) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_float(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new float[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, double datumValue) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_double(myId, NcAtt.NC_GLOBAL, name, type.GetId(), 1, new double[] { datumValue }));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, sbyte[] dataValues) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_schar(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, byte[] dataValues) {
CheckNull();
CheckDefine();
if(!type.IsFixedType()) {
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
}
NcCheck.Check(NetCDF.nc_put_att_uchar(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues ));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, Int16[] dataValues) {
CheckNull();
CheckDefine();
//TODO: Support for VLEN | OPAQUE | ENUM | COMPOUND
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_short(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues ));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, UInt16[] dataValues) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_ushort(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues ));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, Int32[] dataValues) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_int(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues ));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, UInt32[] dataValues) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_uint(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues ));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, Int64[] dataValues) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_longlong(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues ));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, UInt64[] dataValues) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_ulonglong(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues ));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, float[] dataValues) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_float(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues ));
return GetAtt(name);
}
public NcGroupAtt PutAtt(string name, NcType type, double[] dataValues) {
CheckNull();
CheckDefine();
if(!type.IsFixedType())
throw new NotImplementedException("PutAtt() not implemented for non-fixed types");
NcCheck.Check(NetCDF.nc_put_att_double(myId, NcAtt.NC_GLOBAL, name, type.GetId(), dataValues.Length, dataValues ));
return GetAtt(name);
}
public int GetDimCount(Location location=Location.Current) {
CheckNull();
int ndims =0;
// Search current group
if(LocationIsCurrentGroup(location)) {
int ndimsp=0;
NcCheck.Check(NetCDF.nc_inq_ndims(myId, ref ndimsp));
ndims += ndimsp;
}
// Search in parent group
if(LocationIsParentGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
ndims += k.Value.GetDimCount();
}
}
if(LocationIsChildGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.AllChildrenGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
ndims += k.Value.GetDimCount();
}
}
return ndims;
}
private bool LocationIsCurrentGroup(Location location) {
return (location == Location.Current || location == Location.ParentsAndCurrent
|| location == Location.ChildrenAndCurrent
|| location == Location.All);
}
private bool LocationIsParentGroup(Location location) {
return (location == Location.Parents || location == Location.ParentsAndCurrent
|| location == Location.All);
}
private bool LocationIsChildGroup(Location location) {
return (location == Location.Children || location == Location.ChildrenAndCurrent
|| location == Location.All);
}
// Get the dictionary (map) of NcDim objects
public Dictionary<string, NcDim> GetDims(Location location=Location.Current) {
CheckNull();
Dictionary<string, NcDim> ncDims = new Dictionary<string, NcDim>();
// search current group
if(LocationIsCurrentGroup(location)) {
Int32 dimCount = GetDimCount();
Int32[] dimIds = new Int32[dimCount];
NcCheck.Check(NetCDF.nc_inq_dimids(myId, ref dimCount, dimIds, 0));
for(int i=0;i<dimCount;i++) {
NcDim tmpDim = new NcDim(this, dimIds[i]);
ncDims.Add(tmpDim.GetName(), tmpDim);
}
}
if(LocationIsParentGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
k.Value.GetDims().ToList().ForEach(x => ncDims[x.Key] = x.Value);
}
}
if(LocationIsChildGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.AllChildrenGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
k.Value.GetDims().ToList().ForEach(x => ncDims[x.Key] = x.Value);
}
}
return ncDims;
}
// Get all NcDim objects with a given name
public HashSet<NcDim> GetDims(string name, Location location=Location.Current) {
CheckNull();
HashSet<NcDim> dimSet = new HashSet<NcDim>();
Dictionary<string, NcDim> ncDims = GetDims(location);
foreach(KeyValuePair<string, NcDim> k in ncDims) {
if(k.Key == name)
dimSet.Add(k.Value);
}
return dimSet;
}
public NcDim GetDim(string name, Location location=Location.Current) {
CheckNull();
Dictionary<string, NcDim> ncDims = GetDims(location);
foreach(KeyValuePair<string, NcDim> k in ncDims) {
if(k.Key == name)
return k.Value;
}
return new NcDim(); // null dim
}
public NcDim AddDim(NcDim dim) {
CheckNull();
CheckDefine();
Int32 dimId = 0;
NcCheck.Check(NetCDF.nc_def_dim(myId, dim.GetName(), dim.IsUnlimited() ? NetCDF.NC_UNLIMITED : dim.GetSize(), ref dimId));
return new NcDim(this, dimId);
}
// Adds a dimension of limited size
public NcDim AddDim(string name, Int32 dimSize) {
CheckNull();
CheckDefine();
Int32 dimId=0;
NcCheck.Check(NetCDF.nc_def_dim(myId, name, dimSize, ref dimId));
return new NcDim(this, dimId);
}
// Adds a dimension of unlimited size
public NcDim AddDim(string name) {
CheckNull();
CheckDefine();
Int32 dimId = 0;
NcCheck.Check(NetCDF.nc_def_dim(myId, name, NetCDF.NC_UNLIMITED, ref dimId));
return new NcDim(this, dimId);
}
public int GetTypeCount(Location location=Location.Current) {
CheckNull();
Int32 ntypes=0;
// search in current group
if(location == Location.Current || location == Location.ParentsAndCurrent
|| location == Location.ChildrenAndCurrent
|| location == Location.All) {
Int32 ntypesp=0;
Int32[] typeidsp = null;
NcCheck.Check(NetCDF.nc_inq_typeids(myId, ref ntypesp, typeidsp));
ntypes += ntypesp;
}
// search in parent groups.
if(location == Location.Parents || location == Location.ParentsAndCurrent
|| location == Location.All) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
ntypes += k.Value.GetTypeCount();
}
}
// search in child groups
if(location == Location.Children || location == Location.ChildrenAndCurrent
|| location == Location.All) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.AllChildrenGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
ntypes += k.Value.GetTypeCount();
}
}
return ntypes;
}
public int GetTypeCount(NcTypeEnum enumType, Location location=Location.Current) {
CheckNull();
Int32 ntypes=0;
// search in current group
if(location == Location.Current || location == Location.ParentsAndCurrent
|| location == Location.ChildrenAndCurrent
|| location == Location.All) {
Int32 ntypesp=0;
Int32[] typeidsp = null;
NcCheck.Check(NetCDF.nc_inq_typeids(myId, ref ntypesp, typeidsp));
typeidsp = new Int32[ntypesp];
NcCheck.Check(NetCDF.nc_inq_typeids(myId, ref ntypesp, typeidsp));
foreach(Int32 i in typeidsp) {
NcType typeTmp = new NcType(this,i);
if(typeTmp.GetTypeClass() == enumType)
ntypes++;
}
}
// search in parent groups
if(location == Location.Parents || location == Location.ParentsAndCurrent
|| location == Location.All) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
ntypes += k.Value.GetTypeCount(enumType);
}
}
// search in children groups
if(location == Location.Children || location == Location.ChildrenAndCurrent
|| location == Location.All) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.AllChildrenGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
ntypes += k.Value.GetTypeCount(enumType);
}
}
return ntypes;
}
public Dictionary<string, NcType> GetTypes(Location location=Location.Current) {
CheckNull();
Dictionary<string, NcType> ncTypes = new Dictionary<string, NcType>();
// search in current group
if(location == Location.Current || location == Location.ParentsAndCurrent
|| location == Location.ChildrenAndCurrent
|| location == Location.All) {
Int32 typeCount = GetTypeCount();
Int32[] typeIds = new Int32[typeCount];
NcCheck.Check(NetCDF.nc_inq_typeids(myId, ref typeCount, typeIds));
foreach(Int32 i in typeIds) {
NcType tmpType = new NcType(this, i);
ncTypes.Add(tmpType.GetName(), tmpType);
}
}
// search in parent groups
if(location == Location.Parents || location == Location.ParentsAndCurrent
|| location == Location.All) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
k.Value.GetTypes().ToList().ForEach(x => ncTypes[x.Key] = x.Value);
}
}
// search in child groups
if(location == Location.Children || location == Location.ChildrenAndCurrent
|| location == Location.All) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.AllChildrenGrps);
foreach(KeyValuePair<string, NcGroup> k in groups) {
k.Value.GetTypes().ToList().ForEach(x => ncTypes[x.Key] = x.Value);
}
}
return ncTypes;
}
public HashSet<NcType> GetTypes(string name, Location location=Location.Current) {
CheckNull();
Dictionary<string, NcType> types = GetTypes(location);
HashSet<NcType> ncTypes = new HashSet<NcType>();
foreach(KeyValuePair<string, NcType> k in types) {
if(k.Key == name)
ncTypes.Add(k.Value);
}
return ncTypes;
}
public HashSet<NcType> GetTypes(NcTypeEnum enumType, Location location=Location.Current) {
CheckNull();
Dictionary<string, NcType> types = GetTypes(location);
HashSet<NcType> ncTypes = new HashSet<NcType>();
foreach(KeyValuePair<string, NcType> k in types) {
if(k.Value.GetTypeClass() == enumType)
ncTypes.Add(k.Value);
}
return ncTypes;
}
public HashSet<NcType> GetTypes(string name, NcTypeEnum enumType, Location location=Location.Current) {
CheckNull();
Dictionary<string, NcType> types = GetTypes(location);
HashSet<NcType> ncTypes = new HashSet<NcType>();
foreach(KeyValuePair<string, NcType> k in types) {
if(k.Value.GetTypeClass() == enumType && k.Key == name)
ncTypes.Add(k.Value);
}
return ncTypes;
}
public NcType GetType(string name, Location location=Location.Current) {
CheckNull();
if(name == "byte") return NcByte.Instance;
if(name == "ubyte") return NcUbyte.Instance;
if(name == "char") return NcChar.Instance;
if(name == "short") return NcShort.Instance;
if(name == "ushort") return NcUshort.Instance;
if(name == "int") return NcInt.Instance;
if(name == "uint") return NcUint.Instance;
if(name == "int64") return NcInt64.Instance;
if(name == "uint64") return NcUint64.Instance;
if(name == "float") return NcFloat.Instance;
if(name == "double") return NcDouble.Instance;
if(name == "string") return NcString.Instance;
Dictionary<string, NcType> types = GetTypes(location);
foreach(KeyValuePair<string, NcType> k in types) {
if(k.Key == name)
return k.Value;
}
return new NcType(); // null
}
public NcEnumType AddEnumType(string name, NcEnumType.Types baseType) {
CheckNull();
CheckDefine();
Int32 typeId=0;
NcCheck.Check(NetCDF.nc_def_enum(myId, (int)baseType, name, ref typeId));
NcEnumType tmp = new NcEnumType(this, name);
return tmp;
}
public NcVlenType AddVlenType(string name, NcType baseType) {
CheckNull();
CheckDefine();
Int32 typeId=0;
NcCheck.Check(NetCDF.nc_def_vlen(myId, name, baseType.GetId(), ref typeId));
NcVlenType ncTypeTmp = new NcVlenType(this, name);
return ncTypeTmp;
}
public NcOpaqueType AddOpaqueType(string name, Int32 size) {
CheckNull();
CheckDefine();
Int32 typeid=0;
NcCheck.Check(NetCDF.nc_def_opaque(myId, size, name, ref typeid));
return new NcOpaqueType(this, name);
}
public NcCompoundType AddCompoundType(string name, long size) {
throw new NotImplementedException("AddCompoundType() not implemented");
return null;
}
public Dictionary<string, NcGroup> GetCoordVars(Location location=Location.Current) {
Dictionary<string, NcGroup> coordVars = new Dictionary<string, NcGroup>();
if(LocationIsCurrentGroup(location)) {
foreach(KeyValuePair<string, NcDim> dim in GetDims()) {
if(GetVars().ContainsKey(dim.Key))
coordVars.Add(dim.Key, this);
}
}
if(LocationIsParentGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
foreach(KeyValuePair<string,NcGroup> k in groups) {
k.Value.GetCoordVars().ToList().ForEach(x => coordVars[x.Key] = x.Value);
}
}
if(LocationIsChildGroup(location)) {
Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.AllChildrenGrps);
foreach(KeyValuePair<string,NcGroup> k in groups) {
k.Value.GetCoordVars().ToList().ForEach(x => coordVars[x.Key] = x.Value);
}
}
return coordVars;
}
public void GetCoordVar(string coordVarName, ref NcDim ncDim, ref NcVar ncVar, Location location = Location.Current) {
ncDim = GetDim(coordVarName, location);
ncVar = GetVar(coordVarName, location);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
#if CORECLR
// Use stub for TypeLibTypeAttribute
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
#pragma warning disable 1591
namespace Microsoft.WSMan.Management
{
#region "public Api"
#region WsManEnumFlags
/// <summary><para>_WSManEnumFlags enumeration.</para></summary>
[SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")]
[TypeLibType((short)0)]
public enum WSManEnumFlags
{
/// <summary><para><c>WSManFlagNonXmlText</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 1.</para></summary>
WSManFlagNonXmlText = 1,
/// <summary><para><c>WSManFlagReturnObject</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 0.</para></summary>
WSManFlagReturnObject = 0,
/// <summary><para><c>WSManFlagReturnEPR</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 2.</para></summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")]
WSManFlagReturnEPR = 2,
/// <summary><para><c>WSManFlagReturnObjectAndEPR</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 4.</para></summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")]
WSManFlagReturnObjectAndEPR = 4,
/// <summary><para><c>WSManFlagHierarchyDeep</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 0.</para></summary>
WSManFlagHierarchyDeep = 0,
/// <summary><para><c>WSManFlagHierarchyShallow</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 32.</para></summary>
WSManFlagHierarchyShallow = 32,
/// <summary><para><c>WSManFlagHierarchyDeepBasePropsOnly</c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 64.</para></summary>
WSManFlagHierarchyDeepBasePropsOnly = 64,
/// <summary><para><c>WSManFlagAssociationInstance </c> constant of <c>_WSManEnumFlags</c> enumeration. </para><para>Constant value is 64.</para></summary>
WSManFlagAssociationInstance = 128
}
#endregion WsManEnumFlags
#region WsManSessionFlags
/// <summary><para>WSManSessionFlags enumeration.</para></summary>
///
[SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")]
[TypeLibType((short)0)]
public enum WSManSessionFlags
{
/// <summary><para><c>no flag</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 1.</para></summary>
WSManNone = 0,
/// <summary><para><c>WSManFlagUTF8</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 1.</para></summary>
WSManFlagUtf8 = 1,
/// <summary><para><c>WSManFlagCredUsernamePassword</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 4096.</para></summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")]
WSManFlagCredUserNamePassword = 4096,
/// <summary><para><c>WSManFlagSkipCACheck</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 8192.</para></summary>
WSManFlagSkipCACheck = 8192,
/// <summary><para><c>WSManFlagSkipCNCheck</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 16384.</para></summary>
WSManFlagSkipCNCheck = 16384,
/// <summary><para><c>WSManFlagUseNoAuthentication</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 32768.</para></summary>
WSManFlagUseNoAuthentication = 32768,
/// <summary><para><c>WSManFlagUseDigest</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 65536.</para></summary>
WSManFlagUseDigest = 65536,
/// <summary><para><c>WSManFlagUseNegotiate</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 131072.</para></summary>
WSManFlagUseNegotiate = 131072,
/// <summary><para><c>WSManFlagUseBasic</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 262144.</para></summary>
WSManFlagUseBasic = 262144,
/// <summary><para><c>WSManFlagUseKerberos</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 524288.</para></summary>
WSManFlagUseKerberos = 524288,
/// <summary><para><c>WSManFlagNoEncryption</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 1048576.</para></summary>
WSManFlagNoEncryption = 1048576,
/// <summary><para><c>WSManFlagEnableSPNServerPort</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 4194304.</para></summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Spn")]
WSManFlagEnableSpnServerPort = 4194304,
/// <summary><para><c>WSManFlagUTF16</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 8388608.</para></summary>
WSManFlagUtf16 = 8388608,
/// <summary><para><c>WSManFlagUseCredSsp</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 16777216.</para></summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ssp")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")]
WSManFlagUseCredSsp = 16777216,
/// <summary><para><c>WSManFlagUseClientCertificate</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 2097152.</para></summary>
WSManFlagUseClientCertificate = 2097152,
/// <summary><para><c>WSManFlagSkipRevocationCheck</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 33554432.</para></summary>
WSManFlagSkipRevocationCheck = 33554432,
/// <summary><para><c>WSManFlagAllowNegotiateImplicitCredentials</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 67108864.</para></summary>
WSManFlagAllowNegotiateImplicitCredentials = 67108864,
/// <summary><para><c>WSManFlagUseSsl</c> constant of <c>_WSManSessionFlags</c> enumeration. </para><para>Constant value is 134217728.</para></summary>
WSManFlagUseSsl = 134217728
}
#endregion WsManSessionFlags
#region AuthenticationMechanism
/// <summary>WSManEnumFlags enumeration</summary>
///
[SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")]
public enum AuthenticationMechanism
{
/// <summary>
/// Use no authentication
/// </summary>
None = 0x0,
/// <summary>
/// Use Default authentication
/// </summary>
Default = 0x1,
/// <summary>
/// Use digest authentication for a remote operation
/// </summary>
Digest = 0x2,
/// <summary>
/// Use negotiate authentication for a remote operation (may use kerberos or ntlm)
/// </summary>
Negotiate = 0x4,
/// <summary>
/// Use basic authentication for a remote operation
/// </summary>
Basic = 0x8,
/// <summary>
/// Use kerberos authentication for a remote operation
/// </summary>
Kerberos = 0x10,
/// <summary>
/// Use client certificate authentication for a remote operation
/// </summary>
ClientCertificate = 0x20,
/// <summary>
/// Use CredSSP authentication for a remote operation
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Credssp")]
Credssp = 0x80,
}
#endregion AuthenticationMechanism
#region IWsMan
/// <summary><para><c>IWSMan</c> interface.</para></summary>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")]
[Guid("190D8637-5CD3-496D-AD24-69636BB5A3B5")]
[ComImport]
[TypeLibType((short)4304)]
#if CORECLR
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
#else
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
#endif
public interface IWSMan
{
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfoCount();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfo();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetIDsOfNames();
[return: MarshalAs(UnmanagedType.IUnknown)]
object Invoke();
#endif
/// <summary><para><c>CreateSession</c> method of <c>IWSMan</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>CreateSession</c> method was the following: <c>HRESULT CreateSession ([optional, defaultvalue("")] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks>
// IDL: HRESULT CreateSession ([optional, defaultvalue("")] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue);
[DispId(1)]
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IUnknown)] object connectionOptions);
#else
[return: MarshalAs(UnmanagedType.IDispatch)]
object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IDispatch)] object connectionOptions);
#endif
/// <summary><para><c>CreateConnectionOptions</c> method of <c>IWSMan</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>CreateConnectionOptions</c> method was the following: <c>HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue)</c>;</para></remarks>
// IDL: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue);
//
[DispId(2)]
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
#else
[return: MarshalAs(UnmanagedType.IDispatch)]
#endif
object CreateConnectionOptions();
/// <summary><para><c>CommandLine</c> property of <c>IWSMan</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>CommandLine</c> property was the following: <c>BSTR CommandLine</c>;</para></remarks>
// IDL: BSTR CommandLine;
//
string CommandLine
{
// IDL: HRESULT CommandLine ([out, retval] BSTR* ReturnValue);
[DispId(3)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
/// <summary><para><c>Error</c> property of <c>IWSMan</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks>
// IDL: BSTR Error;
//
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
string Error
{
// IDL: HRESULT Error ([out, retval] BSTR* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
[DispId(4)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
}
#endregion IWsMan
#region IWSManConnectionOptions
/// <summary><para><c>IWSManConnectionOptions</c> interface.</para></summary>
[Guid("F704E861-9E52-464F-B786-DA5EB2320FDD")]
[ComImport]
[TypeLibType((short)4288)]
#if CORECLR
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
#else
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
#endif
[SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")]
public interface IWSManConnectionOptions
{
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfoCount();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfo();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetIDsOfNames();
[return: MarshalAs(UnmanagedType.IUnknown)]
object Invoke();
#endif
/// <summary><para><c>UserName</c> property of <c>IWSManConnectionOptions</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>UserName</c> property was the following: <c>BSTR UserName</c>;</para></remarks>
// IDL: BSTR UserName;
string UserName
{
// IDL: HRESULT UserName ([out, retval] BSTR* ReturnValue);
[DispId(1)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
// IDL: HRESULT UserName (BSTR value);
[DispId(1)]
set;
}
/// <summary><para><c>Password</c> property of <c>IWSManConnectionOptions</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Password</c> property was the following: <c>BSTR Password</c>;</para></remarks>
// IDL: BSTR Password;
[SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")]
string Password
{
// IDL: HRESULT Password (BSTR value);
[SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly")]
[DispId(2)]
set;
}
}
/// <summary><para><c>IWSManConnectionOptions</c> interface.</para></summary>
[Guid("EF43EDF7-2A48-4d93-9526-8BD6AB6D4A6B")]
[ComImport]
[TypeLibType((short)4288)]
#if CORECLR
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
#else
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
#endif
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public interface IWSManConnectionOptionsEx : IWSManConnectionOptions
{
/// <summary><para><c>CertificateThumbprint</c> property of <c>IWSManConnectionOptionsEx</c> interface.</para></summary>
string CertificateThumbprint
{
[DispId(3)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
[DispId(1)]
set;
}
}
/// <summary><para><c>IWSManConnectionOptions</c> interface.</para></summary>
[Guid("F500C9EC-24EE-48ab-B38D-FC9A164C658E")]
[ComImport]
[TypeLibType((short)4288)]
#if CORECLR
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
#else
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
#endif
public interface IWSManConnectionOptionsEx2 : IWSManConnectionOptionsEx
{
/// <summary><para><c>SetProxy</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary>
[DispId(4)]
void SetProxy(int accessType,
int authenticationMechanism,
[In, MarshalAs(UnmanagedType.BStr)] string userName,
[In, MarshalAs(UnmanagedType.BStr)] string password);
/// <summary><para><c>ProxyIEConfig</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary>
[DispId(5)]
int ProxyIEConfig();
/// <summary><para><c>ProxyWinHttpConfig</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary>
[DispId(6)]
int ProxyWinHttpConfig();
/// <summary><para><c>ProxyAutoDetect</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary>
[DispId(7)]
int ProxyAutoDetect();
/// <summary><para><c>ProxyNoProxyServer</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary>
[DispId(8)]
int ProxyNoProxyServer();
/// <summary><para><c>ProxyAuthenticationUseNegotiate</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary>
[DispId(9)]
int ProxyAuthenticationUseNegotiate();
/// <summary><para><c>ProxyAuthenticationUseBasic</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary>
[DispId(10)]
int ProxyAuthenticationUseBasic();
/// <summary><para><c>ProxyAuthenticationUseDigest</c> method of <c>IWSManConnectionOptionsEx2</c> interface.</para></summary>
[DispId(11)]
int ProxyAuthenticationUseDigest();
};
#endregion IWSManConnectionOptions
#region IWSManEnumerator
/// <summary><para><c>IWSManEnumerator</c> interface.</para></summary>
[Guid("F3457CA9-ABB9-4FA5-B850-90E8CA300E7F")]
[ComImport]
[TypeLibType((short)4288)]
#if CORECLR
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
#else
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
#endif
public interface IWSManEnumerator
{
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfoCount();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfo();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetIDsOfNames();
[return: MarshalAs(UnmanagedType.IUnknown)]
object Invoke();
#endif
/// <summary><para><c>ReadItem</c> method of <c>IWSManEnumerator</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>ReadItem</c> method was the following: <c>HRESULT ReadItem ([out, retval] BSTR* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT ReadItem ([out, retval] BSTR* ReturnValue);
[DispId(1)]
[return: MarshalAs(UnmanagedType.BStr)]
string ReadItem();
/// <summary><para><c>AtEndOfStream</c> property of <c>IWSManEnumerator</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>AtEndOfStream</c> property was the following: <c>BOOL AtEndOfStream</c>;</para></remarks>
// IDL: BOOL AtEndOfStream;
bool AtEndOfStream
{
// IDL: HRESULT AtEndOfStream ([out, retval] BOOL* ReturnValue);
[DispId(2)]
[return: MarshalAs(UnmanagedType.Bool)]
get;
}
/// <summary><para><c>Error</c> property of <c>IWSManEnumerator</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks>
// IDL: BSTR Error;
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
string Error
{
// IDL: HRESULT Error ([out, retval] BSTR* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
[DispId(8)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
}
#endregion IWSManEnumerator
#region IWSManEx
/// <summary><para><c>IWSManEx</c> interface.</para></summary>
[Guid("2D53BDAA-798E-49E6-A1AA-74D01256F411")]
[ComImport]
[TypeLibType((short)4304)]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
#if CORECLR
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
#else
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
#endif
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "str")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
public interface IWSManEx
{
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfoCount();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfo();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetIDsOfNames();
[return: MarshalAs(UnmanagedType.IUnknown)]
object Invoke();
#endif
/// <summary><para><c>CreateSession</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>CreateSession</c> method was the following: <c>HRESULT CreateSession ([optional, defaultvalue("")] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks>
// IDL: HRESULT CreateSession ([optional, defaultvalue("")] BSTR connection, [optional, defaultvalue(0)] long flags, [optional] IDispatch* connectionOptions, [out, retval] IDispatch** ReturnValue);
[DispId(1)]
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IUnknown)] object connectionOptions);
#else
[return: MarshalAs(UnmanagedType.IDispatch)]
object CreateSession([MarshalAs(UnmanagedType.BStr)] string connection, int flags, [MarshalAs(UnmanagedType.IDispatch)] object connectionOptions);
#endif
/// <summary><para><c>CreateConnectionOptions</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>CreateConnectionOptions</c> method was the following: <c>HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue)</c>;</para></remarks>
// IDL: HRESULT CreateConnectionOptions ([out, retval] IDispatch** ReturnValue);
[DispId(2)]
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
#else
[return: MarshalAs(UnmanagedType.IDispatch)]
#endif
object CreateConnectionOptions();
/// <summary>
///
/// </summary>
/// <returns></returns>
string CommandLine
{
// IDL: HRESULT CommandLine ([out, retval] BSTR* ReturnValue);
[DispId(3)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
/// <summary><para><c>Error</c> property of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks>
// IDL: BSTR Error;
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
string Error
{
// IDL: HRESULT Error ([out, retval] BSTR* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
[DispId(4)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
/// <summary><para><c>CreateResourceLocator</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>CreateResourceLocator</c> method was the following: <c>HRESULT CreateResourceLocator ([optional, defaultvalue("")] BSTR strResourceLocator, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks>
// IDL: HRESULT CreateResourceLocator ([optional, defaultvalue("")] BSTR strResourceLocator, [out, retval] IDispatch** ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "str")]
[DispId(5)]
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
#else
[return: MarshalAs(UnmanagedType.IDispatch)]
#endif
object CreateResourceLocator([MarshalAs(UnmanagedType.BStr)] string strResourceLocator);
/// <summary><para><c>SessionFlagUTF8</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagUTF8</c> method was the following: <c>HRESULT SessionFlagUTF8 ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagUTF8 ([out, retval] long* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")]
[DispId(6)]
int SessionFlagUTF8();
/// <summary><para><c>SessionFlagCredUsernamePassword</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagCredUsernamePassword</c> method was the following: <c>HRESULT SessionFlagCredUsernamePassword ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagCredUsernamePassword ([out, retval] long* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")]
[DispId(7)]
int SessionFlagCredUsernamePassword();
/// <summary><para><c>SessionFlagSkipCACheck</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagSkipCACheck</c> method was the following: <c>HRESULT SessionFlagSkipCACheck ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagSkipCACheck ([out, retval] long* ReturnValue);
[DispId(8)]
int SessionFlagSkipCACheck();
/// <summary><para><c>SessionFlagSkipCNCheck</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagSkipCNCheck</c> method was the following: <c>HRESULT SessionFlagSkipCNCheck ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagSkipCNCheck ([out, retval] long* ReturnValue);
[DispId(9)]
int SessionFlagSkipCNCheck();
/// <summary><para><c>SessionFlagUseDigest</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagUseDigest</c> method was the following: <c>HRESULT SessionFlagUseDigest ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagUseDigest ([out, retval] long* ReturnValue);
[DispId(10)]
int SessionFlagUseDigest();
/// <summary><para><c>SessionFlagUseNegotiate</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagUseNegotiate</c> method was the following: <c>HRESULT SessionFlagUseNegotiate ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagUseNegotiate ([out, retval] long* ReturnValue);
[DispId(11)]
int SessionFlagUseNegotiate();
/// <summary><para><c>SessionFlagUseBasic</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagUseBasic</c> method was the following: <c>HRESULT SessionFlagUseBasic ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagUseBasic ([out, retval] long* ReturnValue);
[DispId(12)]
int SessionFlagUseBasic();
/// <summary><para><c>SessionFlagUseKerberos</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagUseKerberos</c> method was the following: <c>HRESULT SessionFlagUseKerberos ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagUseKerberos ([out, retval] long* ReturnValue);
[DispId(13)]
int SessionFlagUseKerberos();
/// <summary><para><c>SessionFlagNoEncryption</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagNoEncryption</c> method was the following: <c>HRESULT SessionFlagNoEncryption ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagNoEncryption ([out, retval] long* ReturnValue);
[DispId(14)]
int SessionFlagNoEncryption();
/// <summary><para><c>SessionFlagEnableSPNServerPort</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagEnableSPNServerPort</c> method was the following: <c>HRESULT SessionFlagEnableSPNServerPort ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagEnableSPNServerPort ([out, retval] long* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")]
[DispId(15)]
int SessionFlagEnableSPNServerPort();
/// <summary><para><c>SessionFlagUseNoAuthentication</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>SessionFlagUseNoAuthentication</c> method was the following: <c>HRESULT SessionFlagUseNoAuthentication ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT SessionFlagUseNoAuthentication ([out, retval] long* ReturnValue);
[DispId(16)]
int SessionFlagUseNoAuthentication();
/// <summary><para><c>EnumerationFlagNonXmlText</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>EnumerationFlagNonXmlText</c> method was the following: <c>HRESULT EnumerationFlagNonXmlText ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT EnumerationFlagNonXmlText ([out, retval] long* ReturnValue);
[DispId(17)]
int EnumerationFlagNonXmlText();
/// <summary><para><c>EnumerationFlagReturnEPR</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>EnumerationFlagReturnEPR</c> method was the following: <c>HRESULT EnumerationFlagReturnEPR ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT EnumerationFlagReturnEPR ([out, retval] long* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")]
[DispId(18)]
int EnumerationFlagReturnEPR();
/// <summary><para><c>EnumerationFlagReturnObjectAndEPR</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>EnumerationFlagReturnObjectAndEPR</c> method was the following: <c>HRESULT EnumerationFlagReturnObjectAndEPR ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT EnumerationFlagReturnObjectAndEPR ([out, retval] long* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "EPR")]
[DispId(19)]
int EnumerationFlagReturnObjectAndEPR();
/// <summary><para><c>GetErrorMessage</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>GetErrorMessage</c> method was the following: <c>HRESULT GetErrorMessage (unsigned long errorNumber, [out, retval] BSTR* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT GetErrorMessage (unsigned long errorNumber, [out, retval] BSTR* ReturnValue);
[DispId(20)]
[return: MarshalAs(UnmanagedType.BStr)]
string GetErrorMessage(uint errorNumber);
/// <summary><para><c>EnumerationFlagHierarchyDeep</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>EnumerationFlagHierarchyDeep</c> method was the following: <c>HRESULT EnumerationFlagHierarchyDeep ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT EnumerationFlagHierarchyDeep ([out, retval] long* ReturnValue);
[DispId(21)]
int EnumerationFlagHierarchyDeep();
/// <summary><para><c>EnumerationFlagHierarchyShallow</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>EnumerationFlagHierarchyShallow</c> method was the following: <c>HRESULT EnumerationFlagHierarchyShallow ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT EnumerationFlagHierarchyShallow ([out, retval] long* ReturnValue);
[DispId(22)]
int EnumerationFlagHierarchyShallow();
/// <summary><para><c>EnumerationFlagHierarchyDeepBasePropsOnly</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>EnumerationFlagHierarchyDeepBasePropsOnly</c> method was the following: <c>HRESULT EnumerationFlagHierarchyDeepBasePropsOnly ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT EnumerationFlagHierarchyDeepBasePropsOnly ([out, retval] long* ReturnValue);
[DispId(23)]
int EnumerationFlagHierarchyDeepBasePropsOnly();
/// <summary><para><c>EnumerationFlagReturnObject</c> method of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>EnumerationFlagReturnObject</c> method was the following: <c>HRESULT EnumerationFlagReturnObject ([out, retval] long* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT EnumerationFlagReturnObject ([out, retval] long* ReturnValue);
[DispId(24)]
int EnumerationFlagReturnObject();
/// <summary><para><c>CommandLine</c> property of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>CommandLine</c> property was the following: <c>BSTR CommandLine</c>;</para></remarks>
// IDL: BSTR CommandLine;
[DispId(28)]
int EnumerationFlagAssociationInstance();
/// <summary><para><c>CommandLine</c> property of <c>IWSManEx</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>CommandLine</c> property was the following: <c>BSTR CommandLine</c>;</para></remarks>
// IDL: BSTR CommandLine;
[DispId(29)]
int EnumerationFlagAssociatedInstance();
}
#endregion IWsManEx
#region IWsManResourceLocator
/// <summary><para><c>IWSManResourceLocator</c> interface.</para></summary>
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")]
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sel")]
[Guid("A7A1BA28-DE41-466A-AD0A-C4059EAD7428")]
[ComImport]
[TypeLibType((short)4288)]
#if CORECLR
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
#else
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
#endif
public interface IWSManResourceLocator
{
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfoCount();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfo();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetIDsOfNames();
[return: MarshalAs(UnmanagedType.IUnknown)]
object Invoke();
#endif
/// <summary><para><c>resourceUri</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Set the resource URI. Must contain path only -- query string is not allowed here.</para></summary>
/// <remarks><para>An original IDL definition of <c>resourceUri</c> property was the following: <c>BSTR resourceUri</c>;</para></remarks>
// Set the resource URI. Must contain path only -- query string is not allowed here.
// IDL: BSTR resourceUri;
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")]
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
string ResourceUri
{
// IDL: HRESULT resourceUri (BSTR value);
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")]
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
[DispId(1)]
set;
// IDL: HRESULT resourceUri ([out, retval] BSTR* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")]
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
[DispId(1)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
/// <summary><para><c>AddSelector</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Add selector to resource locator</para></summary>
/// <remarks><para>An original IDL definition of <c>AddSelector</c> method was the following: <c>HRESULT AddSelector (BSTR resourceSelName, VARIANT selValue)</c>;</para></remarks>
// Add selector to resource locator
// IDL: HRESULT AddSelector (BSTR resourceSelName, VARIANT selValue);
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "sel")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sel")]
[DispId(2)]
void AddSelector([MarshalAs(UnmanagedType.BStr)] string resourceSelName, object selValue);
/// <summary><para><c>ClearSelectors</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Clear all selectors</para></summary>
/// <remarks><para>An original IDL definition of <c>ClearSelectors</c> method was the following: <c>HRESULT ClearSelectors (void)</c>;</para></remarks>
// Clear all selectors
// IDL: HRESULT ClearSelectors (void);
[DispId(3)]
void ClearSelectors();
/// <summary><para><c>FragmentPath</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Gets the fragment path</para></summary>
/// <remarks><para>An original IDL definition of <c>FragmentPath</c> property was the following: <c>BSTR FragmentPath</c>;</para></remarks>
// Gets the fragment path
// IDL: BSTR FragmentPath;
string FragmentPath
{
// IDL: HRESULT FragmentPath ([out, retval] BSTR* ReturnValue);
[DispId(4)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
// IDL: HRESULT FragmentPath (BSTR value);
[DispId(4)]
set;
}
/// <summary><para><c>FragmentDialect</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Gets the Fragment dialect</para></summary>
/// <remarks><para>An original IDL definition of <c>FragmentDialect</c> property was the following: <c>BSTR FragmentDialect</c>;</para></remarks>
// Gets the Fragment dialect
// IDL: BSTR FragmentDialect;
string FragmentDialect
{
// IDL: HRESULT FragmentDialect ([out, retval] BSTR* ReturnValue);
[DispId(5)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
// IDL: HRESULT FragmentDialect (BSTR value);
[DispId(5)]
set;
}
/// <summary><para><c>AddOption</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Add option to resource locator</para></summary>
/// <remarks><para>An original IDL definition of <c>AddOption</c> method was the following: <c>HRESULT AddOption (BSTR OptionName, VARIANT OptionValue, [optional, defaultvalue(0)] long mustComply)</c>;</para></remarks>
// Add option to resource locator
// IDL: HRESULT AddOption (BSTR OptionName, VARIANT OptionValue, [optional, defaultvalue(0)] long mustComply);
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Option")]
[DispId(6)]
void AddOption([MarshalAs(UnmanagedType.BStr)] string OptionName, object OptionValue, int mustComply);
/// <summary><para><c>MustUnderstandOptions</c> property of <c>IWSManResourceLocator</c> interface. </para><para>Sets the MustUnderstandOptions value</para></summary>
/// <remarks><para>An original IDL definition of <c>MustUnderstandOptions</c> property was the following: <c>long MustUnderstandOptions</c>;</para></remarks>
// Sets the MustUnderstandOptions value
// IDL: long MustUnderstandOptions;
int MustUnderstandOptions
{
// IDL: HRESULT MustUnderstandOptions ([out, retval] long* ReturnValue);
[DispId(7)]
get;
// IDL: HRESULT MustUnderstandOptions (long value);
[DispId(7)]
set;
}
/// <summary><para><c>ClearOptions</c> method of <c>IWSManResourceLocator</c> interface. </para><para>Clear all options</para></summary>
/// <remarks><para>An original IDL definition of <c>ClearOptions</c> method was the following: <c>HRESULT ClearOptions (void)</c>;</para></remarks>
// Clear all options
// IDL: HRESULT ClearOptions (void);
[DispId(8)]
void ClearOptions();
/// <summary><para><c>Error</c> property of <c>IWSManResourceLocator</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks>
// IDL: BSTR Error;
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
string Error
{
// IDL: HRESULT Error ([out, retval] BSTR* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
[DispId(9)]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
}
#endregion IWsManResourceLocator
#region IWSManSession
/// <summary><para><c>IWSManSession</c> interface.</para></summary>
[Guid("FC84FC58-1286-40C4-9DA0-C8EF6EC241E0")]
[ComImport]
[TypeLibType((short)4288)]
#if CORECLR
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
#else
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
#endif
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")]
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]
public interface IWSManSession
{
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfoCount();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfo();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetIDsOfNames();
[return: MarshalAs(UnmanagedType.IUnknown)]
object Invoke();
#endif
/// <summary><para><c>Get</c> method of <c>IWSManSession</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Get</c> method was the following: <c>HRESULT Get (VARIANT resourceUri, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT Get (VARIANT resourceUri, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")]
[DispId(1)]
[return: MarshalAs(UnmanagedType.BStr)]
string Get(object resourceUri, int flags);
/// <summary><para><c>Put</c> method of <c>IWSManSession</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Put</c> method was the following: <c>HRESULT Put (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT Put (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue);
[DispId(2)]
[return: MarshalAs(UnmanagedType.BStr)]
string Put(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string resource, int flags);
/// <summary><para><c>Create</c> method of <c>IWSManSession</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Create</c> method was the following: <c>HRESULT Create (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT Create (VARIANT resourceUri, BSTR resource, [optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue);
[DispId(3)]
[return: MarshalAs(UnmanagedType.BStr)]
string Create(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string resource, int flags);
/// <summary><para><c>Delete</c> method of <c>IWSManSession</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Delete</c> method was the following: <c>HRESULT Delete (VARIANT resourceUri, [optional, defaultvalue(0)] long flags)</c>;</para></remarks>
// IDL: HRESULT Delete (VARIANT resourceUri, [optional, defaultvalue(0)] long flags);
[DispId(4)]
void Delete(object resourceUri, int flags);
/// <summary>
///
/// </summary>
/// <param name="actionURI"></param>
/// <param name="resourceUri"></param>
/// <param name="parameters"></param>
/// <param name="flags"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")]
[DispId(5)]
String Invoke([MarshalAs(UnmanagedType.BStr)] string actionURI, [In] object resourceUri, [MarshalAs(UnmanagedType.BStr)] string parameters, [In] int flags);
/// <summary><para><c>Enumerate</c> method of <c>IWSManSession</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Enumerate</c> method was the following: <c>HRESULT Enumerate (VARIANT resourceUri, [optional, defaultvalue("")] BSTR filter, [optional, defaultvalue("")] BSTR dialect, [optional, defaultvalue(0)] long flags, [out, retval] IDispatch** ReturnValue)</c>;</para></remarks>
// IDL: HRESULT Enumerate (VARIANT resourceUri, [optional, defaultvalue("")] BSTR filter, [optional, defaultvalue("")] BSTR dialect, [optional, defaultvalue(0)] long flags, [out, retval] IDispatch** ReturnValue);
[DispId(6)]
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
#else
[return: MarshalAs(UnmanagedType.IDispatch)]
#endif
object Enumerate(object resourceUri, [MarshalAs(UnmanagedType.BStr)] string filter, [MarshalAs(UnmanagedType.BStr)] string dialect, int flags);
/// <summary><para><c>Identify</c> method of <c>IWSManSession</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Identify</c> method was the following: <c>HRESULT Identify ([optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue)</c>;</para></remarks>
// IDL: HRESULT Identify ([optional, defaultvalue(0)] long flags, [out, retval] BSTR* ReturnValue);
[DispId(7)]
[return: MarshalAs(UnmanagedType.BStr)]
string Identify(int flags);
/// <summary><para><c>Error</c> property of <c>IWSManSession</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Error</c> property was the following: <c>BSTR Error</c>;</para></remarks>
// IDL: BSTR Error;
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
string Error
{
// IDL: HRESULT Error ([out, retval] BSTR* ReturnValue);
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
[DispId(8)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
/// <summary><para><c>BatchItems</c> property of <c>IWSManSession</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>BatchItems</c> property was the following: <c>long BatchItems</c>;</para></remarks>
// IDL: long BatchItems;
int BatchItems
{
// IDL: HRESULT BatchItems ([out, retval] long* ReturnValue);
[DispId(9)]
get;
// IDL: HRESULT BatchItems (long value);
[DispId(9)]
set;
}
/// <summary><para><c>Timeout</c> property of <c>IWSManSession</c> interface.</para></summary>
/// <remarks><para>An original IDL definition of <c>Timeout</c> property was the following: <c>long Timeout</c>;</para></remarks>
// IDL: long Timeout;
int Timeout
{
// IDL: HRESULT Timeout ([out, retval] long* ReturnValue);
[DispId(10)]
get;
// IDL: HRESULT Timeout (long value);
[DispId(10)]
set;
}
}
#endregion IWSManSession
#region IWSManResourceLocatorInternal
/// <summary><para><c>IWSManResourceLocatorInternal</c> interface.</para></summary>
[Guid("EFFAEAD7-7EC8-4716-B9BE-F2E7E9FB4ADB")]
[ComImport]
[TypeLibType((short)400)]
#if CORECLR
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
#else
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
#endif
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")]
public interface IWSManResourceLocatorInternal
{
#if CORECLR
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfoCount();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetTypeInfo();
[return: MarshalAs(UnmanagedType.IUnknown)]
object GetIDsOfNames();
[return: MarshalAs(UnmanagedType.IUnknown)]
object Invoke();
#endif
}
#endregion IWSManResourceLocatorInternal
/// <summary><para><c>WSMan</c> interface.</para></summary>
[Guid("BCED617B-EC03-420b-8508-977DC7A686BD")]
[ComImport]
#if CORECLR
[ClassInterface(ClassInterfaceType.None)]
#else
[ClassInterface(ClassInterfaceType.AutoDual)]
#endif
public class WSManClass
{
}
#region IGroupPolicyObject
/// <summary><para><c>GPClass</c> interface.</para></summary>
[Guid("EA502722-A23D-11d1-A7D3-0000F87571E3")]
[ComImport]
[ClassInterface(ClassInterfaceType.None)]
public class GPClass
{
}
[ComImport, Guid("EA502723-A23D-11d1-A7D3-0000F87571E3"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IGroupPolicyObject
{
void New(
[MarshalAs(UnmanagedType.LPWStr)] string pszDomainName,
[MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName,
uint dwFlags);
void OpenDSGPO(
[MarshalAs(UnmanagedType.LPWStr)] string pszPath,
uint dwFlags);
void OpenLocalMachineGPO(uint dwFlags);
void OpenRemoteMachineGPO(
[MarshalAs(UnmanagedType.LPWStr)] string pszComputerName,
uint dwFlags);
void Save(
[MarshalAs(UnmanagedType.Bool)] bool bMachine,
[MarshalAs(UnmanagedType.Bool)] bool bAdd,
[MarshalAs(UnmanagedType.LPStruct)] Guid pGuidExtension,
[MarshalAs(UnmanagedType.LPStruct)] Guid pGuid);
void Delete();
void GetName(
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName,
int cchMaxLength);
void GetDisplayName(
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName,
int cchMaxLength);
void SetDisplayName(
[MarshalAs(UnmanagedType.LPWStr)] string pszName);
void GetPath(
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath,
int cchMaxPath);
void GetDSPath(
uint dwSection,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath,
int cchMaxPath);
void GetFileSysPath(
uint dwSection,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath,
int cchMaxPath);
IntPtr GetRegistryKey(uint dwSection);
uint GetOptions();
void SetOptions(uint dwOptions, uint dwMask);
void GetMachineName(
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName,
int cchMaxLength);
uint GetPropertySheetPages(out IntPtr hPages);
}
#endregion IGroupPolicyObject
/// <summary><para><c>GpoNativeApi</c></para></summary>
public sealed class GpoNativeApi
{
private GpoNativeApi() { }
[DllImport("Userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern System.IntPtr EnterCriticalPolicySection(
[In, MarshalAs(UnmanagedType.Bool)] bool bMachine);
[DllImport("Userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool LeaveCriticalPolicySection(
[In] System.IntPtr hSection);
}
#endregion
}
#pragma warning restore 1591
| |
using Bridge.Contract;
using Bridge.Contract.Constants;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bridge.Translator
{
public class AsyncBlock : AbstractEmitterBlock, IAsyncBlock
{
public AsyncBlock(IEmitter emitter, MethodDeclaration methodDeclaration)
: base(emitter, methodDeclaration)
{
this.Emitter = emitter;
this.MethodDeclaration = methodDeclaration;
}
public AsyncBlock(IEmitter emitter, LambdaExpression lambdaExpression)
: base(emitter, lambdaExpression)
{
this.Emitter = emitter;
this.LambdaExpression = lambdaExpression;
}
public AsyncBlock(IEmitter emitter, AnonymousMethodExpression anonymousMethodExpression)
: base(emitter, anonymousMethodExpression)
{
this.Emitter = emitter;
this.AnonymousMethodExpression = anonymousMethodExpression;
}
public AstNode Node
{
get
{
if (this.MethodDeclaration != null)
{
return this.MethodDeclaration;
}
if (this.AnonymousMethodExpression != null)
{
return this.AnonymousMethodExpression;
}
if (this.LambdaExpression != null)
{
return this.LambdaExpression;
}
return null;
}
}
public MethodDeclaration MethodDeclaration
{
get;
set;
}
public LambdaExpression LambdaExpression
{
get;
set;
}
public AnonymousMethodExpression AnonymousMethodExpression
{
get;
set;
}
public List<IAsyncJumpLabel> JumpLabels
{
get;
set;
}
public AstNode Body
{
get
{
if (this.MethodDeclaration != null)
{
return this.MethodDeclaration.Body;
}
if (this.LambdaExpression != null)
{
return this.LambdaExpression.Body;
}
if (this.AnonymousMethodExpression != null)
{
return this.AnonymousMethodExpression.Body;
}
return null;
}
}
protected bool PreviousIsAync
{
get;
set;
}
protected List<string> PreviousAsyncVariables
{
get;
set;
}
protected IAsyncBlock PreviousAsyncBlock
{
get;
set;
}
public AstNode[] AwaitExpressions
{
get;
set;
}
public List<AstNode> WrittenAwaitExpressions
{
get;
set;
}
public IType ReturnType
{
get;
set;
}
public bool IsTaskReturn
{
get;
set;
}
public bool IsEnumeratorReturn
{
get;
set;
}
public int Step
{
get;
set;
}
public List<IAsyncStep> Steps
{
get;
set;
}
public List<IAsyncStep> EmittedAsyncSteps
{
get;
set;
}
public bool ReplaceAwaiterByVar
{
get;
set;
}
public List<IAsyncTryInfo> TryInfos
{
get;
set;
}
public void InitAsyncBlock()
{
this.PreviousAsyncExpressionHandling = this.Emitter.AsyncExpressionHandling;
this.Emitter.AsyncExpressionHandling = false;
this.PreviousIsAync = this.Emitter.IsAsync;
this.Emitter.IsAsync = true;
this.PreviousAsyncVariables = this.Emitter.AsyncVariables;
this.Emitter.AsyncVariables = new List<string>();
this.PreviousAsyncBlock = this.Emitter.AsyncBlock;
this.Emitter.AsyncBlock = this;
this.ReplaceAwaiterByVar = this.Emitter.ReplaceAwaiterByVar;
this.Emitter.ReplaceAwaiterByVar = false;
this.DetectReturnType();
this.FindAwaitNodes();
this.Steps = new List<IAsyncStep>();
this.TryInfos = new List<IAsyncTryInfo>();
this.JumpLabels = new List<IAsyncJumpLabel>();
this.WrittenAwaitExpressions = new List<AstNode>();
}
public bool PreviousAsyncExpressionHandling { get; set; }
protected void DetectReturnType()
{
AstNode node = this.MethodDeclaration != null ? this.MethodDeclaration.ReturnType : null;
if (node == null)
{
node = this.AnonymousMethodExpression;
}
if (node == null)
{
node = this.LambdaExpression;
}
var resolveResult = this.Emitter.Resolver.ResolveNode(node, this.Emitter);
if (resolveResult is LambdaResolveResult)
{
this.ReturnType = ((LambdaResolveResult)resolveResult).ReturnType;
}
else if (resolveResult is TypeResolveResult)
{
this.ReturnType = ((TypeResolveResult)resolveResult).Type;
}
this.IsTaskReturn = this.ReturnType != null && this.ReturnType.Name == "Task" && this.ReturnType.FullName.StartsWith("System.Threading.Tasks.Task");
}
protected void FindAwaitNodes()
{
this.AwaitExpressions = this.GetAwaiters(this.Body);
for (int i = 0; i < this.AwaitExpressions.Length; i++)
{
if (this.AwaitExpressions[i] is Expression)
{
this.Emitter.AsyncVariables.Add(JS.Vars.ASYNC_TASK + (i + 1));
if (this.IsTaskResult((Expression)this.AwaitExpressions[i]))
{
this.Emitter.AsyncVariables.Add(JS.Vars.ASYNC_TASK_RESULT + (i + 1));
}
}
}
}
protected bool IsTaskResult(Expression expression)
{
var resolveResult = this.Emitter.Resolver.ResolveNode(expression, this.Emitter);
IType type;
if (resolveResult is DynamicInvocationResolveResult)
{
return expression.Parent is UnaryOperatorExpression && !(expression.Parent.Parent is Statement);
}
else if (resolveResult is InvocationResolveResult)
{
type = ((InvocationResolveResult)resolveResult).Member.ReturnType;
}
else
{
type = resolveResult.Type;
}
if ((type.FullName == "System.Threading.Tasks.TaskAwaiter" || type.FullName == "System.Threading.Tasks.Task") && type.TypeParameterCount > 0)
{
return true;
}
var unaryExpr = expression.Parent as UnaryOperatorExpression;
if (unaryExpr != null && unaryExpr.Operator == UnaryOperatorType.Await)
{
var rr = this.Emitter.Resolver.ResolveNode(unaryExpr, this.Emitter) as AwaitResolveResult;
if (rr != null)
{
var awaiterMethod = rr.GetAwaiterInvocation as InvocationResolveResult;
if (awaiterMethod != null)
{
type = awaiterMethod.Type;
if ((type.FullName == "System.Threading.Tasks.TaskAwaiter" || type.FullName == "System.Threading.Tasks.Task") && type.TypeParameterCount > 0)
{
return true;
}
}
}
}
return false;
}
protected void FinishAsyncBlock()
{
this.Emitter.IsAsync = this.PreviousIsAync;
this.Emitter.AsyncVariables = this.PreviousAsyncVariables;
this.Emitter.AsyncBlock = this.PreviousAsyncBlock;
this.Emitter.ReplaceAwaiterByVar = this.ReplaceAwaiterByVar;
this.Emitter.AsyncExpressionHandling = this.PreviousAsyncExpressionHandling;
}
protected override void DoEmit()
{
this.Emit(false);
}
public void Emit(bool skipInit)
{
if (!skipInit)
{
this.InitAsyncBlock();
}
this.EmitAsyncBlock();
this.FinishAsyncBlock();
}
protected void EmitAsyncBlock()
{
this.BeginBlock();
this.WriteVar(true);
this.Write(JS.Vars.ASYNC_STEP + " = 0,");
var pos = this.Emitter.Output.Length;
this.WriteNewLine();
this.Indent();
this.Write(JS.Funcs.ASYNC_BODY + " = " + JS.Funcs.BRIDGE_BIND + "(this, ");
this.WriteFunction();
this.Write("() ");
this.EmitAsyncBody();
string temp = this.Emitter.Output.ToString(pos, this.Emitter.Output.Length - pos);
this.Emitter.Output.Length = pos;
foreach (var localVar in this.Emitter.AsyncVariables)
{
this.WriteNewLine();
this.Write(localVar);
this.WriteComma();
}
this.Emitter.Output.Append(temp);
this.Write(", " + JS.Vars.ARGUMENTS + ")");
this.WriteSemiColon();
this.WriteNewLine();
this.WriteNewLine();
this.Outdent();
if (this.Emitter.AsyncBlock.MethodDeclaration != null &&
!this.Emitter.AsyncBlock.MethodDeclaration.HasModifier(Modifiers.Async))
{
this.Write("return ");
}
this.Write(JS.Funcs.ASYNC_BODY + "();");
if (this.IsTaskReturn)
{
this.WriteNewLine();
this.Write("return " + JS.Vars.ASYNC_TCS + "." + JS.Fields.ASYNC_TASK + ";");
}
this.WriteNewLine();
this.EndBlock();
}
protected void EmitAsyncBody()
{
this.BeginBlock();
var asyncTryVisitor = new AsyncTryVisitor();
this.Node.AcceptChildren(asyncTryVisitor);
var needTry = asyncTryVisitor.Found || this.IsTaskReturn;
this.Emitter.AsyncVariables.Add(JS.Vars.ASYNC_JUMP);
if (needTry)
{
if (this.IsTaskReturn)
{
this.Emitter.AsyncVariables.Add(JS.Vars.ASYNC_TCS + " = new " + JS.Types.TASK_COMPLETION_SOURCE + "()");
}
this.Emitter.AsyncVariables.Add(JS.Vars.ASYNC_RETURN_VALUE);
this.Write("try");
this.WriteSpace();
this.BeginBlock();
}
this.Write("for (;;) ");
this.BeginBlock();
this.WriteIndent();
int checkerPos = this.Emitter.Output.Length;
this.WriteNewLine();
this.Write("switch (" + JS.Vars.ASYNC_STEP + ") ");
this.BeginBlock();
this.Step = 0;
var writer = this.SaveWriter();
this.AddAsyncStep();
if (this.Body.Parent is LambdaExpression && this.Body is Expression && this.IsTaskReturn && this.ReturnType.FullName == "System.Threading.Tasks.Task" && this.ReturnType.TypeParameterCount > 0)
{
new ReturnBlock(this.Emitter, (Expression)this.Body).Emit();
}
else
{
var level = this.Emitter.InitialLevel;
((Emitter) this.Emitter).InitialLevel = 0;
this.Emitter.ResetLevel();
this.Body.AcceptVisitor(this.Emitter);
((Emitter)this.Emitter).InitialLevel = level;
}
this.RestoreWriter(writer);
this.InjectSteps();
this.WriteNewLine();
this.EndBlock();
this.InjectStepsChecker(checkerPos);
this.WriteNewLine();
this.EndBlock();
if (needTry)
{
if (!this.Emitter.Locals.ContainsKey(JS.Vars.ASYNC_E))
{
this.AddLocal(JS.Vars.ASYNC_E, null, AstType.Null);
}
this.WriteNewLine();
this.EndBlock();
this.Write(" catch(" + JS.Vars.ASYNC_E1 + ") ");
this.BeginBlock();
this.Write(JS.Vars.ASYNC_E + " = " + JS.Types.System.Exception.CREATE + "(" + JS.Vars.ASYNC_E1 + ");");
this.WriteNewLine();
this.InjectCatchHandlers();
this.WriteNewLine();
this.EndBlock();
}
this.WriteNewLine();
this.EndBlock();
}
protected void InjectStepsChecker(int pos)
{
var list = new List<int>();
for (int i = 0; i < this.Steps.Count; i++)
{
var step = this.Steps[i];
if (string.IsNullOrWhiteSpace(this.RemoveTokens(step.Output.ToString())) && step.JumpToStep == (i + 1) && step.FromTaskNumber < 0)
{
continue;
}
list.Add(i);
}
this.Emitter.Output.Insert(pos, JS.Vars.ASYNC_STEP + " = " + JS.Types.System.Array.MIN + "(" + this.Emitter.ToJavaScript(list.ToArray()) + ", " + JS.Vars.ASYNC_STEP + ");");
}
protected void InjectCatchHandlers()
{
var infos = this.TryInfos;
foreach (var info in infos)
{
if (info.CatchBlocks.Count > 0)
{
this.WriteIf();
this.WriteOpenParentheses(true);
this.Write(string.Format(JS.Vars.ASYNC_STEP + " >= {0} && " + JS.Vars.ASYNC_STEP + " <= {1}", info.StartStep, info.EndStep));
this.WriteCloseParentheses(true);
this.WriteSpace();
this.BeginBlock();
var firstClause = true;
for (int i = 0; i < info.CatchBlocks.Count; i++)
{
var clause = info.CatchBlocks[i];
var varName = clause.Item1;
var exceptionType = clause.Item2;
var step = clause.Item3;
var isBaseException = exceptionType == JS.Types.System.Exception.NAME;
if (info.CatchBlocks.Count == 1 && isBaseException)
{
if (!string.IsNullOrEmpty(varName))
{
this.Write(varName + " = " + JS.Vars.ASYNC_E + ";");
this.WriteNewLine();
}
this.Write(JS.Vars.ASYNC_STEP + " = " + step + ";");
this.WriteNewLine();
this.Write(JS.Funcs.ASYNC_BODY + "();");
this.WriteNewLine();
this.Write("return;");
}
else
{
if (!firstClause)
{
this.WriteSpace();
this.WriteElse();
}
if (!isBaseException)
{
this.WriteIf();
this.WriteOpenParentheses();
this.Write(JS.Types.Bridge.IS + "(" + JS.Vars.ASYNC_E + ", " + exceptionType + ")");
this.WriteCloseParentheses();
this.WriteSpace();
}
firstClause = false;
this.BeginBlock();
if (!string.IsNullOrEmpty(varName))
{
this.Write(varName + " = " + JS.Vars.ASYNC_E + ";");
this.WriteNewLine();
}
this.Write(JS.Vars.ASYNC_STEP + " = " + step + ";");
this.WriteNewLine();
this.Write(JS.Funcs.ASYNC_BODY + "();");
this.WriteNewLine();
this.Write("return;");
this.WriteNewLine();
this.EndBlock();
}
}
this.WriteNewLine();
this.EndBlock();
this.WriteNewLine();
}
if (info.FinallyStep > 0)
{
if (!this.Emitter.Locals.ContainsKey(JS.Vars.ASYNC_E))
{
this.AddLocal(JS.Vars.ASYNC_E, null, AstType.Null);
}
this.WriteIf();
this.WriteOpenParentheses();
this.Write(string.Format(JS.Vars.ASYNC_STEP + " >= {0} && " + JS.Vars.ASYNC_STEP + " <= {1}", info.StartStep, info.CatchBlocks.Count > 0 ? info.CatchBlocks.Last().Item4 : info.EndStep));
this.WriteCloseParentheses();
this.WriteSpace();
this.BeginBlock();
//this.Write(Variables.E + " = " + Variables.ASYNC_E + ";");
//this.WriteNewLine();
this.Write(JS.Vars.ASYNC_STEP + " = " + info.FinallyStep + ";");
this.WriteNewLine();
this.Write(JS.Funcs.ASYNC_BODY + "();");
this.WriteNewLine();
this.Write("return;");
this.WriteNewLine();
this.EndBlock();
this.WriteNewLine();
}
}
if (this.IsTaskReturn)
{
this.Write(JS.Vars.ASYNC_TCS + "." + JS.Funcs.SET_EXCEPTION + "(" + JS.Vars.ASYNC_E + ");");
}
else
{
this.Write("throw " + JS.Vars.ASYNC_E + ";");
}
}
protected void InjectSteps()
{
foreach (var label in this.JumpLabels)
{
var tostep = this.Steps.First(s => s.Node == label.Node);
label.Output.Replace(Helpers.PrefixDollar("{", label.Node.GetHashCode(), "}"), tostep.Step.ToString());
}
for (int i = 0; i < this.Steps.Count; i++)
{
var step = this.Steps[i];
if (i != 0)
{
this.WriteNewLine();
}
var output = step.Output.ToString();
var cleanOutput = this.RemoveTokens(output);
if (string.IsNullOrWhiteSpace(cleanOutput) && step.JumpToStep == (i + 1) && step.FromTaskNumber < 0)
{
continue;
}
this.Write("case " + i + ": ");
this.BeginBlock();
bool addNewLine = false;
if (step.FromTaskNumber > -1)
{
var expression = (Expression)this.AwaitExpressions[step.FromTaskNumber - 1];
if (this.IsTaskResult(expression))
{
this.Write(string.Format("{0}{1} = {2}{1}.{3}();", JS.Vars.ASYNC_TASK_RESULT, step.FromTaskNumber, JS.Vars.ASYNC_TASK, JS.Funcs.GET_AWAITED_RESULT));
}
else
{
this.Write(string.Format("{0}{1}.{2}();", JS.Vars.ASYNC_TASK, step.FromTaskNumber, JS.Funcs.GET_AWAITED_RESULT));
}
addNewLine = true;
}
if (!string.IsNullOrWhiteSpace(cleanOutput))
{
if (addNewLine)
{
this.WriteNewLine();
}
this.Write(this.WriteIndentToString(output.TrimEnd()));
}
if (!this.IsOnlyWhitespaceOnPenultimateLine(false))
{
addNewLine = true;
}
if (step.JumpToStep > -1 && !AbstractEmitterBlock.IsJumpStatementLast(cleanOutput))
{
if (addNewLine)
{
this.WriteNewLine();
}
this.Write(JS.Vars.ASYNC_STEP + " = " + step.JumpToStep + ";");
this.WriteNewLine();
this.Write("continue;");
}
else if (step.JumpToNode != null && !AbstractEmitterBlock.IsJumpStatementLast(cleanOutput))
{
var tostep = this.Steps.First(s => s.Node == step.JumpToNode);
if (addNewLine)
{
this.WriteNewLine();
}
this.Write(JS.Vars.ASYNC_STEP + " = " + tostep.Step + ";");
this.WriteNewLine();
this.Write("continue;");
}
else if (i == (this.Steps.Count - 1) && !AbstractEmitterBlock.IsReturnLast(cleanOutput))
{
if (addNewLine)
{
this.WriteNewLine();
}
if (this.IsTaskReturn)
{
this.Write(JS.Vars.ASYNC_TCS + "." + JS.Funcs.SET_RESULT + "(null);");
this.WriteNewLine();
}
this.Write("return;");
}
this.WriteNewLine();
this.EndBlock();
}
this.WriteNewLine();
this.Write("default: ");
this.BeginBlock();
if (this.IsTaskReturn)
{
this.Write(JS.Vars.ASYNC_TCS + "." + JS.Funcs.SET_RESULT + "(null);");
this.WriteNewLine();
}
this.Write("return;");
this.WriteNewLine();
this.EndBlock();
}
public IAsyncStep AddAsyncStep(int fromTaskNumber = -1)
{
var step = this.Step++;
var asyncStep = new AsyncStep(this.Emitter, step, fromTaskNumber);
this.Steps.Add(asyncStep);
return asyncStep;
}
public IAsyncStep AddAsyncStep(AstNode node)
{
var asyncStep = this.AddAsyncStep();
asyncStep.Node = node;
return asyncStep;
}
public bool IsParentForAsync(AstNode child)
{
if (child is IfElseStatement)
{
return false;
}
else
{
foreach (var awaiter in this.AwaitExpressions)
{
if (child.IsInside(awaiter.StartLocation))
{
return true;
}
}
}
return false;
}
public static bool HasGoto(AstNode node)
{
var visitor = new GotoSearchVisitor();
node.AcceptVisitor(visitor);
return visitor.Found;
}
}
public class AsyncStep : IAsyncStep
{
public AsyncStep(IEmitter emitter, int step, int fromTaskNumber)
{
this.Step = step;
this.Emitter = emitter;
this.JumpToStep = -1;
this.FromTaskNumber = -1;
if (this.Emitter.LastSavedWriter != null)
{
this.Emitter.LastSavedWriter.Comma = this.Emitter.Comma;
this.Emitter.LastSavedWriter.IsNewLine = this.Emitter.IsNewLine;
this.Emitter.LastSavedWriter.Level = this.Emitter.Level;
this.Emitter.LastSavedWriter = null;
}
this.Output = new StringBuilder();
this.Emitter.Output = this.Output;
this.Emitter.IsNewLine = false;
this.Emitter.ResetLevel();
this.Emitter.Comma = false;
this.FromTaskNumber = fromTaskNumber;
}
public int FromTaskNumber
{
get;
set;
}
public int JumpToStep
{
get;
set;
}
public AstNode JumpToNode
{
get;
set;
}
public AstNode Node
{
get;
set;
}
public int Step
{
get;
set;
}
protected IEmitter Emitter
{
get;
set;
}
public StringBuilder Output
{
get;
set;
}
public object Label
{
get; set;
}
}
public class AsyncJumpLabel : IAsyncJumpLabel
{
public StringBuilder Output
{
get;
set;
}
public AstNode Node
{
get;
set;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Orleans.CodeGeneration;
using Orleans.Serialization;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.Serialization
{
/// <summary>
/// Summary description for SerializationTests
/// </summary>
[Collection(TestEnvironmentFixture.DefaultCollection)]
public class SerializationTestsDifferentTypes
{
private readonly TestEnvironmentFixture fixture;
public SerializationTestsDifferentTypes(TestEnvironmentFixture fixture)
{
this.fixture = fixture;
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_DateTime()
{
// Local Kind
DateTime inputLocal = DateTime.Now;
DateTime outputLocal = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputLocal);
Assert.Equal(inputLocal.ToString(CultureInfo.InvariantCulture), outputLocal.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputLocal.Kind, outputLocal.Kind);
// UTC Kind
DateTime inputUtc = DateTime.UtcNow;
DateTime outputUtc = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUtc);
Assert.Equal(inputUtc.ToString(CultureInfo.InvariantCulture), outputUtc.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUtc.Kind, outputUtc.Kind);
// Unspecified Kind
DateTime inputUnspecified = new DateTime(0x08d27e2c0cc7dfb9);
DateTime outputUnspecified = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUnspecified);
Assert.Equal(inputUnspecified.ToString(CultureInfo.InvariantCulture), outputUnspecified.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUnspecified.Kind, outputUnspecified.Kind);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_DateTimeOffset()
{
// Local Kind
DateTime inputLocalDateTime = DateTime.Now;
DateTimeOffset inputLocal = new DateTimeOffset(inputLocalDateTime);
DateTimeOffset outputLocal = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputLocal);
Assert.Equal(inputLocal, outputLocal);
Assert.Equal(
inputLocal.ToString(CultureInfo.InvariantCulture),
outputLocal.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputLocal.DateTime.Kind, outputLocal.DateTime.Kind);
// UTC Kind
DateTime inputUtcDateTime = DateTime.UtcNow;
DateTimeOffset inputUtc = new DateTimeOffset(inputUtcDateTime);
DateTimeOffset outputUtc = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUtc);
Assert.Equal(inputUtc, outputUtc);
Assert.Equal(
inputUtc.ToString(CultureInfo.InvariantCulture),
outputUtc.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUtc.DateTime.Kind, outputUtc.DateTime.Kind);
// Unspecified Kind
DateTime inputUnspecifiedDateTime = new DateTime(0x08d27e2c0cc7dfb9);
DateTimeOffset inputUnspecified = new DateTimeOffset(inputUnspecifiedDateTime);
DateTimeOffset outputUnspecified = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUnspecified);
Assert.Equal(inputUnspecified, outputUnspecified);
Assert.Equal(
inputUnspecified.ToString(CultureInfo.InvariantCulture),
outputUnspecified.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUnspecified.DateTime.Kind, outputUnspecified.DateTime.Kind);
}
[Serializer(typeof(TestTypeA))]
internal class TestTypeASerialization
{
[CopierMethod]
public static object DeepCopier(object original, ICopyContext context)
{
TestTypeA input = (TestTypeA)original;
TestTypeA result = new TestTypeA();
context.RecordCopy(original, result);
result.Collection = (ICollection<TestTypeA>)SerializationManager.DeepCopyInner(input.Collection, context);
return result;
}
[SerializerMethod]
public static void Serializer(object untypedInput, ISerializationContext context, Type expected)
{
TestTypeA input = (TestTypeA)untypedInput;
SerializationManager.SerializeInner(input.Collection, context, typeof(ICollection<TestTypeA>));
}
[DeserializerMethod]
public static object Deserializer(Type expected, IDeserializationContext context)
{
TestTypeA result = new TestTypeA();
context.RecordObject(result);
result.Collection = (ICollection<TestTypeA>)SerializationManager.DeserializeInner(typeof(ICollection<TestTypeA>), context);
return result;
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_RecursiveSerialization()
{
TestTypeA input = new TestTypeA();
input.Collection = new HashSet<TestTypeA>();
input.Collection.Add(input);
TestTypeA output1 = Orleans.TestingHost.Utils.TestingUtils.RoundTripDotNetSerializer(input, this.fixture.GrainFactory, this.fixture.SerializationManager);
TestTypeA output2 = this.fixture.SerializationManager.RoundTripSerializationForTesting(input);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_CultureInfo()
{
var input = new List<CultureInfo> { CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de") };
foreach (var cultureInfo in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(cultureInfo);
Assert.Equal(cultureInfo, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_CultureInfoList()
{
var input = new List<CultureInfo> { CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de") };
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(input);
Assert.True(input.SequenceEqual(output));
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple()
{
var input = new List<ValueTuple<int>> { ValueTuple.Create(1), ValueTuple.Create(100) };
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple2()
{
var input = new List<ValueTuple<int, int>> { ValueTuple.Create(1, 2), ValueTuple.Create(100, 200) };
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple3()
{
var input = new List<ValueTuple<int, int, int>>
{
ValueTuple.Create(1, 2, 3),
ValueTuple.Create(100, 200, 300)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple4()
{
var input = new List<ValueTuple<int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4),
ValueTuple.Create(100, 200, 300, 400)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple5()
{
var input = new List<ValueTuple<int, int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4, 5),
ValueTuple.Create(100, 200, 300, 400, 500)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple6()
{
var input = new List<ValueTuple<int, int, int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4, 5, 6),
ValueTuple.Create(100, 200, 300, 400, 500, 600)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple7()
{
var input = new List<ValueTuple<int, int, int, int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4, 5, 6, 7),
ValueTuple.Create(100, 200, 300, 400, 500, 600, 700)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Functional"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple8()
{
var valueTuple = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, 8);
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
namespace Microsoft.AzureStack.Management
{
public static partial class GalleryItemOperationsExtensions
{
/// <summary>
/// Creates or updates the Gallery Item
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <param name='parameters'>
/// Required. Gallery item Upload parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse CreateOrUpdate(this IGalleryItemOperations operations, GalleryItemCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGalleryItemOperations)s).CreateOrUpdateAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates the Gallery Item
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <param name='parameters'>
/// Required. Gallery item Upload parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateOrUpdateAsync(this IGalleryItemOperations operations, GalleryItemCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Gallery item Delete operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <param name='galleryItemId'>
/// Required. Gallery item identity.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IGalleryItemOperations operations, string galleryItemId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGalleryItemOperations)s).DeleteAsync(galleryItemId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gallery item Delete operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <param name='galleryItemId'>
/// Required. Gallery item identity.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IGalleryItemOperations operations, string galleryItemId)
{
return operations.DeleteAsync(galleryItemId, CancellationToken.None);
}
/// <summary>
/// Gallery item Get operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <param name='galleryItemId'>
/// Required. Gallery item identity.
/// </param>
/// <returns>
/// Gallery item Get operation result.
/// </returns>
public static GalleryItemGetResult Get(this IGalleryItemOperations operations, string galleryItemId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGalleryItemOperations)s).GetAsync(galleryItemId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gallery item Get operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <param name='galleryItemId'>
/// Required. Gallery item identity.
/// </param>
/// <returns>
/// Gallery item Get operation result.
/// </returns>
public static Task<GalleryItemGetResult> GetAsync(this IGalleryItemOperations operations, string galleryItemId)
{
return operations.GetAsync(galleryItemId, CancellationToken.None);
}
/// <summary>
/// Gallery items List operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <returns>
/// Gallery item List operation result.
/// </returns>
public static GalleryItemListResult List(this IGalleryItemOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGalleryItemOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gallery items List operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <returns>
/// Gallery item List operation result.
/// </returns>
public static Task<GalleryItemListResult> ListAsync(this IGalleryItemOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// Gallery items List operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <param name='nextLink'>
/// Required. Gets or sets the URL to get the next set of results.
/// </param>
/// <returns>
/// Gallery item List operation result.
/// </returns>
public static GalleryItemListResult ListNext(this IGalleryItemOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGalleryItemOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gallery items List operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IGalleryItemOperations.
/// </param>
/// <param name='nextLink'>
/// Required. Gets or sets the URL to get the next set of results.
/// </param>
/// <returns>
/// Gallery item List operation result.
/// </returns>
public static Task<GalleryItemListResult> ListNextAsync(this IGalleryItemOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddUInt32()
{
var test = new SimpleBinaryOpTest__AddUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddUInt32
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[ElementCount];
private static UInt32[] _data2 = new UInt32[ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32> _dataTable;
static SimpleBinaryOpTest__AddUInt32()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AddUInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32>(_data1, _data2, new UInt32[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Add(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Add(
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Add(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr);
var result = Avx2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddUInt32();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[ElementCount];
UInt32[] inArray2 = new UInt32[ElementCount];
UInt32[] outArray = new UInt32[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[ElementCount];
UInt32[] inArray2 = new UInt32[ElementCount];
UInt32[] outArray = new UInt32[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
if ((uint)(left[0] + right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((uint)(left[i] + right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Add)}<UInt32>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Gem.Network.Shooter.Client.Level
{
using Camera;
using Scene;
public class TileMap
{
#region Declarations
public int TileWidth;
public int TileHeight;
int MapWidth;
int MapHeight;
MapSquare[,] mapCells;
Texture2D tileSheet;
CameraManager Camera;
EffectsManager effectsManager;
#endregion
#region Instance
static TileMap tileMap;
public static TileMap GetInstance()
{
if (tileMap == null)
tileMap = new TileMap();
return tileMap;
}
private TileMap()
{
Camera = CameraManager.GetInstance();
effectsManager = EffectsManager.GetInstance();
}
#endregion
#region Initialization
public void Initialize(Texture2D tileTexture, int tileWidth, int tileHeight)
{
tileSheet = tileTexture;
this.TileWidth = tileWidth;
this.TileHeight = tileHeight;
}
#endregion
#region Randomize Map
//TODO: update randomize algorithm
public void Randomize(int mapWidth, int mapHeight)
{
this.MapWidth = mapWidth;
this.MapHeight = mapHeight;
Random rand = new Random();
mapCells = new MapSquare[MapWidth, MapHeight];
for (int x = 0; x < MapWidth; x++)
{
for (int y = 0; y < MapHeight; y++)
{
if ((y >= 10 || x==0 || x==MapWidth-1))
{
mapCells[x, y] = new MapSquare(rand.Next(1, 4), false, " ");
}
else
{
mapCells[x, y] = new MapSquare();
}
}
}
}
#endregion
#region Tile and Tile Sheet Handling
public int TilesPerRow
{
get { return tileSheet.Width / TileWidth; }
}
public Rectangle TileSourceRectangle(int tileIndex)
{
return new Rectangle(
0,0,
TileWidth,
TileHeight);
}
#endregion
#region Information about Map Cells
public int GetCellByPixelX(int pixelX)
{
return pixelX / TileWidth;
}
public int GetCellByPixelY(int pixelY)
{
return pixelY / TileHeight;
}
public Vector2 GetCellByPixel(Vector2 pixelLocation)
{
return new Vector2(
GetCellByPixelX((int)pixelLocation.X),
GetCellByPixelY((int)pixelLocation.Y));
}
public Vector2 GetCellCenter(int cellX, int cellY)
{
return new Vector2(
(cellX * TileWidth) + (TileWidth / 2),
(cellY * TileHeight) + (TileHeight / 2));
}
public Vector2 GetCellCenter(Vector2 cell)
{
return GetCellCenter(
(int)cell.X,
(int)cell.Y);
}
public Rectangle CellWorldRectangle(int cellX, int cellY)
{
return new Rectangle(
cellX * TileWidth,
cellY * TileHeight,
TileWidth,
TileHeight);
}
public Rectangle MapToScreenRectangle(int cellX, int cellY)
{
return new Rectangle(
cellX * TileWidth / 4 + (int)Camera.Position.X,
cellY * TileHeight / 4 + (int)Camera.Position.Y,
TileWidth / 4,
TileHeight / 4);
}
public Rectangle CellWorldRectangle(Vector2 cell)
{
return CellWorldRectangle(
(int)cell.X,
(int)cell.Y);
}
public Rectangle CellScreenRectangle(int cellX, int cellY)
{
return Camera.WorldToScreen(CellWorldRectangle(cellX, cellY));
}
public Rectangle CellSreenRectangle(Vector2 cell)
{
return CellScreenRectangle((int)cell.X, (int)cell.Y);
}
public bool CellIsPassable(int cellX, int cellY)
{
MapSquare square = GetMapSquareAtCell(cellX, cellY);
if (square == null)
return false;
else
return square.Passable;
}
public bool CellIsPassable(Vector2 cell)
{
return CellIsPassable((int)cell.X, (int)cell.Y);
}
public bool CellIsPassableByPixel(Vector2 pixelLocation)
{
return CellIsPassable(
GetCellByPixelX((int)pixelLocation.X),
GetCellByPixelY((int)pixelLocation.Y));
}
public string CellCodeValue(int cellX, int cellY)
{
MapSquare square = GetMapSquareAtCell(cellX, cellY);
if (square == null)
return "";
else
return square.CodeValue;
}
public string CellCodeValue(Vector2 cell)
{
return CellCodeValue((int)cell.X, (int)cell.Y);
}
#endregion
#region Information about MapSquare objects
public MapSquare GetMapSquareAtCell(int tileX, int tileY)
{
if ((tileX >= 0) && (tileX < MapWidth) &&
(tileY >= 0) && (tileY < MapHeight))
{
return mapCells[tileX, tileY];
}
else
{
return null;
}
}
public void SetMapSquareAtCell(
int tileX,
int tileY,
MapSquare tile)
{
if ((tileX >= 0) && (tileX < MapWidth) &&
(tileY >= 0) && (tileY < MapHeight))
{
mapCells[tileX, tileY] = tile;
}
}
public void SetTileAtCell(
int tileX,
int tileY,
int tileIndex)
{
if ((tileX >= 0) && (tileX < MapWidth) &&
(tileY >= 0) && (tileY < MapHeight))
{
mapCells[tileX, tileY].LayerTile = tileIndex;
}
}
public MapSquare GetMapSquareAtPixel(int pixelX, int pixelY)
{
return GetMapSquareAtCell(
GetCellByPixelX(pixelX),
GetCellByPixelY(pixelY));
}
public MapSquare GetMapSquareAtPixel(Vector2 pixelLocation)
{
return GetMapSquareAtPixel(
(int)pixelLocation.X,
(int)pixelLocation.Y);
}
public Vector2 GetCellLocation(Vector2 cell)
{
return new Vector2(cell.X * TileWidth, cell.Y * TileHeight);
}
#endregion
#region Draw
private readonly Color Ground = new Color(175, 108, 66);
private readonly Color GroundDark = new Color(138, 85, 52);
private readonly Color Sky = new Color(71, 196, 241);
private Color GetColorById(int id)
{
if (id == 0) return Sky;
if (id == 3) return GroundDark;
else return Ground;
}
public void Draw(SpriteBatch spriteBatch)
{
int startX = GetCellByPixelX((int)Camera.Position.X);
int endX = GetCellByPixelX((int)Camera.Position.X + Camera.ViewPortWidth);
int startY = GetCellByPixelY((int)Camera.Position.Y);
int endY = GetCellByPixelY((int)Camera.Position.Y + Camera.ViewPortHeight);
for (int x = startX; x <= endX; x++)
for (int y = startY; y <= endY; y++)
{
if ((x >= 0) && (y >= 0) &&
(x < MapWidth) && (y < MapHeight))
{
spriteBatch.Draw(tileSheet, CellScreenRectangle(x, y), TileSourceRectangle(mapCells[x, y].LayerTile),
GetColorById(mapCells[x, y].LayerTile), 0.0f, Vector2.Zero, SpriteEffects.None, 1.0f);
}
}
}
#endregion
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
///
/// First published in XenServer 4.1.
/// </summary>
public partial class Bond : XenObject<Bond>
{
public Bond()
{
}
public Bond(string uuid,
XenRef<PIF> master,
List<XenRef<PIF>> slaves,
Dictionary<string, string> other_config,
XenRef<PIF> primary_slave,
bond_mode mode,
Dictionary<string, string> properties,
long links_up)
{
this.uuid = uuid;
this.master = master;
this.slaves = slaves;
this.other_config = other_config;
this.primary_slave = primary_slave;
this.mode = mode;
this.properties = properties;
this.links_up = links_up;
}
/// <summary>
/// Creates a new Bond from a Proxy_Bond.
/// </summary>
/// <param name="proxy"></param>
public Bond(Proxy_Bond proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Bond update)
{
uuid = update.uuid;
master = update.master;
slaves = update.slaves;
other_config = update.other_config;
primary_slave = update.primary_slave;
mode = update.mode;
properties = update.properties;
links_up = update.links_up;
}
internal void UpdateFromProxy(Proxy_Bond proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
master = proxy.master == null ? null : XenRef<PIF>.Create(proxy.master);
slaves = proxy.slaves == null ? null : XenRef<PIF>.Create(proxy.slaves);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
primary_slave = proxy.primary_slave == null ? null : XenRef<PIF>.Create(proxy.primary_slave);
mode = proxy.mode == null ? (bond_mode) 0 : (bond_mode)Helper.EnumParseDefault(typeof(bond_mode), (string)proxy.mode);
properties = proxy.properties == null ? null : Maps.convert_from_proxy_string_string(proxy.properties);
links_up = proxy.links_up == null ? 0 : long.Parse((string)proxy.links_up);
}
public Proxy_Bond ToProxy()
{
Proxy_Bond result_ = new Proxy_Bond();
result_.uuid = (uuid != null) ? uuid : "";
result_.master = (master != null) ? master : "";
result_.slaves = (slaves != null) ? Helper.RefListToStringArray(slaves) : new string[] {};
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.primary_slave = (primary_slave != null) ? primary_slave : "";
result_.mode = bond_mode_helper.ToString(mode);
result_.properties = Maps.convert_to_proxy_string_string(properties);
result_.links_up = links_up.ToString();
return result_;
}
/// <summary>
/// Creates a new Bond from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Bond(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
master = Marshalling.ParseRef<PIF>(table, "master");
slaves = Marshalling.ParseSetRef<PIF>(table, "slaves");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
primary_slave = Marshalling.ParseRef<PIF>(table, "primary_slave");
mode = (bond_mode)Helper.EnumParseDefault(typeof(bond_mode), Marshalling.ParseString(table, "mode"));
properties = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "properties"));
links_up = Marshalling.ParseLong(table, "links_up");
}
public bool DeepEquals(Bond other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._master, other._master) &&
Helper.AreEqual2(this._slaves, other._slaves) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._primary_slave, other._primary_slave) &&
Helper.AreEqual2(this._mode, other._mode) &&
Helper.AreEqual2(this._properties, other._properties) &&
Helper.AreEqual2(this._links_up, other._links_up);
}
public override string SaveChanges(Session session, string opaqueRef, Bond server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Bond.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given Bond.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static Bond get_record(Session session, string _bond)
{
return new Bond((Proxy_Bond)session.proxy.bond_get_record(session.uuid, (_bond != null) ? _bond : "").parse());
}
/// <summary>
/// Get a reference to the Bond instance with the specified UUID.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Bond> get_by_uuid(Session session, string _uuid)
{
return XenRef<Bond>.Create(session.proxy.bond_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get the uuid field of the given Bond.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static string get_uuid(Session session, string _bond)
{
return (string)session.proxy.bond_get_uuid(session.uuid, (_bond != null) ? _bond : "").parse();
}
/// <summary>
/// Get the master field of the given Bond.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static XenRef<PIF> get_master(Session session, string _bond)
{
return XenRef<PIF>.Create(session.proxy.bond_get_master(session.uuid, (_bond != null) ? _bond : "").parse());
}
/// <summary>
/// Get the slaves field of the given Bond.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static List<XenRef<PIF>> get_slaves(Session session, string _bond)
{
return XenRef<PIF>.Create(session.proxy.bond_get_slaves(session.uuid, (_bond != null) ? _bond : "").parse());
}
/// <summary>
/// Get the other_config field of the given Bond.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static Dictionary<string, string> get_other_config(Session session, string _bond)
{
return Maps.convert_from_proxy_string_string(session.proxy.bond_get_other_config(session.uuid, (_bond != null) ? _bond : "").parse());
}
/// <summary>
/// Get the primary_slave field of the given Bond.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static XenRef<PIF> get_primary_slave(Session session, string _bond)
{
return XenRef<PIF>.Create(session.proxy.bond_get_primary_slave(session.uuid, (_bond != null) ? _bond : "").parse());
}
/// <summary>
/// Get the mode field of the given Bond.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static bond_mode get_mode(Session session, string _bond)
{
return (bond_mode)Helper.EnumParseDefault(typeof(bond_mode), (string)session.proxy.bond_get_mode(session.uuid, (_bond != null) ? _bond : "").parse());
}
/// <summary>
/// Get the properties field of the given Bond.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static Dictionary<string, string> get_properties(Session session, string _bond)
{
return Maps.convert_from_proxy_string_string(session.proxy.bond_get_properties(session.uuid, (_bond != null) ? _bond : "").parse());
}
/// <summary>
/// Get the links_up field of the given Bond.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static long get_links_up(Session session, string _bond)
{
return long.Parse((string)session.proxy.bond_get_links_up(session.uuid, (_bond != null) ? _bond : "").parse());
}
/// <summary>
/// Set the other_config field of the given Bond.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _bond, Dictionary<string, string> _other_config)
{
session.proxy.bond_set_other_config(session.uuid, (_bond != null) ? _bond : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given Bond.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _bond, string _key, string _value)
{
session.proxy.bond_add_to_other_config(session.uuid, (_bond != null) ? _bond : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given Bond. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _bond, string _key)
{
session.proxy.bond_remove_from_other_config(session.uuid, (_bond != null) ? _bond : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Create an interface bond
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">Network to add the bonded PIF to</param>
/// <param name="_members">PIFs to add to this bond</param>
/// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param>
public static XenRef<Bond> create(Session session, string _network, List<XenRef<PIF>> _members, string _mac)
{
return XenRef<Bond>.Create(session.proxy.bond_create(session.uuid, (_network != null) ? _network : "", (_members != null) ? Helper.RefListToStringArray(_members) : new string[] {}, (_mac != null) ? _mac : "").parse());
}
/// <summary>
/// Create an interface bond
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">Network to add the bonded PIF to</param>
/// <param name="_members">PIFs to add to this bond</param>
/// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param>
public static XenRef<Task> async_create(Session session, string _network, List<XenRef<PIF>> _members, string _mac)
{
return XenRef<Task>.Create(session.proxy.async_bond_create(session.uuid, (_network != null) ? _network : "", (_members != null) ? Helper.RefListToStringArray(_members) : new string[] {}, (_mac != null) ? _mac : "").parse());
}
/// <summary>
/// Create an interface bond
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">Network to add the bonded PIF to</param>
/// <param name="_members">PIFs to add to this bond</param>
/// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param>
/// <param name="_mode">Bonding mode to use for the new bond First published in XenServer 6.0.</param>
public static XenRef<Bond> create(Session session, string _network, List<XenRef<PIF>> _members, string _mac, bond_mode _mode)
{
return XenRef<Bond>.Create(session.proxy.bond_create(session.uuid, (_network != null) ? _network : "", (_members != null) ? Helper.RefListToStringArray(_members) : new string[] {}, (_mac != null) ? _mac : "", bond_mode_helper.ToString(_mode)).parse());
}
/// <summary>
/// Create an interface bond
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">Network to add the bonded PIF to</param>
/// <param name="_members">PIFs to add to this bond</param>
/// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param>
/// <param name="_mode">Bonding mode to use for the new bond First published in XenServer 6.0.</param>
public static XenRef<Task> async_create(Session session, string _network, List<XenRef<PIF>> _members, string _mac, bond_mode _mode)
{
return XenRef<Task>.Create(session.proxy.async_bond_create(session.uuid, (_network != null) ? _network : "", (_members != null) ? Helper.RefListToStringArray(_members) : new string[] {}, (_mac != null) ? _mac : "", bond_mode_helper.ToString(_mode)).parse());
}
/// <summary>
/// Create an interface bond
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">Network to add the bonded PIF to</param>
/// <param name="_members">PIFs to add to this bond</param>
/// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param>
/// <param name="_mode">Bonding mode to use for the new bond First published in XenServer 6.0.</param>
/// <param name="_properties">Additional configuration parameters specific to the bond mode First published in XenServer 6.1.</param>
public static XenRef<Bond> create(Session session, string _network, List<XenRef<PIF>> _members, string _mac, bond_mode _mode, Dictionary<string, string> _properties)
{
return XenRef<Bond>.Create(session.proxy.bond_create(session.uuid, (_network != null) ? _network : "", (_members != null) ? Helper.RefListToStringArray(_members) : new string[] {}, (_mac != null) ? _mac : "", bond_mode_helper.ToString(_mode), Maps.convert_to_proxy_string_string(_properties)).parse());
}
/// <summary>
/// Create an interface bond
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">Network to add the bonded PIF to</param>
/// <param name="_members">PIFs to add to this bond</param>
/// <param name="_mac">The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave.</param>
/// <param name="_mode">Bonding mode to use for the new bond First published in XenServer 6.0.</param>
/// <param name="_properties">Additional configuration parameters specific to the bond mode First published in XenServer 6.1.</param>
public static XenRef<Task> async_create(Session session, string _network, List<XenRef<PIF>> _members, string _mac, bond_mode _mode, Dictionary<string, string> _properties)
{
return XenRef<Task>.Create(session.proxy.async_bond_create(session.uuid, (_network != null) ? _network : "", (_members != null) ? Helper.RefListToStringArray(_members) : new string[] {}, (_mac != null) ? _mac : "", bond_mode_helper.ToString(_mode), Maps.convert_to_proxy_string_string(_properties)).parse());
}
/// <summary>
/// Destroy an interface bond
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static void destroy(Session session, string _bond)
{
session.proxy.bond_destroy(session.uuid, (_bond != null) ? _bond : "").parse();
}
/// <summary>
/// Destroy an interface bond
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
public static XenRef<Task> async_destroy(Session session, string _bond)
{
return XenRef<Task>.Create(session.proxy.async_bond_destroy(session.uuid, (_bond != null) ? _bond : "").parse());
}
/// <summary>
/// Change the bond mode
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
/// <param name="_value">The new bond mode</param>
public static void set_mode(Session session, string _bond, bond_mode _value)
{
session.proxy.bond_set_mode(session.uuid, (_bond != null) ? _bond : "", bond_mode_helper.ToString(_value)).parse();
}
/// <summary>
/// Change the bond mode
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
/// <param name="_value">The new bond mode</param>
public static XenRef<Task> async_set_mode(Session session, string _bond, bond_mode _value)
{
return XenRef<Task>.Create(session.proxy.async_bond_set_mode(session.uuid, (_bond != null) ? _bond : "", bond_mode_helper.ToString(_value)).parse());
}
/// <summary>
/// Set the value of a property of the bond
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
/// <param name="_name">The property name</param>
/// <param name="_value">The property value</param>
public static void set_property(Session session, string _bond, string _name, string _value)
{
session.proxy.bond_set_property(session.uuid, (_bond != null) ? _bond : "", (_name != null) ? _name : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Set the value of a property of the bond
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_bond">The opaque_ref of the given bond</param>
/// <param name="_name">The property name</param>
/// <param name="_value">The property value</param>
public static XenRef<Task> async_set_property(Session session, string _bond, string _name, string _value)
{
return XenRef<Task>.Create(session.proxy.async_bond_set_property(session.uuid, (_bond != null) ? _bond : "", (_name != null) ? _name : "", (_value != null) ? _value : "").parse());
}
/// <summary>
/// Return a list of all the Bonds known to the system.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Bond>> get_all(Session session)
{
return XenRef<Bond>.Create(session.proxy.bond_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the Bond Records at once, in a single XML RPC call
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Bond>, Bond> get_all_records(Session session)
{
return XenRef<Bond>.Create<Proxy_Bond>(session.proxy.bond_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// The bonded interface
/// </summary>
public virtual XenRef<PIF> master
{
get { return _master; }
set
{
if (!Helper.AreEqual(value, _master))
{
_master = value;
Changed = true;
NotifyPropertyChanged("master");
}
}
}
private XenRef<PIF> _master;
/// <summary>
/// The interfaces which are part of this bond
/// </summary>
public virtual List<XenRef<PIF>> slaves
{
get { return _slaves; }
set
{
if (!Helper.AreEqual(value, _slaves))
{
_slaves = value;
Changed = true;
NotifyPropertyChanged("slaves");
}
}
}
private List<XenRef<PIF>> _slaves;
/// <summary>
/// additional configuration
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
/// <summary>
/// The PIF of which the IP configuration and MAC were copied to the bond, and which will receive all configuration/VLANs/VIFs on the bond if the bond is destroyed
/// First published in XenServer 6.0.
/// </summary>
public virtual XenRef<PIF> primary_slave
{
get { return _primary_slave; }
set
{
if (!Helper.AreEqual(value, _primary_slave))
{
_primary_slave = value;
Changed = true;
NotifyPropertyChanged("primary_slave");
}
}
}
private XenRef<PIF> _primary_slave;
/// <summary>
/// The algorithm used to distribute traffic among the bonded NICs
/// First published in XenServer 6.0.
/// </summary>
public virtual bond_mode mode
{
get { return _mode; }
set
{
if (!Helper.AreEqual(value, _mode))
{
_mode = value;
Changed = true;
NotifyPropertyChanged("mode");
}
}
}
private bond_mode _mode;
/// <summary>
/// Additional configuration properties specific to the bond mode.
/// First published in XenServer 6.1.
/// </summary>
public virtual Dictionary<string, string> properties
{
get { return _properties; }
set
{
if (!Helper.AreEqual(value, _properties))
{
_properties = value;
Changed = true;
NotifyPropertyChanged("properties");
}
}
}
private Dictionary<string, string> _properties;
/// <summary>
/// Number of links up in this bond
/// First published in XenServer 6.1.
/// </summary>
public virtual long links_up
{
get { return _links_up; }
set
{
if (!Helper.AreEqual(value, _links_up))
{
_links_up = value;
Changed = true;
NotifyPropertyChanged("links_up");
}
}
}
private long _links_up;
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
using System.Drawing.Design;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
namespace InnovatorAdmin.Controls
{
/// <summary>
/// Summary description for FlatTabControl.
/// </summary>
[ToolboxBitmap(typeof(System.Windows.Forms.TabControl))] //,
//Designer(typeof(Designers.FlatTabControlDesigner))]
public class FlatTabControl : System.Windows.Forms.TabControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private SubClass scUpDown = null;
private bool bUpDown; // true when the button UpDown is required
private ImageList leftRightImages = null;
private const int nMargin = 5;
private Color mBackColor = SystemColors.Control;
private bool _tabsVisible;
public FlatTabControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// double buffering
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
bUpDown = false;
this.ControlAdded += new ControlEventHandler(FlatTabControl_ControlAdded);
this.ControlRemoved += new ControlEventHandler(FlatTabControl_ControlRemoved);
this.SelectedIndexChanged += new EventHandler(FlatTabControl_SelectedIndexChanged);
leftRightImages = new ImageList();
//leftRightImages.ImageSize = new Size(16, 16); // default
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FlatTabControl));
Bitmap updownImage = ((System.Drawing.Bitmap)(resources.GetObject("TabIcons.bmp")));
if (updownImage != null)
{
updownImage.MakeTransparent(Color.White);
leftRightImages.Images.AddStrip(updownImage);
}
this.DrawBorder = false;
this.myBackColor = System.Drawing.Color.White;
}
[DefaultValue(true)]
public bool DrawBorder { get; set; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool TabsVisible
{
get { return _tabsVisible; }
set
{
_tabsVisible = value;
if (_tabsVisible)
{
this.ItemSize = Size.Empty;
this.SizeMode = TabSizeMode.Normal;
}
else
{
this.ItemSize = new Size(0, 1);
this.SizeMode = TabSizeMode.Fixed;
}
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
leftRightImages.Dispose();
}
base.Dispose( disposing );
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawControl(e.Graphics);
}
internal void DrawControl(Graphics g)
{
if (!Visible)
return;
Rectangle TabControlArea = this.ClientRectangle;
Rectangle TabArea = this.DisplayRectangle;
//----------------------------
// fill client area
Brush br = new SolidBrush(mBackColor); //(SystemColors.Control); UPDATED
g.FillRectangle(br, TabControlArea);
br.Dispose();
//----------------------------
//----------------------------
// draw border
if (this.DrawBorder)
{
int nDelta = SystemInformation.Border3DSize.Width;
using (var border = new Pen(SystemColors.ControlDark))
{
TabArea.Inflate(nDelta, nDelta);
g.DrawRectangle(border, TabArea);
}
}
//----------------------------
//----------------------------
// clip region for drawing tabs
Region rsaved = g.Clip;
Rectangle rreg;
int nWidth = TabArea.Width + nMargin;
if (bUpDown)
{
// exclude updown control for painting
if (Win32.IsWindowVisible(scUpDown.Handle))
{
Rectangle rupdown = new Rectangle();
Win32.GetWindowRect(scUpDown.Handle, ref rupdown);
Rectangle rupdown2 = this.RectangleToClient(rupdown);
nWidth = rupdown2.X;
}
}
rreg = new Rectangle(TabArea.Left, TabControlArea.Top, nWidth - nMargin, TabControlArea.Height);
g.SetClip(rreg);
// draw tabs
if (this.ItemSize.Height > 1)
{
for (int i = 0; i < this.TabCount; i++)
DrawTab(g, this.TabPages[i], i);
}
g.Clip = rsaved;
//----------------------------
//----------------------------
// draw background to cover flat border areas
if (this.SelectedTab != null)
{
TabPage tabPage = this.SelectedTab;
Color color = tabPage.BackColor;
using (var border = new Pen(color))
{
TabArea.Offset(1, 1);
TabArea.Width -= 2;
TabArea.Height -= 2;
g.DrawRectangle(border, TabArea);
TabArea.Width -= 1;
TabArea.Height -= 1;
g.DrawRectangle(border, TabArea);
}
}
//----------------------------
}
internal void DrawTab(Graphics g, TabPage tabPage, int nIndex)
{
Rectangle recBounds = this.GetTabRect(nIndex);
RectangleF tabTextArea = (RectangleF)this.GetTabRect(nIndex);
bool bSelected = (this.SelectedIndex == nIndex);
Point[] pt = new Point[7];
if (this.Alignment == TabAlignment.Top)
{
pt[0] = new Point(recBounds.Left, recBounds.Bottom);
pt[1] = new Point(recBounds.Left, recBounds.Top + 3);
pt[2] = new Point(recBounds.Left + 3, recBounds.Top);
pt[3] = new Point(recBounds.Right - 3, recBounds.Top);
pt[4] = new Point(recBounds.Right, recBounds.Top + 3);
pt[5] = new Point(recBounds.Right, recBounds.Bottom);
pt[6] = new Point(recBounds.Left, recBounds.Bottom);
}
else
{
pt[0] = new Point(recBounds.Left, recBounds.Top);
pt[1] = new Point(recBounds.Right, recBounds.Top);
pt[2] = new Point(recBounds.Right, recBounds.Bottom - 3);
pt[3] = new Point(recBounds.Right - 3, recBounds.Bottom);
pt[4] = new Point(recBounds.Left + 3, recBounds.Bottom);
pt[5] = new Point(recBounds.Left, recBounds.Bottom - 3);
pt[6] = new Point(recBounds.Left, recBounds.Top);
}
//----------------------------
// fill this tab with background color
using (var br = new SolidBrush(myBackColor))
{
g.FillPolygon(br, pt);
}
//----------------------------
//----------------------------
// draw border
//g.DrawPolygon(SystemPens.ControlDark, pt);
if (bSelected)
{
using (var pen = new Pen(Color.FromArgb(204, 0, 51), 3))
{
g.DrawLine(pen, recBounds.Left, recBounds.Bottom, recBounds.Right, recBounds.Bottom);
}
}
else
{
using (var pen = new Pen(Color.FromArgb(91, 104, 113), 1))
{
g.DrawLine(pen, recBounds.Left, recBounds.Bottom, recBounds.Right, recBounds.Bottom);
}
}
//if (bSelected)
//{
// //----------------------------
// // clear bottom lines
// var color = tabPage.BackColor;
// if (color == Color.Transparent || color == Color.Empty)
// color = this.myBackColor;
// using (var pen = new Pen(color))
// {
// switch (this.Alignment)
// {
// case TabAlignment.Top:
// g.DrawLine(pen, recBounds.Left + 1, recBounds.Bottom, recBounds.Right - 1, recBounds.Bottom);
// g.DrawLine(pen, recBounds.Left + 1, recBounds.Bottom + 1, recBounds.Right - 1, recBounds.Bottom + 1);
// break;
// case TabAlignment.Bottom:
// g.DrawLine(pen, recBounds.Left + 1, recBounds.Top, recBounds.Right - 1, recBounds.Top);
// g.DrawLine(pen, recBounds.Left + 1, recBounds.Top - 1, recBounds.Right - 1, recBounds.Top - 1);
// g.DrawLine(pen, recBounds.Left + 1, recBounds.Top - 2, recBounds.Right - 1, recBounds.Top - 2);
// break;
// }
// }
// //----------------------------
//}
//----------------------------
//----------------------------
// draw tab's icon
if ((tabPage.ImageIndex >= 0) && (ImageList != null) && (ImageList.Images[tabPage.ImageIndex] != null))
{
int nLeftMargin = 8;
int nRightMargin = 2;
Image img = ImageList.Images[tabPage.ImageIndex];
Rectangle rimage = new Rectangle(recBounds.X + nLeftMargin, recBounds.Y + 1, img.Width, img.Height);
// adjust rectangles
float nAdj = (float)(nLeftMargin + img.Width + nRightMargin);
rimage.Y += (recBounds.Height - img.Height) / 2;
tabTextArea.X += nAdj;
tabTextArea.Width -= nAdj;
// draw icon
g.DrawImage(img, rimage);
}
//----------------------------
//----------------------------
// draw string
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
using (var br = new SolidBrush(tabPage.ForeColor))
{
g.DrawString(tabPage.Text, Font, br, tabTextArea, stringFormat);
}
//----------------------------
}
internal void DrawIcons(Graphics g)
{
if ((leftRightImages == null) || (leftRightImages.Images.Count != 4))
return;
//----------------------------
// calc positions
Rectangle TabControlArea = this.ClientRectangle;
Rectangle r0 = new Rectangle();
Win32.GetClientRect(scUpDown.Handle, ref r0);
Brush br = new SolidBrush(SystemColors.Control);
g.FillRectangle(br, r0);
br.Dispose();
Pen border = new Pen(SystemColors.ControlDark);
Rectangle rborder = r0;
rborder.Inflate(-1, -1);
g.DrawRectangle(border, rborder);
border.Dispose();
int nMiddle = (r0.Width / 2);
int nTop = (r0.Height - 16) / 2;
int nLeft = (nMiddle - 16) / 2;
Rectangle r1 = new Rectangle(nLeft, nTop, 16, 16);
Rectangle r2 = new Rectangle(nMiddle+nLeft, nTop, 16, 16);
//----------------------------
//----------------------------
// draw buttons
Image img = leftRightImages.Images[1];
if (img != null)
{
if (this.TabCount > 0)
{
Rectangle r3 = this.GetTabRect(0);
if (r3.Left < TabControlArea.Left)
g.DrawImage(img, r1);
else
{
img = leftRightImages.Images[3];
if (img != null)
g.DrawImage(img, r1);
}
}
}
img = leftRightImages.Images[0];
if (img != null)
{
if (this.TabCount > 0)
{
Rectangle r3 = this.GetTabRect(this.TabCount - 1);
if (r3.Right > (TabControlArea.Width - r0.Width))
g.DrawImage(img, r2);
else
{
img = leftRightImages.Images[2];
if (img != null)
g.DrawImage(img, r2);
}
}
}
//----------------------------
}
protected override void OnCreateControl()
{
base.OnCreateControl();
FindUpDown();
}
private void FlatTabControl_ControlAdded(object sender, ControlEventArgs e)
{
FindUpDown();
UpdateUpDown();
}
private void FlatTabControl_ControlRemoved(object sender, ControlEventArgs e)
{
FindUpDown();
UpdateUpDown();
}
private void FlatTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateUpDown();
Invalidate(); // we need to update border and background colors
}
private void FindUpDown()
{
bool bFound = false;
// find the UpDown control
IntPtr pWnd = Win32.GetWindow(this.Handle, Win32.GW_CHILD);
while (pWnd != IntPtr.Zero)
{
//----------------------------
// Get the window class name
char[] className = new char[33];
int length = Win32.GetClassName(pWnd, className, 32);
string s = new string(className, 0, length);
//----------------------------
if (s == "msctls_updown32")
{
bFound = true;
if (!bUpDown)
{
//----------------------------
// Subclass it
this.scUpDown = new SubClass(pWnd, true);
this.scUpDown.SubClassedWndProc += new SubClass.SubClassWndProcEventHandler(scUpDown_SubClassedWndProc);
//----------------------------
bUpDown = true;
}
break;
}
pWnd = Win32.GetWindow(pWnd, Win32.GW_HWNDNEXT);
}
if ((!bFound) && (bUpDown))
bUpDown = false;
}
private void UpdateUpDown()
{
if (bUpDown)
{
if (Win32.IsWindowVisible(scUpDown.Handle))
{
Rectangle rect = new Rectangle();
Win32.GetClientRect(scUpDown.Handle, ref rect);
Win32.InvalidateRect(scUpDown.Handle, ref rect, true);
}
}
}
#region scUpDown_SubClassedWndProc Event Handler
private int scUpDown_SubClassedWndProc(ref Message m)
{
switch (m.Msg)
{
case Win32.WM_PAINT:
{
//------------------------
// redraw
IntPtr hDC = Win32.GetWindowDC(scUpDown.Handle);
Graphics g = Graphics.FromHdc(hDC);
DrawIcons(g);
g.Dispose();
Win32.ReleaseDC(scUpDown.Handle, hDC);
//------------------------
// return 0 (processed)
m.Result = IntPtr.Zero;
//------------------------
// validate current rect
Rectangle rect = new Rectangle();
Win32.GetClientRect(scUpDown.Handle, ref rect);
Win32.ValidateRect(scUpDown.Handle, ref rect);
//------------------------
}
return 1;
}
return 0;
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
#region Properties
//[Editor(typeof(TabpageExCollectionEditor), typeof(UITypeEditor))]
public new TabPageCollection TabPages
{
get
{
return base.TabPages;
}
}
new public TabAlignment Alignment
{
get {return base.Alignment;}
set {
TabAlignment ta = value;
if ((ta != TabAlignment.Top) && (ta != TabAlignment.Bottom))
ta = TabAlignment.Top;
base.Alignment = ta;}
}
[Browsable(false)]
new public bool Multiline
{
get {return base.Multiline;}
set {base.Multiline = false;}
}
[Browsable(true)]
new public Color myBackColor
{
get {return mBackColor;}
set {mBackColor = value; this.Invalidate();}
}
#endregion
//#region TabpageExCollectionEditor
//internal class TabpageExCollectionEditor : CollectionEditor
//{
// public TabpageExCollectionEditor(System.Type type): base(type)
// {
// }
// protected override Type CreateCollectionItemType()
// {
// return typeof(TabPage);
// }
//}
//#endregion
}
//#endregion
}
| |
using Prism.Windows.Navigation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Windows.ApplicationModel.Resources;
using Windows.Security.Cryptography.DataProtection;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
namespace Prism.Windows.AppModel
{
/// <summary>
/// SessionStateService captures global session state to simplify process lifetime management
/// for an application. Note that session state will be automatically cleared under a variety
/// of conditions and should only be used to store information that would be convenient to
/// carry across sessions, but that should be discarded when an application crashes or is
/// upgraded.
/// </summary>
public class SessionStateService : ISessionStateService
{
private Dictionary<string, object> _sessionState = new Dictionary<string, object>();
private List<Type> _knownTypes = new List<Type>();
/// <summary>
/// Provides access to global session state for the current session. This state is
/// serialized by <see cref="SaveAsync"/> and restored by
/// <see cref="RestoreSessionStateAsync"/>, so values must be serializable by
/// <see cref="DataContractSerializer"/> and should be as compact as possible. Strings
/// and other self-contained data types are strongly recommended.
/// </summary>
public Dictionary<string, object> SessionState
{
get { return _sessionState; }
}
/// <summary>
/// Adds a type to the list of custom types provided to the <see cref="DataContractSerializer"/> when
/// reading and writing session state. Initially empty, additional types may be
/// added to customize the serialization process.
/// </summary>
public void RegisterKnownType(Type type)
{
_knownTypes.Add(type);
}
/// <summary>
/// Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances
/// registered with <see cref="RegisterFrame"/> will also preserve their current
/// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
/// to save its state.
/// </summary>
/// <returns>An asynchronous task that reflects when session state has been saved.</returns>
public async Task SaveAsync()
{
try
{
// Save the navigation state for all registered frames
foreach (var weakFrameReference in _registeredFrames)
{
IFrameFacade frame;
if (weakFrameReference.TryGetTarget(out frame))
{
SaveFrameNavigationState(frame);
}
}
// Serialize the session state synchronously to avoid asynchronous access to shared
// state
MemoryStream sessionData = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
serializer.WriteObject(sessionData, _sessionState);
// Get an output stream for the SessionState file and write the state asynchronously
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(Constants.SessionStateFileName, CreationCollisionOption.ReplaceExisting);
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
sessionData.Seek(0, SeekOrigin.Begin);
var provider = new DataProtectionProvider("LOCAL=user");
// Encrypt the session data and write it to disk.
await provider.ProtectStreamAsync(sessionData.AsInputStream(), fileStream);
await fileStream.FlushAsync();
}
}
catch (Exception e)
{
throw new SessionStateServiceException(e);
}
}
/// <summary>
/// Restores previously saved <see cref="SessionState"/>.
/// </summary>
/// <returns>An asynchronous task that reflects when session state has been read. The
/// content of <see cref="SessionState"/> should not be relied upon until this task
/// completes.</returns>
public async Task RestoreSessionStateAsync()
{
_sessionState = new Dictionary<String, Object>();
try
{
// Get the input stream for the SessionState file
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(Constants.SessionStateFileName);
using (IInputStream inStream = await file.OpenSequentialReadAsync())
{
var memoryStream = new MemoryStream();
var provider = new DataProtectionProvider("LOCAL=user");
// Decrypt the prevously saved session data.
await provider.UnprotectStreamAsync(inStream, memoryStream.AsOutputStream());
memoryStream.Seek(0, SeekOrigin.Begin);
// Deserialize the Session State
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>),
_knownTypes);
_sessionState = (Dictionary<string, object>)serializer.ReadObject(memoryStream);
}
}
catch (Exception e)
{
throw new SessionStateServiceException(e);
}
}
/// <summary>
/// Any <see cref="Frame"/> instances registered with <see cref="RegisterFrame"/> will
/// restore their prior navigation state, which in turn gives their active <see cref="Page"/>
/// an opportunity restore its state.
///
/// This method requires that RestoreSessionStateAsync be called prior to this method.
/// </summary>
public void RestoreFrameState()
{
try
{
// Restore any registered frames to their saved state
foreach (var weakFrameReference in _registeredFrames)
{
IFrameFacade frame;
if (weakFrameReference.TryGetTarget(out frame))
{
frame.ClearValue(FrameSessionStateProperty);
RestoreFrameNavigationState(frame);
}
}
}
catch (Exception e)
{
throw new SessionStateServiceException(e);
}
}
private static DependencyProperty FrameSessionStateKeyProperty =
DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SessionStateService), null);
private static DependencyProperty FrameSessionStateProperty =
DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary<String, Object>), typeof(SessionStateService), null);
private static List<WeakReference<IFrameFacade>> _registeredFrames = new List<WeakReference<IFrameFacade>>();
/// <summary>
/// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
/// and restored from <see cref="SessionState"/>. Frames should be registered once
/// immediately after creation if they will participate in session state management. Upon
/// registration, if state has already been restored for the specified key,
/// the navigation history will immediately be restored. Subsequent invocations of
/// <see cref="RestoreFrameState"/> will also restore navigation history.
/// </summary>
/// <param name="frame">An instance whose navigation history should be managed by
/// <see cref="SessionStateServiceException"/></param>
/// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
/// store navigation-related information.</param>
public void RegisterFrame(IFrameFacade frame, String sessionStateKey)
{
if (frame == null) throw new ArgumentNullException("frame");
var resourceLoader = ResourceLoader.GetForCurrentView(Constants.InfrastructureResourceMapId);
if (frame.GetValue(FrameSessionStateKeyProperty) != null)
{
var errorString = resourceLoader.GetString("FrameAlreadyRegisteredWithKey");
throw new InvalidOperationException(errorString);
}
if (frame.GetValue(FrameSessionStateProperty) != null)
{
var errorString = resourceLoader.GetString("FrameRegistrationRequirement");
throw new InvalidOperationException(errorString);
}
// Use a dependency property to associate the session key with a frame, and keep a list of frames whose
// navigation state should be managed
frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey);
_registeredFrames.Add(new WeakReference<IFrameFacade>(frame));
// Check to see if navigation state can be restored
RestoreFrameNavigationState(frame);
}
/// <summary>
/// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
/// from <see cref="SessionState"/>. Any navigation state previously captured will be
/// removed.
/// </summary>
/// <param name="frame">An instance whose navigation history should no longer be
/// managed.</param>
public void UnregisterFrame(IFrameFacade frame)
{
// Remove session state and remove the frame from the list of frames whose navigation
// state will be saved (along with any weak references that are no longer reachable)
SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty));
_registeredFrames.RemoveAll((weakFrameReference) =>
{
IFrameFacade testFrame;
return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame;
});
}
/// <summary>
/// Provides storage for session state associated with the specified <see cref="Frame"/>.
/// Frames that have been previously registered with <see cref="RegisterFrame"/> have
/// their session state saved and restored automatically as a part of the global
/// <see cref="SessionState"/>. Frames that are not registered have transient state
/// that can still be useful when restoring pages that have been discarded from the
/// navigation cache.
/// </summary>
/// <remarks>Apps may choose to rely on <see cref="VisualStateAwarePage"/> to manage
/// page-specific state instead of working with Frame session state directly.</remarks>
/// <param name="frame">The instance for which session state is desired.</param>
/// <returns>A collection of state, subject to the same serialization mechanism as
/// <see cref="SessionState"/>.</returns>
public Dictionary<String, Object> GetSessionStateForFrame(IFrameFacade frame)
{
if (frame == null) throw new ArgumentNullException("frame");
var frameState = (Dictionary<String, Object>)frame.GetValue(FrameSessionStateProperty);
if (frameState == null)
{
var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty);
if (frameSessionKey != null)
{
// Registered frames reflect the corresponding session state
if (!_sessionState.ContainsKey(frameSessionKey))
{
_sessionState[frameSessionKey] = new Dictionary<String, Object>();
}
frameState = (Dictionary<String, Object>)_sessionState[frameSessionKey];
}
else
{
// Frames that aren't registered have transient state
frameState = new Dictionary<String, Object>();
}
frame.SetValue(FrameSessionStateProperty, frameState);
}
return frameState;
}
private void RestoreFrameNavigationState(IFrameFacade frame)
{
var frameState = GetSessionStateForFrame(frame);
if (frameState.ContainsKey("Navigation"))
{
frame.SetNavigationState((String)frameState["Navigation"]);
}
}
private void SaveFrameNavigationState(IFrameFacade frame)
{
var frameState = GetSessionStateForFrame(frame);
frameState["Navigation"] = frame.GetNavigationState();
}
}
/// <summary>
/// The exception that is thrown when a session state service error is detected.
/// </summary>
public class SessionStateServiceException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="SessionStateServiceException"/> class.
/// </summary>
public SessionStateServiceException() : base((ResourceLoader.GetForCurrentView(Constants.InfrastructureResourceMapId)).GetString("SessionStateServiceFailed"))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SessionStateServiceException"/> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public SessionStateServiceException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SessionStateServiceException"/> class.
/// </summary>
/// <param name="exception">The exception.</param>
public SessionStateServiceException(Exception exception)
: base((ResourceLoader.GetForCurrentView(Constants.InfrastructureResourceMapId)).GetString("SessionStateServiceFailed"), exception)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SessionStateServiceException"/> class.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The inner exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
public SessionStateServiceException(string message, Exception innerException):base(message, innerException)
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// Public type to communicate multiple failures to an end-user.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Threading;
namespace System
{
/// <summary>Represents one or more errors that occur during application execution.</summary>
/// <remarks>
/// <see cref="AggregateException"/> is used to consolidate multiple failures into a single, throwable
/// exception object.
/// </remarks>
[Serializable]
[DebuggerDisplay("Count = {InnerExceptionCount}")]
public class AggregateException : Exception
{
private ReadOnlyCollection<Exception> m_innerExceptions; // Complete set of exceptions.
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class.
/// </summary>
public AggregateException()
: base(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"))
{
m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]);
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with
/// a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public AggregateException(string message)
: base(message)
{
m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]);
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
/// message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerException"/> argument
/// is null.</exception>
public AggregateException(string message, Exception innerException)
: base(message, innerException)
{
if (innerException == null)
{
throw new ArgumentNullException("innerException");
}
m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[] { innerException });
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with
/// references to the inner exceptions that are the cause of this exception.
/// </summary>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(IEnumerable<Exception> innerExceptions) :
this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with
/// references to the inner exceptions that are the cause of this exception.
/// </summary>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(params Exception[] innerExceptions) :
this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
/// message and references to the inner exceptions that are the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(string message, IEnumerable<Exception> innerExceptions)
// If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along
// null typed correctly. Otherwise, create an IList from the enumerable and pass that along.
: this(message, innerExceptions as IList<Exception> ?? (innerExceptions == null ? (List<Exception>)null : new List<Exception>(innerExceptions)))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
/// message and references to the inner exceptions that are the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(string message, params Exception[] innerExceptions) :
this(message, (IList<Exception>)innerExceptions)
{
}
/// <summary>
/// Allocates a new aggregate exception with the specified message and list of inner exceptions.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
private AggregateException(string message, IList<Exception> innerExceptions)
: base(message, innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null)
{
if (innerExceptions == null)
{
throw new ArgumentNullException("innerExceptions");
}
// Copy exceptions to our internal array and validate them. We must copy them,
// because we're going to put them into a ReadOnlyCollection which simply reuses
// the list passed in to it. We don't want callers subsequently mutating.
Exception[] exceptionsCopy = new Exception[innerExceptions.Count];
for (int i = 0; i < exceptionsCopy.Length; i++)
{
exceptionsCopy[i] = innerExceptions[i];
if (exceptionsCopy[i] == null)
{
throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull"));
}
}
m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy);
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with
/// references to the inner exception dispatch info objects that represent the cause of this exception.
/// </summary>
/// <param name="innerExceptionInfos">
/// Information about the exceptions that are the cause of the current exception.
/// </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is
/// null.</exception>
internal AggregateException(IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) :
this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptionInfos)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
/// message and references to the inner exception dispatch info objects that represent the cause of
/// this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptionInfos">
/// Information about the exceptions that are the cause of the current exception.
/// </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is
/// null.</exception>
internal AggregateException(string message, IEnumerable<ExceptionDispatchInfo> innerExceptionInfos)
// If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along
// null typed correctly. Otherwise, create an IList from the enumerable and pass that along.
: this(message, innerExceptionInfos as IList<ExceptionDispatchInfo> ??
(innerExceptionInfos == null ?
(List<ExceptionDispatchInfo>)null :
new List<ExceptionDispatchInfo>(innerExceptionInfos)))
{
}
/// <summary>
/// Allocates a new aggregate exception with the specified message and list of inner
/// exception dispatch info objects.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptionInfos">
/// Information about the exceptions that are the cause of the current exception.
/// </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is
/// null.</exception>
private AggregateException(string message, IList<ExceptionDispatchInfo> innerExceptionInfos)
: base(message, innerExceptionInfos != null && innerExceptionInfos.Count > 0 && innerExceptionInfos[0] != null ?
innerExceptionInfos[0].SourceException : null)
{
if (innerExceptionInfos == null)
{
throw new ArgumentNullException("innerExceptionInfos");
}
// Copy exceptions to our internal array and validate them. We must copy them,
// because we're going to put them into a ReadOnlyCollection which simply reuses
// the list passed in to it. We don't want callers subsequently mutating.
Exception[] exceptionsCopy = new Exception[innerExceptionInfos.Count];
for (int i = 0; i < exceptionsCopy.Length; i++)
{
var edi = innerExceptionInfos[i];
if (edi != null) exceptionsCopy[i] = edi.SourceException;
if (exceptionsCopy[i] == null)
{
throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull"));
}
}
m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy);
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds
/// the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that
/// contains contextual information about the source or destination. </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The exception could not be deserialized correctly.</exception>
[SecurityCritical]
protected AggregateException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[];
if (innerExceptions == null)
{
throw new SerializationException(Environment.GetResourceString("AggregateException_DeserializationFailure"));
}
m_innerExceptions = new ReadOnlyCollection<Exception>(innerExceptions);
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about
/// the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds
/// the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that
/// contains contextual information about the source or destination. </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
[SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
base.GetObjectData(info, context);
Exception[] innerExceptions = new Exception[m_innerExceptions.Count];
m_innerExceptions.CopyTo(innerExceptions, 0);
info.AddValue("InnerExceptions", innerExceptions, typeof(Exception[]));
}
/// <summary>
/// Returns the <see cref="System.AggregateException"/> that is the root cause of this exception.
/// </summary>
public override Exception GetBaseException()
{
// Returns the first inner AggregateException that contains more or less than one inner exception
// Recursively traverse the inner exceptions as long as the inner exception of type AggregateException and has only one inner exception
Exception back = this;
AggregateException backAsAggregate = this;
while (backAsAggregate != null && backAsAggregate.InnerExceptions.Count == 1)
{
back = back.InnerException;
backAsAggregate = back as AggregateException;
}
return back;
}
/// <summary>
/// Gets a read-only collection of the <see cref="T:System.Exception"/> instances that caused the
/// current exception.
/// </summary>
public ReadOnlyCollection<Exception> InnerExceptions
{
get { return m_innerExceptions; }
}
/// <summary>
/// Invokes a handler on each <see cref="T:System.Exception"/> contained by this <see
/// cref="AggregateException"/>.
/// </summary>
/// <param name="predicate">The predicate to execute for each exception. The predicate accepts as an
/// argument the <see cref="T:System.Exception"/> to be processed and returns a Boolean to indicate
/// whether the exception was handled.</param>
/// <remarks>
/// Each invocation of the <paramref name="predicate"/> returns true or false to indicate whether the
/// <see cref="T:System.Exception"/> was handled. After all invocations, if any exceptions went
/// unhandled, all unhandled exceptions will be put into a new <see cref="AggregateException"/>
/// which will be thrown. Otherwise, the <see cref="Handle"/> method simply returns. If any
/// invocations of the <paramref name="predicate"/> throws an exception, it will halt the processing
/// of any more exceptions and immediately propagate the thrown exception as-is.
/// </remarks>
/// <exception cref="AggregateException">An exception contained by this <see
/// cref="AggregateException"/> was not handled.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="predicate"/> argument is
/// null.</exception>
public void Handle(Func<Exception, bool> predicate)
{
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
List<Exception> unhandledExceptions = null;
for (int i = 0; i < m_innerExceptions.Count; i++)
{
// If the exception was not handled, lazily allocate a list of unhandled
// exceptions (to be rethrown later) and add it.
if (!predicate(m_innerExceptions[i]))
{
if (unhandledExceptions == null)
{
unhandledExceptions = new List<Exception>();
}
unhandledExceptions.Add(m_innerExceptions[i]);
}
}
// If there are unhandled exceptions remaining, throw them.
if (unhandledExceptions != null)
{
throw new AggregateException(Message, unhandledExceptions);
}
}
/// <summary>
/// Flattens an <see cref="AggregateException"/> instances into a single, new instance.
/// </summary>
/// <returns>A new, flattened <see cref="AggregateException"/>.</returns>
/// <remarks>
/// If any inner exceptions are themselves instances of
/// <see cref="AggregateException"/>, this method will recursively flatten all of them. The
/// inner exceptions returned in the new <see cref="AggregateException"/>
/// will be the union of all of the the inner exceptions from exception tree rooted at the provided
/// <see cref="AggregateException"/> instance.
/// </remarks>
public AggregateException Flatten()
{
// Initialize a collection to contain the flattened exceptions.
List<Exception> flattenedExceptions = new List<Exception>();
// Create a list to remember all aggregates to be flattened, this will be accessed like a FIFO queue
List<AggregateException> exceptionsToFlatten = new List<AggregateException>();
exceptionsToFlatten.Add(this);
int nDequeueIndex = 0;
// Continue removing and recursively flattening exceptions, until there are no more.
while (exceptionsToFlatten.Count > nDequeueIndex)
{
// dequeue one from exceptionsToFlatten
IList<Exception> currentInnerExceptions = exceptionsToFlatten[nDequeueIndex++].InnerExceptions;
for (int i = 0; i < currentInnerExceptions.Count; i++)
{
Exception currentInnerException = currentInnerExceptions[i];
if (currentInnerException == null)
{
continue;
}
AggregateException currentInnerAsAggregate = currentInnerException as AggregateException;
// If this exception is an aggregate, keep it around for later. Otherwise,
// simply add it to the list of flattened exceptions to be returned.
if (currentInnerAsAggregate != null)
{
exceptionsToFlatten.Add(currentInnerAsAggregate);
}
else
{
flattenedExceptions.Add(currentInnerException);
}
}
}
return new AggregateException(Message, flattenedExceptions);
}
/// <summary>Gets a message that describes the exception.</summary>
public override string Message
{
get
{
if (m_innerExceptions.Count == 0)
{
return base.Message;
}
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(base.Message);
sb.Append(' ');
for (int i = 0; i < m_innerExceptions.Count; i++)
{
sb.Append('(');
sb.Append(m_innerExceptions[i].Message);
sb.Append(") ");
}
sb.Length -= 1;
return StringBuilderCache.GetStringAndRelease(sb);
}
}
/// <summary>
/// Creates and returns a string representation of the current <see cref="AggregateException"/>.
/// </summary>
/// <returns>A string representation of the current exception.</returns>
public override string ToString()
{
string text = base.ToString();
for (int i = 0; i < m_innerExceptions.Count; i++)
{
text = String.Format(
CultureInfo.InvariantCulture,
Environment.GetResourceString("AggregateException_ToString"),
text, Environment.NewLine, i, m_innerExceptions[i].ToString(), "<---", Environment.NewLine);
}
return text;
}
/// <summary>
/// This helper property is used by the DebuggerDisplay.
///
/// Note that we don't want to remove this property and change the debugger display to {InnerExceptions.Count}
/// because DebuggerDisplay should be a single property access or parameterless method call, so that the debugger
/// can use a fast path without using the expression evaluator.
///
/// See http://msdn.microsoft.com/en-us/library/x810d419.aspx
/// </summary>
private int InnerExceptionCount
{
get
{
return InnerExceptions.Count;
}
}
}
}
| |
//
// InternetAddressList.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
#if ENABLE_SNM
using System.Net.Mail;
#endif
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A list of email addresses.
/// </summary>
/// <remarks>
/// <para>An <see cref="InternetAddressList"/> may contain any number of addresses of any type
/// defined by the original Internet Message specification.</para>
/// <para>There are effectively two (2) types of addresses: mailboxes and groups.</para>
/// <para>Mailbox addresses are what are most commonly known as email addresses and are
/// represented by the <see cref="MailboxAddress"/> class.</para>
/// <para>Group addresses are themselves lists of addresses and are represented by the
/// <see cref="GroupAddress"/> class. While rare, it is still important to handle these
/// types of addresses. They typically only contain mailbox addresses, but may also
/// contain other group addresses.</para>
/// </remarks>
public class InternetAddressList : IList<InternetAddress>, IEquatable<InternetAddressList>
{
readonly List<InternetAddress> list = new List<InternetAddress> ();
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.InternetAddressList"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="InternetAddressList"/> containing the supplied addresses.
/// </remarks>
/// <param name="addresses">An initial list of addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="addresses"/> is <c>null</c>.
/// </exception>
public InternetAddressList (IEnumerable<InternetAddress> addresses)
{
if (addresses == null)
throw new ArgumentNullException ("addresses");
foreach (var address in addresses) {
address.Changed += AddressChanged;
list.Add (address);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.InternetAddressList"/> class.
/// </summary>
/// <remarks>
/// Creates a new, empty, <see cref="InternetAddressList"/>.
/// </remarks>
public InternetAddressList ()
{
}
/// <summary>
/// Recursively gets all of the mailboxes contained within the <see cref="MimeKit.InternetAddressList"/>.
/// </summary>
/// <remarks>
/// This API is useful for collecting a flattened list of <see cref="MimeKit.MailboxAddress"/>
/// recipients for use with sending via SMTP or for encrypting via S/MIME or PGP/MIME.
/// </remarks>
/// <value>The mailboxes.</value>
public IEnumerable<MailboxAddress> Mailboxes {
get {
foreach (var address in list) {
var group = address as GroupAddress;
if (group != null) {
foreach (var mailbox in group.Members.Mailboxes)
yield return mailbox;
} else {
yield return (MailboxAddress) address;
}
}
yield break;
}
}
#region IList implementation
/// <summary>
/// Gets the index of the specified address.
/// </summary>
/// <remarks>
/// Finds the index of the specified address, if it exists.
/// </remarks>
/// <returns>The index of the specified address if found; otherwise <c>-1</c>.</returns>
/// <param name="address">The address to get the index of.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
public int IndexOf (InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
return list.IndexOf (address);
}
/// <summary>
/// Inserts the address at the specified index.
/// </summary>
/// <remarks>
/// Inserts the address at the specified index in the list.
/// </remarks>
/// <param name="index">The index to insert the address.</param>
/// <param name="address">The address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
public void Insert (int index, InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
address.Changed += AddressChanged;
list.Insert (index, address);
OnChanged ();
}
/// <summary>
/// Removes the address at the specified index.
/// </summary>
/// <remarks>
/// Removes the address at the specified index.
/// </remarks>
/// <param name="index">The index of the address to remove.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
public void RemoveAt (int index)
{
if (index < 0 || index >= list.Count)
throw new ArgumentOutOfRangeException ("index");
list[index].Changed -= AddressChanged;
list.RemoveAt (index);
OnChanged ();
}
/// <summary>
/// Gets or sets the <see cref="MimeKit.InternetAddress"/> at the specified index.
/// </summary>
/// <remarks>
/// Gets or sets the <see cref="MimeKit.InternetAddress"/> at the specified index.
/// </remarks>
/// <value>The internet address at the specified index.</value>
/// <param name="index">The index of the address to get or set.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
public InternetAddress this [int index] {
get { return list[index]; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (list[index] == value)
return;
list[index] = value;
OnChanged ();
}
}
#endregion
#region ICollection implementation
/// <summary>
/// Gets the number of addresses in the <see cref="MimeKit.InternetAddressList"/>.
/// </summary>
/// <remarks>
/// Indicates the number of addresses in the list.
/// </remarks>
/// <value>The number of addresses.</value>
public int Count {
get { return list.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <remarks>
/// A <see cref="InternetAddressList"/> is never read-only.
/// </remarks>
/// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value>
public bool IsReadOnly {
get { return false; }
}
/// <summary>
/// Adds the specified address.
/// </summary>
/// <remarks>
/// Adds the specified address to the end of the address list.
/// </remarks>
/// <param name="address">The address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
public void Add (InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
address.Changed += AddressChanged;
list.Add (address);
OnChanged ();
}
/// <summary>
/// Adds a collection of addresses.
/// </summary>
/// <remarks>
/// Adds a range of addresses to the end of the address list.
/// </remarks>
/// <param name="addresses">A colelction of addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="addresses"/> is <c>null</c>.
/// </exception>
public void AddRange (IEnumerable<InternetAddress> addresses)
{
if (addresses == null)
throw new ArgumentNullException ("addresses");
bool changed = false;
foreach (var address in addresses) {
address.Changed += AddressChanged;
list.Add (address);
changed = true;
}
if (changed)
OnChanged ();
}
/// <summary>
/// Clears the address list.
/// </summary>
/// <remarks>
/// Removes all of the addresses from the list.
/// </remarks>
public void Clear ()
{
if (list.Count == 0)
return;
for (int i = 0; i < list.Count; i++)
list[i].Changed -= AddressChanged;
list.Clear ();
OnChanged ();
}
/// <summary>
/// Checks if the <see cref="MimeKit.InternetAddressList"/> contains the specified address.
/// </summary>
/// <remarks>
/// Determines whether or not the address list contains the specified address.
/// </remarks>
/// <returns><value>true</value> if the specified address exists;
/// otherwise <value>false</value>.</returns>
/// <param name="address">The address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
public bool Contains (InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
return list.Contains (address);
}
/// <summary>
/// Copies all of the addresses in the <see cref="MimeKit.InternetAddressList"/> to the specified array.
/// </summary>
/// <remarks>
/// Copies all of the addresses within the <see cref="InternetAddressList"/> into the array,
/// starting at the specified array index.
/// </remarks>
/// <param name="array">The array to copy the addresses to.</param>
/// <param name="arrayIndex">The index into the array.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="array"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="arrayIndex"/> is out of range.
/// </exception>
public void CopyTo (InternetAddress[] array, int arrayIndex)
{
list.CopyTo (array, arrayIndex);
}
/// <summary>
/// Removes the specified address.
/// </summary>
/// <remarks>
/// Removes the specified address.
/// </remarks>
/// <returns><value>true</value> if the address was removed; otherwise <value>false</value>.</returns>
/// <param name="address">The address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="address"/> is <c>null</c>.
/// </exception>
public bool Remove (InternetAddress address)
{
if (address == null)
throw new ArgumentNullException ("address");
if (list.Remove (address)) {
address.Changed -= AddressChanged;
OnChanged ();
return true;
}
return false;
}
#endregion
#region IEnumerable implementation
/// <summary>
/// Gets an enumerator for the list of addresses.
/// </summary>
/// <remarks>
/// Gets an enumerator for the list of addresses.
/// </remarks>
/// <returns>The enumerator.</returns>
public IEnumerator<InternetAddress> GetEnumerator ()
{
return list.GetEnumerator ();
}
#endregion
#region IEnumerable implementation
/// <summary>
/// Gets an enumerator for the list of addresses.
/// </summary>
/// <remarks>
/// Gets an enumerator for the list of addresses.
/// </remarks>
/// <returns>The enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator ()
{
return list.GetEnumerator ();
}
#endregion
#region IEquatable implementation
/// <summary>
/// Determines whether the specified <see cref="MimeKit.InternetAddressList"/> is equal to the current <see cref="MimeKit.InternetAddressList"/>.
/// </summary>
/// <remarks>
/// Determines whether the specified <see cref="MimeKit.InternetAddressList"/> is equal to the current <see cref="MimeKit.InternetAddressList"/>.
/// </remarks>
/// <param name="other">The <see cref="MimeKit.InternetAddressList"/> to compare with the current <see cref="MimeKit.InternetAddressList"/>.</param>
/// <returns><c>true</c> if the specified <see cref="MimeKit.InternetAddressList"/> is equal to the current
/// <see cref="MimeKit.InternetAddressList"/>; otherwise, <c>false</c>.</returns>
public bool Equals (InternetAddressList other)
{
if (other == null)
return false;
if (other.Count != Count)
return false;
var otherSorted = new List<InternetAddress> (other);
otherSorted.Sort ();
var sorted = new List<InternetAddress> (this);
sorted.Sort ();
for (int i = 0; i < sorted.Count; i++) {
if (!sorted[i].Equals (otherSorted[i]))
return false;
}
return true;
}
#endregion
internal void Encode (FormatOptions options, StringBuilder builder, ref int lineLength)
{
for (int i = 0; i < list.Count; i++) {
if (i > 0)
builder.Append (", ");
list[i].Encode (options, builder, ref lineLength);
}
}
/// <summary>
/// Returns a string representation of the email addresses in the <see cref="InternetAddressList"/>,
/// optionally encoding them for transport.
/// </summary>
/// <remarks>
/// <para>If <paramref name="encode"/> is <c>true</c>, each address in the list will be encoded
/// according to the rules defined in rfc2047.</para>
/// <para>If there are multiple addresses in the list, they will be separated by a comma.</para>
/// </remarks>
/// <returns>A string representing the <see cref="InternetAddressList"/>.</returns>
/// <param name="options">The formatting options.</param>
/// <param name="encode">If set to <c>true</c>, each <see cref="InternetAddress"/> in the list will be encoded.</param>
public string ToString (FormatOptions options, bool encode)
{
var builder = new StringBuilder ();
if (encode) {
int lineLength = 0;
Encode (options, builder, ref lineLength);
return builder.ToString ();
}
for (int i = 0; i < list.Count; i++) {
if (i > 0)
builder.Append (", ");
builder.Append (list[i].ToString ());
}
return builder.ToString ();
}
/// <summary>
/// Returns a string representation of the email addresses in the <see cref="InternetAddressList"/>,
/// optionally encoding them for transport.
/// </summary>
/// <remarks>
/// <para>If <paramref name="encode"/> is <c>true</c>, each address in the list will be encoded
/// according to the rules defined in rfc2047.</para>
/// <para>If there are multiple addresses in the list, they will be separated by a comma.</para>
/// </remarks>
/// <returns>A string representing the <see cref="InternetAddressList"/>.</returns>
/// <param name="encode">If set to <c>true</c>, each <see cref="InternetAddress"/> in the list will be encoded.</param>
public string ToString (bool encode)
{
return ToString (FormatOptions.GetDefault (), encode);
}
/// <summary>
/// Returns a string representation of the email addresses in the <see cref="InternetAddressList"/>.
/// </summary>
/// <remarks>
/// If there are multiple addresses in the list, they will be separated by a comma.
/// </remarks>
/// <returns>A string representing the <see cref="InternetAddressList"/>.</returns>
public override string ToString ()
{
return ToString (FormatOptions.GetDefault (), false);
}
internal event EventHandler Changed;
void OnChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
void AddressChanged (object sender, EventArgs e)
{
OnChanged ();
}
internal static bool TryParse (ParserOptions options, byte[] text, ref int index, int endIndex, bool isGroup, bool throwOnError, out List<InternetAddress> addresses)
{
List<InternetAddress> list = new List<InternetAddress> ();
InternetAddress address;
addresses = null;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index == endIndex) {
if (throwOnError)
throw new ParseException ("No addresses found.", index, index);
return false;
}
while (index < endIndex) {
if (isGroup && text[index] == (byte) ';')
break;
if (!InternetAddress.TryParse (options, text, ref index, endIndex, throwOnError, out address)) {
// skip this address...
while (index < endIndex && text[index] != (byte) ',' && (!isGroup || text[index] != (byte) ';'))
index++;
} else {
list.Add (address);
}
// Note: we loop here in case there are any null addresses between commas
do {
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex || text[index] != (byte) ',')
break;
index++;
} while (true);
}
addresses = list;
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out InternetAddressList addresses)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || length > (buffer.Length - startIndex))
throw new ArgumentOutOfRangeException ("length");
List<InternetAddress> addrlist;
int index = startIndex;
if (!TryParse (options, buffer, ref index, startIndex + length, false, false, out addrlist)) {
addresses = null;
return false;
}
addresses = new InternetAddressList (addrlist);
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, int length, out InternetAddressList addresses)
{
return TryParse (ParserOptions.Default, buffer, startIndex, length, out addresses);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out InternetAddressList addresses)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex >= buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
List<InternetAddress> addrlist;
int index = startIndex;
if (!TryParse (options, buffer, ref index, buffer.Length, false, false, out addrlist)) {
addresses = null;
return false;
}
addresses = new InternetAddressList (addrlist);
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, out InternetAddressList addresses)
{
return TryParse (ParserOptions.Default, buffer, startIndex, out addresses);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the specified buffer.
/// </remarks>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, out InternetAddressList addresses)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
List<InternetAddress> addrlist;
int index = 0;
if (!TryParse (options, buffer, ref index, buffer.Length, false, false, out addrlist)) {
addresses = null;
return false;
}
addresses = new InternetAddressList (addrlist);
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the specified buffer.
/// </remarks>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
public static bool TryParse (byte[] buffer, out InternetAddressList addresses)
{
return TryParse (ParserOptions.Default, buffer, out addresses);
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the specified text.
/// </remarks>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="text">The text.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
public static bool TryParse (ParserOptions options, string text, out InternetAddressList addresses)
{
if (options == null)
throw new ArgumentNullException ("options");
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
List<InternetAddress> addrlist;
int index = 0;
if (!TryParse (options, buffer, ref index, buffer.Length, false, false, out addrlist)) {
addresses = null;
return false;
}
addresses = new InternetAddressList (addrlist);
return true;
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the specified text.
/// </remarks>
/// <returns><c>true</c>, if the address list was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text.</param>
/// <param name="addresses">The parsed addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (string text, out InternetAddressList addresses)
{
return TryParse (ParserOptions.Default, text, out addresses);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (ParserOptions options, byte[] buffer, int startIndex, int length)
{
List<InternetAddress> addrlist;
int index = startIndex;
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || length > (buffer.Length - startIndex))
throw new ArgumentOutOfRangeException ("length");
TryParse (options, buffer, ref index, startIndex + length, false, true, out addrlist);
return new InternetAddressList (addrlist);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (byte[] buffer, int startIndex, int length)
{
return Parse (ParserOptions.Default, buffer, startIndex, length);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/>is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (ParserOptions options, byte[] buffer, int startIndex)
{
List<InternetAddress> addrlist;
int index = startIndex;
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
TryParse (options, buffer, ref index, buffer.Length, false, true, out addrlist);
return new InternetAddressList (addrlist);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (byte[] buffer, int startIndex)
{
return Parse (ParserOptions.Default, buffer, startIndex);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the specified buffer.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (ParserOptions options, byte[] buffer)
{
List<InternetAddress> addrlist;
int index = 0;
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
TryParse (options, buffer, ref index, buffer.Length, false, true, out addrlist);
return new InternetAddressList (addrlist);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the specified buffer.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (byte[] buffer)
{
return Parse (ParserOptions.Default, buffer);
}
/// <summary>
/// Parses the given text into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the specified text.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="text">The text.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="text"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (ParserOptions options, string text)
{
if (options == null)
throw new ArgumentNullException ("options");
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
List<InternetAddress> addrlist;
int index = 0;
TryParse (options, buffer, ref index, buffer.Length, false, true, out addrlist);
return new InternetAddressList (addrlist);
}
/// <summary>
/// Parses the given text into a new <see cref="MimeKit.InternetAddressList"/> instance.
/// </summary>
/// <remarks>
/// Parses a list of addresses from the specified text.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddressList"/>.</returns>
/// <param name="text">The text.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="text"/> could not be parsed.
/// </exception>
public static InternetAddressList Parse (string text)
{
return Parse (ParserOptions.Default, text);
}
#if ENABLE_SNM
/// <summary>
/// Explicit cast to convert a <see cref="InternetAddressList"/> to a
/// <see cref="System.Net.Mail.MailAddressCollection"/>.
/// </summary>
/// <remarks>
/// Casts a <see cref="InternetAddressList"/> to a <see cref="System.Net.Mail.MailAddressCollection"/>
/// in cases where you might want to make use of the System.Net.Mail APIs.
/// </remarks>
/// <returns>The equivalent <see cref="System.Net.Mail.MailAddressCollection"/>.</returns>
/// <param name="addresses">The addresses.</param>
/// <exception cref="System.InvalidCastException">
/// <paramref name="addresses"/> contains one or more group addresses and cannot be converted.
/// </exception>
public static explicit operator MailAddressCollection (InternetAddressList addresses)
{
if (addresses == null)
return null;
var collection = new MailAddressCollection ();
for (int i = 0; i < addresses.Count; i++) {
if (addresses[i] is GroupAddress)
throw new InvalidCastException ("Cannot cast a MailKit.GroupAddress to a System.Net.Mail.MailAddress.");
var mailbox = (MailboxAddress) addresses[i];
collection.Add ((MailAddress) mailbox);
}
return collection;
}
/// <summary>
/// Explicit cast to convert a <see cref="System.Net.Mail.MailAddressCollection"/>
/// to a <see cref="InternetAddressList"/>.
/// </summary>
/// <remarks>
/// Casts a <see cref="System.Net.Mail.MailAddressCollection"/> to a <see cref="InternetAddressList"/>
/// in cases where you might want to make use of the the superior MimeKit APIs.
/// </remarks>
/// <returns>The equivalent <see cref="InternetAddressList"/>.</returns>
/// <param name="addresses">The mail address.</param>
public static explicit operator InternetAddressList (MailAddressCollection addresses)
{
if (addresses == null)
return null;
var list = new InternetAddressList ();
foreach (var address in addresses)
list.Add ((MailboxAddress) address);
return list;
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class represents settings specified by de jure or
// de facto standards for a particular country/region. In
// contrast to CultureInfo, the RegionInfo does not represent
// preferences of the user and does not depend on the user's
// language or culture.
//
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
[Serializable]
public partial class RegionInfo
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Variables.
//
//
// Name of this region (ie: es-US): serialized, the field used for deserialization
//
internal String _name;
//
// The CultureData instance that we are going to read data from.
//
internal CultureData _cultureData;
//
// The RegionInfo for our current region
//
internal static volatile RegionInfo s_currentRegionInfo;
////////////////////////////////////////////////////////////////////////
//
// RegionInfo Constructors
//
// Note: We prefer that a region be created with a full culture name (ie: en-US)
// because otherwise the native strings won't be right.
//
// In Silverlight we enforce that RegionInfos must be created with a full culture name
//
////////////////////////////////////////////////////////////////////////
public RegionInfo(String name)
{
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0) //The InvariantCulture has no matching region
{
throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, "name");
}
Contract.EndContractBlock();
//
// For CoreCLR we only want the region names that are full culture names
//
_cultureData = CultureData.GetCultureDataForRegion(name, true);
if (_cultureData == null)
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.Argument_InvalidCultureName, name), "name");
// Not supposed to be neutral
if (_cultureData.IsNeutralCulture)
throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), "name");
SetName(name);
}
[System.Security.SecuritySafeCritical] // auto-generated
public RegionInfo(int culture)
{
if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region
{
throw new ArgumentException(SR.Argument_NoRegionInvariantCulture);
}
if (culture == CultureInfo.LOCALE_NEUTRAL)
{
// Not supposed to be neutral
throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), "culture");
}
if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT)
{
// Not supposed to be neutral
throw new ArgumentException(SR.Format(SR.Argument_CustomCultureCannotBePassedByNumber, culture), "culture");
}
_cultureData = CultureData.GetCultureData(culture, true);
_name = _cultureData.SREGIONNAME;
if (_cultureData.IsNeutralCulture)
{
// Not supposed to be neutral
throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), "culture");
}
}
internal RegionInfo(CultureData cultureData)
{
_cultureData = cultureData;
_name = _cultureData.SREGIONNAME;
}
private void SetName(string name)
{
// Use the name of the region we found
_name = _cultureData.SREGIONNAME;
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx) { }
[System.Security.SecurityCritical] // auto-generated
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
_cultureData = CultureData.GetCultureData(_name, true);
if (_cultureData == null)
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, _name),
"_name");
}
_name = _cultureData.SREGIONNAME;
}
////////////////////////////////////////////////////////////////////////
//
// GetCurrentRegion
//
// This instance provides methods based on the current user settings.
// These settings are volatile and may change over the lifetime of the
// thread.
//
////////////////////////////////////////////////////////////////////////
public static RegionInfo CurrentRegion
{
get
{
RegionInfo temp = s_currentRegionInfo;
if (temp == null)
{
temp = new RegionInfo(CultureInfo.CurrentCulture.m_cultureData);
// Need full name for custom cultures
temp._name = temp._cultureData.SREGIONNAME;
s_currentRegionInfo = temp;
}
return temp;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetName
//
// Returns the name of the region (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
public virtual String Name
{
get
{
Contract.Assert(_name != null, "Expected RegionInfo._name to be populated already");
return (_name);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetEnglishName
//
// Returns the name of the region in English. (ie: United States)
//
////////////////////////////////////////////////////////////////////////
public virtual String EnglishName
{
get
{
return (_cultureData.SENGCOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetDisplayName
//
// Returns the display name (localized) of the region. (ie: United States
// if the current UI language is en-US)
//
////////////////////////////////////////////////////////////////////////
public virtual String DisplayName
{
get
{
return (_cultureData.SLOCALIZEDCOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetNativeName
//
// Returns the native name of the region. (ie: Deutschland)
// WARNING: You need a full locale name for this to make sense.
//
////////////////////////////////////////////////////////////////////////
public virtual String NativeName
{
get
{
return (_cultureData.SNATIVECOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// TwoLetterISORegionName
//
// Returns the two letter ISO region name (ie: US)
//
////////////////////////////////////////////////////////////////////////
public virtual String TwoLetterISORegionName
{
get
{
return (_cultureData.SISO3166CTRYNAME);
}
}
////////////////////////////////////////////////////////////////////////
//
// ThreeLetterISORegionName
//
// Returns the three letter ISO region name (ie: USA)
//
////////////////////////////////////////////////////////////////////////
public virtual String ThreeLetterISORegionName
{
get
{
return (_cultureData.SISO3166CTRYNAME2);
}
}
////////////////////////////////////////////////////////////////////////
//
// ThreeLetterWindowsRegionName
//
// Returns the three letter windows region name (ie: USA)
//
////////////////////////////////////////////////////////////////////////
public virtual String ThreeLetterWindowsRegionName
{
get
{
// ThreeLetterWindowsRegionName is really same as ThreeLetterISORegionName
return ThreeLetterISORegionName;
}
}
////////////////////////////////////////////////////////////////////////
//
// IsMetric
//
// Returns true if this region uses the metric measurement system
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsMetric
{
get
{
int value = _cultureData.IMEASURE;
return (value == 0);
}
}
public virtual int GeoId
{
get
{
return (_cultureData.IGEOID);
}
}
////////////////////////////////////////////////////////////////////////
//
// CurrencyEnglishName
//
// English name for this region's currency, ie: Swiss Franc
//
////////////////////////////////////////////////////////////////////////
public virtual string CurrencyEnglishName
{
get
{
return (_cultureData.SENGLISHCURRENCY);
}
}
////////////////////////////////////////////////////////////////////////
//
// CurrencyNativeName
//
// Native name for this region's currency, ie: Schweizer Franken
// WARNING: You need a full locale name for this to make sense.
//
////////////////////////////////////////////////////////////////////////
public virtual string CurrencyNativeName
{
get
{
return (_cultureData.SNATIVECURRENCY);
}
}
////////////////////////////////////////////////////////////////////////
//
// CurrencySymbol
//
// Currency Symbol for this locale, ie: Fr. or $
//
////////////////////////////////////////////////////////////////////////
public virtual String CurrencySymbol
{
get
{
return (_cultureData.SCURRENCY);
}
}
////////////////////////////////////////////////////////////////////////
//
// ISOCurrencySymbol
//
// ISO Currency Symbol for this locale, ie: CHF
//
////////////////////////////////////////////////////////////////////////
public virtual String ISOCurrencySymbol
{
get
{
return (_cultureData.SINTLSYMBOL);
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same RegionInfo as the current instance.
//
// RegionInfos are considered equal if and only if they have the same name
// (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
RegionInfo that = value as RegionInfo;
if (that != null)
{
return this.Name.Equals(that.Name);
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for RegionInfo
// A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns the name of the Region, ie: es-US
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return (Name);
}
}
}
| |
namespace Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using FakeItEasy;
using Nancy.Json;
using Nancy.ModelBinding;
using Nancy.ModelBinding.DefaultBodyDeserializers;
using Xunit;
using Xunit.Extensions;
public class JsonBodyDeserializerFixture
{
private readonly JavaScriptSerializer serializer;
private readonly JsonBodyDeserializer deserialize;
private readonly TestModel testModel;
private readonly string testModelJson;
public JsonBodyDeserializerFixture()
{
this.deserialize = new JsonBodyDeserializer();
this.testModel = new TestModel()
{
IntProperty = 12,
StringProperty = "More cowbell",
DateProperty = DateTime.Parse("2011/12/25"),
ArrayProperty = new[] { "Ping", "Pong" }
};
this.serializer = new JavaScriptSerializer();
this.serializer.RegisterConverters(JsonSettings.Converters);
this.testModelJson = this.serializer.Serialize(this.testModel);
}
[Fact]
public void Should_report_false_for_can_deserialize_for_non_json_format()
{
// Given
const string contentType = "application/xml";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_report_true_for_can_deserialize_for_application_json()
{
// Given
const string contentType = "application/json";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_report_true_for_can_deserialize_for_text_json()
{
// Given
const string contentType = "text/json";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_report_true_for_can_deserialize_for_custom_json_format()
{
// Given
const string contentType = "application/vnd.org.nancyfx.mything+json";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_be_case_insensitive_in_can_deserialize()
{
// Given
const string contentType = "appLicaTion/jsOn";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_deserialize_timespan()
{
// Given
var json = this.serializer.Serialize(TimeSpan.FromDays(14));
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
var context = new BindingContext()
{
DestinationType = typeof(TimeSpan),
ValidModelBindingMembers = BindingMemberInfo.Collect<TimeSpan>().ToList(),
};
// When
var result = (TimeSpan)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.Days.ShouldEqual(14);
}
[Fact]
public void Should_deserialize_enum()
{
// Given
var json = this.serializer.Serialize(TestEnum.One);
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
var context = new BindingContext()
{
DestinationType = typeof (TestEnum),
ValidModelBindingMembers = BindingMemberInfo.Collect<TestEnum>().ToList(),
};
// When
var result = (TestEnum)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.ShouldEqual(TestEnum.One);
}
[Theory]
[InlineData(TestEnum.Hundred)]
[InlineData(null)]
public void Should_deserialize_nullable_enum(TestEnum? propertyValue)
{
var context = new BindingContext()
{
DestinationType = typeof(TestModel),
ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToList(),
};
var model = new TestModel { NullableEnumProperty = propertyValue };
var s = new JavaScriptSerializer();
var serialized = s.Serialize(model);
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));
// When
var result = (TestModel)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.NullableEnumProperty.ShouldEqual(propertyValue);
}
[Fact]
public void Should_deserialize_list_of_primitives()
{
// Given
var context = new BindingContext()
{
DestinationType = typeof (TestModel),
ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToList(),
};
var model =
new TestModel
{
ListOfPrimitivesProperty = new List<int> { 1, 3, 5 },
ListOfPrimitivesField = new List<int> { 2, 4, 6 },
};
var s = new JavaScriptSerializer();
var serialized = s.Serialize(model);
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));
// When
var result = (TestModel)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.ListOfPrimitivesProperty.ShouldHaveCount(3);
result.ListOfPrimitivesProperty[0].ShouldEqual(1);
result.ListOfPrimitivesProperty[1].ShouldEqual(3);
result.ListOfPrimitivesProperty[2].ShouldEqual(5);
result.ListOfPrimitivesField.ShouldHaveCount(3);
result.ListOfPrimitivesField[0].ShouldEqual(2);
result.ListOfPrimitivesField[1].ShouldEqual(4);
result.ListOfPrimitivesField[2].ShouldEqual(6);
}
[Fact]
public void Should_deserialize_list_of_complex_objects()
{
// Given
var context = new BindingContext()
{
DestinationType = typeof(TestModel),
ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToList(),
};
var model =
new TestModel
{
ListOfComplexObjectsProperty = new List<ModelWithStringValues>
{
new ModelWithStringValues() { Value1 = "one", Value2 = "two"},
new ModelWithStringValues() { Value1 = "three", Value2 = "four"}
},
ListOfComplexObjectsField = new List<ModelWithStringValues>
{
new ModelWithStringValues() { Value1 = "five", Value2 = "six"},
new ModelWithStringValues() { Value1 = "seven", Value2 = "eight"}
}
};
var s = new JavaScriptSerializer();
var serialized = s.Serialize(model);
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));
// When
var result = (TestModel)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.ListOfComplexObjectsProperty.ShouldHaveCount(2);
result.ListOfComplexObjectsProperty[0].Value1.ShouldEqual("one");
result.ListOfComplexObjectsProperty[0].Value2.ShouldEqual("two");
result.ListOfComplexObjectsProperty[1].Value1.ShouldEqual("three");
result.ListOfComplexObjectsProperty[1].Value2.ShouldEqual("four");
result.ListOfComplexObjectsField.ShouldHaveCount(2);
result.ListOfComplexObjectsField[0].Value1.ShouldEqual("five");
result.ListOfComplexObjectsField[0].Value2.ShouldEqual("six");
result.ListOfComplexObjectsField[1].Value1.ShouldEqual("seven");
result.ListOfComplexObjectsField[1].Value2.ShouldEqual("eight");
}
[Fact]
public void Should_Deserialize_Signed_And_Unsigned_Nullable_Numeric_Types()
{
//Given
const string json = "{P1: 1, P2: 2, P3: 3, F1: 4, F2: 5, F3: 6}";
//When
var model = this.serializer.Deserialize<ModelWithNullables> (json);
//Should
Assert.Equal (1, model.P1);
Assert.Equal ((uint)2, model.P2);
Assert.Equal ((uint)3, model.P3);
Assert.Equal (4, model.F1);
Assert.Equal ((uint)5, model.F2);
Assert.Equal ((uint)6, model.F3);
}
#if !__MonoCS__
[Fact]
public void Should_Serialize_Doubles_In_Different_Cultures()
{
// TODO - fixup on mono, seems to throw inside double.parse
// Given
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");
var modelWithDoubleValues =
new ModelWithDoubleValues
{
Latitude = 50.933984,
Longitude = 7.330627
};
var s = new JavaScriptSerializer();
var serialized = s.Serialize(modelWithDoubleValues);
// When
var deserializedModelWithDoubleValues = s.Deserialize<ModelWithDoubleValues>(serialized);
// Then
Assert.Equal(modelWithDoubleValues.Latitude, deserializedModelWithDoubleValues.Latitude);
Assert.Equal(modelWithDoubleValues.Longitude, deserializedModelWithDoubleValues.Longitude);
}
#endif
[Theory]
[InlineData("\n")]
[InlineData("\n\r")]
[InlineData("\r\n")]
[InlineData("\r")]
public void Should_Serialize_Last_Prop_is_Bool_And_Trailing_NewLine(string lineEndings)
{
// Given
var json = string.Concat("{\"Property\": true", lineEndings, "}");
// When
var s = new JavaScriptSerializer();
var deserialized = (dynamic)s.DeserializeObject(json);
// Then
Assert.True(deserialized["Property"]);
}
[Fact]
public void Should_Serialize_Last_Prop_is_Bool()
{
// Given
var json = "{\"Property\": true}";
// When
var s = new JavaScriptSerializer();
var deserialized = (dynamic)s.DeserializeObject(json);
// Then
Assert.True(deserialized["Property"]);
}
public class TestModel : IEquatable<TestModel>
{
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public DateTime DateProperty { get; set; }
public string[] ArrayProperty { get; set; }
public TestEnum? NullableEnumProperty { get; set; }
public List<int> ListOfPrimitivesProperty { get; set; }
public List<int> ListOfPrimitivesField;
public List<ModelWithStringValues> ListOfComplexObjectsProperty { get; set; }
public List<ModelWithStringValues> ListOfComplexObjectsField { get; set; }
public bool Equals(TestModel other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return other.StringProperty == this.StringProperty &&
other.IntProperty == this.IntProperty &&
!other.ArrayProperty.Except(this.ArrayProperty).Any() &&
other.DateProperty.ToShortDateString() == this.DateProperty.ToShortDateString();
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(TestModel))
{
return false;
}
return Equals((TestModel)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = (this.StringProperty != null ? this.StringProperty.GetHashCode() : 0);
result = (result * 397) ^ this.IntProperty;
result = (result * 397) ^ this.DateProperty.GetHashCode();
result = (result * 397) ^ (this.ArrayProperty != null ? this.ArrayProperty.GetHashCode() : 0);
return result;
}
}
public static bool operator ==(TestModel left, TestModel right)
{
return Equals(left, right);
}
public static bool operator !=(TestModel left, TestModel right)
{
return !Equals(left, right);
}
}
public enum TestEnum
{
One = 1,
Hundred = 100
}
}
public class ModelWithStringValues
{
public string Value1 { get; set; }
public string Value2;
}
public class ModelWithDoubleValues
{
public double Latitude { get; set; }
public double Longitude;
}
public class ModelWithNullables
{
public int? P1 { get; set; }
public uint P2 { get; set; }
public uint? P3 { get; set; }
public int? F1;
public uint F2;
public uint? F3;
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.SmartDeviceManagement.v1
{
/// <summary>The SmartDeviceManagement Service.</summary>
public class SmartDeviceManagementService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public SmartDeviceManagementService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public SmartDeviceManagementService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Enterprises = new EnterprisesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "smartdevicemanagement";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://smartdevicemanagement.googleapis.com/";
#else
"https://smartdevicemanagement.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://smartdevicemanagement.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Smart Device Management API.</summary>
public class Scope
{
/// <summary>See and/or control the devices that you selected</summary>
public static string SdmService = "https://www.googleapis.com/auth/sdm.service";
/// <summary>See and control the Nest thermostats that you select</summary>
public static string SdmThermostatService = "https://www.googleapis.com/auth/sdm.thermostat.service";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Smart Device Management API.</summary>
public static class ScopeConstants
{
/// <summary>See and/or control the devices that you selected</summary>
public const string SdmService = "https://www.googleapis.com/auth/sdm.service";
/// <summary>See and control the Nest thermostats that you select</summary>
public const string SdmThermostatService = "https://www.googleapis.com/auth/sdm.thermostat.service";
}
/// <summary>Gets the Enterprises resource.</summary>
public virtual EnterprisesResource Enterprises { get; }
}
/// <summary>A base abstract class for SmartDeviceManagement requests.</summary>
public abstract class SmartDeviceManagementBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new SmartDeviceManagementBaseServiceRequest instance.</summary>
protected SmartDeviceManagementBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes SmartDeviceManagement parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "enterprises" collection of methods.</summary>
public class EnterprisesResource
{
private const string Resource = "enterprises";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public EnterprisesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Devices = new DevicesResource(service);
Structures = new StructuresResource(service);
}
/// <summary>Gets the Devices resource.</summary>
public virtual DevicesResource Devices { get; }
/// <summary>The "devices" collection of methods.</summary>
public class DevicesResource
{
private const string Resource = "devices";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public DevicesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Executes a command to device managed by the enterprise.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the device requested. For example: "enterprises/XYZ/devices/123"</param>
public virtual ExecuteCommandRequest ExecuteCommand(Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1ExecuteDeviceCommandRequest body, string name)
{
return new ExecuteCommandRequest(service, body, name);
}
/// <summary>Executes a command to device managed by the enterprise.</summary>
public class ExecuteCommandRequest : SmartDeviceManagementBaseServiceRequest<Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1ExecuteDeviceCommandResponse>
{
/// <summary>Constructs a new ExecuteCommand request.</summary>
public ExecuteCommandRequest(Google.Apis.Services.IClientService service, Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1ExecuteDeviceCommandRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the device requested. For example: "enterprises/XYZ/devices/123"</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1ExecuteDeviceCommandRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "executeCommand";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:executeCommand";
/// <summary>Initializes ExecuteCommand parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^enterprises/[^/]+/devices/[^/]+$",
});
}
}
/// <summary>Gets a device managed by the enterprise.</summary>
/// <param name="name">The name of the device requested. For example: "enterprises/XYZ/devices/123"</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets a device managed by the enterprise.</summary>
public class GetRequest : SmartDeviceManagementBaseServiceRequest<Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1Device>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the device requested. For example: "enterprises/XYZ/devices/123"</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^enterprises/[^/]+/devices/[^/]+$",
});
}
}
/// <summary>Lists devices managed by the enterprise.</summary>
/// <param name="parent">The parent enterprise to list devices under. E.g. "enterprises/XYZ".</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists devices managed by the enterprise.</summary>
public class ListRequest : SmartDeviceManagementBaseServiceRequest<Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1ListDevicesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>The parent enterprise to list devices under. E.g. "enterprises/XYZ".</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional filter to list devices. Filters can be done on: Device custom name (substring match):
/// 'customName=wing'
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional requested page size. Server may return fewer devices than requested. If unspecified, server
/// will pick an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>Optional token of the page to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/devices";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^enterprises/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets the Structures resource.</summary>
public virtual StructuresResource Structures { get; }
/// <summary>The "structures" collection of methods.</summary>
public class StructuresResource
{
private const string Resource = "structures";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public StructuresResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Rooms = new RoomsResource(service);
}
/// <summary>Gets the Rooms resource.</summary>
public virtual RoomsResource Rooms { get; }
/// <summary>The "rooms" collection of methods.</summary>
public class RoomsResource
{
private const string Resource = "rooms";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public RoomsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Gets a room managed by the enterprise.</summary>
/// <param name="name">
/// The name of the room requested. For example: "enterprises/XYZ/structures/ABC/rooms/123".
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets a room managed by the enterprise.</summary>
public class GetRequest : SmartDeviceManagementBaseServiceRequest<Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1Room>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// The name of the room requested. For example: "enterprises/XYZ/structures/ABC/rooms/123".
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^enterprises/[^/]+/structures/[^/]+/rooms/[^/]+$",
});
}
}
/// <summary>Lists rooms managed by the enterprise.</summary>
/// <param name="parent">
/// The parent resource name of the rooms requested. For example: "enterprises/XYZ/structures/ABC".
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists rooms managed by the enterprise.</summary>
public class ListRequest : SmartDeviceManagementBaseServiceRequest<Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1ListRoomsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// The parent resource name of the rooms requested. For example: "enterprises/XYZ/structures/ABC".
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Requested page size. Server may return fewer rooms than requested. If unspecified, server will
/// pick an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The token of the page to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/rooms";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^enterprises/[^/]+/structures/[^/]+$",
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets a structure managed by the enterprise.</summary>
/// <param name="name">
/// The name of the structure requested. For example: "enterprises/XYZ/structures/ABC".
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets a structure managed by the enterprise.</summary>
public class GetRequest : SmartDeviceManagementBaseServiceRequest<Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1Structure>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// The name of the structure requested. For example: "enterprises/XYZ/structures/ABC".
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^enterprises/[^/]+/structures/[^/]+$",
});
}
}
/// <summary>Lists structures managed by the enterprise.</summary>
/// <param name="parent">The parent enterprise to list structures under. E.g. "enterprises/XYZ".</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists structures managed by the enterprise.</summary>
public class ListRequest : SmartDeviceManagementBaseServiceRequest<Google.Apis.SmartDeviceManagement.v1.Data.GoogleHomeEnterpriseSdmV1ListStructuresResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>The parent enterprise to list structures under. E.g. "enterprises/XYZ".</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional filter to list structures.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Requested page size. Server may return fewer structures than requested. If unspecified, server will
/// pick an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The token of the page to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/structures";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^enterprises/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
}
namespace Google.Apis.SmartDeviceManagement.v1.Data
{
/// <summary>Device resource represents an instance of enterprise managed device in the property.</summary>
public class GoogleHomeEnterpriseSdmV1Device : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The resource name of the device. For example: "enterprises/XYZ/devices/123".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Assignee details of the device.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parentRelations")]
public virtual System.Collections.Generic.IList<GoogleHomeEnterpriseSdmV1ParentRelation> ParentRelations { get; set; }
/// <summary>Output only. Device traits.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("traits")]
public virtual System.Collections.Generic.IDictionary<string, object> Traits { get; set; }
/// <summary>
/// Output only. Type of the device for general display purposes. For example: "THERMOSTAT". The device type
/// should not be used to deduce or infer functionality of the actual device it is assigned to. Instead, use the
/// returned traits for the device.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for SmartDeviceManagementService.ExecuteDeviceCommand</summary>
public class GoogleHomeEnterpriseSdmV1ExecuteDeviceCommandRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The command name to execute, represented by the fully qualified protobuf message name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("command")]
public virtual string Command { get; set; }
/// <summary>The command message to execute, represented as a Struct.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("params")]
public virtual System.Collections.Generic.IDictionary<string, object> Params__ { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for SmartDeviceManagementService.ExecuteDeviceCommand</summary>
public class GoogleHomeEnterpriseSdmV1ExecuteDeviceCommandResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The results of executing the command.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("results")]
public virtual System.Collections.Generic.IDictionary<string, object> Results { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for SmartDeviceManagementService.ListDevices</summary>
public class GoogleHomeEnterpriseSdmV1ListDevicesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of devices.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("devices")]
public virtual System.Collections.Generic.IList<GoogleHomeEnterpriseSdmV1Device> Devices { get; set; }
/// <summary>The pagination token to retrieve the next page of results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for SmartDeviceManagementService.ListRooms</summary>
public class GoogleHomeEnterpriseSdmV1ListRoomsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The pagination token to retrieve the next page of results. If this field is omitted, there are no subsequent
/// pages.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of rooms.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rooms")]
public virtual System.Collections.Generic.IList<GoogleHomeEnterpriseSdmV1Room> Rooms { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for SmartDeviceManagementService.ListStructures</summary>
public class GoogleHomeEnterpriseSdmV1ListStructuresResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The pagination token to retrieve the next page of results. If this field is omitted, there are no subsequent
/// pages.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of structures.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("structures")]
public virtual System.Collections.Generic.IList<GoogleHomeEnterpriseSdmV1Structure> Structures { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents device relationships, for instance, structure/room to which the device is assigned to.
/// </summary>
public class GoogleHomeEnterpriseSdmV1ParentRelation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. The custom name of the relation -- e.g., structure/room where the device is assigned to.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>
/// Output only. The name of the relation -- e.g., structure/room where the device is assigned to. For example:
/// "enterprises/XYZ/structures/ABC" or "enterprises/XYZ/structures/ABC/rooms/123"
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("parent")]
public virtual string Parent { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Room resource represents an instance of sub-space within a structure such as rooms in a hotel suite or rental
/// apartment.
/// </summary>
public class GoogleHomeEnterpriseSdmV1Room : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. The resource name of the room. For example: "enterprises/XYZ/structures/ABC/rooms/123".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Room traits.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("traits")]
public virtual System.Collections.Generic.IDictionary<string, object> Traits { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Structure resource represents an instance of enterprise managed home or hotel room.</summary>
public class GoogleHomeEnterpriseSdmV1Structure : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. The resource name of the structure. For example: "enterprises/XYZ/structures/ABC".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Structure traits.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("traits")]
public virtual System.Collections.Generic.IDictionary<string, object> Traits { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
#pragma warning disable IDE1006 // Naming Styles
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Vanara.PInvoke
{
/// <summary>Items from the WinMm.dll</summary>
public static partial class WinMm
{
private const string Lib_Winmm = "winmm.dll";
/// <summary>Describes optional functionality supported by the auxiliary audio device.</summary>
[PInvokeData("mmeapi.h", MSDNShortId = "NS:mmeapi.auxcaps_tag")]
[Flags]
public enum AUX_CAPS : uint
{
/// <summary>Supports volume control.</summary>
AUXCAPS_VOLUME = 0x0001,
/// <summary>Supports separate left and right volume control.</summary>
AUXCAPS_LRVOLUME = 0x0002,
}
/// <summary>The <c>auxGetDevCaps</c> function retrieves the capabilities of a given auxiliary output device.</summary>
/// <param name="uDeviceID">
/// <para>
/// Identifier of the auxiliary output device to be queried. Specify a valid device identifier (see the following comments section),
/// or use the following constant:
/// </para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>AUX_MAPPER</term>
/// <term>Auxiliary audio mapper. The function returns an error if no auxiliary audio mapper is installed.</term>
/// </item>
/// </list>
/// </param>
/// <param name="pac">Pointer to an AUXCAPS structure to be filled with information about the capabilities of the device.</param>
/// <param name="cbac">Size, in bytes, of the AUXCAPS structure.</param>
/// <returns>
/// <para>Returns MMSYSERR_NOERROR if successful or an error otherwise. Possible error values include the following.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>MMSYSERR_BADDEVICEID</term>
/// <term>Specified device identifier is out of range.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// The device identifier in uDeviceID varies from zero to one less than the number of devices present. AUX_MAPPER may also be used.
/// Use the auxGetNumDevs function to determine the number of auxiliary output devices present in the system.
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/mmeapi/nf-mmeapi-auxgetdevcaps MMRESULT auxGetDevCaps( UINT uDeviceID,
// LPAUXCAPS pac, UINT cbac );
[DllImport(Lib_Winmm, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("mmeapi.h", MSDNShortId = "NF:mmeapi.auxGetDevCaps")]
public static extern MMRESULT auxGetDevCaps(uint uDeviceID, out AUXCAPS pac, uint cbac);
/// <summary>The <c>auxGetNumDevs</c> function retrieves the number of auxiliary output devices present in the system.</summary>
/// <returns>Returns the number of device. A return value of zero means that no devices are present or that an error occurred.</returns>
// https://docs.microsoft.com/en-us/windows/win32/api/mmeapi/nf-mmeapi-auxgetnumdevs UINT auxGetNumDevs();
[DllImport(Lib_Winmm, SetLastError = false, ExactSpelling = true)]
[PInvokeData("mmeapi.h", MSDNShortId = "NF:mmeapi.auxGetNumDevs")]
public static extern uint auxGetNumDevs();
/// <summary>The <c>auxGetVolume</c> function retrieves the current volume setting of the specified auxiliary output device.</summary>
/// <param name="uDeviceID">Identifier of the auxiliary output device to be queried.</param>
/// <param name="pdwVolume">
/// <para>
/// Pointer to a variable to be filled with the current volume setting. The low-order word of this location contains the left
/// channel volume setting, and the high-order word contains the right channel setting. A value of 0xFFFF represents full volume,
/// and a value of 0x0000 is silence.
/// </para>
/// <para>
/// If a device does not support both left and right volume control, the low-order word of the specified location contains the
/// volume level.
/// </para>
/// <para>
/// The full 16-bit setting(s) set with the auxSetVolume function are returned, regardless of whether the device supports the full
/// 16 bits of volume-level control.
/// </para>
/// </param>
/// <returns>
/// <para>Returns MMSYSERR_NOERROR if successful or an error otherwise. Possible error values include the following.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>MMSYSERR_BADDEVICEID</term>
/// <term>Specified device identifier is out of range.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// Not all devices support volume control. To determine whether a device supports volume control, use the AUXCAPS_VOLUME flag to
/// test the <c>dwSupport</c> member of the AUXCAPS structure (filled by the auxGetDevCaps function).
/// </para>
/// <para>
/// To determine whether a device supports volume control on both the left and right channels, use the AUXCAPS_LRVOLUME flag to test
/// the <c>dwSupport</c> member of the AUXCAPS structure (filled by auxGetDevCaps).
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/mmeapi/nf-mmeapi-auxgetvolume MMRESULT auxGetVolume( UINT uDeviceID, LPDWORD
// pdwVolume );
[DllImport(Lib_Winmm, SetLastError = false, ExactSpelling = true)]
[PInvokeData("mmeapi.h", MSDNShortId = "NF:mmeapi.auxGetVolume")]
public static extern MMRESULT auxGetVolume(uint uDeviceID, out uint pdwVolume);
/// <summary>
/// The <c>auxOutMessage</c> function sends a message to the given auxiliary output device. This function also performs error
/// checking on the device identifier passed as part of the message.
/// </summary>
/// <param name="uDeviceID">Identifier of the auxiliary output device to receive the message.</param>
/// <param name="uMsg">Message to send.</param>
/// <param name="dw1">Message parameter.</param>
/// <param name="dw2">Message parameter.</param>
/// <returns>Returns the message return value.</returns>
/// <remarks>
/// <para>The
/// <code>DRV_QUERYDEVICEINTERFACE</code>
/// message queries for the device-interface name of a <c>waveIn</c>, <c>waveOut</c>, <c>midiIn</c>, <c>midiOut</c>, or <c>mixer</c> device.
/// </para>
/// <para>For
/// <code>DRV_QUERYDEVICEINTERFACE</code>
/// , dwParam1 is a pointer to a caller-allocated buffer into which the function writes a null-terminated Unicode string containing
/// the device-interface name. If the device has no device interface, the string length is zero.
/// </para>
/// <para>For
/// <code>DRV_QUERYDEVICEINTERFACE</code>
/// , dwParam2 specifies the buffer size in bytes. This is an input parameter to the function. The caller should specify a size that
/// is greater than or equal to the buffer size retrieved by the DRV_QUERYDEVICEINTERFACESIZE message.
/// </para>
/// <para>
/// The DRV_QUERYDEVICEINTERFACE message is supported in Windows Me, and Windows 2000 and later. This message is valid only for the
/// waveInMessage, waveOutMessage, midiInMessage, midiOutMessage, and mixerMessage functions. The system intercepts this message and
/// returns the appropriate value without sending the message to the device driver. For general information about system-intercepted
/// <c>xxxMessage</c> functions, see System-Intercepted Device Messages.
/// </para>
/// <para>The following two message constants are used together for the purpose of obtaining device interface names:</para>
/// <list type="bullet">
/// <item>
/// <term>DRV_QUERYDEVICEINTERFACESIZE</term>
/// </item>
/// <item>
/// <term>DRV_QUERYDEVICEINTERFACE</term>
/// </item>
/// </list>
/// <para>
/// The first message obtains the size in bytes of the buffer needed to hold the string containing the device interface name. The
/// second message retrieves the name string in a buffer of the required size.
/// </para>
/// <para>For more information, see Obtaining a Device Interface Name.</para>
/// <para>The
/// <code>DRV_QUERYDEVICEINTERFACESIZE</code>
/// message queries for the size of the buffer required to hold the device-interface name.
/// </para>
/// <para>For
/// <code>DRV_QUERYDEVICEINTERFACESIZE</code>
/// , dwParam1 is a pointer to buffer size. This parameter points to a ULONG variable into which the function writes the required
/// buffer size in bytes. The size includes storage space for the name string's terminating null. The size is zero if the device ID
/// identifies a device that has no device interface.
/// </para>
/// <para>For
/// <code>DRV_QUERYDEVICEINTERFACESIZE</code>
/// , dwParam2 is unused. Set this parameter to zero.
/// </para>
/// <para>
/// This message is valid only for the waveInMessage, waveOutMessage, midiInMessage, midiOutMessage, and mixerMessage functions. The
/// system intercepts this message and returns the appropriate value without sending the message to the device driver. For general
/// information about system-intercepted <c>xxxMessage</c> functions, see System-Intercepted Device Messages.
/// </para>
/// <para>
/// The buffer size retrieved by this message is expressed as a byte count. It specifies the size of the buffer needed to hold the
/// null-terminated Unicode string that contains the device-interface name. The caller allocates a buffer of the specified size and
/// uses the DRV_QUERYDEVICEINTERFACE message to retrieve the device-interface name string.
/// </para>
/// <para>For more information, see Obtaining a Device Interface Name.</para>
/// <para>The
/// <code>DRV_QUERYDEVNODE</code>
/// message queries for the devnode number assigned to the device by the Plug and Play manager.
/// </para>
/// <para>For
/// <code>DRV_QUERYDEVNODE</code>
/// , dwParam1 is a pointer to a caller-allocated DWORD variable into which the function writes the devnode number. If no devnode is
/// assigned to the device, the function sets this variable to zero.
/// </para>
/// <para>For
/// <code>DRV_QUERYDEVNODE</code>
/// , dwParam2 is unused. Set this parameter to zero.
/// </para>
/// <para>
/// In Windows 2000 and later, the message always returns MMSYSERR_NOTSUPPORTED. This message is valid only for the waveInMessage,
/// waveOutMessage, midiInMessage, midiOutMessage, and mixerMessage functions. The system intercepts this message and returns the
/// appropriate value without sending the message to the device driver. For general information about system-intercepted
/// <c>xxxMessage</c> functions, see System-Intercepted Device Messages.
/// </para>
/// <para>The
/// <code>DRV_QUERYMAPPABLE</code>
/// message queries for whether the specified device can be used by a mapper.
/// </para>
/// <para>For
/// <code>DRV_QUERYMAPPABLE</code>
/// , dwParam1 is unused. Set this parameter to zero.
/// </para>
/// <para>For
/// <code>DRV_QUERYMAPPABLE</code>
/// , dwParam2 is unused. Set this parameter to zero.
/// </para>
/// <para>
/// This message is valid only for the waveInMessage, waveOutMessage, midiInMessage, midiOutMessage, mixerMessage and
/// <c>auxOutMessage</c> functions. The system intercepts this message and returns the appropriate value without sending the message
/// to the device driver. For general information about system-intercepted <c>xxxMessage</c> functions, see System-Intercepted
/// Device Messages.
/// </para>
/// <para>
/// When an application program opens a mapper instead of a specific audio device, the system inserts a mapper between the
/// application and the available devices. The mapper selects an appropriate device by mapping the application's requirements to one
/// of the available devices. For more information about mappers, see the Microsoft Windows SDK documentation.
/// </para>
/// <para>The
/// <code>DRVM_MAPPER_CONSOLEVOICECOM_GET</code>
/// message retrieves the device ID of the preferred voice-communications device.
/// </para>
/// <para>For
/// <code>DRVM_MAPPER_CONSOLEVOICECOM_GET</code>
/// , dwParam1 is a pointer to device ID. This parameter points to a DWORD variable into which the function writes the device ID of
/// the current preferred voice-communications device. The function writes the value (-1) if no device is available that qualifies
/// as a preferred voice-communications device.
/// </para>
/// <para>For
/// <code>DRVM_MAPPER_CONSOLEVOICECOM_GET</code>
/// , dwParam2 is a pointer to status flags. This parameter points to a DWORD variable into which the function writes the
/// device-status flags. Only one flag bit is currently defined: DRVM_MAPPER_PREFERRED_FLAGS_PREFERREDONLY.
/// </para>
/// <para>
/// This message is valid only for the waveInMessage and waveOutMessage functions. When a caller calls these two functions with the
/// DRVM_MAPPER_CONSOLEVOICECOM_GET message, the caller must specify the device ID as WAVE_MAPPER, and then cast this value to the
/// appropriate handle type. For the <c>waveInMessage</c>, <c>waveOutMessage</c>, midiInMessage, midiOutMessage, or mixerMessage
/// functions, the caller must cast the device ID to a handle of type HWAVEIN, HWAVEOUT, HMIDIIN, HMIDIOUT, or HMIXER, respectively.
/// Note that if the caller supplies a valid handle instead of a device ID for this parameter, the function fails and returns error
/// code MMSYSERR_NOSUPPORT.
/// </para>
/// <para>
/// The system intercepts this message and returns the appropriate value without sending the message to the device driver. For
/// general information about system-intercepted <c>xxxMessage</c> functions, see System-Intercepted Device Messages.
/// </para>
/// <para>
/// This message provides a way to determine which device is preferred specifically for voice communications, in contrast to the
/// DRVM_MAPPER_PREFERRED_GET message, which determines which device is preferred for all other audio functions.
/// </para>
/// <para>
/// For example, the preferred <c>waveOut</c> device for voice communications might be the earpiece in a headset, but the preferred
/// <c>waveOut</c> device for all other audio functions might be a set of stereo speakers.
/// </para>
/// <para>
/// When the DRVM_MAPPER_PREFERRED_FLAGS_PREFERREDONLY flag bit is set in the DWORD location pointed to by dwParam2, the
/// <c>waveIn</c> and <c>waveOut</c> APIs use only the current preferred voice-communications device and do not search for other
/// available devices if the preferred device is unavailable. The flag that is output by either the <c>waveInMessage</c> or
/// <c>waveOutMessage</c> call applies to the preferred voice-communications device for both the <c>waveIn</c> and <c>waveOut</c>
/// APIs, regardless of whether the call is made to <c>waveInMessage</c> or <c>waveOutMessage</c>. For more information, see
/// Preferred Voice-Communications Device ID.
/// </para>
/// <para>The
/// <code>DRVM_MAPPER_PREFERRED_GET</code>
/// message retrieves the device ID of the preferred audio device.
/// </para>
/// <para>For
/// <code>DRVM_MAPPER_PREFERRED_GET</code>
/// , dwParam1 is a pointer to device ID. This parameter points to a DWORD variable into which the function writes the device ID of
/// the current preferred device. The function writes the value (-1) if no device is available that qualifies as a preferred device.
/// </para>
/// <para>For
/// <code>DRVM_MAPPER_PREFERRED_GET</code>
/// , dwParam2 is a pointer to status flags. This parameter points to a DWORD variable into which the function writes the
/// device-status flags. Only one flag bit is currently defined (for <c>waveInMessage</c> and <c>waveOutMessage</c> calls only): DRVM_MAPPER_PREFERRED_FLAGS_PREFERREDONLY.
/// </para>
/// <para>
/// This message is valid only for the waveInMessage, waveOutMessage and midiOutMessage functions. When the caller calls these
/// functions with the DRVM_MAPPER_PREFERRED_GET message, the caller must first specify the device ID as WAVE_MAPPER (for
/// <c>waveInMessage</c> or <c>waveOutMessage</c>) or MIDI_MAPPER (for <c>midiOutMessage</c>), and then cast this value to the
/// appropriate handle type. For the <c>waveInMessage</c>, <c>waveOutMessage</c>, or <c>midiOutMessage</c> functions, the caller
/// must cast the device ID to a handle type HWAVEIN, HWAVEOUT or HMIDIOUT, respectively. Note that if the caller supplies a valid
/// handle instead of a device ID for this parameter, the function fails and returns error code MMSYSERR_NOSUPPORT.
/// </para>
/// <para>
/// The system intercepts this message and returns the appropriate value without sending the message to the device driver. For
/// general information about system-intercepted <c>xxxMessage</c> functions, see System-Intercepted Device Messages.
/// </para>
/// <para>
/// This message provides a way to determine which device is preferred for audio functions in general, in contrast to the
/// DRVM_MAPPER_CONSOLEVOICECOM_GET message, which determines which device is preferred specifically for voice communications.
/// </para>
/// <para>
/// When the DRVM_MAPPER_PREFERRED_FLAGS_PREFERREDONLY flag bit is set in the DWORD location pointed to by dwParam2, the
/// <c>waveIn</c> and <c>waveOut</c> APIs use only the current preferred device and do not search for other available devices if the
/// preferred device is unavailable. Note that the <c>midiOutMessage</c> function does not output this flag--the <c>midiOut</c> API
/// always uses only the preferred device. The flag that is output by either the <c>waveInMessage</c> or <c>waveOutMessage</c> call
/// applies to the preferred device for both the <c>waveIn</c> and <c>waveOut</c> APIs, regardless of whether the call is made to
/// <c>waveInMessage</c> or <c>waveOutMessage</c>.
/// </para>
/// <para>
/// The xxxMessage functions accept this value in place of a valid device handle in order to allow an application to determine the
/// default device ID without first having to open a device. For more information, see Accessing the Preferred Device ID.
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/mmeapi/nf-mmeapi-auxoutmessage MMRESULT auxOutMessage( UINT uDeviceID, UINT
// uMsg, DWORD_PTR dw1, DWORD_PTR dw2 );
[DllImport(Lib_Winmm, SetLastError = false, ExactSpelling = true)]
[PInvokeData("mmeapi.h", MSDNShortId = "NF:mmeapi.auxOutMessage")]
public static extern MMRESULT auxOutMessage(uint uDeviceID, uint uMsg, IntPtr dw1, IntPtr dw2);
/// <summary>The <c>auxSetVolume</c> function sets the volume of the specified auxiliary output device.</summary>
/// <param name="uDeviceID">
/// Identifier of the auxiliary output device to be queried. Device identifiers are determined implicitly from the number of devices
/// present in the system. Device identifier values range from zero to one less than the number of devices present. Use the
/// auxGetNumDevs function to determine the number of auxiliary devices in the system.
/// </param>
/// <param name="dwVolume">
/// <para>
/// Specifies the new volume setting. The low-order word specifies the left-channel volume setting, and the high-order word
/// specifies the right-channel setting. A value of 0xFFFF represents full volume, and a value of 0x0000 is silence.
/// </para>
/// <para>
/// If a device does not support both left and right volume control, the low-order word of dwVolume specifies the volume level, and
/// the high-order word is ignored.
/// </para>
/// </param>
/// <returns>
/// <para>Returns MMSYSERR_NOERROR if successful or an error otherwise. Possible error values include the following.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>MMSYSERR_BADDEVICEID</term>
/// <term>Specified device identifier is out of range.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// Not all devices support volume control. To determine whether the device supports volume control, use the AUXCAPS_VOLUME flag to
/// test the <c>dwSupport</c> member of the AUXCAPS structure (filled by the auxGetDevCaps function).
/// </para>
/// <para>
/// To determine whether the device supports volume control on both the left and right channels, use the AUXCAPS_LRVOLUME flag to
/// test the <c>dwSupport</c> member of the AUXCAPS structure (filled by auxGetDevCaps).
/// </para>
/// <para>
/// Most devices do not support the full 16 bits of volume-level control and will use only the high-order bits of the requested
/// volume setting. For example, for a device that supports 4 bits of volume control, requested volume level values of 0x4000,
/// 0x4FFF, and 0x43BE will produce the same physical volume setting, 0x4000. The auxGetVolume function will return the full 16-bit
/// setting set with <c>auxSetVolume</c>.
/// </para>
/// <para>
/// Volume settings are interpreted logarithmically. This means the perceived volume increase is the same when increasing the volume
/// level from 0x5000 to 0x6000 as it is from 0x4000 to 0x5000.
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/mmeapi/nf-mmeapi-auxsetvolume MMRESULT auxSetVolume( UINT uDeviceID, DWORD
// dwVolume );
[DllImport(Lib_Winmm, SetLastError = false, ExactSpelling = true)]
[PInvokeData("mmeapi.h", MSDNShortId = "NF:mmeapi.auxSetVolume")]
public static extern MMRESULT auxSetVolume(uint uDeviceID, uint dwVolume);
/// <summary>The <c>AUXCAPS</c> structure describes the capabilities of an auxiliary output device.</summary>
// https://docs.microsoft.com/en-us/windows/win32/api/mmeapi/ns-mmeapi-auxcaps typedef struct auxcaps_tag { WORD wMid; WORD wPid;
// VERSION vDriverVersion; char szPname[MAXPNAMELEN]; WORD wTechnology; DWORD dwSupport; } AUXCAPS, *PAUXCAPS, *NPAUXCAPS, *LPAUXCAPS;
[PInvokeData("mmeapi.h", MSDNShortId = "NS:mmeapi.auxcaps_tag")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct AUXCAPS
{
/// <summary>
/// Manufacturer identifier for the device driver for the auxiliary audio device. Manufacturer identifiers are defined in
/// Manufacturer and Product Identifiers.
/// </summary>
public ushort wMid;
/// <summary>
/// Product identifier for the auxiliary audio device. Currently, no product identifiers are defined for auxiliary audio devices.
/// </summary>
public ushort wPid;
/// <summary>
/// Version number of the device driver for the auxiliary audio device. The high-order byte is the major version number, and the
/// low-order byte is the minor version number.
/// </summary>
public uint vDriverVersion;
/// <summary>Product name in a null-terminated string.</summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string szPname;
/// <summary>
/// <para>Type of the auxiliary audio output:</para>
/// <list type="table">
/// <listheader>
/// <term>Name</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>AUXCAPS_AUXIN</term>
/// <term>Audio output from auxiliary input jacks.</term>
/// </item>
/// <item>
/// <term>AUXCAPS_CDAUDIO</term>
/// <term>Audio output from an internal CD-ROM drive.</term>
/// </item>
/// </list>
/// </summary>
public ushort wTechnology;
/// <summary>
/// <para>Describes optional functionality supported by the auxiliary audio device.</para>
/// <list type="table">
/// <listheader>
/// <term>Name</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>AUXCAPS_LRVOLUME</term>
/// <term>Supports separate left and right volume control.</term>
/// </item>
/// <item>
/// <term>AUXCAPS_VOLUME</term>
/// <term>Supports volume control.</term>
/// </item>
/// </list>
/// <para>
/// If a device supports volume changes, the AUXCAPS_VOLUME flag will be set. If a device supports separate volume changes on
/// the left and right channels, both AUXCAPS_VOLUME and the AUXCAPS_LRVOLUME will be set.
/// </para>
/// </summary>
public AUX_CAPS dwSupport;
}
/*
MM_WIM_CLOSE
MM_WIM_DATA
MM_WIM_OPEN
MM_WOM_CLOSE
MM_WOM_DONE
MM_WOM_OPEN
WIM_CLOSE
WIM_DATA
WIM_OPEN
WOM_CLOSE
WOM_DONE
WOM_OPEN
*/
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.