context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using Microsoft.Samples.CodeDomTestSuite;
public class SubsetBinaryOperatorsTest : CodeDomTestTree {
public override TestTypes TestType {
get {
return TestTypes.Subset;
}
}
public override bool ShouldCompile {
get {
return true;
}
}
public override bool ShouldVerify {
get {
return true;
}
}
public override string Name {
get {
return "SubsetBinaryOperatorsTest";
}
}
public override string Description {
get {
return "Tests binary operators while staying within the subset spec.";
}
}
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
// GENERATES (C#):
// namespace Namespace1 {
// using System;
//
//
// public class Class1 : object {
//
// public int ReturnMethod(int intInput) {
AddScenario ("ReturnMethod", "Verifies binary operators in a series of operations.");
CodeNamespace ns = new CodeNamespace ("Namespace1");
ns.Imports.Add (new CodeNamespaceImport ("System"));
cu.Namespaces.Add (ns);
CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
class1.Name = "Class1";
class1.BaseTypes.Add (new CodeTypeReference (typeof (object)));
ns.Types.Add (class1);
CodeMemberMethod retMethod = new CodeMemberMethod ();
retMethod.Name = "ReturnMethod";
retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
retMethod.ReturnType = new CodeTypeReference (typeof (int));
retMethod.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "intInput"));
// GENERATES (C#):
// int x1;
// x1 = 6 - 4;
// double x1d = x1;
// x1d = 18 / x1d;
// x1 = (int) x1d;
// x1 = x1 * intInput;
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "x1"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("x1", 6, CodeBinaryOperatorType.Subtract, 4));
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (double), "x1d", new CodeVariableReferenceExpression ("x1")));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("x1d", 18, CodeBinaryOperatorType.Divide, "x1d"));
retMethod.Statements.Add (new CodeAssignStatement (new CodeVariableReferenceExpression ("x1"),
new CodeCastExpression (typeof (int), new CodeVariableReferenceExpression ("x1d"))));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("x1", "x1", CodeBinaryOperatorType.Multiply,
new CodeArgumentReferenceExpression ("intInput")));
// GENERATES (C#):
// int x2;
// x2 = (19 % 8);
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "x2"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("x2", 19, CodeBinaryOperatorType.Modulus, 8));
// GENERATES (C#):
// int x3;
// x3 = 15 & 35;
// x3 = x3 | 129;
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "x3"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("x3", 15, CodeBinaryOperatorType.BitwiseAnd, 35));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("x3", "x3", CodeBinaryOperatorType.BitwiseOr, 129));
// GENERATES (C#):
// int x4 = 0;
retMethod.Statements.Add (
new CodeVariableDeclarationStatement (
typeof (int),
"x4",
new CodePrimitiveExpression (0)));
// GENERATES (C#):
// bool res1;
// res1 = x2 == 3;
// bool res2;
// res2 = x3 < 129;
// bool res3;
// res3 = res1 || res2;
// if (res3) {
// x4 = (x4 + 1);
// }
// else {
// x4 = (x4 + 2);
// }
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (bool), "res1"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("res1", "x2", CodeBinaryOperatorType.ValueEquality, 3));
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (bool), "res2"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("res2", "x3", CodeBinaryOperatorType.LessThan, 129));
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (bool), "res3"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("res3", "res1", CodeBinaryOperatorType.BooleanOr, "res2"));
retMethod.Statements.Add (
new CodeConditionStatement (new CodeVariableReferenceExpression ("res3"),
new CodeStatement [] { CDHelper.CreateIncrementByStatement ("x4", 1) },
new CodeStatement [] { CDHelper.CreateIncrementByStatement ("x4", 2) }));
// GENERATES (C#):
// bool res4;
// res4 = x2 > -1;
// bool res5;
// res5 = x3 > 5000;
// bool res6;
// res6 = res4 && res5;
// if (res6) {
// x4 = (x4 + 4);
// }
// else {
// x4 = (x4 + 8);
// }
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (bool), "res4"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("res4", "x2", CodeBinaryOperatorType.GreaterThan, -1));
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (bool), "res5"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("res5", "x3", CodeBinaryOperatorType.GreaterThanOrEqual, 5000));
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (bool), "res6"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("res6", "res4", CodeBinaryOperatorType.BooleanAnd, "res5"));
retMethod.Statements.Add (
new CodeConditionStatement (
new CodeVariableReferenceExpression ("res6"),
new CodeStatement [] { CDHelper.CreateIncrementByStatement ("x4", 4) },
new CodeStatement [] { CDHelper.CreateIncrementByStatement ("x4", 8) }));
// GENERATES (C#):
// bool res7;
// res7 = x2 < 3;
// bool res8;
// res8 = x3 != 1;
// bool res9;
// res9 = res7 && res8;
// if (res9) {
// x4 = (x4 + 16);
// }
// else {
// x4 = (x4 + 32);
// }
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (bool), "res7"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("res7", "x2", CodeBinaryOperatorType.LessThanOrEqual, 3));
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (bool), "res8"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("res8", "x3", CodeBinaryOperatorType.IdentityInequality, 1));
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (bool), "res9"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("res9", "res7", CodeBinaryOperatorType.BooleanAnd, "res8"));
retMethod.Statements.Add (
new CodeConditionStatement (
new CodeVariableReferenceExpression ("res9"),
new CodeStatement [] { CDHelper.CreateIncrementByStatement ("x4", 16) },
new CodeStatement [] { CDHelper.CreateIncrementByStatement ("x4", 32) }));
// GENERATES (C#):
// int theSum;
// theSum = x1 + x2;
// theSum = theSum + x3;
// theSum = theSum + x4;
// return theSum;
// }
//
retMethod.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "theSum"));
retMethod.Statements.Add (CDHelper.CreateBinaryOperatorStatement ("theSum", "x1", CodeBinaryOperatorType.Add, "x2"));
retMethod.Statements.Add (CDHelper.CreateIncrementByStatement ("theSum", "x3"));
retMethod.Statements.Add (CDHelper.CreateIncrementByStatement ("theSum", "x4"));
retMethod.Statements.Add (new CodeMethodReturnStatement (
new CodeVariableReferenceExpression ("theSum")));
class1.Members.Add (retMethod);
}
public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) {
object genObject;
Type genType;
AddScenario ("InstantiateClass1", "Find and instantiate Namespace1.Class1.");
if (!FindAndInstantiate ("Namespace1.Class1", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateClass1");
// Verify Return value from function
if (VerifyMethod (genType, genObject, "ReturnMethod", new object[] {5}, 204))
VerifyScenario ("ReturnMethod");
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G09_CityColl (editable child list).<br/>
/// This is a generated base class of <see cref="G09_CityColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="G08_Region"/> editable child object.<br/>
/// The items of the collection are <see cref="G10_City"/> objects.
/// </remarks>
[Serializable]
public partial class G09_CityColl : BusinessListBase<G09_CityColl, G10_City>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="G10_City"/> item from the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to be removed.</param>
public void Remove(int city_ID)
{
foreach (var g10_City in this)
{
if (g10_City.City_ID == city_ID)
{
Remove(g10_City);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="G10_City"/> item is in the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the G10_City is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int city_ID)
{
foreach (var g10_City in this)
{
if (g10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="G10_City"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the G10_City is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int city_ID)
{
foreach (var g10_City in DeletedList)
{
if (g10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="G10_City"/> item of the <see cref="G09_CityColl"/> collection, based on a given City_ID.
/// </summary>
/// <param name="city_ID">The City_ID.</param>
/// <returns>A <see cref="G10_City"/> object.</returns>
public G10_City FindG10_CityByCity_ID(int city_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].City_ID.Equals(city_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G09_CityColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="G09_CityColl"/> collection.</returns>
internal static G09_CityColl NewG09_CityColl()
{
return DataPortal.CreateChild<G09_CityColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="G09_CityColl"/> collection, based on given parameters.
/// </summary>
/// <param name="parent_Region_ID">The Parent_Region_ID parameter of the G09_CityColl to fetch.</param>
/// <returns>A reference to the fetched <see cref="G09_CityColl"/> collection.</returns>
internal static G09_CityColl GetG09_CityColl(int parent_Region_ID)
{
return DataPortal.FetchChild<G09_CityColl>(parent_Region_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G09_CityColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G09_CityColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="G09_CityColl"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="parent_Region_ID">The Parent Region ID.</param>
protected void Child_Fetch(int parent_Region_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetG09_CityColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Region_ID", parent_Region_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, parent_Region_ID);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
foreach (var item in this)
{
item.FetchChildren();
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="G09_CityColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(G10_City.GetG10_City(dr));
}
RaiseListChangedEvents = rlce;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// #define NUNIT25
using System;
using log4net.Config;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenMetaverse;
using OpenSim.Framework;
using log4net;
using System.Reflection;
using System.Data.Common;
// DBMS-specific:
using MySql.Data.MySqlClient;
using OpenSim.Data.MySQL;
using System.Data.SqlClient;
using OpenSim.Data.MSSQL;
using Mono.Data.Sqlite;
using OpenSim.Data.SQLite;
namespace OpenSim.Data.Tests
{
#if NUNIT25
[TestFixture(typeof(SqliteConnection), typeof(SQLiteInventoryStore), Description = "Inventory store tests (SQLite)")]
[TestFixture(typeof(MySqlConnection), typeof(MySQLInventoryData), Description = "Inventory store tests (MySQL)")]
[TestFixture(typeof(SqlConnection), typeof(MSSQLInventoryData), Description = "Inventory store tests (MS SQL Server)")]
#else
[TestFixture(Description = "Inventory store tests (SQLite)")]
public class SQLiteInventoryTests : InventoryTests<SqliteConnection, SQLiteInventoryStore>
{
}
[TestFixture(Description = "Inventory store tests (MySQL)")]
public class MySqlInventoryTests : InventoryTests<MySqlConnection, MySQLInventoryData>
{
}
[TestFixture(Description = "Inventory store tests (MS SQL Server)")]
public class MSSQLInventoryTests : InventoryTests<SqlConnection, MSSQLInventoryData>
{
}
#endif
public class InventoryTests<TConn, TInvStore> : BasicDataServiceTest<TConn, TInvStore>
where TConn : DbConnection, new()
where TInvStore : class, IInventoryDataPlugin, new()
{
public IInventoryDataPlugin db;
public UUID zero = UUID.Zero;
public UUID folder1 = UUID.Random();
public UUID folder2 = UUID.Random();
public UUID folder3 = UUID.Random();
public UUID owner1 = UUID.Random();
public UUID owner2 = UUID.Random();
public UUID owner3 = UUID.Random();
public UUID item1 = UUID.Random();
public UUID item2 = UUID.Random();
public UUID item3 = UUID.Random();
public UUID asset1 = UUID.Random();
public UUID asset2 = UUID.Random();
public UUID asset3 = UUID.Random();
public string name1;
public string name2 = "First Level folder";
public string name3 = "First Level folder 2";
public string niname1 = "My Shirt";
public string iname1 = "Shirt";
public string iname2 = "Text Board";
public string iname3 = "No Pants Barrel";
public InventoryTests(string conn) : base(conn)
{
name1 = "Root Folder for " + owner1.ToString();
}
public InventoryTests() : this("") { }
protected override void InitService(object service)
{
ClearDB();
db = (IInventoryDataPlugin)service;
db.Initialise(m_connStr);
}
private void ClearDB()
{
DropTables("inventoryitems", "inventoryfolders");
ResetMigrations("InventoryStore");
}
[Test]
public void T001_LoadEmpty()
{
Assert.That(db.getInventoryFolder(zero), Is.Null);
Assert.That(db.getInventoryFolder(folder1), Is.Null);
Assert.That(db.getInventoryFolder(folder2), Is.Null);
Assert.That(db.getInventoryFolder(folder3), Is.Null);
Assert.That(db.getInventoryItem(zero), Is.Null);
Assert.That(db.getInventoryItem(item1), Is.Null);
Assert.That(db.getInventoryItem(item2), Is.Null);
Assert.That(db.getInventoryItem(item3), Is.Null);
Assert.That(db.getUserRootFolder(zero), Is.Null);
Assert.That(db.getUserRootFolder(owner1), Is.Null);
}
// 01x - folder tests
[Test]
public void T010_FolderNonParent()
{
InventoryFolderBase f1 = NewFolder(folder2, folder1, owner1, name2);
// the folder will go in
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner1);
Assert.That(f1a, Is.Null);
}
[Test]
public void T011_FolderCreate()
{
InventoryFolderBase f1 = NewFolder(folder1, zero, owner1, name1);
// TODO: this is probably wrong behavior, but is what we have
// db.updateInventoryFolder(f1);
// InventoryFolderBase f1a = db.getUserRootFolder(owner1);
// Assert.That(uuid1, Is.EqualTo(f1a.ID))
// Assert.That(name1, Text.Matches(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))");
// Assert.That(db.getUserRootFolder(owner1), Is.Null);
// succeed with true
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner1);
Assert.That(folder1, Is.EqualTo(f1a.ID), "Assert.That(folder1, Is.EqualTo(f1a.ID))");
Assert.That(name1, Text.Matches(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))");
}
// we now have the following tree
// folder1
// +--- folder2
// +--- folder3
[Test]
public void T012_FolderList()
{
InventoryFolderBase f2 = NewFolder(folder3, folder1, owner1, name3);
db.addInventoryFolder(f2);
Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(2), "Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T013_FolderHierarchy()
{
int n = db.getFolderHierarchy(zero).Count; // (for dbg - easier to see what's returned)
Assert.That(n, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))");
n = db.getFolderHierarchy(folder1).Count;
Assert.That(n, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T014_MoveFolder()
{
InventoryFolderBase f2 = db.getInventoryFolder(folder2);
f2.ParentID = folder3;
db.moveInventoryFolder(f2);
Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T015_FolderHierarchy()
{
Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(1), "Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(1))");
Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0))");
}
// Item tests
[Test]
public void T100_NoItems()
{
Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(0))");
}
// TODO: Feeding a bad inventory item down the data path will
// crash the system. This is largely due to the builder
// routines. That should be fixed and tested for.
[Test]
public void T101_CreatItems()
{
db.addInventoryItem(NewItem(item1, folder3, owner1, iname1, asset1));
db.addInventoryItem(NewItem(item2, folder3, owner1, iname2, asset2));
db.addInventoryItem(NewItem(item3, folder3, owner1, iname3, asset3));
Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(3), "Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(3))");
}
[Test]
public void T102_CompareItems()
{
InventoryItemBase i1 = db.getInventoryItem(item1);
InventoryItemBase i2 = db.getInventoryItem(item2);
InventoryItemBase i3 = db.getInventoryItem(item3);
Assert.That(i1.Name, Is.EqualTo(iname1), "Assert.That(i1.Name, Is.EqualTo(iname1))");
Assert.That(i2.Name, Is.EqualTo(iname2), "Assert.That(i2.Name, Is.EqualTo(iname2))");
Assert.That(i3.Name, Is.EqualTo(iname3), "Assert.That(i3.Name, Is.EqualTo(iname3))");
Assert.That(i1.Owner, Is.EqualTo(owner1), "Assert.That(i1.Owner, Is.EqualTo(owner1))");
Assert.That(i2.Owner, Is.EqualTo(owner1), "Assert.That(i2.Owner, Is.EqualTo(owner1))");
Assert.That(i3.Owner, Is.EqualTo(owner1), "Assert.That(i3.Owner, Is.EqualTo(owner1))");
Assert.That(i1.AssetID, Is.EqualTo(asset1), "Assert.That(i1.AssetID, Is.EqualTo(asset1))");
Assert.That(i2.AssetID, Is.EqualTo(asset2), "Assert.That(i2.AssetID, Is.EqualTo(asset2))");
Assert.That(i3.AssetID, Is.EqualTo(asset3), "Assert.That(i3.AssetID, Is.EqualTo(asset3))");
}
[Test]
public void T103_UpdateItem()
{
// TODO: probably shouldn't have the ability to have an
// owner of an item in a folder not owned by the user
InventoryItemBase i1 = db.getInventoryItem(item1);
i1.Name = niname1;
i1.Description = niname1;
i1.Owner = owner2;
db.updateInventoryItem(i1);
i1 = db.getInventoryItem(item1);
Assert.That(i1.Name, Is.EqualTo(niname1), "Assert.That(i1.Name, Is.EqualTo(niname1))");
Assert.That(i1.Description, Is.EqualTo(niname1), "Assert.That(i1.Description, Is.EqualTo(niname1))");
Assert.That(i1.Owner, Is.EqualTo(owner2), "Assert.That(i1.Owner, Is.EqualTo(owner2))");
}
[Test]
public void T104_RandomUpdateItem()
{
PropertyScrambler<InventoryFolderBase> folderScrambler =
new PropertyScrambler<InventoryFolderBase>()
.DontScramble(x => x.Owner)
.DontScramble(x => x.ParentID)
.DontScramble(x => x.ID);
UUID owner = UUID.Random();
UUID folder = UUID.Random();
UUID rootId = UUID.Random();
UUID rootAsset = UUID.Random();
InventoryFolderBase f1 = NewFolder(folder, zero, owner, name1);
folderScrambler.Scramble(f1);
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner);
Assert.That(f1a, Constraints.PropertyCompareConstraint(f1));
folderScrambler.Scramble(f1a);
db.updateInventoryFolder(f1a);
InventoryFolderBase f1b = db.getUserRootFolder(owner);
Assert.That(f1b, Constraints.PropertyCompareConstraint(f1a));
//Now we have a valid folder to insert into, we can insert the item.
PropertyScrambler<InventoryItemBase> inventoryScrambler =
new PropertyScrambler<InventoryItemBase>()
.DontScramble(x => x.ID)
.DontScramble(x => x.AssetID)
.DontScramble(x => x.Owner)
.DontScramble(x => x.Folder);
InventoryItemBase root = NewItem(rootId, folder, owner, iname1, rootAsset);
inventoryScrambler.Scramble(root);
db.addInventoryItem(root);
InventoryItemBase expected = db.getInventoryItem(rootId);
Assert.That(expected, Constraints.PropertyCompareConstraint(root)
.IgnoreProperty(x => x.InvType)
.IgnoreProperty(x => x.CreatorIdAsUuid)
.IgnoreProperty(x => x.Description)
.IgnoreProperty(x => x.CreatorId));
inventoryScrambler.Scramble(expected);
db.updateInventoryItem(expected);
InventoryItemBase actual = db.getInventoryItem(rootId);
Assert.That(actual, Constraints.PropertyCompareConstraint(expected)
.IgnoreProperty(x => x.InvType)
.IgnoreProperty(x => x.CreatorIdAsUuid)
.IgnoreProperty(x => x.Description)
.IgnoreProperty(x => x.CreatorId));
}
[Test]
public void T999_StillNull()
{
// After all tests are run, these should still return no results
Assert.That(db.getInventoryFolder(zero), Is.Null);
Assert.That(db.getInventoryItem(zero), Is.Null);
Assert.That(db.getUserRootFolder(zero), Is.Null);
Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0))");
}
private InventoryItemBase NewItem(UUID id, UUID parent, UUID owner, string name, UUID asset)
{
InventoryItemBase i = new InventoryItemBase();
i.ID = id;
i.Folder = parent;
i.Owner = owner;
i.CreatorId = owner.ToString();
i.Name = name;
i.Description = name;
i.AssetID = asset;
return i;
}
private InventoryFolderBase NewFolder(UUID id, UUID parent, UUID owner, string name)
{
InventoryFolderBase f = new InventoryFolderBase();
f.ID = id;
f.ParentID = parent;
f.Owner = owner;
f.Name = name;
return f;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
using Orleans.Runtime;
using Orleans.Utilities;
namespace Orleans.Serialization
{
/// <summary>
/// Serializer for types which implement <see cref="ISerializable"/>, including the required constructor.
/// </summary>
internal sealed class DotNetSerializableSerializer : IKeyedSerializer
{
private readonly IFormatterConverter _formatterConverter = new FormatterConverter();
private readonly TypeInfo _serializableType = typeof(ISerializable).GetTypeInfo();
private readonly SerializationConstructorFactory _constructorFactory = new SerializationConstructorFactory();
private readonly SerializationCallbacksFactory _serializationCallbacks = new SerializationCallbacksFactory();
private readonly ValueTypeSerializerFactory _valueTypeSerializerFactory;
private readonly ITypeResolver _typeResolver;
private readonly ObjectSerializer _objectSerializer;
public DotNetSerializableSerializer(ITypeResolver typeResolver)
{
_typeResolver = typeResolver;
_objectSerializer = new ObjectSerializer(_constructorFactory, _serializationCallbacks, _formatterConverter);
_valueTypeSerializerFactory = new ValueTypeSerializerFactory(_constructorFactory, _serializationCallbacks, _formatterConverter);
}
/// <inheritdoc />
public KeyedSerializerId SerializerId => KeyedSerializerId.ISerializableSerializer;
/// <inheritdoc />
public bool IsSupportedType(Type itemType) => _serializableType.IsAssignableFrom(itemType) &&
(_constructorFactory.GetSerializationConstructor(itemType) != null || typeof(Exception).IsAssignableFrom(itemType));
/// <inheritdoc />
public object DeepCopy(object source, ICopyContext context)
{
var type = source.GetType();
if (type.IsValueType)
{
var serializer = _valueTypeSerializerFactory.GetSerializer(type);
return serializer.DeepCopy(source, context);
}
return _objectSerializer.DeepCopy(source, context);
}
/// <inheritdoc />
public void Serialize(object item, ISerializationContext context, Type expectedType)
{
var type = item.GetType();
if (typeof(Exception).IsAssignableFrom(type))
{
context.StreamWriter.Write((byte)SerializerTypeToken.Exception);
var typeName = RuntimeTypeNameFormatter.Format(type);
SerializationManager.SerializeInner(typeName, context);
_objectSerializer.Serialize(item, context);
}
else
{
context.StreamWriter.Write((byte)SerializerTypeToken.Other);
SerializationManager.SerializeInner(type, context);
if (type.IsValueType)
{
var serializer = _valueTypeSerializerFactory.GetSerializer(type);
serializer.Serialize(item, context);
}
else
{
_objectSerializer.Serialize(item, context);
}
}
}
/// <inheritdoc />
public object Deserialize(Type expectedType, IDeserializationContext context)
{
var startOffset = context.CurrentObjectOffset;
var token = (SerializerTypeToken)context.StreamReader.ReadByte();
if (token == SerializerTypeToken.Exception)
{
var typeName = SerializationManager.DeserializeInner<string>(context);
if (!_typeResolver.TryResolveType(typeName, out var type))
{
// Deserialize into a fallback type for unknown exceptions
// This means that missing fields will not be represented.
var result = (UnavailableExceptionFallbackException)_objectSerializer.Deserialize(typeof(UnavailableExceptionFallbackException), startOffset, context);
result.ExceptionType = typeName;
return result;
}
return _objectSerializer.Deserialize(type, startOffset, context);
}
else
{
var type = SerializationManager.DeserializeInner<Type>(context);
if (type.IsValueType)
{
var serializer = _valueTypeSerializerFactory.GetSerializer(type);
return serializer.Deserialize(type, startOffset, context);
}
return _objectSerializer.Deserialize(type, startOffset, context);
}
}
/// <summary>
/// Serializer for ISerializable reference types.
/// </summary>
internal class ObjectSerializer
{
private readonly IFormatterConverter _formatterConverter;
private readonly SerializationConstructorFactory _constructorFactory;
private readonly SerializationCallbacksFactory _serializationCallbacks;
public ObjectSerializer(
SerializationConstructorFactory constructorFactory,
SerializationCallbacksFactory serializationCallbacks,
IFormatterConverter formatterConverter)
{
_constructorFactory = constructorFactory;
_serializationCallbacks = serializationCallbacks;
_formatterConverter = formatterConverter;
}
/// <inheritdoc />
public object DeepCopy(object source, ICopyContext context)
{
var type = source.GetType();
var callbacks = _serializationCallbacks.GetReferenceTypeCallbacks(type);
var serializable = (ISerializable)source;
var result = FormatterServices.GetUninitializedObject(type);
context.RecordCopy(source, result);
// Shallow-copy the object into the serialization info.
var originalInfo = new SerializationInfo(type, _formatterConverter);
var streamingContext = new StreamingContext(StreamingContextStates.All, context);
callbacks.OnSerializing?.Invoke(source, streamingContext);
serializable.GetObjectData(originalInfo, streamingContext);
// Deep-copy the serialization info.
var copyInfo = new SerializationInfo(type, _formatterConverter);
foreach (var item in originalInfo)
{
copyInfo.AddValue(item.Name, SerializationManager.DeepCopyInner(item.Value, context));
}
callbacks.OnSerialized?.Invoke(source, streamingContext);
callbacks.OnDeserializing?.Invoke(result, streamingContext);
// Shallow-copy the serialization info into the result.
var constructor = _constructorFactory.GetSerializationConstructorDelegate(type);
constructor(result, copyInfo, streamingContext);
callbacks.OnDeserialized?.Invoke(result, streamingContext);
if (result is IDeserializationCallback callback)
{
callback.OnDeserialization(context);
}
return result;
}
/// <inheritdoc />
public void Serialize(object item, ISerializationContext context)
{
var type = item.GetType();
var callbacks = _serializationCallbacks.GetReferenceTypeCallbacks(type);
var info = new SerializationInfo(type, _formatterConverter);
var streamingContext = new StreamingContext(StreamingContextStates.All, context);
callbacks.OnSerializing?.Invoke(item, streamingContext);
((ISerializable)item).GetObjectData(info, streamingContext);
SerializationManager.SerializeInner(info.MemberCount, context);
foreach (var entry in info)
{
SerializationManager.SerializeInner(entry.Name, context);
var fieldType = entry.Value?.GetType();
SerializationManager.SerializeInner(fieldType, context);
SerializationManager.SerializeInner(entry.Value, context, fieldType);
}
callbacks.OnSerialized?.Invoke(item, streamingContext);
}
/// <inheritdoc />
public object Deserialize(Type type, int startOffset, IDeserializationContext context)
{
var callbacks = _serializationCallbacks.GetReferenceTypeCallbacks(type);
var result = FormatterServices.GetUninitializedObject(type);
context.RecordObject(result, startOffset);
var memberCount = SerializationManager.DeserializeInner<int>(context);
var info = new SerializationInfo(type, _formatterConverter);
var streamingContext = new StreamingContext(StreamingContextStates.All, context);
callbacks.OnDeserializing?.Invoke(result, streamingContext);
for (var i = 0; i < memberCount; i++)
{
var name = SerializationManager.DeserializeInner<string>(context);
var fieldType = SerializationManager.DeserializeInner<Type>(context);
var value = SerializationManager.DeserializeInner(fieldType, context);
info.AddValue(name, value);
}
var constructor = _constructorFactory.GetSerializationConstructorDelegate(type);
constructor(result, info, streamingContext);
callbacks.OnDeserialized?.Invoke(result, streamingContext);
if (result is IDeserializationCallback callback)
{
callback.OnDeserialization(context);
}
return result;
}
}
/// <summary>
/// Serializer for ISerializable value types.
/// </summary>
internal abstract class ValueTypeSerializer
{
public abstract object Deserialize(Type type, int startOffset, IDeserializationContext context);
public abstract void Serialize(object item, ISerializationContext context);
public abstract object DeepCopy(object source, ICopyContext context);
}
/// <summary>
/// Serializer for ISerializable value types.
/// </summary>
/// <typeparam name="T">The type which this serializer can serialize.</typeparam>
internal class ValueTypeSerializer<T> : ValueTypeSerializer where T : struct, ISerializable
{
public delegate void ValueConstructor(ref T value, SerializationInfo info, StreamingContext context);
public delegate void SerializationCallback(ref T value, StreamingContext context);
private readonly ValueConstructor _constructor;
private readonly SerializationCallbacksFactory.SerializationCallbacks<SerializationCallback> _callbacks;
private readonly IFormatterConverter _formatterConverter;
public ValueTypeSerializer(
ValueConstructor constructor,
SerializationCallbacksFactory.SerializationCallbacks<SerializationCallback> callbacks,
IFormatterConverter formatterConverter)
{
_constructor = constructor;
_callbacks = callbacks;
_formatterConverter = formatterConverter;
}
public override object Deserialize(Type type, int startOffset, IDeserializationContext context)
{
var result = default(T);
var memberCount = SerializationManager.DeserializeInner<int>(context);
var info = new SerializationInfo(type, _formatterConverter);
var streamingContext = new StreamingContext(StreamingContextStates.All, context);
_callbacks.OnDeserializing?.Invoke(ref result, streamingContext);
for (var i = 0; i < memberCount; i++)
{
var name = SerializationManager.DeserializeInner<string>(context);
var fieldType = SerializationManager.DeserializeInner<Type>(context);
var value = SerializationManager.DeserializeInner(fieldType, context);
info.AddValue(name, value);
}
_constructor(ref result, info, streamingContext);
_callbacks.OnDeserialized?.Invoke(ref result, streamingContext);
if (result is IDeserializationCallback callback)
{
callback.OnDeserialization(context);
}
return result;
}
public override void Serialize(object item, ISerializationContext context)
{
var localItem = (T)item;
var type = item.GetType();
var info = new SerializationInfo(type, _formatterConverter);
var streamingContext = new StreamingContext(StreamingContextStates.All, context);
_callbacks.OnSerializing?.Invoke(ref localItem, streamingContext);
localItem.GetObjectData(info, streamingContext);
SerializationManager.SerializeInner(info.MemberCount, context);
foreach (var entry in info)
{
SerializationManager.SerializeInner(entry.Name, context);
var fieldType = entry.Value?.GetType();
SerializationManager.SerializeInner(fieldType, context);
SerializationManager.SerializeInner(entry.Value, context, fieldType);
}
_callbacks.OnSerialized?.Invoke(ref localItem, streamingContext);
}
public override object DeepCopy(object source, ICopyContext context)
{
var localSource = (T)source;
var type = source.GetType();
var result = default(T);
// Shallow-copy the object into the serialization info.
var originalInfo = new SerializationInfo(type, _formatterConverter);
var streamingContext = new StreamingContext(StreamingContextStates.All, context);
_callbacks.OnSerializing?.Invoke(ref localSource, streamingContext);
localSource.GetObjectData(originalInfo, streamingContext);
// Deep-copy the serialization info.
var copyInfo = new SerializationInfo(type, _formatterConverter);
foreach (var item in originalInfo)
{
copyInfo.AddValue(item.Name, SerializationManager.DeepCopyInner(item.Value, context));
}
_callbacks.OnSerialized?.Invoke(ref localSource, streamingContext);
_callbacks.OnDeserializing?.Invoke(ref localSource, streamingContext);
// Shallow-copy the serialization info into the result.
_constructor(ref result, copyInfo, streamingContext);
_callbacks.OnDeserialized?.Invoke(ref result, streamingContext);
if (result is IDeserializationCallback callback)
{
callback.OnDeserialization(context);
}
return result;
}
}
/// <summary>
/// Creates <see cref="ValueTypeSerializer"/> instances for value types.
/// </summary>
internal class ValueTypeSerializerFactory
{
private readonly SerializationConstructorFactory _constructorFactory;
private readonly SerializationCallbacksFactory _callbacksFactory;
private readonly IFormatterConverter _formatterConverter;
private readonly Func<Type, ValueTypeSerializer> _createSerializerDelegate;
private readonly ConcurrentDictionary<Type, ValueTypeSerializer> _serializers = new ConcurrentDictionary<Type, ValueTypeSerializer>();
private readonly MethodInfo _createTypedSerializerMethodInfo = typeof(ValueTypeSerializerFactory).GetMethod(
nameof(CreateTypedSerializer),
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
public ValueTypeSerializerFactory(
SerializationConstructorFactory constructorFactory,
SerializationCallbacksFactory callbacksFactory,
IFormatterConverter formatterConverter)
{
_constructorFactory = constructorFactory;
_callbacksFactory = callbacksFactory;
_formatterConverter = formatterConverter;
_createSerializerDelegate = type => (ValueTypeSerializer)
_createTypedSerializerMethodInfo.MakeGenericMethod(type).Invoke(this, null);
}
public ValueTypeSerializer GetSerializer(Type type)
{
return _serializers.GetOrAdd(type, _createSerializerDelegate);
}
private ValueTypeSerializer CreateTypedSerializer<T>() where T : struct, ISerializable
{
var constructor = _constructorFactory.GetSerializationConstructorDelegate<T, ValueTypeSerializer<T>.ValueConstructor>();
var callbacks =
_callbacksFactory.GetValueTypeCallbacks<T, ValueTypeSerializer<T>.SerializationCallback>(typeof(T));
return new ValueTypeSerializer<T>(constructor, callbacks, _formatterConverter);
}
}
/// <summary>
/// Creates delegates for calling ISerializable-conformant constructors.
/// </summary>
internal class SerializationConstructorFactory
{
private static readonly Type[] SerializationConstructorParameterTypes = { typeof(SerializationInfo), typeof(StreamingContext) };
private readonly Func<Type, object> _createConstructorDelegate;
private readonly ConcurrentDictionary<Type, object> _constructors = new ConcurrentDictionary<Type, object>();
public SerializationConstructorFactory()
{
_createConstructorDelegate =
GetSerializationConstructorInvoker<object, Action<object, SerializationInfo, StreamingContext>>;
}
public Action<object, SerializationInfo, StreamingContext> GetSerializationConstructorDelegate(Type type)
{
return (Action<object, SerializationInfo, StreamingContext>)_constructors.GetOrAdd(
type,
_createConstructorDelegate);
}
public TConstructor GetSerializationConstructorDelegate<TOwner, TConstructor>()
{
return (TConstructor) _constructors.GetOrAdd(
typeof(TOwner),
type => (object) GetSerializationConstructorInvoker<TOwner, TConstructor>(type));
}
public ConstructorInfo GetSerializationConstructor(Type type)
{
return type.GetConstructor(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
null,
SerializationConstructorParameterTypes,
null);
}
private TConstructor GetSerializationConstructorInvoker<TOwner, TConstructor>(Type type)
{
var constructor = GetSerializationConstructor(type) ?? (typeof(Exception).IsAssignableFrom(type) ? GetSerializationConstructor(typeof(Exception)) : null);
if (constructor == null) throw new SerializationException($"{nameof(ISerializable)} constructor not found on type {type}.");
Type[] parameterTypes;
if (typeof(TOwner).IsValueType)
{
parameterTypes = new[] { typeof(TOwner).MakeByRefType(), typeof(SerializationInfo), typeof(StreamingContext) };
}
else
{
parameterTypes = new[] { typeof(object), typeof(SerializationInfo), typeof(StreamingContext) };
}
var method = new DynamicMethod($"{type}_serialization_ctor", null, parameterTypes, typeof(TOwner), skipVisibility: true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
if (type != typeof(TOwner))
{
il.Emit(OpCodes.Castclass, type);
}
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Call, constructor);
il.Emit(OpCodes.Ret);
object result = method.CreateDelegate(typeof(TConstructor));
return (TConstructor)result;
}
}
/// <summary>
/// Creates delegates for calling methods marked with serialization attributes.
/// </summary>
internal class SerializationCallbacksFactory
{
private readonly ConcurrentDictionary<Type, object> _cache = new ConcurrentDictionary<Type, object>();
private readonly Func<Type, object> _factory;
public SerializationCallbacksFactory()
{
_factory = CreateTypedCallbacks<object, Action<object, StreamingContext>>;
}
public SerializationCallbacks<Action<object, StreamingContext>> GetReferenceTypeCallbacks(Type type) => (
SerializationCallbacks<Action<object, StreamingContext>>)_cache.GetOrAdd(type, _factory);
public SerializationCallbacks<TDelegate> GetValueTypeCallbacks<TOwner, TDelegate>(Type type) => (
SerializationCallbacks<TDelegate>) _cache.GetOrAdd(type, t => (object) CreateTypedCallbacks<TOwner, TDelegate>(type));
private SerializationCallbacks<TDelegate> CreateTypedCallbacks<TOwner, TDelegate>(Type type)
{
var typeInfo = type.GetTypeInfo();
var onDeserializing = default(TDelegate);
var onDeserialized = default(TDelegate);
var onSerializing = default(TDelegate);
var onSerialized = default(TDelegate);
foreach (var method in typeInfo.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
var parameterInfos = method.GetParameters();
if (parameterInfos.Length != 1) continue;
if (parameterInfos[0].ParameterType != typeof(StreamingContext)) continue;
if (method.GetCustomAttribute<OnDeserializingAttribute>() != null)
{
onDeserializing = GetSerializationMethod<TOwner, TDelegate>(typeInfo, method);
}
if (method.GetCustomAttribute<OnDeserializedAttribute>() != null)
{
onDeserialized = GetSerializationMethod<TOwner, TDelegate>(typeInfo, method);
}
if (method.GetCustomAttribute<OnSerializingAttribute>() != null)
{
onSerializing = GetSerializationMethod<TOwner, TDelegate>(typeInfo, method);
}
if (method.GetCustomAttribute<OnSerializedAttribute>() != null)
{
onSerialized = GetSerializationMethod<TOwner, TDelegate>(typeInfo, method);
}
}
return new SerializationCallbacks<TDelegate>(onDeserializing, onDeserialized, onSerializing, onSerialized);
}
private static TDelegate GetSerializationMethod<TOwner, TDelegate>(Type type, MethodInfo callbackMethod)
{
Type[] callbackParameterTypes;
if (typeof(TOwner).IsValueType)
{
callbackParameterTypes = new[] { typeof(TOwner).MakeByRefType(), typeof(StreamingContext) };
}
else
{
callbackParameterTypes = new[] { typeof(object), typeof(StreamingContext) };
}
var method = new DynamicMethod($"{callbackMethod.Name}_Trampoline", null, callbackParameterTypes, type, skipVisibility: true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
if (type != typeof(TOwner))
{
il.Emit(OpCodes.Castclass, type);
}
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, callbackMethod);
il.Emit(OpCodes.Ret);
object result = method.CreateDelegate(typeof(TDelegate));
return (TDelegate)result;
}
public class SerializationCallbacks<TDelegate>
{
public SerializationCallbacks(
TDelegate onDeserializing,
TDelegate onDeserialized,
TDelegate onSerializing,
TDelegate onSerialized)
{
OnDeserializing = onDeserializing;
OnDeserialized = onDeserialized;
OnSerializing = onSerializing;
OnSerialized = onSerialized;
}
public TDelegate OnDeserializing { get; }
public TDelegate OnDeserialized { get; }
public TDelegate OnSerializing { get; }
public TDelegate OnSerialized { get; }
}
}
public enum SerializerTypeToken : byte
{
None = 0,
Exception = 1,
Other = 2
}
}
}
| |
/*
* 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.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.World.Warp3DMap
{
public static class TerrainSplat
{
#region Constants
private static readonly UUID DIRT_DETAIL = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
private static readonly UUID GRASS_DETAIL = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
private static readonly UUID MOUNTAIN_DETAIL = new UUID("303cd381-8560-7579-23f1-f0a880799740");
private static readonly UUID ROCK_DETAIL = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
private static readonly UUID[] DEFAULT_TERRAIN_DETAIL = new UUID[]
{
DIRT_DETAIL,
GRASS_DETAIL,
MOUNTAIN_DETAIL,
ROCK_DETAIL
};
private static readonly Color[] DEFAULT_TERRAIN_COLOR = new Color[]
{
Color.FromArgb(255, 164, 136, 117),
Color.FromArgb(255, 65, 87, 47),
Color.FromArgb(255, 157, 145, 131),
Color.FromArgb(255, 125, 128, 130)
};
private static readonly UUID TERRAIN_CACHE_MAGIC = new UUID("2c0c7ef2-56be-4eb8-aacb-76712c535b4b");
#endregion Constants
private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
private static string LogHeader = "[WARP3D TERRAIN SPLAT]";
/// <summary>
/// Builds a composited terrain texture given the region texture
/// and heightmap settings
/// </summary>
/// <param name="terrain">Terrain heightmap</param>
/// <param name="regionInfo">Region information including terrain texture parameters</param>
/// <returns>A 256x256 square RGB texture ready for rendering</returns>
/// <remarks>Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
/// Note we create a 256x256 dimension texture even if the actual terrain is larger.
/// </remarks>
public static Bitmap Splat(ITerrainChannel terrain, UUID[] textureIDs,
float[] startHeights, float[] heightRanges,
uint regionPositionX, uint regionPositionY,
IAssetService assetService, IJ2KDecoder decoder,
bool textureTerrain, bool averagetextureTerrain,
int twidth, int theight)
{
Debug.Assert(textureIDs.Length == 4);
Debug.Assert(startHeights.Length == 4);
Debug.Assert(heightRanges.Length == 4);
Bitmap[] detailTexture = new Bitmap[4];
byte[] mapColorsRed = new byte[4];
byte[] mapColorsGreen = new byte[4];
byte[] mapColorsBlue = new byte[4];
bool usecolors = false;
if (textureTerrain)
{
// Swap empty terrain textureIDs with default IDs
for(int i = 0; i < textureIDs.Length; i++)
{
if(textureIDs[i] == UUID.Zero)
textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
}
#region Texture Fetching
if(assetService != null)
{
for(int i = 0; i < 4; i++)
{
AssetBase asset = null;
// asset cache indexes are strings
string cacheName ="MAP-Patch" + textureIDs[i].ToString();
// Try to fetch a cached copy of the decoded/resized version of this texture
asset = assetService.GetCached(cacheName);
if(asset != null)
{
try
{
using(System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
detailTexture[i] = (Bitmap)Image.FromStream(stream);
if(detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
{
detailTexture[i].Dispose();
detailTexture[i] = null;
}
}
catch(Exception ex)
{
m_log.Warn("Failed to decode cached terrain patch texture" + textureIDs[i] + "): " + ex.Message);
}
}
if(detailTexture[i] == null)
{
// Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
asset = assetService.Get(textureIDs[i].ToString());
if(asset != null)
{
try
{
detailTexture[i] = (Bitmap)decoder.DecodeToImage(asset.Data);
}
catch(Exception ex)
{
m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
}
}
if(detailTexture[i] != null)
{
if(detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
using(Bitmap origBitmap = detailTexture[i])
detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
// Save the decoded and resized texture to the cache
byte[] data;
using(System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
detailTexture[i].Save(stream, ImageFormat.Png);
data = stream.ToArray();
}
// Cache a PNG copy of this terrain texture
AssetBase newAsset = new AssetBase
{
Data = data,
Description = "PNG",
Flags = AssetFlags.Collectable,
FullID = UUID.Zero,
ID = cacheName,
Local = true,
Name = String.Empty,
Temporary = true,
Type = (sbyte)AssetType.Unknown
};
newAsset.Metadata.ContentType = "image/png";
assetService.Store(newAsset);
}
}
}
}
#endregion Texture Fetching
if(averagetextureTerrain)
{
for(int t = 0; t < 4; t++)
{
usecolors = true;
if(detailTexture[t] == null)
{
mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
continue;
}
int npixeis = 0;
int cR = 0;
int cG = 0;
int cB = 0;
BitmapData bmdata = detailTexture[t].LockBits(new Rectangle(0, 0, 16, 16),
ImageLockMode.ReadOnly, detailTexture[t].PixelFormat);
npixeis = bmdata.Height * bmdata.Width;
int ylen = bmdata.Height * bmdata.Stride;
unsafe
{
for(int y = 0; y < ylen; y += bmdata.Stride)
{
byte* ptrc = (byte*)bmdata.Scan0 + y;
for(int x = 0 ; x < bmdata.Width; ++x)
{
cR += *(ptrc++);
cG += *(ptrc++);
cB += *(ptrc++);
}
}
}
detailTexture[t].UnlockBits(bmdata);
detailTexture[t].Dispose();
mapColorsRed[t] = (byte)Util.Clamp(cR / npixeis, 0 , 255);
mapColorsGreen[t] = (byte)Util.Clamp(cG / npixeis, 0 , 255);
mapColorsBlue[t] = (byte)Util.Clamp(cB / npixeis, 0 , 255);
}
}
else
{
// Fill in any missing textures with a solid color
for(int i = 0; i < 4; i++)
{
if(detailTexture[i] == null)
{
m_log.DebugFormat("{0} Missing terrain texture for layer {1}. Filling with solid default color", LogHeader, i);
// Create a solid color texture for this layer
detailTexture[i] = new Bitmap(16, 16, PixelFormat.Format24bppRgb);
using(Graphics gfx = Graphics.FromImage(detailTexture[i]))
{
using(SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
gfx.FillRectangle(brush, 0, 0, 16, 16);
}
}
else
{
if(detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
{
using(Bitmap origBitmap = detailTexture[i])
detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
}
}
}
}
}
else
{
usecolors = true;
for(int t = 0; t < 4; t++)
{
mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
}
}
#region Layer Map
float xFactor = terrain.Width / twidth;
float yFactor = terrain.Height / theight;
#endregion Layer Map
#region Texture Compositing
Bitmap output = new Bitmap(twidth, theight, PixelFormat.Format24bppRgb);
BitmapData outputData = output.LockBits(new Rectangle(0, 0, twidth, theight), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
// Unsafe work as we lock down the source textures for quicker access and access the
// pixel data directly
float invtwitdthMinus1 = 1.0f / (twidth - 1);
float invtheightMinus1 = 1.0f / (theight - 1);
int ty;
int tx;
float pctx;
float pcty;
float height;
float layer;
float layerDiff;
int l0;
int l1;
uint yglobalpos;
if(usecolors)
{
float a;
float b;
unsafe
{
byte* ptrO;
for(int y = 0; y < theight; ++y)
{
pcty = y * invtheightMinus1;
ptrO = (byte*)outputData.Scan0 + y * outputData.Stride;
ty = (int)(y * yFactor);
yglobalpos = (uint)ty + regionPositionY;
for(int x = 0; x < twidth; ++x)
{
tx = (int)(x * xFactor);
pctx = x * invtwitdthMinus1;
height = (float)terrain[tx, ty];
layer = getLayerTex(height, pctx, pcty,
(uint)tx + regionPositionX, yglobalpos,
startHeights, heightRanges);
// Select two textures
l0 = (int)layer;
l1 = Math.Min(l0 + 1, 3);
layerDiff = layer - l0;
a = mapColorsRed[l0];
b = mapColorsRed[l1];
*(ptrO++) = (byte)(a + layerDiff * (b - a));
a = mapColorsGreen[l0];
b = mapColorsGreen[l1];
*(ptrO++) = (byte)(a + layerDiff * (b - a));
a = mapColorsBlue[l0];
b = mapColorsBlue[l1];
*(ptrO++) = (byte)(a + layerDiff * (b - a));
}
}
}
}
else
{
float aB;
float aG;
float aR;
float bB;
float bG;
float bR;
unsafe
{
// Get handles to all of the texture data arrays
BitmapData[] datas = new BitmapData[]
{
detailTexture[0].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
detailTexture[1].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
detailTexture[2].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
detailTexture[3].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
};
byte* ptr;
byte* ptrO;
for(int y = 0; y < theight; y++)
{
pcty = y * invtheightMinus1;
int ypatch = ((int)(y * yFactor) & 0x0f) * datas[0].Stride;
ptrO = (byte*)outputData.Scan0 + y * outputData.Stride;
ty = (int)(y * yFactor);
yglobalpos = (uint)ty + regionPositionY;
for(int x = 0; x < twidth; x++)
{
tx = (int)(x * xFactor);
pctx = x * invtwitdthMinus1;
height = (float)terrain[tx, ty];
layer = getLayerTex(height, pctx, pcty,
(uint)tx + regionPositionX, yglobalpos,
startHeights, heightRanges);
// Select two textures
l0 = (int)layer;
layerDiff = layer - l0;
int patchOffset = (tx & 0x0f) * 3 + ypatch;
ptr = (byte*)datas[l0].Scan0 + patchOffset;
aB = *(ptr++);
aG = *(ptr++);
aR = *(ptr);
l1 = Math.Min(l0 + 1, 3);
ptr = (byte*)datas[l1].Scan0 + patchOffset;
bB = *(ptr++);
bG = *(ptr++);
bR = *(ptr);
// Interpolate between the two selected textures
*(ptrO++) = (byte)(aB + layerDiff * (bB - aB));
*(ptrO++) = (byte)(aG + layerDiff * (bG - aG));
*(ptrO++) = (byte)(aR + layerDiff * (bR - aR));
}
}
for(int i = 0; i < detailTexture.Length; i++)
detailTexture[i].UnlockBits(datas[i]);
}
for(int i = 0; i < detailTexture.Length; i++)
if(detailTexture[i] != null)
detailTexture[i].Dispose();
}
output.UnlockBits(outputData);
//output.Save("terr.png",ImageFormat.Png);
#endregion Texture Compositing
return output;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private static float getLayerTex(float height, float pctX, float pctY, uint X, uint Y,
float[] startHeights, float[] heightRanges)
{
// Use bilinear interpolation between the four corners of start height and
// height range to select the current values at this position
float startHeight = ImageUtils.Bilinear(
startHeights[0], startHeights[2],
startHeights[1], startHeights[3],
pctX, pctY);
startHeight = Utils.Clamp(startHeight, 0f, 255f);
float heightRange = ImageUtils.Bilinear(
heightRanges[0], heightRanges[2],
heightRanges[1], heightRanges[3],
pctX, pctY);
heightRange = Utils.Clamp(heightRange, 0f, 255f);
if(heightRange == 0f)
return 0;
// Generate two frequencies of perlin noise based on our global position
// The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
float sX = X * 0.20319f;
float sY = Y * 0.20319f;
float noise = Perlin.noise2(sX * 0.222222f, sY * 0.222222f) * 13.0f;
noise += Perlin.turbulence2(sX, sY, 2f) * 4.5f;
// Combine the current height, generated noise, start height, and height range parameters, then scale all of it
float layer = ((height + noise - startHeight) / heightRange) * 4f;
return Utils.Clamp(layer, 0f, 3f);
}
}
}
| |
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ChargeBee.Internal;
using ChargeBee.Api;
using ChargeBee.Models.Enums;
using ChargeBee.Filters.Enums;
namespace ChargeBee.Models
{
public class Address : Resource
{
public Address() { }
public Address(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
}
public Address(TextReader reader)
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
public Address(String jsonString)
{
JObj = JToken.Parse(jsonString);
apiVersionCheck (JObj);
}
#region Methods
public static RetrieveRequest Retrieve()
{
string url = ApiUtil.BuildUrl("addresses");
return new RetrieveRequest(url, HttpMethod.GET);
}
public static UpdateRequest Update()
{
string url = ApiUtil.BuildUrl("addresses");
return new UpdateRequest(url, HttpMethod.POST);
}
#endregion
#region Properties
public string Label
{
get { return GetValue<string>("label", true); }
}
public string FirstName
{
get { return GetValue<string>("first_name", false); }
}
public string LastName
{
get { return GetValue<string>("last_name", false); }
}
public string Email
{
get { return GetValue<string>("email", false); }
}
public string Company
{
get { return GetValue<string>("company", false); }
}
public string Phone
{
get { return GetValue<string>("phone", false); }
}
public string Addr
{
get { return GetValue<string>("addr", false); }
}
public string ExtendedAddr
{
get { return GetValue<string>("extended_addr", false); }
}
public string ExtendedAddr2
{
get { return GetValue<string>("extended_addr2", false); }
}
public string City
{
get { return GetValue<string>("city", false); }
}
public string StateCode
{
get { return GetValue<string>("state_code", false); }
}
public string State
{
get { return GetValue<string>("state", false); }
}
public string Country
{
get { return GetValue<string>("country", false); }
}
public string Zip
{
get { return GetValue<string>("zip", false); }
}
public ValidationStatusEnum? ValidationStatus
{
get { return GetEnum<ValidationStatusEnum>("validation_status", false); }
}
public string SubscriptionId
{
get { return GetValue<string>("subscription_id", true); }
}
#endregion
#region Requests
public class RetrieveRequest : EntityRequest<RetrieveRequest>
{
public RetrieveRequest(string url, HttpMethod method)
: base(url, method)
{
}
public RetrieveRequest SubscriptionId(string subscriptionId)
{
m_params.Add("subscription_id", subscriptionId);
return this;
}
public RetrieveRequest Label(string label)
{
m_params.Add("label", label);
return this;
}
}
public class UpdateRequest : EntityRequest<UpdateRequest>
{
public UpdateRequest(string url, HttpMethod method)
: base(url, method)
{
}
public UpdateRequest SubscriptionId(string subscriptionId)
{
m_params.Add("subscription_id", subscriptionId);
return this;
}
public UpdateRequest Label(string label)
{
m_params.Add("label", label);
return this;
}
public UpdateRequest FirstName(string firstName)
{
m_params.AddOpt("first_name", firstName);
return this;
}
public UpdateRequest LastName(string lastName)
{
m_params.AddOpt("last_name", lastName);
return this;
}
public UpdateRequest Email(string email)
{
m_params.AddOpt("email", email);
return this;
}
public UpdateRequest Company(string company)
{
m_params.AddOpt("company", company);
return this;
}
public UpdateRequest Phone(string phone)
{
m_params.AddOpt("phone", phone);
return this;
}
public UpdateRequest Addr(string addr)
{
m_params.AddOpt("addr", addr);
return this;
}
public UpdateRequest ExtendedAddr(string extendedAddr)
{
m_params.AddOpt("extended_addr", extendedAddr);
return this;
}
public UpdateRequest ExtendedAddr2(string extendedAddr2)
{
m_params.AddOpt("extended_addr2", extendedAddr2);
return this;
}
public UpdateRequest City(string city)
{
m_params.AddOpt("city", city);
return this;
}
public UpdateRequest StateCode(string stateCode)
{
m_params.AddOpt("state_code", stateCode);
return this;
}
public UpdateRequest State(string state)
{
m_params.AddOpt("state", state);
return this;
}
public UpdateRequest Zip(string zip)
{
m_params.AddOpt("zip", zip);
return this;
}
public UpdateRequest Country(string country)
{
m_params.AddOpt("country", country);
return this;
}
public UpdateRequest ValidationStatus(ChargeBee.Models.Enums.ValidationStatusEnum validationStatus)
{
m_params.AddOpt("validation_status", validationStatus);
return this;
}
}
#endregion
#region Subclasses
#endregion
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Core.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
using Frapid.WebApi;
namespace Frapid.Core.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Menus.
/// </summary>
[RoutePrefix("api/v1.0/core/menu")]
public class CoreMenuController : FrapidApiController
{
/// <summary>
/// The Menu repository.
/// </summary>
private IMenuRepository MenuRepository;
public CoreMenuController()
{
}
public CoreMenuController(IMenuRepository repository)
{
this.MenuRepository = repository;
}
protected override void Initialize(HttpControllerContext context)
{
base.Initialize(context);
if (this.MenuRepository == null)
{
this.MenuRepository = new Frapid.Core.DataAccess.Menu
{
_Catalog = this.MetaUser.Catalog,
_LoginId = this.MetaUser.LoginId,
_UserId = this.MetaUser.UserId
};
}
}
/// <summary>
/// Creates meta information of "menu" entity.
/// </summary>
/// <returns>Returns the "menu" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/core/menu/meta")]
[RestAuthorize]
public EntityView GetEntityView()
{
return new EntityView
{
PrimaryKey = "menu_id",
Columns = new List<EntityColumn>()
{
new EntityColumn
{
ColumnName = "menu_id",
PropertyName = "MenuId",
DataType = "int",
DbDataType = "int4",
IsNullable = false,
IsPrimaryKey = true,
IsSerial = true,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "sort",
PropertyName = "Sort",
DataType = "int",
DbDataType = "int4",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "app_name",
PropertyName = "AppName",
DataType = "string",
DbDataType = "varchar",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 100
},
new EntityColumn
{
ColumnName = "menu_name",
PropertyName = "MenuName",
DataType = "string",
DbDataType = "varchar",
IsNullable = false,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 100
},
new EntityColumn
{
ColumnName = "url",
PropertyName = "Url",
DataType = "string",
DbDataType = "text",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
},
new EntityColumn
{
ColumnName = "icon",
PropertyName = "Icon",
DataType = "string",
DbDataType = "varchar",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 100
},
new EntityColumn
{
ColumnName = "parent_menu_id",
PropertyName = "ParentMenuId",
DataType = "int",
DbDataType = "int4",
IsNullable = true,
IsPrimaryKey = false,
IsSerial = false,
Value = "",
MaxLength = 0
}
}
};
}
/// <summary>
/// Counts the number of menus.
/// </summary>
/// <returns>Returns the count of the menus.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/core/menu/count")]
[RestAuthorize]
public long Count()
{
try
{
return this.MenuRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of menu.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/core/menu/all")]
[RestAuthorize]
public IEnumerable<Frapid.Core.Entities.Menu> GetAll()
{
try
{
return this.MenuRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of menu for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/core/menu/export")]
[RestAuthorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.MenuRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of menu.
/// </summary>
/// <param name="menuId">Enter MenuId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{menuId}")]
[Route("~/api/core/menu/{menuId}")]
[RestAuthorize]
public Frapid.Core.Entities.Menu Get(int menuId)
{
try
{
return this.MenuRepository.Get(menuId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/core/menu/get")]
[RestAuthorize]
public IEnumerable<Frapid.Core.Entities.Menu> Get([FromUri] int[] menuIds)
{
try
{
return this.MenuRepository.Get(menuIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of menu.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/core/menu/first")]
[RestAuthorize]
public Frapid.Core.Entities.Menu GetFirst()
{
try
{
return this.MenuRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of menu.
/// </summary>
/// <param name="menuId">Enter MenuId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{menuId}")]
[Route("~/api/core/menu/previous/{menuId}")]
[RestAuthorize]
public Frapid.Core.Entities.Menu GetPrevious(int menuId)
{
try
{
return this.MenuRepository.GetPrevious(menuId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of menu.
/// </summary>
/// <param name="menuId">Enter MenuId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{menuId}")]
[Route("~/api/core/menu/next/{menuId}")]
[RestAuthorize]
public Frapid.Core.Entities.Menu GetNext(int menuId)
{
try
{
return this.MenuRepository.GetNext(menuId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of menu.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/core/menu/last")]
[RestAuthorize]
public Frapid.Core.Entities.Menu GetLast()
{
try
{
return this.MenuRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 menus on each page, sorted by the property MenuId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/core/menu")]
[RestAuthorize]
public IEnumerable<Frapid.Core.Entities.Menu> GetPaginatedResult()
{
try
{
return this.MenuRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 menus on each page, sorted by the property MenuId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/core/menu/page/{pageNumber}")]
[RestAuthorize]
public IEnumerable<Frapid.Core.Entities.Menu> GetPaginatedResult(long pageNumber)
{
try
{
return this.MenuRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of menus using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered menus.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/core/menu/count-where")]
[RestAuthorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.MenuRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 menus on each page, sorted by the property MenuId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/core/menu/get-where/{pageNumber}")]
[RestAuthorize]
public IEnumerable<Frapid.Core.Entities.Menu> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.MenuRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of menus using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered menus.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/core/menu/count-filtered/{filterName}")]
[RestAuthorize]
public long CountFiltered(string filterName)
{
try
{
return this.MenuRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 menus on each page, sorted by the property MenuId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/core/menu/get-filtered/{pageNumber}/{filterName}")]
[RestAuthorize]
public IEnumerable<Frapid.Core.Entities.Menu> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.MenuRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of menus.
/// </summary>
/// <returns>Returns an enumerable key/value collection of menus.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/core/menu/display-fields")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.MenuRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for menus.
/// </summary>
/// <returns>Returns an enumerable custom field collection of menus.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/core/menu/custom-fields")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.MenuRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for menus.
/// </summary>
/// <returns>Returns an enumerable custom field collection of menus.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/core/menu/custom-fields/{resourceId}")]
[RestAuthorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.MenuRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of Menu class.
/// </summary>
/// <param name="menu">Your instance of menus class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/core/menu/add-or-edit")]
[RestAuthorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic menu = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (menu == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.MenuRepository.AddOrEdit(menu, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of Menu class.
/// </summary>
/// <param name="menu">Your instance of menus class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{menu}")]
[Route("~/api/core/menu/add/{menu}")]
[RestAuthorize]
public void Add(Frapid.Core.Entities.Menu menu)
{
if (menu == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.MenuRepository.Add(menu);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of Menu class.
/// </summary>
/// <param name="menu">Your instance of Menu class to edit.</param>
/// <param name="menuId">Enter the value for MenuId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{menuId}")]
[Route("~/api/core/menu/edit/{menuId}")]
[RestAuthorize]
public void Edit(int menuId, [FromBody] Frapid.Core.Entities.Menu menu)
{
if (menu == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.MenuRepository.Update(menu, menuId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of Menu class.
/// </summary>
/// <param name="collection">Your collection of Menu class to bulk import.</param>
/// <returns>Returns list of imported menuIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any Menu class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/core/menu/bulk-import")]
[RestAuthorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> menuCollection = this.ParseCollection(collection);
if (menuCollection == null || menuCollection.Count.Equals(0))
{
return null;
}
try
{
return this.MenuRepository.BulkImport(menuCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of Menu class via MenuId.
/// </summary>
/// <param name="menuId">Enter the value for MenuId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{menuId}")]
[Route("~/api/core/menu/delete/{menuId}")]
[RestAuthorize]
public void Delete(int menuId)
{
try
{
this.MenuRepository.Delete(menuId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Automation
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AutomationAccountOperations operations.
/// </summary>
public partial interface IAutomationAccountOperations
{
/// <summary>
/// Update an automation account.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// Automation account name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the update automation account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AutomationAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, AutomationAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update automation account.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// Parameters supplied to the create or update automation account.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update automation account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AutomationAccount>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, AutomationAccountCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete an automation account.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// Automation account name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get information about an Automation Account.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AutomationAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve a list of accounts within a given resource group.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AutomationAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Automation Accounts within an Azure subscription.
/// </summary>
/// <remarks>
/// Retrieve a list of accounts within a given subscription.
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AutomationAccount>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve a list of accounts within a given resource group.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AutomationAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Automation Accounts within an Azure subscription.
/// </summary>
/// <remarks>
/// Retrieve a list of accounts within a given subscription.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AutomationAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace UnityTest
{
[Serializable]
public class IntegrationTestRunnerRenderer
{
private static class Styles
{
public static readonly GUIStyle selectedTestStyle;
public static readonly GUIStyle testStyle;
public static readonly GUIStyle selectedTestGroupStyle;
public static readonly GUIStyle testGroupStyle;
public static readonly GUIStyle iconStyle;
public static GUIStyle buttonLeft;
public static GUIStyle buttonMid;
public static GUIStyle buttonRight;
static Styles ()
{
testStyle = new GUIStyle (EditorStyles.label);
selectedTestStyle = new GUIStyle (EditorStyles.label);
selectedTestStyle.active.textColor = selectedTestStyle.normal.textColor = selectedTestStyle.onActive.textColor = new Color (0.3f, 0.5f, 0.85f);
testGroupStyle = new GUIStyle(EditorStyles.foldout);
selectedTestGroupStyle = new GUIStyle (EditorStyles.foldout);
selectedTestGroupStyle.active.textColor
= selectedTestGroupStyle.normal.textColor
= selectedTestGroupStyle.onNormal.textColor
= selectedTestGroupStyle.focused.textColor
= selectedTestGroupStyle.onFocused.textColor
= selectedTestGroupStyle.onActive.textColor
= new Color (0.3f, 0.5f, 0.85f);
iconStyle = new GUIStyle(EditorStyles.label);
iconStyle.fixedWidth = 24;
buttonLeft = GUI.skin.FindStyle (GUI.skin.button.name + "left");
buttonMid = GUI.skin.FindStyle (GUI.skin.button.name + "mid");
buttonRight = GUI.skin.FindStyle (GUI.skin.button.name + "right");
}
}
private Action<IList<TestComponent>> RunTest;
private TestManager testManager;
private bool showDetails;
#region runner options vars
[SerializeField] private bool showOptions;
[SerializeField] private bool addNewGameObjectUnderSelectedTest;
[SerializeField] internal bool blockUIWhenRunning = true;
#endregion
#region filter vars
[SerializeField] private bool showAdvancedFilter;
[SerializeField] private string filterString = "";
[SerializeField] private bool showSucceededTest = true;
[SerializeField] internal bool showFailedTest = true;
[SerializeField] private bool showNotRunnedTest = true;
[SerializeField] private bool showIgnoredTest = true;
#endregion
#region runner steering vars
[SerializeField] private Vector2 testListScroll;
[SerializeField] public bool forceRepaint;
[SerializeField] private List<TestResult> foldedGroups = new List<TestResult> ();
private List<TestResult> selectedTests = new List<TestResult>();
#endregion
#region GUI Contents
private readonly GUIContent guiOptionsHideLabel = new GUIContent ("Hide", Icons.gearImg);
private readonly GUIContent guiOptionsShowLabel = new GUIContent ("Options", Icons.gearImg);
private readonly GUIContent guiCreateNewTest = new GUIContent (Icons.plusImg, "Create new test");
private readonly GUIContent guiRunSelectedTests = new GUIContent (Icons.runImg, "Run selected test(s)");
private readonly GUIContent guiRunAllTests = new GUIContent (Icons.runAllImg, "Run all tests");
private readonly GUIContent guiAdvancedFilterShow = new GUIContent ("Advanced");
private readonly GUIContent guiAdvancedFilterHide = new GUIContent ("Hide");
private readonly GUIContent guiTimeoutIcon = new GUIContent (Icons.stopwatchImg, "Timeout");
private readonly GUIContent guiRunSelected = new GUIContent ("Run selected");
private readonly GUIContent guiRun = new GUIContent ("Run");
private readonly GUIContent guiRunAll = new GUIContent ("Run All");
private readonly GUIContent guiRunAllIncludingIgnored = new GUIContent ("Run All (include ignored)");
private readonly GUIContent guiDelete = new GUIContent ("Delete");
private readonly GUIContent guiAddGOUderTest = new GUIContent ("Add GOs under test", "Add new GameObject under selected test");
private readonly GUIContent guiBlockUI = new GUIContent ("Block UI when running", "Block UI when running tests");
#endregion
public IntegrationTestRunnerRenderer (Action<IList<TestComponent>> RunTest)
{
testManager = new TestManager ();
this.RunTest = RunTest;
if (EditorPrefs.HasKey ("ITR-addNewGameObjectUnderSelectedTest"))
{
addNewGameObjectUnderSelectedTest = EditorPrefs.GetBool ("ITR-addNewGameObjectUnderSelectedTest");
showOptions = EditorPrefs.GetBool ("ITR-showOptions");
blockUIWhenRunning = EditorPrefs.GetBool ("ITR-blockUIWhenRunning");
showAdvancedFilter = EditorPrefs.GetBool ("ITR-showAdvancedFilter");
filterString = EditorPrefs.GetString ("ITR-filterString");
showSucceededTest = EditorPrefs.GetBool ("ITR-showSucceededTest");
showFailedTest = EditorPrefs.GetBool ("ITR-showFailedTest");
showIgnoredTest = EditorPrefs.GetBool ("ITR-showIgnoredTest");
showNotRunnedTest = EditorPrefs.GetBool ("ITR-showNotRunnedTest");
}
#if !(UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.undoRedoPerformed += InvalidateTestList;
#endif
}
private void SaveSettings()
{
EditorPrefs.SetBool("ITR-addNewGameObjectUnderSelectedTest", addNewGameObjectUnderSelectedTest);
EditorPrefs.SetBool("ITR-showOptions", showOptions);
EditorPrefs.SetBool("ITR-blockUIWhenRunning", blockUIWhenRunning);
EditorPrefs.SetBool ("ITR-showAdvancedFilter", showAdvancedFilter);
EditorPrefs.SetString ("ITR-filterString", filterString);
EditorPrefs.SetBool ("ITR-showSucceededTest", showSucceededTest);
EditorPrefs.SetBool ("ITR-showFailedTest", showFailedTest);
EditorPrefs.SetBool ("ITR-showIgnoredTest", showIgnoredTest);
EditorPrefs.SetBool ("ITR-showNotRunnedTest", showNotRunnedTest);
}
private void DrawTest ( TestResult testInfo, int indent )
{
EditorGUILayout.BeginHorizontal ();
GUILayout.Space (--indent * 15 +10);
EditorGUIUtility.SetIconSize (new Vector2 (15, 15));
Color tempColor = GUI.color;
if (testInfo.isRunning)
{
var frame = Mathf.Abs (Mathf.Cos (Time.realtimeSinceStartup * 4)) * 0.6f + 0.4f;
GUI.color = new Color (1, 1, 1, frame);
}
var label = new GUIContent (testInfo.Name, GetIconBasedOnResultType (testInfo).image);
var labelRect = GUILayoutUtility.GetRect (label, EditorStyles.label, GUILayout.ExpandWidth (true));
if (labelRect.Contains (Event.current.mousePosition)
&& Event.current.type == EventType.MouseDown
&& Event.current.button == 0)
{
SelectTest (testInfo);
}
else if (labelRect.Contains (Event.current.mousePosition)
&& Event.current.type == EventType.ContextClick)
{
Event.current.Use ();
DrawContextTestMenu (testInfo);
}
EditorGUI.LabelField (labelRect,
label,
selectedTests.Contains (testInfo) ? Styles.selectedTestStyle : Styles.testStyle);
if (testInfo.isRunning) GUI.color = tempColor;
EditorGUIUtility.SetIconSize (Vector2.zero);
if (testInfo.resultType == TestResult.ResultType.Timeout)
{
GUILayout.Label (guiTimeoutIcon,
GUILayout.Width (24)
);
GUILayout.FlexibleSpace ();
}
EditorGUILayout.EndHorizontal ();
}
private bool DrawTestGroup ( TestResult testInfo, int indent )
{
EditorGUILayout.BeginHorizontal ();
GUILayout.Space (--indent * 15);
EditorGUIUtility.SetIconSize (new Vector2 (15, 15));
Color tempColor = GUI.color;
if (testInfo.isRunning)
{
var frame = Mathf.Abs (Mathf.Cos (Time.realtimeSinceStartup * 4)) * 0.6f + 0.4f;
GUI.color = new Color (1, 1, 1, frame);
}
var label = new GUIContent (testInfo.Name, GetIconBasedOnResultType (testInfo).image);
var labelRect = GUILayoutUtility.GetRect (label, EditorStyles.label, GUILayout.ExpandWidth (true));
if (labelRect.Contains (Event.current.mousePosition)
&& Event.current.type == EventType.MouseDown
&& Event.current.button == 0)
{
SelectTest (testInfo);
}
else if (labelRect.Contains (Event.current.mousePosition)
&& Event.current.type == EventType.ContextClick)
{
Event.current.Use ();
DrawContextTestMenu (testInfo);
}
bool isClassFolded = foldedGroups.Contains (testInfo);
EditorGUI.BeginChangeCheck ();
isClassFolded = !EditorGUI.Foldout (labelRect, !isClassFolded, label
,selectedTests.Contains (testInfo) ? Styles.selectedTestGroupStyle : Styles.testGroupStyle
);
if (EditorGUI.EndChangeCheck ())
{
if (isClassFolded)
foldedGroups.Add (testInfo);
else
foldedGroups.Remove (testInfo);
}
if (testInfo.isRunning) GUI.color = tempColor;
EditorGUIUtility.SetIconSize (Vector2.zero);
if (testInfo.resultType == TestResult.ResultType.Timeout)
{
GUILayout.Label (guiTimeoutIcon,
GUILayout.Width (24)
);
GUILayout.FlexibleSpace ();
}
EditorGUILayout.EndHorizontal ();
return !isClassFolded;
}
private void SelectTest (TestResult testToSelect)
{
if (!Event.current.control && !Event.current.shift)
selectedTests.Clear();
if (Event.current.control && selectedTests.Contains (testToSelect))
selectedTests.Remove (testToSelect);
else if (Event.current.shift && selectedTests.Any ())
{
var tests = testManager.GetTestsToSelect(selectedTests, testToSelect);
selectedTests.Clear ();
selectedTests.AddRange (tests);
}
else
selectedTests.Add (testToSelect);
if (!EditorApplication.isPlayingOrWillChangePlaymode && selectedTests.Count == 1)
{
var selectedTest = selectedTests.Single ();
testManager.SelectInHierarchy(selectedTest);
EditorApplication.RepaintHierarchyWindow ();
}
Selection.objects = selectedTests.Select (result => result.GameObject).ToArray ();
forceRepaint = true;
GUI.FocusControl("");
}
private GUIContent GetIconBasedOnResultType (TestResult result)
{
if (result == null)
return Icons.guiUnknownImg;
if (result.TestComponent.IsTestGroup ())
{
var childrenResults = testManager.GetChildrenTestsResults (result.TestComponent);
if (childrenResults.Any (t => t.resultType == TestResult.ResultType.Failed
|| t.resultType == TestResult.ResultType.FailedException
|| t.resultType == TestResult.ResultType.Timeout))
result.resultType = TestResult.ResultType.Failed;
else if (childrenResults.Any (t => t.resultType == TestResult.ResultType.Success))
result.resultType = TestResult.ResultType.Success;
else if (childrenResults.All (t => t.TestComponent.ignored))
result.resultType = TestResult.ResultType.Ignored;
else
result.resultType = TestResult.ResultType.NotRun;
result.isRunning = childrenResults.Any (t => t.isRunning);
}
if (result.isRunning)
return Icons.guiUnknownImg;
if (result.resultType == TestResult.ResultType.NotRun
&& result.TestComponent.ignored)
return Icons.guiIgnoreImg;
switch (result.resultType)
{
case TestResult.ResultType.Success:
return Icons.guiSuccessImg;
case TestResult.ResultType.Timeout:
case TestResult.ResultType.Failed:
case TestResult.ResultType.FailedException:
return Icons.guiFailImg;
case TestResult.ResultType.Ignored:
return Icons.guiIgnoreImg;
case TestResult.ResultType.NotRun:
default:
return Icons.guiUnknownImg;
}
}
public void PrintHeadPanel (bool isRunning)
{
var sceneName = "";
if (!string.IsNullOrEmpty (EditorApplication.currentScene))
{
sceneName = EditorApplication.currentScene.Substring (EditorApplication.currentScene.LastIndexOf ('/') + 1);
sceneName = sceneName.Substring (0,
sceneName.LastIndexOf ('.'));
}
GUILayout.Label ("Integration Tests (" + sceneName + ")",
EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal ();
var layoutOptions = new [] {
GUILayout.Height(24),
GUILayout.Width(32),
};
if (GUILayout.Button (guiRunAllTests,
Styles.buttonLeft,
layoutOptions
) && !EditorApplication.isPlayingOrWillChangePlaymode)
{
RunTest (GetVisibleNotIgnoredTests ());
}
if (GUILayout.Button(guiRunSelectedTests,
Styles.buttonMid,
layoutOptions
) && !EditorApplication.isPlayingOrWillChangePlaymode)
{
RunTest(selectedTests.Select (t=>t.TestComponent).ToList ());
}
if (GUILayout.Button (guiCreateNewTest,
Styles.buttonRight,
layoutOptions
) && !EditorApplication.isPlayingOrWillChangePlaymode )
{
var test = testManager.AddTest ();
if (selectedTests.Count == 1
&& Selection.activeGameObject != null
&& Selection.activeGameObject.GetComponent<TestComponent> ())
{
test.GameObject.transform.parent = Selection.activeGameObject.transform.parent;
}
SelectTest (test);
}
GUILayout.FlexibleSpace ();
if (GUILayout.Button (showOptions ? guiOptionsHideLabel : guiOptionsShowLabel, GUILayout.Height (24), GUILayout.Width (80)))
{
showOptions = !showOptions;
SaveSettings ();
}
EditorGUILayout.EndHorizontal ();
if(showOptions)
PrintOptions();
EditorGUILayout.BeginHorizontal ();
EditorGUILayout.LabelField ("Filter:", GUILayout.Width (35));
EditorGUI.BeginChangeCheck ();
filterString = EditorGUILayout.TextField (filterString);
if(EditorGUI.EndChangeCheck ())
SaveSettings ();
if (GUILayout.Button (showAdvancedFilter ? guiAdvancedFilterHide : guiAdvancedFilterShow, GUILayout.Width (80)))
{
showAdvancedFilter = !showAdvancedFilter;
SaveSettings ();
}
EditorGUILayout.EndHorizontal ();
if (showAdvancedFilter)
PrintAdvancedFilter ();
GUILayout.Space (5);
}
private void PrintAdvancedFilter ()
{
EditorGUILayout.BeginHorizontal ();
EditorGUILayout.BeginVertical ();
EditorGUI.BeginChangeCheck ();
showSucceededTest = EditorGUILayout.Toggle ("Show succeeded",
showSucceededTest);
showFailedTest = EditorGUILayout.Toggle ("Show failed",
showFailedTest);
EditorGUILayout.EndVertical ();
EditorGUILayout.BeginVertical ();
showIgnoredTest = EditorGUILayout.Toggle ("Show ignored",
showIgnoredTest);
showNotRunnedTest = EditorGUILayout.Toggle ("Show not runed",
showNotRunnedTest);
if(EditorGUI.EndChangeCheck ())
SaveSettings ();
EditorGUILayout.EndVertical ();
EditorGUILayout.EndHorizontal ();
}
public void PrintTestList ()
{
if (!testManager.AnyTestsOnScene ())
{
GUILayout.Label ("No tests found on the scene",
EditorStyles.boldLabel);
GUILayout.FlexibleSpace ();
return;
}
GUILayout.Box ("",
new[] {GUILayout.ExpandWidth (true), GUILayout.Height (1)});
GUILayout.Space (5);
testListScroll = EditorGUILayout.BeginScrollView (testListScroll,
new[] {GUILayout.ExpandHeight (true)});
DrawGroup (null, 0);
EditorGUILayout.EndScrollView ();
}
private void DrawGroup ( TestComponent parent, int indent )
{
++indent;
foreach (var test in testManager.GetChildrenTestsResults (parent))
{
if (test.TestComponent.IsTestGroup ())
{
if (DrawTestGroup (test, indent))
DrawGroup (test.TestComponent, indent);
}
else
{
if (IsNotFiltered (test))
DrawTest (test, indent);
}
}
}
public void PrintSelectedTestDetails ()
{
if (!testManager.AnyTestsOnScene ()) return;
if (Event.current.type == EventType.Layout)
{
if (showDetails != selectedTests.Any ())
showDetails = !showDetails;
}
if (!showDetails) return;
GUILayout.Box ("",
new[] { GUILayout.ExpandWidth (true), GUILayout.Height (1) });
EditorGUILayout.LabelField ("Test details");
string messages = "", stacktrace = "";
if (selectedTests.Count == 1)
{
var test = selectedTests.Single();
if (test != null)
{
messages = test.messages;
stacktrace = test.stacktrace;
}
}
EditorGUILayout.SelectableLabel (messages,
EditorStyles.miniLabel,
GUILayout.MaxHeight(50));
EditorGUILayout.SelectableLabel(stacktrace,
EditorStyles.miniLabel,
GUILayout.MaxHeight(50));
}
private void DrawContextTestMenu (TestResult test)
{
if (EditorApplication.isPlayingOrWillChangePlaymode) return;
var m = new GenericMenu ();
var localTest = test;
if(selectedTests.Count > 1)
m.AddItem(guiRunSelected,
false,
data => RunTest(selectedTests.Select (t=>t.TestComponent).ToList ()),
"");
m.AddItem (guiRun,
false,
data => RunTest(new List<TestComponent> { localTest.TestComponent}),
"");
m.AddItem (guiRunAll,
false,
data => RunTest (GetVisibleNotIgnoredTests ()),
"");
m.AddItem (guiRunAllIncludingIgnored,
false,
data => RunTest (GetVisibleTestsIncludingIgnored ()),
"");
m.AddSeparator ("");
m.AddItem (guiDelete,
false,
data => RemoveTest (localTest),
"");
m.ShowAsContext ();
}
private void RemoveTest (TestResult test)
{
var testsToDelete = new List<TestResult> { test };
if (selectedTests.Count > 1)
testsToDelete = selectedTests;
foreach (var t in testsToDelete)
{
#if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo ("Destroy Tests");
GameObject.DestroyImmediate (t.TestComponent.gameObject);
#else
Undo.DestroyObjectImmediate (t.TestComponent.gameObject);
#endif
}
TestManager.InvalidateTestList ();
selectedTests.Clear ();
forceRepaint = true;
}
public void OnHierarchyWindowItemOnGui (int id, Rect rect)
{
var o = EditorUtility.InstanceIDToObject (id);
if (o is GameObject)
{
var go = o as GameObject;
var tc = go.GetComponent<TestComponent> ();
if (testManager.AnyTestsOnScene() && tc != null)
{
if (!EditorApplication.isPlayingOrWillChangePlaymode
&& rect.Contains (Event.current.mousePosition)
&& Event.current.type == EventType.MouseDown
&& Event.current.button == 1)
{
DrawContextTestMenu (testManager.GetResultFor(go));
}
EditorGUIUtility.SetIconSize (new Vector2 (15, 15));
var icon = GetIconBasedOnResultType (testManager.GetResultFor (go));
EditorGUI.LabelField (new Rect (rect.xMax - 18,
rect.yMin - 2,
rect.width,
rect.height), icon);
EditorGUIUtility.SetIconSize (Vector2.zero);
}
}
}
public void PrintOptions ()
{
var style = EditorStyles.toggle;
EditorGUILayout.BeginVertical ();
EditorGUI.BeginChangeCheck();
addNewGameObjectUnderSelectedTest = EditorGUILayout.Toggle(guiAddGOUderTest, addNewGameObjectUnderSelectedTest, style);
blockUIWhenRunning = EditorGUILayout.Toggle(guiBlockUI, blockUIWhenRunning, style);
if (EditorGUI.EndChangeCheck ()) SaveSettings ();
EditorGUILayout.EndVertical ();
}
public void SelectInHierarchy (IEnumerable<GameObject> go)
{
selectedTests.Clear();
selectedTests.AddRange(go.Select (o=>testManager.GetResultFor (o)));
if (selectedTests.Count () == 1)
testManager.SelectInHierarchy (selectedTests.Single ());
}
public void InvalidateTestList ()
{
selectedTests.Clear ();
testManager.ClearTestList ();
}
public void UpdateResults (List<TestResult> testToRun)
{
testManager.UpdateResults (testToRun);
}
public void OnHierarchyChange(bool isRunning)
{
if (!testManager.AnyTestsOnScene ()) return;
//create a test runner if it doesn't exist
TestRunner.GetTestRunner ();
if (isRunning || EditorApplication.isPlayingOrWillChangePlaymode)
return;
if (addNewGameObjectUnderSelectedTest
&& Selection.activeGameObject != null)
{
var go = Selection.activeGameObject;
if (selectedTests.Count == 1
&& go.transform.parent == null
&& go.GetComponent<TestComponent>() == null
&& go.GetComponent<TestRunner>() == null)
{
go.transform.parent = selectedTests.Single ().GameObject.transform;
}
}
//make tests are not places under a go that is not a test itself
foreach (var test in TestRunner.FindAllTestsOnScene ())
{
if (test.gameObject.transform.parent != null && test.gameObject.transform.parent.gameObject.GetComponent<TestComponent> () == null)
{
test.gameObject.transform.parent = null;
Debug.LogWarning("Tests need to be on top of hierarchy or directly under another test.");
}
}
if (Selection.gameObjects.Count() > 1
&& Selection.gameObjects.All(o => o is GameObject && o.GetComponent<TestComponent>()))
{
selectedTests.Clear ();
selectedTests.AddRange (Selection.gameObjects.Select (go => testManager.GetResultFor (go)).ToList ());
forceRepaint = true;
}
}
public void OnTestRunFinished ()
{
if(selectedTests.Count==1)
testManager.SelectInHierarchy(selectedTests.Single());
}
public List<TestResult> GetTestResultsForTestComponent ( IList<TestComponent> tests )
{
return testManager.GetAllTestsResults ().Where (t => tests.Contains (t.TestComponent)).ToList ();
}
private bool IsNotFiltered (TestResult testInfo)
{
if (!testInfo.Name.ToLower ().Contains (filterString.Trim ().ToLower ())) return false;
if (!showSucceededTest && testInfo.resultType == TestResult.ResultType.Success) return false;
if (!showFailedTest && (testInfo.resultType == TestResult.ResultType.Failed
|| testInfo.resultType == TestResult.ResultType.FailedException
|| testInfo.resultType == TestResult.ResultType.Timeout)) return false;
if (!showIgnoredTest && (testInfo.resultType == TestResult.ResultType.Ignored || testInfo.TestComponent.ignored)) return false;
if (!showNotRunnedTest && testInfo.resultType == TestResult.ResultType.NotRun) return false;
return true;
}
public List<TestComponent> GetVisibleNotIgnoredTests ()
{
return testManager.GetAllTestsResults ().Where (tr => tr.TestComponent.ignored != true).Where (IsNotFiltered).Select (result => result.TestComponent).ToList ();
}
public List<TestComponent> GetVisibleTestsIncludingIgnored ()
{
return testManager.GetAllTestsResults ().Where (IsNotFiltered).Select (result => result.TestComponent).ToList ();
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
/**
* Call a delegate method on execution.
* This command can be used to schedule arbitrary script code.
*/
public class CallCommand : CommandQueue.Command
{
Action callAction;
public CallCommand(Action _callAction)
{
if (_callAction == null)
{
Debug.LogError("Action must not be null.");
return;
}
callAction = _callAction;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
if (callAction != null)
{
callAction();
}
// Execute next command
onComplete();
}
}
/**
* Wait for a period of time.
*/
public class WaitCommand : CommandQueue.Command
{
float duration;
public WaitCommand(float _duration)
{
duration = _duration;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
commandQueue.StartCoroutine(WaitCoroutine(duration, onComplete));
}
IEnumerator WaitCoroutine(float duration, Action onComplete)
{
yield return new WaitForSeconds(duration);
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Sets the currently active view immediately.
* The main camera snaps to the active view.
*/
public class SetViewCommand : CommandQueue.Command
{
View view;
public SetViewCommand(View _view)
{
if (_view == null)
{
Debug.LogError("View must not be null");
}
view = _view;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game game = Game.GetInstance();
game.cameraController.SnapToView(view);
game.activeView = view;
// Set the first page component found (if any) as the active page
Page page = view.gameObject.GetComponentInChildren<Page>();
if (page != null)
{
Game.GetInstance().activePage = page;
}
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Sets the currently active page for text rendering.
*/
public class SetPageCommand : CommandQueue.Command
{
Page page;
public SetPageCommand(Page _page)
{
page = _page;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game.GetInstance().activePage = page;
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Sets the currently active Page Style for rendering Pages.
*/
public class SetPageStyleCommand : CommandQueue.Command
{
PageStyle pageStyle;
public SetPageStyleCommand(PageStyle _pageStyle)
{
pageStyle = _pageStyle;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game.GetInstance().activePageStyle = pageStyle;
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Sets the title text displayed at the top of the active page.
*/
public class TitleCommand : CommandQueue.Command
{
string titleText;
public TitleCommand(string _titleText)
{
titleText = _titleText;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Page page = Game.GetInstance().activePage;
if (page == null)
{
Debug.LogError("Active page must not be null");
}
else
{
page.SetTitle(titleText);
}
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Writes story text to the currently active page.
* A 'continue' button is displayed when the text has fully appeared.
*/
public class SayCommand : CommandQueue.Command
{
string storyText;
public SayCommand(string _storyText)
{
storyText = _storyText;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Page page = Game.GetInstance().activePage;
if (page == null)
{
Debug.LogError("Active page must not be null");
}
else
{
page.Say(storyText, onComplete);
}
}
}
/**
* Adds an option button to the current list of options.
* Use the Choose command to display added options.
*/
public class AddOptionCommand : CommandQueue.Command
{
string optionText;
Action optionAction;
public AddOptionCommand(string _optionText, Action _optionAction)
{
optionText = _optionText;
optionAction = _optionAction;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Page page = Game.GetInstance().activePage;
if (page == null)
{
Debug.LogError("Active page must not be null");
}
else
{
page.AddOption(optionText, optionAction);
}
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Displays all previously added options.
*/
public class ChooseCommand : CommandQueue.Command
{
string chooseText;
public ChooseCommand(string _chooseText)
{
chooseText = _chooseText;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Page page = Game.GetInstance().activePage;
if (page == null)
{
Debug.LogError("Active page must not be null");
}
else
{
page.Choose(chooseText);
}
// Choose always clears commandQueue, so no need to call onComplete()
}
}
/**
* Changes the active room to a different room
*/
public class MoveToRoomCommand : CommandQueue.Command
{
Room room;
public MoveToRoomCommand(Room _room)
{
if (_room == null)
{
Debug.LogError("Room must not be null.");
return;
}
room = _room;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game.GetInstance().MoveToRoom(room);
// MoveToRoom always resets the command queue so no need to call onComplete
}
}
/**
* Sets a global boolean flag value
*/
public class SetFlagCommand : CommandQueue.Command
{
string key;
bool value;
public SetFlagCommand(string _key, bool _value)
{
key = _key;
value = _value;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game.GetInstance().state.SetFlag(key, value);
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Sets a global integer counter value
*/
public class SetCounterCommand : CommandQueue.Command
{
string key;
int value;
public SetCounterCommand(string _key, int _value)
{
key = _key;
value = _value;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game.GetInstance().state.SetCounter(key, value);
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Sets a global inventory count value
*/
public class SetInventoryCommand : CommandQueue.Command
{
string key;
int value;
public SetInventoryCommand(string _key, int _value)
{
key = _key;
value = _value;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game.GetInstance().state.SetInventory(key, value);
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Fades a sprite to a given alpha value over a period of time
*/
public class FadeSpriteCommand : CommandQueue.Command
{
SpriteRenderer spriteRenderer;
Color targetColor;
float fadeDuration;
Vector2 slideOffset = Vector2.zero;
public FadeSpriteCommand(SpriteRenderer _spriteRenderer,
Color _targetColor,
float _fadeDuration,
Vector2 _slideOffset)
{
if (_spriteRenderer == null)
{
Debug.LogError("Sprite renderer must not be null.");
return;
}
spriteRenderer = _spriteRenderer;
targetColor = _targetColor;
fadeDuration = _fadeDuration;
slideOffset = _slideOffset;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
SpriteFader.FadeSprite(spriteRenderer, targetColor, fadeDuration, slideOffset);
// Fade is asynchronous, but command completes immediately.
// If you need to wait for the fade to complete, just use an additional Wait() command
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Sets an animator trigger to change the animator state for an animated sprite
*/
public class SetAnimatorTriggerCommand : CommandQueue.Command
{
Animator animator;
string triggerName;
public SetAnimatorTriggerCommand(Animator _animator,
string _triggerName)
{
if (_animator == null)
{
Debug.LogError("Animator must not be null.");
return;
}
animator = _animator;
triggerName = _triggerName;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
animator.SetTrigger(triggerName);
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Makes a sprite behave as a clickable button
*/
public class AddButtonCommand : CommandQueue.Command
{
SpriteRenderer spriteRenderer;
Action buttonAction;
public AddButtonCommand(SpriteRenderer _spriteRenderer,
Action _buttonAction)
{
if (_spriteRenderer == null)
{
Debug.LogError("Sprite renderer must not be null.");
return;
}
spriteRenderer = _spriteRenderer;
buttonAction = _buttonAction;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Button.MakeButton(spriteRenderer, buttonAction);
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Makes a sprite stop behaving as a clickable button
*/
public class RemoveButtonCommand : CommandQueue.Command
{
SpriteRenderer spriteRenderer;
public RemoveButtonCommand(SpriteRenderer _spriteRenderer)
{
if (_spriteRenderer == null)
{
Debug.LogError("Sprite renderer must not be null.");
return;
}
spriteRenderer = _spriteRenderer;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Button button = spriteRenderer.gameObject.GetComponent<Button>();
GameObject.Destroy(button);
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Pans the camera to a view over a period of time.
*/
public class PanToViewCommand : CommandQueue.Command
{
View view;
float duration;
public PanToViewCommand(View _view,
float _duration)
{
if (_view == null)
{
Debug.LogError("View must not be null.");
return;
}
view = _view;
duration = _duration;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game game = Game.GetInstance();
game.cameraController.PanToView(view, duration, delegate {
game.activeView = view;
// Try to find a page that is a child of the active view.
// If there are multiple child pages then it is the client's responsibility
// to set the correct active page in the room script.
Page defaultPage = view.gameObject.GetComponentInChildren<Page>();
if (defaultPage)
{
game.activePage = defaultPage;
}
if (onComplete != null)
{
onComplete();
}
});
}
}
/**
* Pans the camera through a sequence of views over a period of time.
*/
public class PanToPathCommand : CommandQueue.Command
{
View[] views;
float duration;
public PanToPathCommand(View[] _views,
float _duration)
{
if (_views.Length == 0)
{
Debug.LogError("View list must not be empty.");
return;
}
views = _views;
duration = _duration;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game game = Game.GetInstance();
game.cameraController.PanToPath(views, duration, delegate {
if (views.Length > 0)
{
game.activeView = views[views.Length - 1];
// Try to find a page that is a child of the active view.
// If there are multiple child pages then it is the client's responsibility
// to set the correct active page in the room script.
Page defaultPage = game.activeView.gameObject.GetComponentInChildren<Page>();
if (defaultPage)
{
game.activePage = defaultPage;
}
}
if (onComplete != null)
{
onComplete();
}
});
}
}
/**
* Fades the camera to a view over a period of time.
*/
public class FadeToViewCommand : CommandQueue.Command
{
View view;
float duration;
public FadeToViewCommand(View _view,
float _duration)
{
if (_view == null)
{
Debug.LogError("View must not be null.");
return;
}
view = _view;
duration = _duration;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game game = Game.GetInstance();
game.cameraController.FadeToView(view, duration, delegate {
game.activeView = view;
// Try to find a page that is a child of the active view.
// If there are multiple child pages then it is the client's responsibility
// to set the correct active page in the room script.
Page defaultPage = view.gameObject.GetComponentInChildren<Page>();
if (defaultPage)
{
game.activePage = defaultPage;
}
if (onComplete != null)
{
onComplete();
}
});
}
}
/**
* Plays a music clip
*/
public class PlayMusicCommand : CommandQueue.Command
{
AudioClip audioClip;
public PlayMusicCommand(AudioClip _audioClip)
{
if (_audioClip == null)
{
Debug.LogError("Audio clip must not be null.");
return;
}
audioClip = _audioClip;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game game = Game.GetInstance();
game.audio.clip = audioClip;
game.audio.Play();
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Stops a music clip
*/
public class StopMusicCommand : CommandQueue.Command
{
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game game = Game.GetInstance();
game.audio.Stop();
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Fades music volume to required level over a period of time
*/
public class SetMusicVolumeCommand : CommandQueue.Command
{
float musicVolume;
float duration;
public SetMusicVolumeCommand(float _musicVolume, float _duration)
{
musicVolume = _musicVolume;
duration = _duration;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game game = Game.GetInstance();
iTween.AudioTo(game.gameObject, musicVolume, 1f, duration);
if (onComplete != null)
{
onComplete();
}
}
}
/**
* Plays a sound effect once
*/
public class PlaySoundCommand : CommandQueue.Command
{
AudioClip audioClip;
float volume;
public PlaySoundCommand(AudioClip _audioClip, float _volume)
{
audioClip = _audioClip;
volume = _volume;
}
public override void Execute(CommandQueue commandQueue, Action onComplete)
{
Game game = Game.GetInstance();
game.audio.PlayOneShot(audioClip, volume);
if (onComplete != null)
{
onComplete();
}
}
}
}
| |
/*
Copyright (c) 2005 Poderosa Project, All Rights Reserved.
This file is a part of the Granados SSH Client Library that is subject to
the license included in the distributed package.
You may not use this file except in compliance with the license.
$Id: SSH1Packet.cs,v 1.2 2005/04/20 08:58:56 okajima Exp $
*/
/*
* structure of packet
*
* length(4) padding(1-8) type(1) data(0+) crc(4)
*
* 1. length = type+data+crc
* 2. the length of padding+type+data+crc must be a multiple of 8
* 3. padding length must be 1 at least
* 4. crc is calculated from padding,type and data
*
*/
using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using Granados.Crypto;
using Granados.SSHC;
namespace Granados.SSHCV1
{
internal class SSH1Packet
{
private byte _type;
private byte[] _data;
private uint _CRC;
/**
* reads type, data, and crc from byte array.
* an exception is thrown if crc check fails.
*/
internal void ConstructAndCheck(byte[] buf, int packet_length, int padding_length, bool check_crc) {
_type = buf[padding_length];
//System.out.println("Type: " + _type);
if(packet_length > 5) //the body is not empty
{
_data = new byte[packet_length-5]; //5 is the length of [type] and [crc]
Array.Copy(buf, padding_length+1, _data, 0, packet_length-5);
}
_CRC = (uint)SSHUtil.ReadInt32(buf, buf.Length-4);
if(check_crc) {
uint c = CRC.Calc(buf, 0, buf.Length-4);
if(_CRC != c)
throw new SSHException("CRC Error", buf);
}
}
/**
* constructs from the packet type and the body
*/
public static SSH1Packet FromPlainPayload(PacketType type, byte[] data) {
SSH1Packet p = new SSH1Packet();
p._type = (byte)type;
p._data = data;
return p;
}
public static SSH1Packet FromPlainPayload(PacketType type) {
SSH1Packet p = new SSH1Packet();
p._type = (byte)type;
p._data = new byte[0];
return p;
}
/**
* creates a packet as the input of shell
*/
static SSH1Packet AsStdinString(byte[] input) {
SSH1DataWriter w = new SSH1DataWriter();
w.WriteAsString(input);
SSH1Packet p = SSH1Packet.FromPlainPayload(PacketType.SSH_CMSG_STDIN_DATA, w.ToByteArray());
return p;
}
private byte[] BuildImage() {
int packet_length = (_data==null? 0 : _data.Length) + 5; //type and CRC
int padding_length = 8 - (packet_length % 8);
byte[] image = new byte[packet_length + padding_length + 4];
SSHUtil.WriteIntToByteArray(image, 0, packet_length);
for(int i=0; i<padding_length; i++) image[4+i]=0; //padding: filling by random values is better
image[4+padding_length] = _type;
if(_data!=null)
Array.Copy(_data, 0, image, 4+padding_length+1, _data.Length);
_CRC = CRC.Calc(image, 4, image.Length-8);
SSHUtil.WriteIntToByteArray(image, image.Length-4, (int)_CRC);
return image;
}
/**
* writes to plain stream
*/
public void WriteTo(AbstractSocket output) {
byte[] image = BuildImage();
output.Write(image, 0, image.Length);
}
/**
* writes to encrypted stream
*/
public void WriteTo(AbstractSocket output, Cipher cipher) {
byte[] image = BuildImage();
//dumpBA(image);
byte[] encrypted = new byte[image.Length-4];
cipher.Encrypt(image, 4, image.Length-4, encrypted, 0); //length field must not be encrypted
Array.Copy(encrypted, 0, image, 4, encrypted.Length);
output.Write(image, 0, image.Length);
}
public PacketType Type {
get {
return (PacketType)_type;
}
}
public byte[] Data {
get {
return _data;
}
}
public int DataLength {
get {
return _data==null? 0 : _data.Length;
}
}
}
internal interface ISSH1PacketHandler : IHandlerBase {
void OnPacket(SSH1Packet packet);
}
internal class SynchronizedSSH1PacketHandler : SynchronizedHandlerBase, ISSH1PacketHandler {
internal ArrayList _packets;
internal SynchronizedSSH1PacketHandler() {
_packets = new ArrayList();
}
public void OnPacket(SSH1Packet packet) {
lock(this) {
_packets.Add(packet);
if(_packets.Count > 0)
SetReady();
}
}
public void OnError(Exception error, string msg) {
base.SetError(msg);
}
public void OnClosed() {
base.SetClosed();
}
public bool HasPacket {
get {
return _packets.Count>0;
}
}
public SSH1Packet PopPacket() {
lock(this) {
if(_packets.Count==0)
return null;
else {
SSH1Packet p = null;
p = (SSH1Packet)_packets[0];
_packets.RemoveAt(0);
if(_packets.Count==0) _event.Reset();
return p;
}
}
}
}
internal class CallbackSSH1PacketHandler : ISSH1PacketHandler {
internal SSH1Connection _connection;
internal CallbackSSH1PacketHandler(SSH1Connection con) {
_connection = con;
}
public void OnPacket(SSH1Packet packet) {
_connection.AsyncReceivePacket(packet);
}
public void OnError(Exception error, string msg) {
_connection.EventReceiver.OnError(error, msg);
}
public void OnClosed() {
_connection.EventReceiver.OnConnectionClosed();
}
}
internal class SSH1PacketBuilder : IByteArrayHandler {
private ISSH1PacketHandler _handler;
private byte[] _buffer;
private int _readOffset;
private int _writeOffset;
private Cipher _cipher;
private bool _checkMAC;
private ManualResetEvent _event;
public SSH1PacketBuilder(ISSH1PacketHandler handler) {
_handler = handler;
_buffer = new byte[0x1000];
_readOffset = 0;
_writeOffset = 0;
_cipher = null;
_checkMAC = false;
_event = null;
}
public void SetSignal(bool value) {
if(_event==null) _event = new ManualResetEvent(true);
if(value)
_event.Set();
else
_event.Reset();
}
public void SetCipher(Cipher c, bool check_mac) {
_cipher = c;
_checkMAC = check_mac;
}
public ISSH1PacketHandler Handler {
get {
return _handler;
}
set {
_handler = value;
}
}
public void OnData(byte[] data, int offset, int length) {
try {
while(_buffer.Length - _writeOffset < length)
ExpandBuffer();
Array.Copy(data, offset, _buffer, _writeOffset, length);
_writeOffset += length;
SSH1Packet p = ConstructPacket();
while(p!=null) {
_handler.OnPacket(p);
p = ConstructPacket();
}
ReduceBuffer();
}
catch(Exception ex) {
OnError(ex, ex.Message);
}
}
//returns true if a new packet could be obtained
private SSH1Packet ConstructPacket() {
if(_event!=null && !_event.WaitOne(3000, false))
throw new Exception("waithandle timed out");
if(_writeOffset-_readOffset<4) return null;
int packet_length = SSHUtil.ReadInt32(_buffer, _readOffset);
int padding_length = 8 - (packet_length % 8); //padding length
int total = packet_length + padding_length;
if(_writeOffset-_readOffset<4+total) return null;
byte[] decrypted = new byte[total];
if(_cipher!=null)
_cipher.Decrypt(_buffer, _readOffset+4, total, decrypted, 0);
else
Array.Copy(_buffer, _readOffset+4, decrypted, 0, total);
_readOffset += 4 + total;
SSH1Packet p = new SSH1Packet();
p.ConstructAndCheck(decrypted, packet_length, padding_length, _checkMAC);
return p;
}
private void ExpandBuffer() {
byte[] t = new byte[_buffer.Length*2];
Array.Copy(_buffer, 0, t, 0, _buffer.Length);
_buffer = t;
}
private void ReduceBuffer() {
if(_readOffset==_writeOffset) {
_readOffset = 0;
_writeOffset = 0;
}
else {
byte[] temp = new byte[_writeOffset - _readOffset];
Array.Copy(_buffer, _readOffset, temp, 0, temp.Length);
Array.Copy(temp, 0, _buffer, 0, temp.Length);
_readOffset = 0;
_writeOffset = temp.Length;
}
}
public void OnError(Exception error, string msg) {
_handler.OnError(error, msg);
}
public void OnClosed() {
_handler.OnClosed();
if(_event!=null) _event.Close();
}
}
}
| |
//
// Copyright (c) 2004-2017 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.Conditions
{
using System;
using System.Globalization;
using System.Collections.Generic;
using NLog.Common;
/// <summary>
/// Condition relational (<b>==</b>, <b>!=</b>, <b><</b>, <b><=</b>,
/// <b>></b> or <b>>=</b>) expression.
/// </summary>
internal sealed class ConditionRelationalExpression : ConditionExpression
{
/// <summary>
/// Initializes a new instance of the <see cref="ConditionRelationalExpression" /> class.
/// </summary>
/// <param name="leftExpression">The left expression.</param>
/// <param name="rightExpression">The right expression.</param>
/// <param name="relationalOperator">The relational operator.</param>
public ConditionRelationalExpression(ConditionExpression leftExpression, ConditionExpression rightExpression, ConditionRelationalOperator relationalOperator)
{
LeftExpression = leftExpression;
RightExpression = rightExpression;
RelationalOperator = relationalOperator;
}
/// <summary>
/// Gets the left expression.
/// </summary>
/// <value>The left expression.</value>
public ConditionExpression LeftExpression { get; private set; }
/// <summary>
/// Gets the right expression.
/// </summary>
/// <value>The right expression.</value>
public ConditionExpression RightExpression { get; private set; }
/// <summary>
/// Gets the relational operator.
/// </summary>
/// <value>The operator.</value>
public ConditionRelationalOperator RelationalOperator { get; private set; }
/// <summary>
/// Returns a string representation of the expression.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the condition expression.
/// </returns>
public override string ToString()
{
return $"({LeftExpression} {GetOperatorString()} {RightExpression})";
}
/// <summary>
/// Evaluates the expression.
/// </summary>
/// <param name="context">Evaluation context.</param>
/// <returns>Expression result.</returns>
protected override object EvaluateNode(LogEventInfo context)
{
object v1 = LeftExpression.Evaluate(context);
object v2 = RightExpression.Evaluate(context);
return Compare(v1, v2, RelationalOperator);
}
/// <summary>
/// Compares the specified values using specified relational operator.
/// </summary>
/// <param name="leftValue">The first value.</param>
/// <param name="rightValue">The second value.</param>
/// <param name="relationalOperator">The relational operator.</param>
/// <returns>Result of the given relational operator.</returns>
private static object Compare(object leftValue, object rightValue, ConditionRelationalOperator relationalOperator)
{
#if !NETSTANDARD1_0
StringComparer comparer = StringComparer.InvariantCulture;
#else
var comparer = new System.Collections.Comparer(CultureInfo.InvariantCulture);
#endif
PromoteTypes(ref leftValue, ref rightValue);
switch (relationalOperator)
{
case ConditionRelationalOperator.Equal:
return comparer.Compare(leftValue, rightValue) == 0;
case ConditionRelationalOperator.NotEqual:
return comparer.Compare(leftValue, rightValue) != 0;
case ConditionRelationalOperator.Greater:
return comparer.Compare(leftValue, rightValue) > 0;
case ConditionRelationalOperator.GreaterOrEqual:
return comparer.Compare(leftValue, rightValue) >= 0;
case ConditionRelationalOperator.LessOrEqual:
return comparer.Compare(leftValue, rightValue) <= 0;
case ConditionRelationalOperator.Less:
return comparer.Compare(leftValue, rightValue) < 0;
default:
throw new NotSupportedException($"Relational operator {relationalOperator} is not supported.");
}
}
/// <summary>
/// Promote values to the type needed for the comparision, e.g. parse a string to int.
/// </summary>
/// <param name="leftValue"></param>
/// <param name="rightValue"></param>
private static void PromoteTypes(ref object leftValue, ref object rightValue)
{
if (leftValue == null || rightValue == null)
{
return;
}
var leftType = leftValue.GetType();
var rightType = rightValue.GetType();
if (leftType == rightType)
{
return;
}
//types are not equal
var leftTypeOrder = GetOrder(leftType);
var rightTypeOrder = GetOrder(rightType);
if (leftTypeOrder < rightTypeOrder)
{
// first try promote right value with left type
if (TryPromoteTypes(ref rightValue, leftType, ref leftValue, rightType)) return;
}
else
{
// otherwise try promote leftValue with right type
if (TryPromoteTypes(ref leftValue, rightType, ref rightValue, leftType)) return;
}
throw new ConditionEvaluationException($"Cannot find common type for '{leftType.Name}' and '{rightType.Name}'.");
}
/// <summary>
/// Promoto <paramref name="val"/> to type
/// </summary>
/// <param name="val"></param>
/// <param name="type1"></param>
/// <returns>success?</returns>
private static bool TryPromoteType(ref object val, Type type1)
{
try
{
if (type1 == typeof(DateTime))
{
val = Convert.ToDateTime(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(double))
{
val = Convert.ToDouble(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(float))
{
val = Convert.ToSingle(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(decimal))
{
val = Convert.ToDecimal(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(long))
{
val = Convert.ToInt64(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(int))
{
val = Convert.ToInt32(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(bool))
{
val = Convert.ToBoolean(val, CultureInfo.InvariantCulture);
return true;
}
if (type1 == typeof(string))
{
val = Convert.ToString(val, CultureInfo.InvariantCulture);
InternalLogger.Debug("Using string comparision");
return true;
}
}
catch (Exception)
{
InternalLogger.Debug("conversion of {0} to {1} failed", val, type1.Name);
}
return false;
}
/// <summary>
/// Try to promote both values. First try to promote <paramref name="val1"/> to <paramref name="type1"/>,
/// when failed, try <paramref name="val2"/> to <paramref name="type2"/>.
/// </summary>
/// <returns></returns>
private static bool TryPromoteTypes(ref object val1, Type type1, ref object val2, Type type2)
{
return TryPromoteType(ref val1, type1) || TryPromoteType(ref val2, type2);
}
/// <summary>
/// Get the order for the type for comparision.
/// </summary>
/// <param name="type1"></param>
/// <returns>index, 0 to maxint. Lower is first</returns>
private static int GetOrder(Type type1)
{
int order;
var success = TypePromoteOrder.TryGetValue(type1, out order);
if (success)
{
return order;
}
//not found, try as last
return int.MaxValue;
}
/// <summary>
/// Dictionary from type to index. Lower index should be tested first.
/// </summary>
private static Dictionary<Type, int> TypePromoteOrder = BuildTypeOrderDictionary();
/// <summary>
/// Build the dictionary needed for the order of the types.
/// </summary>
/// <returns></returns>
private static Dictionary<Type, int> BuildTypeOrderDictionary()
{
var list = new List<Type>
{
typeof(DateTime),
typeof(double),
typeof(float),
typeof(decimal),
typeof(long),
typeof(int),
typeof(bool),
typeof(string),
};
var dict = new Dictionary<Type, int>(list.Count);
for (int i = 0; i < list.Count; i++)
{
dict.Add(list[i], i);
}
return dict;
}
/// <summary>
/// Get the string representing the current <see cref="ConditionRelationalOperator"/>
/// </summary>
/// <returns></returns>
private string GetOperatorString()
{
switch (RelationalOperator)
{
case ConditionRelationalOperator.Equal:
return "==";
case ConditionRelationalOperator.NotEqual:
return "!=";
case ConditionRelationalOperator.Greater:
return ">";
case ConditionRelationalOperator.Less:
return "<";
case ConditionRelationalOperator.GreaterOrEqual:
return ">=";
case ConditionRelationalOperator.LessOrEqual:
return "<=";
default:
throw new NotSupportedException($"Relational operator {RelationalOperator} is not supported.");
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System;
public class Math3D : MonoBehaviour {
private static Transform tempChild = null;
private static Transform tempParent = null;
public static void Init(){
tempChild = (new GameObject("Math3d_TempChild")).transform;
tempParent = (new GameObject("Math3d_TempParent")).transform;
tempChild.gameObject.hideFlags = HideFlags.HideAndDontSave;
DontDestroyOnLoad(tempChild.gameObject);
tempParent.gameObject.hideFlags = HideFlags.HideAndDontSave;
DontDestroyOnLoad(tempParent.gameObject);
//set the parent
tempChild.parent = tempParent;
}
//increase or decrease the length of vector by size
public static Vector3 AddVectorLength(Vector3 vector, float size){
//get the vector length
float magnitude = Vector3.Magnitude(vector);
//change the length
magnitude += size;
//normalize the vector
Vector3 vectorNormalized = Vector3.Normalize(vector);
//scale the vector
return Vector3.Scale(vectorNormalized, new Vector3(magnitude, magnitude, magnitude));
}
//create a vector of direction "vector" with length "size"
public static Vector3 SetVectorLength(Vector3 vector, float size){
//normalize the vector
Vector3 vectorNormalized = Vector3.Normalize(vector);
//scale the vector
return vectorNormalized *= size;
}
//caclulate the rotational difference from A to B
public static Quaternion SubtractRotation(Quaternion B, Quaternion A){
Quaternion C = Quaternion.Inverse(A) * B;
return C;
}
//Find the line of intersection between two planes. The planes are defined by a normal and a point on that plane.
//The outputs are a point on the line and a vector which indicates it's direction. If the planes are not parallel,
//the function outputs true, otherwise false.
public static bool PlanePlaneIntersection(out Vector3 linePoint, out Vector3 lineVec, Vector3 plane1Normal, Vector3 plane1Position, Vector3 plane2Normal, Vector3 plane2Position){
linePoint = Vector3.zero;
lineVec = Vector3.zero;
//We can get the direction of the line of intersection of the two planes by calculating the
//cross product of the normals of the two planes. Note that this is just a direction and the line
//is not fixed in space yet. We need a point for that to go with the line vector.
lineVec = Vector3.Cross(plane1Normal, plane2Normal);
//Next is to calculate a point on the line to fix it's position in space. This is done by finding a vector from
//the plane2 location, moving parallel to it's plane, and intersecting plane1. To prevent rounding
//errors, this vector also has to be perpendicular to lineDirection. To get this vector, calculate
//the cross product of the normal of plane2 and the lineDirection.
Vector3 ldir = Vector3.Cross(plane2Normal, lineVec);
float denominator = Vector3.Dot(plane1Normal, ldir);
//Prevent divide by zero and rounding errors by requiring about 5 degrees angle between the planes.
if(Mathf.Abs(denominator) > 0.006f){
Vector3 plane1ToPlane2 = plane1Position - plane2Position;
float t = Vector3.Dot(plane1Normal, plane1ToPlane2) / denominator;
linePoint = plane2Position + t * ldir;
return true;
}
//output not valid
else{
return false;
}
}
//Get the intersection between a line and a plane.
//If the line and plane are not parallel, the function outputs true, otherwise false.
public static bool LinePlaneIntersection(out Vector3 intersection, Vector3 linePoint, Vector3 lineVec, Vector3 planeNormal, Vector3 planePoint){
float length;
float dotNumerator;
float dotDenominator;
Vector3 vector;
intersection = Vector3.zero;
//calculate the distance between the linePoint and the line-plane intersection point
dotNumerator = Vector3.Dot((planePoint - linePoint), planeNormal);
dotDenominator = Vector3.Dot(lineVec, planeNormal);
//line and plane are not parallel
if(dotDenominator != 0.0f){
length = dotNumerator / dotDenominator;
//create a vector from the linePoint to the intersection point
vector = SetVectorLength(lineVec, length);
//get the coordinates of the line-plane intersection point
intersection = linePoint + vector;
return true;
}
//output not valid
else{
return false;
}
}
//Calculate the intersection point of two lines. Returns true if lines intersect, otherwise false.
//Note that in 3d, two lines do not intersect most of the time. So if the two lines are not in the
//same plane, use ClosestPointsOnTwoLines() instead.
public static bool LineLineIntersection(out Vector3 intersection, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2){
intersection = Vector3.zero;
Vector3 lineVec3 = linePoint2 - linePoint1;
Vector3 crossVec1and2 = Vector3.Cross(lineVec1, lineVec2);
Vector3 crossVec3and2 = Vector3.Cross(lineVec3, lineVec2);
float planarFactor = Vector3.Dot(lineVec3, crossVec1and2);
//Lines are not coplanar. Take into account rounding errors.
if((planarFactor >= 0.00001f) || (planarFactor <= -0.00001f)){
return false;
}
//Note: sqrMagnitude does x*x+y*y+z*z on the input vector.
float s = Vector3.Dot(crossVec3and2, crossVec1and2) / crossVec1and2.sqrMagnitude;
if((s >= 0.0f) && (s <= 1.0f)){
intersection = linePoint1 + (lineVec1 * s);
return true;
}
else{
return false;
}
}
//Two non-parallel lines which may or may not touch each other have a point on each line which are closest
//to each other. This function finds those two points. If the lines are not parallel, the function
//outputs true, otherwise false.
public static bool ClosestPointsOnTwoLines(out Vector3 closestPointLine1, out Vector3 closestPointLine2, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2){
closestPointLine1 = Vector3.zero;
closestPointLine2 = Vector3.zero;
float a = Vector3.Dot(lineVec1, lineVec1);
float b = Vector3.Dot(lineVec1, lineVec2);
float e = Vector3.Dot(lineVec2, lineVec2);
float d = a*e - b*b;
//lines are not parallel
if(d != 0.0f){
Vector3 r = linePoint1 - linePoint2;
float c = Vector3.Dot(lineVec1, r);
float f = Vector3.Dot(lineVec2, r);
float s = (b*f - c*e) / d;
float t = (a*f - c*b) / d;
closestPointLine1 = linePoint1 + lineVec1 * s;
closestPointLine2 = linePoint2 + lineVec2 * t;
return true;
}
else{
return false;
}
}
//This function returns a point which is a projection from a point to a line.
public static Vector3 ProjectPointOnLine(Vector3 linePoint, Vector3 lineVec, Vector3 point){
//get vector from point on line to point in space
Vector3 linePointToPoint = point - linePoint;
float t = Vector3.Dot(linePointToPoint, lineVec);
return linePoint + lineVec * t;
}
//This function returns a point which is a projection from a point to a plane.
public static Vector3 ProjectPointOnPlane(Vector3 planeNormal, Vector3 planePoint, Vector3 point){
float distance;
Vector3 translationVector;
//First calculate the distance from the point to the plane:
distance = SignedDistancePlanePoint(planeNormal, planePoint, point);
//Reverse the sign of the distance
distance *= -1;
//Get a translation vector
translationVector = SetVectorLength(planeNormal, distance);
//Translate the point to form a projection
return point + translationVector;
}
//Projects a vector onto a plane. The output is not normalized.
public static Vector3 ProjectVectorOnPlane(Vector3 planeNormal, Vector3 vector){
return vector - (Vector3.Dot(vector, planeNormal) * planeNormal);
}
//Get the shortest distance between a point and a plane. The output is signed so it holds information
//as to which side of the plane normal the point is.
public static float SignedDistancePlanePoint(Vector3 planeNormal, Vector3 planePoint, Vector3 point){
return Vector3.Dot(planeNormal, (point - planePoint));
}
//This function calculates a signed (+ or - sign instead of being ambiguous) dot product. It is basically used
//to figure out whether a vector is positioned to the left or right of another vector. The way this is done is
//by calculating a vector perpendicular to one of the vectors and using that as a reference. This is because
//the result of a dot product only has signed information when an angle is transitioning between more or less
//then 90 degrees.
public static float SignedDotProduct(Vector3 vectorA, Vector3 vectorB, Vector3 normal){
Vector3 perpVector;
float dot;
//Use the geometry object normal and one of the input vectors to calculate the perpendicular vector
perpVector = Vector3.Cross(normal, vectorA);
//Now calculate the dot product between the perpendicular vector (perpVector) and the other input vector
dot = Vector3.Dot(perpVector, vectorB);
return dot;
}
//Calculate the angle between a vector and a plane. The plane is made by a normal vector.
//Output is in radians.
public static float AngleVectorPlane(Vector3 vector, Vector3 normal){
float dot;
float angle;
//calculate the the dot product between the two input vectors. This gives the cosine between the two vectors
dot = Vector3.Dot(vector, normal);
//this is in radians
angle = (float)Math.Acos(dot);
return 1.570796326794897f - angle; //90 degrees - angle
}
//Calculate the dot product as an angle
public static float DotProductAngle(Vector3 vec1, Vector3 vec2){
double dot;
double angle;
//get the dot product
dot = Vector3.Dot(vec1, vec2);
//Clamp to prevent NaN error. Shouldn't need this in the first place, but there could be a rounding error issue.
if(dot < -1.0f){
dot = -1.0f;
}
if(dot > 1.0f){
dot =1.0f;
}
//Calculate the angle. The output is in radians
//This step can be skipped for optimization...
angle = Math.Acos(dot);
return (float)angle;
}
//Convert a plane defined by 3 points to a plane defined by a vector and a point.
//The plane point is the middle of the triangle defined by the 3 points.
public static void PlaneFrom3Points(out Vector3 planeNormal, out Vector3 planePoint, Vector3 pointA, Vector3 pointB, Vector3 pointC){
planeNormal = Vector3.zero;
planePoint = Vector3.zero;
//Make two vectors from the 3 input points, originating from point A
Vector3 AB = pointB - pointA;
Vector3 AC = pointC - pointA;
//Calculate the normal
planeNormal = Vector3.Normalize(Vector3.Cross(AB, AC));
//Get the points in the middle AB and AC
Vector3 middleAB = pointA + (AB / 2.0f);
Vector3 middleAC = pointA + (AC / 2.0f);
//Get vectors from the middle of AB and AC to the point which is not on that line.
Vector3 middleABtoC = pointC - middleAB;
Vector3 middleACtoB = pointB - middleAC;
//Calculate the intersection between the two lines. This will be the center
//of the triangle defined by the 3 points.
//We could use LineLineIntersection instead of ClosestPointsOnTwoLines but due to rounding errors
//this sometimes doesn't work.
Vector3 temp;
ClosestPointsOnTwoLines(out planePoint, out temp, middleAB, middleABtoC, middleAC, middleACtoB);
}
//Returns the forward vector of a quaternion
public static Vector3 GetForwardVector(Quaternion q){
return q * Vector3.forward;
}
//Returns the up vector of a quaternion
public static Vector3 GetUpVector(Quaternion q){
return q * Vector3.up;
}
//Returns the right vector of a quaternion
public static Vector3 GetRightVector(Quaternion q){
return q * Vector3.right;
}
//Gets a quaternion from a matrix
public static Quaternion QuaternionFromMatrix(Matrix4x4 m){
return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1));
}
//Gets a position from a matrix
public static Vector3 PositionFromMatrix(Matrix4x4 m){
Vector4 vector4Position = m.GetColumn(3);
return new Vector3(vector4Position.x, vector4Position.y, vector4Position.z);
}
//This is an alternative for Quaternion.LookRotation. Instead of aligning the forward and up vector of the game
//object with the input vectors, a custom direction can be used instead of the fixed forward and up vectors.
//alignWithVector and alignWithNormal are in world space.
//customForward and customUp are in object space.
//Usage: use alignWithVector and alignWithNormal as if you are using the default LookRotation function.
//Set customForward and customUp to the vectors you wish to use instead of the default forward and up vectors.
public static void LookRotationExtended(ref GameObject gameObjectInOut, Vector3 alignWithVector, Vector3 alignWithNormal, Vector3 customForward, Vector3 customUp){
//Set the rotation of the destination
Quaternion rotationA = Quaternion.LookRotation(alignWithVector, alignWithNormal);
//Set the rotation of the custom normal and up vectors.
//When using the default LookRotation function, this would be hard coded to the forward and up vector.
Quaternion rotationB = Quaternion.LookRotation(customForward, customUp);
//Calculate the rotation
gameObjectInOut.transform.rotation = rotationA * Quaternion.Inverse(rotationB);
}
//This function transforms one object as if it was parented to the other.
//Before using this function, the Init() function must be called
//Input: parentRotation and parentPosition: the current parent transform.
//Input: startParentRotation and startParentPosition: the transform of the parent object at the time the objects are parented.
//Input: startChildRotation and startChildPosition: the transform of the child object at the time the objects are parented.
//Output: childRotation and childPosition.
//All transforms are in world space.
public static void TransformWithParent(out Quaternion childRotation, out Vector3 childPosition, Quaternion parentRotation, Vector3 parentPosition, Quaternion startParentRotation, Vector3 startParentPosition, Quaternion startChildRotation, Vector3 startChildPosition){
childRotation = Quaternion.identity;
childPosition = Vector3.zero;
//set the parent start transform
tempParent.rotation = startParentRotation;
tempParent.position = startParentPosition;
tempParent.localScale = Vector3.one; //to prevent scale wandering
//set the child start transform
tempChild.rotation = startChildRotation;
tempChild.position = startChildPosition;
tempChild.localScale = Vector3.one; //to prevent scale wandering
//translate and rotate the child by moving the parent
tempParent.rotation = parentRotation;
tempParent.position = parentPosition;
//get the child transform
childRotation = tempChild.rotation;
childPosition = tempChild.position;
}
//With this function you can align a triangle of an object with any transform.
//Usage: gameObjectInOut is the game object you want to transform.
//alignWithVector, alignWithNormal, and alignWithPosition is the transform with which the triangle of the object should be aligned with.
//triangleForward, triangleNormal, and trianglePosition is the transform of the triangle from the object.
//alignWithVector, alignWithNormal, and alignWithPosition are in world space.
//triangleForward, triangleNormal, and trianglePosition are in object space.
//trianglePosition is the mesh position of the triangle. The effect of the scale of the object is handled automatically.
//trianglePosition can be set at any position, it does not have to be at a vertex or in the middle of the triangle.
public static void PreciseAlign(ref GameObject gameObjectInOut, Vector3 alignWithVector, Vector3 alignWithNormal, Vector3 alignWithPosition, Vector3 triangleForward, Vector3 triangleNormal, Vector3 trianglePosition){
//Set the rotation.
LookRotationExtended(ref gameObjectInOut, alignWithVector, alignWithNormal, triangleForward, triangleNormal);
//Get the world space position of trianglePosition
Vector3 trianglePositionWorld = gameObjectInOut.transform.TransformPoint(trianglePosition);
//Get a vector from trianglePosition to alignWithPosition
Vector3 translateVector = alignWithPosition - trianglePositionWorld;
//Now transform the object so the triangle lines up correctly.
gameObjectInOut.transform.Translate(translateVector, Space.World);
}
}
//Convert a position, direction, and normal vector to a transform
/*void VectorsToTransform(ref GameObject gameObjectInOut, Vector3 positionVector, Vector3 directionVector, Vector3 normalVector){
gameObjectInOut.transform.position = positionVector;
gameObjectInOut.transform.rotation = Quaternion.LookRotation(directionVector, normalVector);
}*/
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Factories;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.UnitTesting;
using System.ComponentModel.Composition.Primitives;
using System.Reflection;
using Xunit;
namespace System.ComponentModel.Composition
{
// This is a glorious do nothing ReflectionContext
public class DirectoryCatalogTestsReflectionContext : ReflectionContext
{
public override Assembly MapAssembly(Assembly assembly)
{
return assembly;
}
#if FEATURE_INTERNAL_REFLECTIONCONTEXT
public override Type MapType(Type type)
#else
public override TypeInfo MapType(TypeInfo type)
#endif
{
return type;
}
}
public class DirectoryCatalogTests
{
internal const string NonExistentSearchPattern = "*.NonExistentSearchPattern";
public static void Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull(Func<ReflectionContext, DirectoryCatalog> catalogCreator)
{
Assert.Throws<ArgumentNullException>("reflectionContext", () =>
{
var catalog = catalogCreator(null);
});
}
public static void Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull(Func<ICompositionElement, DirectoryCatalog> catalogCreator)
{
Assert.Throws<ArgumentNullException>("definitionOrigin", () =>
{
var catalog = catalogCreator(null);
});
}
[Fact]
public void Constructor2_NullReflectionContextArgument_ShouldThrowArgumentNull()
{
DirectoryCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) =>
{
return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), rc);
});
}
[Fact]
public void Constructor3_NullDefinitionOriginArgument_ShouldThrowArgumentNull()
{
DirectoryCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) =>
{
return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), dO);
});
}
[Fact]
public void Constructor4_NullReflectionContextArgument_ShouldThrowArgumentNull()
{
DirectoryCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) =>
{
return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), rc, CreateDirectoryCatalog());
});
}
[Fact]
public void Constructor4_NullDefinitionOriginArgument_ShouldThrowArgumentNull()
{
DirectoryCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) =>
{
return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), new DirectoryCatalogTestsReflectionContext(), dO);
});
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.IO.DirectoryNotFoundException : Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/'.
public void ICompositionElementDisplayName_ShouldIncludeCatalogTypeNameAndDirectoryPath()
{
var paths = GetPathExpectations();
foreach (var path in paths)
{
var catalog = (ICompositionElement)CreateDirectoryCatalog(path, NonExistentSearchPattern);
string expected = string.Format("DirectoryCatalog (Path=\"{0}\")", path);
Assert.Equal(expected, catalog.DisplayName);
}
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.IO.DirectoryNotFoundException : Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/'.
public void ICompositionElementDisplayName_ShouldIncludeDerivedCatalogTypeNameAndAssemblyFullName()
{
var paths = GetPathExpectations();
foreach (var path in paths)
{
var catalog = (ICompositionElement)new DerivedDirectoryCatalog(path, NonExistentSearchPattern);
string expected = string.Format("DerivedDirectoryCatalog (Path=\"{0}\")", path);
Assert.Equal(expected, catalog.DisplayName);
}
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.IO.DirectoryNotFoundException : Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/'.
public void ToString_ShouldReturnICompositionElementDisplayName()
{
var paths = GetPathExpectations();
foreach (var path in paths)
{
var catalog = (ICompositionElement)CreateDirectoryCatalog(path, NonExistentSearchPattern);
Assert.Equal(catalog.DisplayName, catalog.ToString());
}
}
[Fact]
public void ICompositionElementDisplayName_WhenCatalogDisposed_ShouldNotThrow()
{
var catalog = CreateDirectoryCatalog();
catalog.Dispose();
var displayName = ((ICompositionElement)catalog).DisplayName;
}
[Fact]
public void ICompositionElementOrigin_WhenCatalogDisposed_ShouldNotThrow()
{
var catalog = CreateDirectoryCatalog();
catalog.Dispose();
var origin = ((ICompositionElement)catalog).Origin;
}
[Fact]
public void Parts_WhenCatalogDisposed_ShouldThrowObjectDisposed()
{
var catalog = CreateDirectoryCatalog();
catalog.Dispose();
ExceptionAssert.ThrowsDisposed(catalog, () =>
{
var parts = catalog.Parts;
});
}
[Fact]
public void GetExports_WhenCatalogDisposed_ShouldThrowObjectDisposed()
{
var catalog = CreateDirectoryCatalog();
catalog.Dispose();
var definition = ImportDefinitionFactory.Create();
ExceptionAssert.ThrowsDisposed(catalog, () =>
{
catalog.GetExports(definition);
});
}
[Fact]
public void Refresh_WhenCatalogDisposed_ShouldThrowObjectDisposed()
{
var catalog = CreateDirectoryCatalog();
catalog.Dispose();
ExceptionAssert.ThrowsDisposed(catalog, () =>
{
catalog.Refresh();
});
}
[Fact]
public void ToString_WhenCatalogDisposed_ShouldNotThrow()
{
var catalog = CreateDirectoryCatalog();
catalog.Dispose();
catalog.ToString();
}
[Fact]
public void GetExports_NullAsConstraintArgument_ShouldThrowArgumentNull()
{
var catalog = CreateDirectoryCatalog();
Assert.Throws<ArgumentNullException>("definition", () =>
{
catalog.GetExports((ImportDefinition)null);
});
}
[Fact]
public void Dispose_ShouldNotThrow()
{
using (var catalog = CreateDirectoryCatalog())
{
}
}
[Fact]
public void Dispose_CanBeCalledMultipleTimes()
{
var catalog = CreateDirectoryCatalog();
catalog.Dispose();
catalog.Dispose();
catalog.Dispose();
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // typeof(System.IO.DirectoryNotFoundException): Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/HTTP:/MICROSOFT.COM/MYASSEMBLY.DLL'.
public void AddAssembly1_NonExistentUriAsAssemblyFileNameArgument_ShouldNotSupportedException()
{
Assert.Throws<NotSupportedException>(() =>
{
var catalog = new DirectoryCatalog("http://microsoft.com/myassembly.dll");
});
}
[Fact]
public void AddAssembly1_NullPathArgument_ShouldThrowArugmentNull()
{
Assert.Throws<ArgumentNullException>(() =>
new DirectoryCatalog((string)null));
}
[Fact]
public void AddAssembly1_EmptyPathArgument_ShouldThrowArugment()
{
Assert.Throws<ArgumentException>(() =>
new DirectoryCatalog(""));
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // typeof(System.IO.DirectoryNotFoundException): Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/*'.
public void AddAssembly1_InvalidPathName_ShouldThrowDirectoryNotFound()
{
Assert.Throws<ArgumentException>(() =>
{
var c1 = new DirectoryCatalog("*");
});
}
[Fact]
[ActiveIssue(25498)]
public void AddAssembly1_TooLongPathNameArgument_ShouldThrowPathTooLongException()
{
Assert.Throws<PathTooLongException>(() =>
{
var c1 = new DirectoryCatalog(@"c:\This is a very long path\And Just to make sure\We will continue to make it very long\This is a very long path\And Just to make sure\We will continue to make it very long\This is a very long path\And Just to make sure\We will continue to make it very long\myassembly.dll");
});
}
[Fact]
[ActiveIssue(25498)]
public void Parts()
{
var catalog = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
Assert.NotNull(catalog.Parts);
Assert.True(catalog.Parts.Count() > 0);
}
[Fact]
[ActiveIssue(25498)]
public void Parts_ShouldSetDefinitionOriginToCatalogItself()
{
var catalog = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
Assert.True(catalog.Parts.Count() > 0);
foreach (ICompositionElement definition in catalog.Parts)
{
Assert.Same(catalog, definition.Origin);
}
}
[Fact]
[ActiveIssue(25498)]
public void Path_ValidPath_ShouldBeFine()
{
var expectations = new ExpectationCollection<string, string>();
expectations.Add(".", ".");
expectations.Add(TemporaryFileCopier.RootTemporaryDirectoryName, TemporaryFileCopier.RootTemporaryDirectoryName);
expectations.Add(TemporaryFileCopier.GetRootTemporaryDirectory(), TemporaryFileCopier.GetRootTemporaryDirectory());
expectations.Add(TemporaryFileCopier.GetTemporaryDirectory(), TemporaryFileCopier.GetTemporaryDirectory());
foreach (var e in expectations)
{
var cat = CreateDirectoryCatalog(e.Input, NonExistentSearchPattern);
Assert.Equal(e.Output, cat.Path);
}
}
[Fact]
[ActiveIssue(25498)]
public void FullPath_ValidPath_ShouldBeFine()
{
var expectations = new ExpectationCollection<string, string>();
// Ensure the path is always normalized properly.
string rootTempPath = Path.GetFullPath(TemporaryFileCopier.GetRootTemporaryDirectory()).ToUpperInvariant();
// Note: These relative paths work properly because the unit test temporary directories are always
// created as a subfolder off the AppDomain.CurrentDomain.BaseDirectory.
expectations.Add(".", Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ".")).ToUpperInvariant());
expectations.Add(TemporaryFileCopier.RootTemporaryDirectoryName, rootTempPath);
expectations.Add(TemporaryFileCopier.GetRootTemporaryDirectory(), rootTempPath);
expectations.Add(TemporaryFileCopier.GetTemporaryDirectory(), Path.GetFullPath(TemporaryFileCopier.GetTemporaryDirectory()).ToUpperInvariant());
foreach (var e in expectations)
{
var cat = CreateDirectoryCatalog(e.Input, NonExistentSearchPattern);
Assert.Equal(e.Output, cat.FullPath);
}
}
[Fact]
public void LoadedFiles_EmptyDirectory_ShouldBeFine()
{
var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
Assert.Equal(0, cat.LoadedFiles.Count);
}
[Fact]
public void LoadedFiles_ContainsMultipleDllsAndSomeNonDll_ShouldOnlyContainDlls()
{
// Add one text file
using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.txt"))) { }
// Add two dll's
string dll1 = Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test1.dll");
string dll2 = Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test2.dll");
File.Copy(Assembly.GetExecutingAssembly().Location, dll1);
File.Copy(Assembly.GetExecutingAssembly().Location, dll2);
var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
EqualityExtensions.CheckEquals(new string[] { dll1.ToUpperInvariant(), dll2.ToUpperInvariant() },
cat.LoadedFiles);
}
[Fact]
public void Constructor_InvalidAssembly_ShouldBeFine()
{
using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll"))) { }
var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
}
[Fact]
public void Constructor_NonExistentDirectory_ShouldThrow()
{
Assert.Throws<DirectoryNotFoundException>(() =>
new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory() + @"\NonexistentDirectoryWithoutEndingSlash"));
Assert.Throws<DirectoryNotFoundException>(() =>
new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory() + @"\NonexistentDirectoryWithEndingSlash\"));
}
[Fact]
[ActiveIssue(25498)]
public void Constructor_PassExistingFileName_ShouldThrow()
{
using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.txt"))) { }
Assert.Throws<IOException>(() =>
new DirectoryCatalog(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.txt")));
}
[Fact]
public void Constructor_PassNonExistingFileName_ShouldThrow()
{
Assert.Throws<DirectoryNotFoundException>(() =>
new DirectoryCatalog(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "NonExistingFile.txt")));
}
[Fact]
[ActiveIssue(25498)]
public void Refresh_AssemblyAdded_ShouldFireOnChanged()
{
bool changedFired = false;
bool changingFired = false;
var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
Assert.Equal(0, cat.Parts.Count());
cat.Changing += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) =>
{
Assert.Equal(0, cat.Parts.Count());
changingFired = true;
});
cat.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) =>
{
Assert.NotEqual(0, cat.Parts.Count());
changedFired = true;
});
File.Copy(Assembly.GetExecutingAssembly().Location, Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll"));
cat.Refresh();
Assert.True(changingFired);
Assert.True(changedFired);
}
[Fact]
[ActiveIssue(25498)]
public void Refresh_AssemblyRemoved_ShouldFireOnChanged()
{
string file = Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll");
File.Copy(Assembly.GetExecutingAssembly().Location, file);
bool changedFired = false;
var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
cat.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) =>
changedFired = true);
// This assembly can be deleted because it was already loaded by the CLR in another context
// in another location so it isn't locked on disk.
File.Delete(file);
cat.Refresh();
Assert.True(changedFired);
}
[Fact]
public void Refresh_NoChanges_ShouldNotFireOnChanged()
{
var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
cat.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) =>
Assert.False(true));
cat.Refresh();
}
[Fact]
[ActiveIssue(25498)]
public void Refresh_DirectoryRemoved_ShouldThrowDirectoryNotFound()
{
DirectoryCatalog cat;
cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
ExceptionAssert.Throws<DirectoryNotFoundException>(RetryMode.DoNotRetry, () =>
cat.Refresh());
}
[Fact]
public void GetExports()
{
var catalog = new AggregateCatalog();
Expression<Func<ExportDefinition, bool>> constraint = (ExportDefinition exportDefinition) => exportDefinition.ContractName == AttributedModelServices.GetContractName(typeof(MyExport));
IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> matchingExports = null;
matchingExports = catalog.GetExports(constraint);
Assert.NotNull(matchingExports);
Assert.True(matchingExports.Count() == 0);
var testsDirectoryCatalog = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
catalog.Catalogs.Add(testsDirectoryCatalog);
matchingExports = catalog.GetExports(constraint);
Assert.NotNull(matchingExports);
Assert.True(matchingExports.Count() >= 0);
IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> expectedMatchingExports = catalog.Parts
.SelectMany(part => part.ExportDefinitions, (part, export) => new Tuple<ComposablePartDefinition, ExportDefinition>(part, export))
.Where(partAndExport => partAndExport.Item2.ContractName == AttributedModelServices.GetContractName(typeof(MyExport)));
Assert.True(matchingExports.SequenceEqual(expectedMatchingExports));
catalog.Catalogs.Remove(testsDirectoryCatalog);
matchingExports = catalog.GetExports(constraint);
Assert.NotNull(matchingExports);
Assert.True(matchingExports.Count() == 0);
}
[Fact]
[ActiveIssue(25498)]
public void AddAndRemoveDirectory()
{
var cat = new AggregateCatalog();
var container = new CompositionContainer(cat);
Assert.False(container.IsPresent<MyExport>());
var dir1 = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory());
cat.Catalogs.Add(dir1);
Assert.True(container.IsPresent<MyExport>());
cat.Catalogs.Remove(dir1);
Assert.False(container.IsPresent<MyExport>());
}
[Fact]
public void AddDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
var cat = new DirectoryCatalog("Directory That Should Never Exist tadfasdfasdfsdf");
});
}
[Fact]
public void ExecuteOnCreationThread()
{
// Add a proper test for event notification on caller thread
}
private DirectoryCatalog CreateDirectoryCatalog()
{
return CreateDirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory());
}
private DirectoryCatalog CreateDirectoryCatalog(string path)
{
return new DirectoryCatalog(path);
}
private DirectoryCatalog CreateDirectoryCatalog(string path, string searchPattern)
{
return new DirectoryCatalog(path, searchPattern);
}
public IEnumerable<string> GetPathExpectations()
{
yield return AppDomain.CurrentDomain.BaseDirectory;
yield return AppDomain.CurrentDomain.BaseDirectory + @"\";
yield return ".";
}
private class DerivedDirectoryCatalog : DirectoryCatalog
{
public DerivedDirectoryCatalog(string path, string searchPattern)
: base(path, searchPattern)
{
}
}
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using Xunit;
using Shouldly;
namespace AutoMapper.UnitTests.ConditionalMapping
{
public class When_adding_a_condition_for_all_members : AutoMapperSpecBase
{
Source _source = new Source { Value = 3 };
Destination _destination = new Destination { Value = 7 };
class Source
{
public int Value { get; set; }
}
class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>().ForAllMembers(o => o.Condition((source, destination, sourceProperty, destinationProperty) =>
{
source.ShouldBeSameAs(_source);
destination.ShouldBeSameAs(_destination);
((int)sourceProperty).ShouldBe(3);
((int)destinationProperty).ShouldBe(7);
return true;
}));
});
protected override void Because_of()
{
Mapper.Map(_source, _destination);
}
}
public class When_ignoring_all_properties_with_an_inaccessible_setter_and_explicitly_implemented_member : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(c => c.CreateMap<SourceClass, DestinationClass>().IgnoreAllPropertiesWithAnInaccessibleSetter());
interface Interface
{
int Value { get; }
}
class SourceClass
{
public int PublicProperty { get; set; }
}
class DestinationClass : Interface
{
int Interface.Value { get { return 123; } }
public int PrivateProperty { get; private set; }
public int PublicProperty { get; set; }
}
}
public class When_configuring_a_member_to_skip_based_on_the_property_value : AutoMapperSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt => opt.Condition(src => src.Value > 0));
});
[Fact]
public void Should_skip_the_mapping_when_the_condition_is_true()
{
var destination = Mapper.Map<Source, Destination>(new Source {Value = -1});
destination.Value.ShouldBe(0);
}
[Fact]
public void Should_execute_the_mapping_when_the_condition_is_false()
{
var destination = Mapper.Map<Source, Destination>(new Source { Value = 7 });
destination.Value.ShouldBe(7);
}
}
public class When_configuring_a_member_to_skip_based_on_the_property_value_with_custom_mapping : AutoMapperSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt =>
{
opt.Condition(src => src.Value > 0);
opt.MapFrom(src => 10);
});
});
[Fact]
public void Should_skip_the_mapping_when_the_condition_is_true()
{
var destination = Mapper.Map<Source, Destination>(new Source { Value = -1 });
destination.Value.ShouldBe(0);
}
[Fact]
public void Should_execute_the_mapping_when_the_condition_is_false()
{
Mapper.Map<Source, Destination>(new Source { Value = 7 }).Value.ShouldBe(10);
}
}
public class When_configuring_a_map_to_ignore_all_properties_with_an_inaccessible_setter : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Id { get; set; }
public string Title { get; set; }
public string CodeName { get; set; }
public string Nickname { get; set; }
public string ScreenName { get; set; }
}
public class Destination
{
private double _height;
public int Id { get; set; }
public virtual string Name { get; protected set; }
public string Title { get; internal set; }
public string CodeName { get; private set; }
public string Nickname { get; private set; }
public string ScreenName { get; private set; }
public int Age { get; private set; }
public double Height
{
get { return _height; }
}
public Destination()
{
_height = 60;
}
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.ScreenName, opt => opt.MapFrom(src => src.ScreenName))
.IgnoreAllPropertiesWithAnInaccessibleSetter()
.ForMember(dest => dest.Nickname, opt => opt.MapFrom(src => src.Nickname));
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Id = 5, CodeName = "007", Nickname = "Jimmy", ScreenName = "jbogard" });
}
[Fact]
public void Should_consider_the_configuration_valid_even_if_some_properties_with_an_inaccessible_setter_are_unmapped()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
[Fact]
public void Should_map_a_property_with_an_inaccessible_setter_if_a_specific_mapping_is_configured_after_the_ignore_method()
{
_destination.Nickname.ShouldBe("Jimmy");
}
[Fact]
public void Should_not_map_a_property_with_an_inaccessible_setter_if_no_specific_mapping_is_configured_even_though_name_and_type_match()
{
_destination.CodeName.ShouldBeNull();
}
[Fact]
public void Should_not_map_a_property_with_no_public_setter_if_a_specific_mapping_is_configured_before_the_ignore_method()
{
_destination.ScreenName.ShouldBeNull();
}
}
public class When_configuring_a_reverse_map_to_ignore_all_source_properties_with_an_inaccessible_setter : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class Source
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Force { get; set; }
public string ReverseForce { get; private set; }
public string Respect { get; private set; }
public int Foo { get; private set; }
public int Bar { get; protected set; }
public void Initialize()
{
ReverseForce = "You With";
Respect = "R-E-S-P-E-C-T";
}
}
public class Destination
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsVisible { get; set; }
public string Force { get; private set; }
public string ReverseForce { get; set; }
public string Respect { get; set; }
public int Foz { get; private set; }
public int Baz { get; protected set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.IgnoreAllPropertiesWithAnInaccessibleSetter()
.ForMember(dest => dest.IsVisible, opt => opt.Ignore())
.ForMember(dest => dest.Force, opt => opt.MapFrom(src => src.Force))
.ReverseMap()
.IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
.ForMember(dest => dest.ReverseForce, opt => opt.MapFrom(src => src.ReverseForce))
.ForSourceMember(dest => dest.IsVisible, opt => opt.DoNotValidate());
});
protected override void Because_of()
{
var source = new Source { Id = 5, Name = "Bob", Age = 35, Force = "With You" };
source.Initialize();
_destination = Mapper.Map<Source, Destination>(source);
_source = Mapper.Map<Destination, Source>(_destination);
}
[Fact]
public void Should_consider_the_configuration_valid_even_if_some_properties_with_an_inaccessible_setter_are_unmapped()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
[Fact]
public void Should_forward_and_reverse_map_a_property_that_is_accessible_on_both_source_and_destination()
{
_source.Name.ShouldBe("Bob");
}
[Fact]
public void Should_forward_and_reverse_map_an_inaccessible_destination_property_if_a_mapping_is_defined()
{
_source.Force.ShouldBe("With You");
}
[Fact]
public void Should_forward_and_reverse_map_an_inaccessible_source_property_if_a_mapping_is_defined()
{
_source.ReverseForce.ShouldBe("You With");
}
[Fact]
public void Should_forward_and_reverse_map_an_inaccessible_source_property_even_if_a_mapping_is_not_defined()
{
_source.Respect.ShouldBe("R-E-S-P-E-C-T"); // justification: if the mapping works one way, it should work in reverse
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2016 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
namespace NUnit.Gui.Model
{
/// <summary>
/// The ResultState class represents the outcome of running a test.
/// It contains two pieces of information. The Status of the test
/// is an enum indicating whether the test passed, failed, was
/// skipped or was inconclusive. The Label provides a more
/// detailed breakdown for use by client runners.
/// </summary>
public class ResultState
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
public ResultState(TestStatus status) : this (status, string.Empty, FailureSite.Test)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="label">The label.</param>
public ResultState(TestStatus status, string label) : this(status, label, FailureSite.Test)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="site">The stage at which the result was produced</param>
public ResultState(TestStatus status, FailureSite site) : this(status, string.Empty, site)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="label">The label.</param>
/// <param name="site">The stage at which the result was produced</param>
public ResultState(TestStatus status, string label, FailureSite site)
{
Status = status;
Label = label == null ? string.Empty : label;
Site = site;
}
#endregion
#region Predefined ResultStates
/// <summary>
/// The suiteResult is inconclusive
/// </summary>
public readonly static ResultState Inconclusive = new ResultState(TestStatus.Inconclusive);
/// <summary>
/// The test was not runnable.
/// </summary>
public readonly static ResultState NotRunnable = new ResultState(TestStatus.Failed, "Invalid");
/// <summary>
/// The test has been skipped.
/// </summary>
public readonly static ResultState Skipped = new ResultState(TestStatus.Skipped);
/// <summary>
/// The test has been ignored.
/// </summary>
public readonly static ResultState Ignored = new ResultState(TestStatus.Skipped, "Ignored");
/// <summary>
/// The test was skipped because it is explicit
/// </summary>
public readonly static ResultState Explicit = new ResultState(TestStatus.Skipped, "Explicit");
/// <summary>
/// The test succeeded
/// </summary>
public readonly static ResultState Success = new ResultState(TestStatus.Passed);
/// <summary>
/// The test failed
/// </summary>
public readonly static ResultState Failure = new ResultState(TestStatus.Failed);
/// <summary>
/// The test encountered an unexpected exception
/// </summary>
public readonly static ResultState Error = new ResultState(TestStatus.Failed, "Error");
/// <summary>
/// The test was cancelled by the user
/// </summary>
public readonly static ResultState Cancelled = new ResultState(TestStatus.Failed, "Cancelled");
/// <summary>
/// A suite failed because one or more child tests failed or had errors
/// </summary>
public readonly static ResultState ChildFailure = ResultState.Failure.WithSite(FailureSite.Child);
/// <summary>
/// A suite failed in its OneTimeSetUp
/// </summary>
public readonly static ResultState SetUpFailure = ResultState.Failure.WithSite(FailureSite.SetUp);
/// <summary>
/// A suite had an unexpected exception in its OneTimeSetUp
/// </summary>
public readonly static ResultState SetUpError = ResultState.Error.WithSite(FailureSite.SetUp);
/// <summary>
/// A suite had an unexpected exception in its OneTimeDown
/// </summary>
public readonly static ResultState TearDownError = ResultState.Error.WithSite(FailureSite.TearDown);
#endregion
#region Properties
/// <summary>
/// Gets the TestStatus for the test.
/// </summary>
/// <val>The status.</val>
public TestStatus Status { get; private set; }
/// <summary>
/// Gets the label under which this test resullt is
/// categorized, if any.
/// </summary>
public string Label { get; private set; }
/// <summary>
/// Gets the stage of test execution in which
/// the failure or other result took place.
/// </summary>
public FailureSite Site { get; private set; }
/// <summary>
/// Get a new ResultState, which is the same as the current
/// one but with the FailureSite set to the specified value.
/// </summary>
/// <param name="site">The FailureSite to use</param>
/// <returns>A new ResultState</returns>
public ResultState WithSite(FailureSite site)
{
return new ResultState(this.Status, this.Label, site);
}
#endregion
#region Equals Override
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
var other = obj as ResultState;
if (other == null) return false;
return Status.Equals(other.Status) && Label.Equals(other.Label) && Site.Equals(other.Site);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return (int)Status << 8 + (int)Site ^ Label.GetHashCode();
}
#endregion
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
string s = Status.ToString();
return Label == null || Label.Length == 0 ? s : string.Format("{0}:{1}", s, Label);
}
}
/// <summary>
/// The FailureSite enum indicates the stage of a test
/// in which an error or failure occurred.
/// </summary>
public enum FailureSite
{
/// <summary>
/// Failure in the test itself
/// </summary>
Test,
/// <summary>
/// Failure in the SetUp method
/// </summary>
SetUp,
/// <summary>
/// Failure in the TearDown method
/// </summary>
TearDown,
/// <summary>
/// Failure of a parent test
/// </summary>
Parent,
/// <summary>
/// Failure of a child test
/// </summary>
Child
}
}
| |
using ICSharpCode.SharpZipLib.Checksum;
using System;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// Strategies for deflater
/// </summary>
public enum DeflateStrategy
{
/// <summary>
/// The default strategy
/// </summary>
Default = 0,
/// <summary>
/// This strategy will only allow longer string repetitions. It is
/// useful for random data with a small character set.
/// </summary>
Filtered = 1,
/// <summary>
/// This strategy will not look for string repetitions at all. It
/// only encodes with Huffman trees (which means, that more common
/// characters get a smaller encoding.
/// </summary>
HuffmanOnly = 2
}
// DEFLATE ALGORITHM:
//
// The uncompressed stream is inserted into the window array. When
// the window array is full the first half is thrown away and the
// second half is copied to the beginning.
//
// The head array is a hash table. Three characters build a hash value
// and they the value points to the corresponding index in window of
// the last string with this hash. The prev array implements a
// linked list of matches with the same hash: prev[index & WMASK] points
// to the previous index with the same hash.
//
/// <summary>
/// Low level compression engine for deflate algorithm which uses a 32K sliding window
/// with secondary compression from Huffman/Shannon-Fano codes.
/// </summary>
public class DeflaterEngine
{
#region Constants
private const int TooFar = 4096;
#endregion Constants
#region Constructors
/// <summary>
/// Construct instance with pending buffer
/// Adler calculation will be peformed
/// </summary>
/// <param name="pending">
/// Pending buffer to use
/// </param>
public DeflaterEngine(DeflaterPending pending)
: this (pending, false)
{
}
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">
/// Pending buffer to use
/// </param>
/// <param name="noAdlerCalculation">
/// If no adler calculation should be performed
/// </param>
public DeflaterEngine(DeflaterPending pending, bool noAdlerCalculation)
{
this.pending = pending;
huffman = new DeflaterHuffman(pending);
if (!noAdlerCalculation)
adler = new Adler32();
window = new byte[2 * DeflaterConstants.WSIZE];
head = new short[DeflaterConstants.HASH_SIZE];
prev = new short[DeflaterConstants.WSIZE];
// We start at index 1, to avoid an implementation deficiency, that
// we cannot build a repeat pattern at index 0.
blockStart = strstart = 1;
}
#endregion Constructors
/// <summary>
/// Deflate drives actual compression of data
/// </summary>
/// <param name="flush">True to flush input buffers</param>
/// <param name="finish">Finish deflation with the current input.</param>
/// <returns>Returns true if progress has been made.</returns>
public bool Deflate(bool flush, bool finish)
{
bool progress;
do
{
FillWindow();
bool canFlush = flush && (inputOff == inputEnd);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.WriteLine("window: [" + blockStart + "," + strstart + ","
+ lookahead + "], " + compressionFunction + "," + canFlush);
}
#endif
switch (compressionFunction)
{
case DeflaterConstants.DEFLATE_STORED:
progress = DeflateStored(canFlush, finish);
break;
case DeflaterConstants.DEFLATE_FAST:
progress = DeflateFast(canFlush, finish);
break;
case DeflaterConstants.DEFLATE_SLOW:
progress = DeflateSlow(canFlush, finish);
break;
default:
throw new InvalidOperationException("unknown compressionFunction");
}
} while (pending.IsFlushed && progress); // repeat while we have no pending output and progress was made
return progress;
}
/// <summary>
/// Sets input data to be deflated. Should only be called when <code>NeedsInput()</code>
/// returns true
/// </summary>
/// <param name="buffer">The buffer containing input data.</param>
/// <param name="offset">The offset of the first byte of data.</param>
/// <param name="count">The number of bytes of data to use as input.</param>
public void SetInput(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (inputOff < inputEnd)
{
throw new InvalidOperationException("Old input was not completely processed");
}
int end = offset + count;
/* We want to throw an ArrayIndexOutOfBoundsException early. The
* check is very tricky: it also handles integer wrap around.
*/
if ((offset > end) || (end > buffer.Length))
{
throw new ArgumentOutOfRangeException(nameof(count));
}
inputBuf = buffer;
inputOff = offset;
inputEnd = end;
}
/// <summary>
/// Determines if more <see cref="SetInput">input</see> is needed.
/// </summary>
/// <returns>Return true if input is needed via <see cref="SetInput">SetInput</see></returns>
public bool NeedsInput()
{
return (inputEnd == inputOff);
}
/// <summary>
/// Set compression dictionary
/// </summary>
/// <param name="buffer">The buffer containing the dictionary data</param>
/// <param name="offset">The offset in the buffer for the first byte of data</param>
/// <param name="length">The length of the dictionary data.</param>
public void SetDictionary(byte[] buffer, int offset, int length)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (strstart != 1) )
{
throw new InvalidOperationException("strstart not 1");
}
#endif
adler?.Update(new ArraySegment<byte>(buffer, offset, length));
if (length < DeflaterConstants.MIN_MATCH)
{
return;
}
if (length > DeflaterConstants.MAX_DIST)
{
offset += length - DeflaterConstants.MAX_DIST;
length = DeflaterConstants.MAX_DIST;
}
System.Array.Copy(buffer, offset, window, strstart, length);
UpdateHash();
--length;
while (--length > 0)
{
InsertString();
strstart++;
}
strstart += 2;
blockStart = strstart;
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
huffman.Reset();
adler?.Reset();
blockStart = strstart = 1;
lookahead = 0;
totalIn = 0;
prevAvailable = false;
matchLen = DeflaterConstants.MIN_MATCH - 1;
for (int i = 0; i < DeflaterConstants.HASH_SIZE; i++)
{
head[i] = 0;
}
for (int i = 0; i < DeflaterConstants.WSIZE; i++)
{
prev[i] = 0;
}
}
/// <summary>
/// Reset Adler checksum
/// </summary>
public void ResetAdler()
{
adler?.Reset();
}
/// <summary>
/// Get current value of Adler checksum
/// </summary>
public int Adler
{
get
{
return (adler != null) ? unchecked((int)adler.Value) : 0;
}
}
/// <summary>
/// Total data processed
/// </summary>
public long TotalIn
{
get
{
return totalIn;
}
}
/// <summary>
/// Get/set the <see cref="DeflateStrategy">deflate strategy</see>
/// </summary>
public DeflateStrategy Strategy
{
get
{
return strategy;
}
set
{
strategy = value;
}
}
/// <summary>
/// Set the deflate level (0-9)
/// </summary>
/// <param name="level">The value to set the level to.</param>
public void SetLevel(int level)
{
if ((level < 0) || (level > 9))
{
throw new ArgumentOutOfRangeException(nameof(level));
}
goodLength = DeflaterConstants.GOOD_LENGTH[level];
max_lazy = DeflaterConstants.MAX_LAZY[level];
niceLength = DeflaterConstants.NICE_LENGTH[level];
max_chain = DeflaterConstants.MAX_CHAIN[level];
if (DeflaterConstants.COMPR_FUNC[level] != compressionFunction)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.WriteLine("Change from " + compressionFunction + " to "
+ DeflaterConstants.COMPR_FUNC[level]);
}
#endif
switch (compressionFunction)
{
case DeflaterConstants.DEFLATE_STORED:
if (strstart > blockStart)
{
huffman.FlushStoredBlock(window, blockStart,
strstart - blockStart, false);
blockStart = strstart;
}
UpdateHash();
break;
case DeflaterConstants.DEFLATE_FAST:
if (strstart > blockStart)
{
huffman.FlushBlock(window, blockStart, strstart - blockStart,
false);
blockStart = strstart;
}
break;
case DeflaterConstants.DEFLATE_SLOW:
if (prevAvailable)
{
huffman.TallyLit(window[strstart - 1] & 0xff);
}
if (strstart > blockStart)
{
huffman.FlushBlock(window, blockStart, strstart - blockStart, false);
blockStart = strstart;
}
prevAvailable = false;
matchLen = DeflaterConstants.MIN_MATCH - 1;
break;
}
compressionFunction = DeflaterConstants.COMPR_FUNC[level];
}
}
/// <summary>
/// Fill the window
/// </summary>
public void FillWindow()
{
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (strstart >= DeflaterConstants.WSIZE + DeflaterConstants.MAX_DIST)
{
SlideWindow();
}
/* If there is not enough lookahead, but still some input left,
* read in the input
*/
if (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd)
{
int more = 2 * DeflaterConstants.WSIZE - lookahead - strstart;
if (more > inputEnd - inputOff)
{
more = inputEnd - inputOff;
}
System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more);
adler?.Update(new ArraySegment<byte>(inputBuf, inputOff, more));
inputOff += more;
totalIn += more;
lookahead += more;
}
if (lookahead >= DeflaterConstants.MIN_MATCH)
{
UpdateHash();
}
}
private void UpdateHash()
{
/*
if (DEBUGGING) {
Console.WriteLine("updateHash: "+strstart);
}
*/
ins_h = (window[strstart] << DeflaterConstants.HASH_SHIFT) ^ window[strstart + 1];
}
/// <summary>
/// Inserts the current string in the head hash and returns the previous
/// value for this hash.
/// </summary>
/// <returns>The previous hash value</returns>
private int InsertString()
{
short match;
int hash = ((ins_h << DeflaterConstants.HASH_SHIFT) ^ window[strstart + (DeflaterConstants.MIN_MATCH - 1)]) & DeflaterConstants.HASH_MASK;
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^
(window[strstart + 1] << HASH_SHIFT) ^
(window[strstart + 2])) & HASH_MASK)) {
throw new SharpZipBaseException("hash inconsistent: " + hash + "/"
+window[strstart] + ","
+window[strstart + 1] + ","
+window[strstart + 2] + "," + HASH_SHIFT);
}
}
#endif
prev[strstart & DeflaterConstants.WMASK] = match = head[hash];
head[hash] = unchecked((short)strstart);
ins_h = hash;
return match & 0xffff;
}
private void SlideWindow()
{
Array.Copy(window, DeflaterConstants.WSIZE, window, 0, DeflaterConstants.WSIZE);
matchStart -= DeflaterConstants.WSIZE;
strstart -= DeflaterConstants.WSIZE;
blockStart -= DeflaterConstants.WSIZE;
// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage).
for (int i = 0; i < DeflaterConstants.HASH_SIZE; ++i)
{
int m = head[i] & 0xffff;
head[i] = (short)(m >= DeflaterConstants.WSIZE ? (m - DeflaterConstants.WSIZE) : 0);
}
// Slide the prev table.
for (int i = 0; i < DeflaterConstants.WSIZE; i++)
{
int m = prev[i] & 0xffff;
prev[i] = (short)(m >= DeflaterConstants.WSIZE ? (m - DeflaterConstants.WSIZE) : 0);
}
}
/// <summary>
/// Find the best (longest) string in the window matching the
/// string starting at strstart.
///
/// Preconditions:
/// <code>
/// strstart + DeflaterConstants.MAX_MATCH <= window.length.</code>
/// </summary>
/// <param name="curMatch"></param>
/// <returns>True if a match greater than the minimum length is found</returns>
private bool FindLongestMatch(int curMatch)
{
int match;
int scan = strstart;
// scanMax is the highest position that we can look at
int scanMax = scan + Math.Min(DeflaterConstants.MAX_MATCH, lookahead) - 1;
int limit = Math.Max(scan - DeflaterConstants.MAX_DIST, 0);
byte[] window = this.window;
short[] prev = this.prev;
int chainLength = this.max_chain;
int niceLength = Math.Min(this.niceLength, lookahead);
matchLen = Math.Max(matchLen, DeflaterConstants.MIN_MATCH - 1);
if (scan + matchLen > scanMax) return false;
byte scan_end1 = window[scan + matchLen - 1];
byte scan_end = window[scan + matchLen];
// Do not waste too much time if we already have a good match:
if (matchLen >= this.goodLength) chainLength >>= 2;
do
{
match = curMatch;
scan = strstart;
if (window[match + matchLen] != scan_end
|| window[match + matchLen - 1] != scan_end1
|| window[match] != window[scan]
|| window[++match] != window[++scan])
{
continue;
}
// scan is set to strstart+1 and the comparison passed, so
// scanMax - scan is the maximum number of bytes we can compare.
// below we compare 8 bytes at a time, so first we compare
// (scanMax - scan) % 8 bytes, so the remainder is a multiple of 8
switch ((scanMax - scan) % 8)
{
case 1:
if (window[++scan] == window[++match]) break;
break;
case 2:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 3:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 4:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 5:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 6:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
case 7:
if (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]) break;
break;
}
if (window[scan] == window[match])
{
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart + 258 unless lookahead is
* exhausted first.
*/
do
{
if (scan == scanMax)
{
++scan; // advance to first position not matched
++match;
break;
}
}
while (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]);
}
if (scan - strstart > matchLen)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (ins_h == 0) )
Console.Error.WriteLine("Found match: " + curMatch + "-" + (scan - strstart));
#endif
matchStart = curMatch;
matchLen = scan - strstart;
if (matchLen >= niceLength)
break;
scan_end1 = window[scan - 1];
scan_end = window[scan];
}
} while ((curMatch = (prev[curMatch & DeflaterConstants.WMASK] & 0xffff)) > limit && 0 != --chainLength);
return matchLen >= DeflaterConstants.MIN_MATCH;
}
private bool DeflateStored(bool flush, bool finish)
{
if (!flush && (lookahead == 0))
{
return false;
}
strstart += lookahead;
lookahead = 0;
int storedLength = strstart - blockStart;
if ((storedLength >= DeflaterConstants.MAX_BLOCK_SIZE) || // Block is full
(blockStart < DeflaterConstants.WSIZE && storedLength >= DeflaterConstants.MAX_DIST) || // Block may move out of window
flush)
{
bool lastBlock = finish;
if (storedLength > DeflaterConstants.MAX_BLOCK_SIZE)
{
storedLength = DeflaterConstants.MAX_BLOCK_SIZE;
lastBlock = false;
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
Console.WriteLine("storedBlock[" + storedLength + "," + lastBlock + "]");
}
#endif
huffman.FlushStoredBlock(window, blockStart, storedLength, lastBlock);
blockStart += storedLength;
return !(lastBlock || storedLength == 0);
}
return true;
}
private bool DeflateFast(bool flush, bool finish)
{
if (lookahead < DeflaterConstants.MIN_LOOKAHEAD && !flush)
{
return false;
}
while (lookahead >= DeflaterConstants.MIN_LOOKAHEAD || flush)
{
if (lookahead == 0)
{
// We are flushing everything
huffman.FlushBlock(window, blockStart, strstart - blockStart, finish);
blockStart = strstart;
return false;
}
if (strstart > 2 * DeflaterConstants.WSIZE - DeflaterConstants.MIN_LOOKAHEAD)
{
/* slide window, as FindLongestMatch needs this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int hashHead;
if (lookahead >= DeflaterConstants.MIN_MATCH &&
(hashHead = InsertString()) != 0 &&
strategy != DeflateStrategy.HuffmanOnly &&
strstart - hashHead <= DeflaterConstants.MAX_DIST &&
FindLongestMatch(hashHead))
{
// longestMatch sets matchStart and matchLen
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
for (int i = 0 ; i < matchLen; i++) {
if (window[strstart + i] != window[matchStart + i]) {
throw new SharpZipBaseException("Match failure");
}
}
}
#endif
bool full = huffman.TallyDist(strstart - matchStart, matchLen);
lookahead -= matchLen;
if (matchLen <= max_lazy && lookahead >= DeflaterConstants.MIN_MATCH)
{
while (--matchLen > 0)
{
++strstart;
InsertString();
}
++strstart;
}
else
{
strstart += matchLen;
if (lookahead >= DeflaterConstants.MIN_MATCH - 1)
{
UpdateHash();
}
}
matchLen = DeflaterConstants.MIN_MATCH - 1;
if (!full)
{
continue;
}
}
else
{
// No match found
huffman.TallyLit(window[strstart] & 0xff);
++strstart;
--lookahead;
}
if (huffman.IsFull())
{
bool lastBlock = finish && (lookahead == 0);
huffman.FlushBlock(window, blockStart, strstart - blockStart, lastBlock);
blockStart = strstart;
return !lastBlock;
}
}
return true;
}
private bool DeflateSlow(bool flush, bool finish)
{
if (lookahead < DeflaterConstants.MIN_LOOKAHEAD && !flush)
{
return false;
}
while (lookahead >= DeflaterConstants.MIN_LOOKAHEAD || flush)
{
if (lookahead == 0)
{
if (prevAvailable)
{
huffman.TallyLit(window[strstart - 1] & 0xff);
}
prevAvailable = false;
// We are flushing everything
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && !flush)
{
throw new SharpZipBaseException("Not flushing, but no lookahead");
}
#endif
huffman.FlushBlock(window, blockStart, strstart - blockStart,
finish);
blockStart = strstart;
return false;
}
if (strstart >= 2 * DeflaterConstants.WSIZE - DeflaterConstants.MIN_LOOKAHEAD)
{
/* slide window, as FindLongestMatch needs this.
* This should only happen when flushing and the window
* is almost full.
*/
SlideWindow();
}
int prevMatch = matchStart;
int prevLen = matchLen;
if (lookahead >= DeflaterConstants.MIN_MATCH)
{
int hashHead = InsertString();
if (strategy != DeflateStrategy.HuffmanOnly &&
hashHead != 0 &&
strstart - hashHead <= DeflaterConstants.MAX_DIST &&
FindLongestMatch(hashHead))
{
// longestMatch sets matchStart and matchLen
// Discard match if too small and too far away
if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == DeflaterConstants.MIN_MATCH && strstart - matchStart > TooFar)))
{
matchLen = DeflaterConstants.MIN_MATCH - 1;
}
}
}
// previous match was better
if ((prevLen >= DeflaterConstants.MIN_MATCH) && (matchLen <= prevLen))
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING)
{
for (int i = 0 ; i < matchLen; i++) {
if (window[strstart-1+i] != window[prevMatch + i])
throw new SharpZipBaseException();
}
}
#endif
huffman.TallyDist(strstart - 1 - prevMatch, prevLen);
prevLen -= 2;
do
{
strstart++;
lookahead--;
if (lookahead >= DeflaterConstants.MIN_MATCH)
{
InsertString();
}
} while (--prevLen > 0);
strstart++;
lookahead--;
prevAvailable = false;
matchLen = DeflaterConstants.MIN_MATCH - 1;
}
else
{
if (prevAvailable)
{
huffman.TallyLit(window[strstart - 1] & 0xff);
}
prevAvailable = true;
strstart++;
lookahead--;
}
if (huffman.IsFull())
{
int len = strstart - blockStart;
if (prevAvailable)
{
len--;
}
bool lastBlock = (finish && (lookahead == 0) && !prevAvailable);
huffman.FlushBlock(window, blockStart, len, lastBlock);
blockStart += len;
return !lastBlock;
}
}
return true;
}
#region Instance Fields
// Hash index of string to be inserted
private int ins_h;
/// <summary>
/// Hashtable, hashing three characters to an index for window, so
/// that window[index]..window[index+2] have this hash code.
/// Note that the array should really be unsigned short, so you need
/// to and the values with 0xffff.
/// </summary>
private short[] head;
/// <summary>
/// <code>prev[index & WMASK]</code> points to the previous index that has the
/// same hash code as the string starting at index. This way
/// entries with the same hash code are in a linked list.
/// Note that the array should really be unsigned short, so you need
/// to and the values with 0xffff.
/// </summary>
private short[] prev;
private int matchStart;
// Length of best match
private int matchLen;
// Set if previous match exists
private bool prevAvailable;
private int blockStart;
/// <summary>
/// Points to the current character in the window.
/// </summary>
private int strstart;
/// <summary>
/// lookahead is the number of characters starting at strstart in
/// window that are valid.
/// So window[strstart] until window[strstart+lookahead-1] are valid
/// characters.
/// </summary>
private int lookahead;
/// <summary>
/// This array contains the part of the uncompressed stream that
/// is of relevance. The current character is indexed by strstart.
/// </summary>
private byte[] window;
private DeflateStrategy strategy;
private int max_chain, max_lazy, niceLength, goodLength;
/// <summary>
/// The current compression function.
/// </summary>
private int compressionFunction;
/// <summary>
/// The input data for compression.
/// </summary>
private byte[] inputBuf;
/// <summary>
/// The total bytes of input read.
/// </summary>
private long totalIn;
/// <summary>
/// The offset into inputBuf, where input data starts.
/// </summary>
private int inputOff;
/// <summary>
/// The end offset of the input data.
/// </summary>
private int inputEnd;
private DeflaterPending pending;
private DeflaterHuffman huffman;
/// <summary>
/// The adler checksum
/// </summary>
private Adler32 adler;
#endregion Instance Fields
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
namespace Microsoft.Build.BuildEngine.Shared
{
/// <summary>
/// This class contains utility methods for XML manipulation.
/// </summary>
/// <owner>SumedhK</owner>
static internal class XmlUtilities
{
/// <summary>
/// This method renames an XML element. Well, actually you can't directly
/// rename an XML element using the DOM, so what you have to do is create
/// a brand new XML element with the new name, and copy over all the attributes
/// and children. This method returns the new XML element object.
/// </summary>
/// <param name="oldElement"></param>
/// <param name="newElementName"></param>
/// <param name="xmlNamespace">Can be null if global namespace.</param>
/// <returns>new/renamed element</returns>
/// <owner>RGoel</owner>
internal static XmlElement RenameXmlElement(XmlElement oldElement, string newElementName, string xmlNamespace)
{
XmlElement newElement = (xmlNamespace == null)
? oldElement.OwnerDocument.CreateElement(newElementName)
: oldElement.OwnerDocument.CreateElement(newElementName, xmlNamespace);
// Copy over all the attributes.
foreach (XmlAttribute oldAttribute in oldElement.Attributes)
{
XmlAttribute newAttribute = (XmlAttribute)oldAttribute.CloneNode(true);
newElement.SetAttributeNode(newAttribute);
}
// Copy over all the child nodes.
foreach (XmlNode oldChildNode in oldElement.ChildNodes)
{
XmlNode newChildNode = oldChildNode.CloneNode(true);
newElement.AppendChild(newChildNode);
}
// Add the new element in the same place the old element was.
oldElement.ParentNode?.ReplaceChild(newElement, oldElement);
return newElement;
}
/// <summary>
/// Retrieves the file that the given XML node was defined in. If the XML node is purely in-memory, it may not have a file
/// associated with it, in which case the default file is returned.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="node"></param>
/// <param name="defaultFile">Can be empty string.</param>
/// <returns>The path to the XML node's file, or the default file.</returns>
internal static string GetXmlNodeFile(XmlNode node, string defaultFile)
{
ErrorUtilities.VerifyThrow(node != null, "Need XML node.");
ErrorUtilities.VerifyThrow(defaultFile != null, "Must specify the default file to use.");
string file = defaultFile;
// NOTE: the XML node may not have a filename if it's purely an in-memory node
if (!string.IsNullOrEmpty(node.OwnerDocument.BaseURI))
{
file = new Uri(node.OwnerDocument.BaseURI).LocalPath;
}
return file;
}
/// <summary>
/// An XML document can have many root nodes, but usually we want the single root
/// element. Callers can test each root node in turn with this method, until it returns
/// true.
/// </summary>
/// <param name="node">Candidate root node</param>
/// <returns>true if node is the root element</returns>
/// <owner>danmose</owner>
internal static bool IsXmlRootElement(XmlNode node)
{
// "A Document node can have the following child node types: XmlDeclaration,
// Element (maximum of one), ProcessingInstruction, Comment, and DocumentType."
return
(node.NodeType != XmlNodeType.Comment) &&
(node.NodeType != XmlNodeType.Whitespace) &&
(node.NodeType != XmlNodeType.XmlDeclaration) &&
(node.NodeType != XmlNodeType.ProcessingInstruction) &&
(node.NodeType != XmlNodeType.DocumentType)
;
}
/// <summary>
/// Verifies that a name is valid for the name of an item, property, or piece of metadata.
/// If it isn't, throws an ArgumentException indicating the invalid character.
/// </summary>
/// <remarks>
/// Note that our restrictions are more stringent than the XML Standard's restrictions.
/// </remarks>
/// <throws>ArgumentException</throws>
/// <param name="name">name to validate</param>
/// <owner>danmose</owner>
internal static void VerifyThrowValidElementName(string name)
{
int firstInvalidCharLocation = LocateFirstInvalidElementNameCharacter(name);
if (-1 != firstInvalidCharLocation)
{
ErrorUtilities.VerifyThrowArgument(false, "NameInvalid", name, name[firstInvalidCharLocation]);
}
}
/// <summary>
/// Verifies that a name is valid for the name of an item, property, or piece of metadata.
/// If it isn't, throws an InvalidProjectException indicating the invalid character.
/// </summary>
/// <remarks>
/// Note that our restrictions are more stringent than the XML Standard's restrictions.
/// </remarks>
internal static void VerifyThrowProjectValidElementName(XmlElement element)
{
string name = element.Name;
int firstInvalidCharLocation = LocateFirstInvalidElementNameCharacter(name);
if (-1 != firstInvalidCharLocation)
{
ProjectErrorUtilities.ThrowInvalidProject(element, "NameInvalid", name, name[firstInvalidCharLocation]);
}
}
/// <summary>
/// Indicates if the given name is valid as the name of an item, property or metadatum.
/// </summary>
/// <remarks>
/// Note that our restrictions are more stringent than those of the XML Standard.
/// </remarks>
/// <owner>SumedhK</owner>
/// <param name="name"></param>
/// <returns>true, if name is valid</returns>
internal static bool IsValidElementName(string name)
{
return LocateFirstInvalidElementNameCharacter(name) == -1;
}
/// <summary>
/// Finds the location of the first invalid character, if any, in the name of an
/// item, property, or piece of metadata. Returns the location of the first invalid character, or -1 if there are none.
/// Valid names must match this pattern: [A-Za-z_][A-Za-z_0-9\-.]*
/// Note, this is a subset of all possible valid XmlElement names: we use a subset because we also
/// have to match this same set in our regular expressions, and allowing all valid XmlElement name
/// characters in a regular expression would be impractical.
/// </summary>
/// <remarks>
/// Note that our restrictions are more stringent than the XML Standard's restrictions.
/// PERF: This method has to be as fast as possible, as it's called when any item, property, or piece
/// of metadata is constructed.
/// </remarks>
internal static int LocateFirstInvalidElementNameCharacter(string name)
{
// Check the first character.
// Try capital letters first.
// Optimize slightly for success.
if (!IsValidInitialElementNameCharacter(name[0]))
{
return 0;
}
// Check subsequent characters.
// Try lower case letters first.
// Optimize slightly for success.
for (int i = 1; i < name.Length; i++)
{
if (!IsValidSubsequentElementNameCharacter(name[i]))
{
return i;
}
}
// If we got here, the name was valid.
return -1;
}
/// <summary>
/// Load the xml file using XMLTextReader and locate the element and attribute specified and then
/// return the value. This is a quick way to peek at the xml file whithout having the go through
/// the XMLDocument (MSDN article (Chapter 9 - Improving XML Performance)).
/// </summary>
internal static string GetAttributeValueForElementFromFile
(
string projectFileName,
string elementName,
string attributeName
)
{
string attributeValue = null;
try
{
using (XmlTextReader xmlReader = new XmlTextReader(projectFileName))
{
xmlReader.DtdProcessing = DtdProcessing.Ignore;
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (String.Equals(xmlReader.Name, elementName, StringComparison.OrdinalIgnoreCase))
{
if (xmlReader.HasAttributes)
{
for (int i = 0; i < xmlReader.AttributeCount; i++)
{
xmlReader.MoveToAttribute(i);
if (String.Equals(xmlReader.Name, attributeName, StringComparison.OrdinalIgnoreCase))
{
attributeValue = xmlReader.Value;
break;
}
}
}
// if we have already located the element then we are done
break;
}
}
}
}
}
catch(XmlException)
{
// Ignore any XML exceptions as it will be caught later on
}
catch (System.IO.IOException)
{
// Ignore any IO exceptions as it will be caught later on
}
return attributeValue;
}
internal static bool IsValidInitialElementNameCharacter(char c)
{
return (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c == '_');
}
internal static bool IsValidSubsequentElementNameCharacter(char c)
{
return (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') ||
(c == '_') ||
(c == '-');
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.SNATTranslationAddressV2Binding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics))]
public partial class LocalLBSNATTranslationAddressV2 : iControlInterface {
public LocalLBSNATTranslationAddressV2() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void create(
string [] translation_addresses,
string [] addresses,
string [] traffic_groups
) {
this.Invoke("create", new object [] {
translation_addresses,
addresses,
traffic_groups});
}
public System.IAsyncResult Begincreate(string [] translation_addresses,string [] addresses,string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
translation_addresses,
addresses,
traffic_groups}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_translation_addresses
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void delete_all_translation_addresses(
) {
this.Invoke("delete_all_translation_addresses", new object [0]);
}
public System.IAsyncResult Begindelete_all_translation_addresses(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_translation_addresses", new object[0], callback, asyncState);
}
public void Enddelete_all_translation_addresses(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_translation_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void delete_translation_address(
string [] translation_addresses
) {
this.Invoke("delete_translation_address", new object [] {
translation_addresses});
}
public System.IAsyncResult Begindelete_translation_address(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_translation_address", new object[] {
translation_addresses}, callback, asyncState);
}
public void Enddelete_translation_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_address(
string [] translation_addresses
) {
object [] results = this.Invoke("get_address", new object [] {
translation_addresses});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_address(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_address", new object[] {
translation_addresses}, callback, asyncState);
}
public string [] Endget_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_arp_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_arp_state(
string [] translation_addresses
) {
object [] results = this.Invoke("get_arp_state", new object [] {
translation_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_arp_state(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_arp_state", new object[] {
translation_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_arp_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_connection_limit(
string [] translation_addresses
) {
object [] results = this.Invoke("get_connection_limit", new object [] {
translation_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_connection_limit(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_limit", new object[] {
translation_addresses}, callback, asyncState);
}
public long [] Endget_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] translation_addresses
) {
object [] results = this.Invoke("get_description", new object [] {
translation_addresses});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
translation_addresses}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_enabled_state(
string [] translation_addresses
) {
object [] results = this.Invoke("get_enabled_state", new object [] {
translation_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_enabled_state(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_enabled_state", new object[] {
translation_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ip_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_ip_timeout(
string [] translation_addresses
) {
object [] results = this.Invoke("get_ip_timeout", new object [] {
translation_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_ip_timeout(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ip_timeout", new object[] {
translation_addresses}, callback, asyncState);
}
public long [] Endget_ip_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics get_statistics(
string [] translation_addresses
) {
object [] results = this.Invoke("get_statistics", new object [] {
translation_addresses});
return ((LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
translation_addresses}, callback, asyncState);
}
public LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_tcp_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_tcp_timeout(
string [] translation_addresses
) {
object [] results = this.Invoke("get_tcp_timeout", new object [] {
translation_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_tcp_timeout(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_tcp_timeout", new object[] {
translation_addresses}, callback, asyncState);
}
public long [] Endget_tcp_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_traffic_group(
string [] translation_addresses
) {
object [] results = this.Invoke("get_traffic_group", new object [] {
translation_addresses});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_traffic_group(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_traffic_group", new object[] {
translation_addresses}, callback, asyncState);
}
public string [] Endget_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_udp_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_udp_timeout(
string [] translation_addresses
) {
object [] results = this.Invoke("get_udp_timeout", new object [] {
translation_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_udp_timeout(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_udp_timeout", new object[] {
translation_addresses}, callback, asyncState);
}
public long [] Endget_udp_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// is_traffic_group_inherited
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_traffic_group_inherited(
string [] translation_addresses
) {
object [] results = this.Invoke("is_traffic_group_inherited", new object [] {
translation_addresses});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_traffic_group_inherited(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_traffic_group_inherited", new object[] {
translation_addresses}, callback, asyncState);
}
public bool [] Endis_traffic_group_inherited(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void reset_statistics(
string [] translation_addresses
) {
this.Invoke("reset_statistics", new object [] {
translation_addresses});
}
public System.IAsyncResult Beginreset_statistics(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
translation_addresses}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_arp_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void set_arp_state(
string [] translation_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_arp_state", new object [] {
translation_addresses,
states});
}
public System.IAsyncResult Beginset_arp_state(string [] translation_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_arp_state", new object[] {
translation_addresses,
states}, callback, asyncState);
}
public void Endset_arp_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void set_connection_limit(
string [] translation_addresses,
long [] limits
) {
this.Invoke("set_connection_limit", new object [] {
translation_addresses,
limits});
}
public System.IAsyncResult Beginset_connection_limit(string [] translation_addresses,long [] limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_limit", new object[] {
translation_addresses,
limits}, callback, asyncState);
}
public void Endset_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void set_description(
string [] translation_addresses,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
translation_addresses,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] translation_addresses,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
translation_addresses,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void set_enabled_state(
string [] translation_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_enabled_state", new object [] {
translation_addresses,
states});
}
public System.IAsyncResult Beginset_enabled_state(string [] translation_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_enabled_state", new object[] {
translation_addresses,
states}, callback, asyncState);
}
public void Endset_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ip_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void set_ip_timeout(
string [] translation_addresses,
long [] timeouts
) {
this.Invoke("set_ip_timeout", new object [] {
translation_addresses,
timeouts});
}
public System.IAsyncResult Beginset_ip_timeout(string [] translation_addresses,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ip_timeout", new object[] {
translation_addresses,
timeouts}, callback, asyncState);
}
public void Endset_ip_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_tcp_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void set_tcp_timeout(
string [] translation_addresses,
long [] timeouts
) {
this.Invoke("set_tcp_timeout", new object [] {
translation_addresses,
timeouts});
}
public System.IAsyncResult Beginset_tcp_timeout(string [] translation_addresses,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_tcp_timeout", new object[] {
translation_addresses,
timeouts}, callback, asyncState);
}
public void Endset_tcp_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void set_traffic_group(
string [] translation_addresses,
string [] traffic_groups
) {
this.Invoke("set_traffic_group", new object [] {
translation_addresses,
traffic_groups});
}
public System.IAsyncResult Beginset_traffic_group(string [] translation_addresses,string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_traffic_group", new object[] {
translation_addresses,
traffic_groups}, callback, asyncState);
}
public void Endset_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_udp_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddressV2",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddressV2")]
public void set_udp_timeout(
string [] translation_addresses,
long [] timeouts
) {
this.Invoke("set_udp_timeout", new object [] {
translation_addresses,
timeouts});
}
public System.IAsyncResult Beginset_udp_timeout(string [] translation_addresses,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_udp_timeout", new object[] {
translation_addresses,
timeouts}, callback, asyncState);
}
public void Endset_udp_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.SNATTranslationAddressV2.SNATTranslationAddressStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBSNATTranslationAddressV2SNATTranslationAddressStatisticEntry
{
private string translation_addressField;
public string translation_address
{
get { return this.translation_addressField; }
set { this.translation_addressField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.SNATTranslationAddressV2.SNATTranslationAddressStatistics", Namespace = "urn:iControl")]
public partial class LocalLBSNATTranslationAddressV2SNATTranslationAddressStatistics
{
private LocalLBSNATTranslationAddressV2SNATTranslationAddressStatisticEntry [] statisticsField;
public LocalLBSNATTranslationAddressV2SNATTranslationAddressStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
using ErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs;
namespace Newtonsoft.Json
{
/// <summary>
/// Serializes and deserializes objects into and from the JSON format.
/// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON.
/// </summary>
public class JsonSerializer
{
#region Properties
private TypeNameHandling _typeNameHandling;
private FormatterAssemblyStyle _typeNameAssemblyFormat;
private PreserveReferencesHandling _preserveReferencesHandling;
private ReferenceLoopHandling _referenceLoopHandling;
private MissingMemberHandling _missingMemberHandling;
private ObjectCreationHandling _objectCreationHandling;
private NullValueHandling _nullValueHandling;
private DefaultValueHandling _defaultValueHandling;
private ConstructorHandling _constructorHandling;
private JsonConverterCollection _converters;
private IContractResolver _contractResolver;
private IReferenceResolver _referenceResolver;
private SerializationBinder _binder;
private StreamingContext _context;
private Formatting? _formatting;
private DateFormatHandling? _dateFormatHandling;
private DateTimeZoneHandling? _dateTimeZoneHandling;
private DateParseHandling? _dateParseHandling;
private CultureInfo _culture;
private int? _maxDepth;
private bool _maxDepthSet;
/// <summary>
/// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization.
/// </summary>
public virtual event EventHandler<ErrorEventArgs> Error;
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
public virtual IReferenceResolver ReferenceResolver
{
get
{
if (_referenceResolver == null)
_referenceResolver = new DefaultReferenceResolver();
return _referenceResolver;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Reference resolver cannot be null.");
_referenceResolver = value;
}
}
/// <summary>
/// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names.
/// </summary>
public virtual SerializationBinder Binder
{
get
{
return _binder;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Serialization binder cannot be null.");
_binder = value;
}
}
/// <summary>
/// Gets or sets how type name writing and reading is handled by the serializer.
/// </summary>
public virtual TypeNameHandling TypeNameHandling
{
get { return _typeNameHandling; }
set
{
if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
throw new ArgumentOutOfRangeException("value");
_typeNameHandling = value;
}
}
/// <summary>
/// Gets or sets how a type name assembly is written and resolved by the serializer.
/// </summary>
/// <value>The type name assembly format.</value>
public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
{
get { return _typeNameAssemblyFormat; }
set
{
if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
throw new ArgumentOutOfRangeException("value");
_typeNameAssemblyFormat = value;
}
}
/// <summary>
/// Gets or sets how object references are preserved by the serializer.
/// </summary>
public virtual PreserveReferencesHandling PreserveReferencesHandling
{
get { return _preserveReferencesHandling; }
set
{
if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
throw new ArgumentOutOfRangeException("value");
_preserveReferencesHandling = value;
}
}
/// <summary>
/// Get or set how reference loops (e.g. a class referencing itself) is handled.
/// </summary>
public virtual ReferenceLoopHandling ReferenceLoopHandling
{
get { return _referenceLoopHandling; }
set
{
if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
throw new ArgumentOutOfRangeException("value");
_referenceLoopHandling = value;
}
}
/// <summary>
/// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
/// </summary>
public virtual MissingMemberHandling MissingMemberHandling
{
get { return _missingMemberHandling; }
set
{
if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
throw new ArgumentOutOfRangeException("value");
_missingMemberHandling = value;
}
}
/// <summary>
/// Get or set how null values are handled during serialization and deserialization.
/// </summary>
public virtual NullValueHandling NullValueHandling
{
get { return _nullValueHandling; }
set
{
if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
throw new ArgumentOutOfRangeException("value");
_nullValueHandling = value;
}
}
/// <summary>
/// Get or set how null default are handled during serialization and deserialization.
/// </summary>
public virtual DefaultValueHandling DefaultValueHandling
{
get { return _defaultValueHandling; }
set
{
if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
throw new ArgumentOutOfRangeException("value");
_defaultValueHandling = value;
}
}
/// <summary>
/// Gets or sets how objects are created during deserialization.
/// </summary>
/// <value>The object creation handling.</value>
public virtual ObjectCreationHandling ObjectCreationHandling
{
get { return _objectCreationHandling; }
set
{
if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
throw new ArgumentOutOfRangeException("value");
_objectCreationHandling = value;
}
}
/// <summary>
/// Gets or sets how constructors are used during deserialization.
/// </summary>
/// <value>The constructor handling.</value>
public virtual ConstructorHandling ConstructorHandling
{
get { return _constructorHandling; }
set
{
if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
throw new ArgumentOutOfRangeException("value");
_constructorHandling = value;
}
}
/// <summary>
/// Gets a collection <see cref="JsonConverter"/> that will be used during serialization.
/// </summary>
/// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value>
public virtual JsonConverterCollection Converters
{
get
{
if (_converters == null)
_converters = new JsonConverterCollection();
return _converters;
}
}
/// <summary>
/// Gets or sets the contract resolver used by the serializer when
/// serializing .NET objects to JSON and vice versa.
/// </summary>
public virtual IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
_contractResolver = DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
/// <summary>
/// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods.
/// </summary>
/// <value>The context.</value>
public virtual StreamingContext Context
{
get { return _context; }
set { _context = value; }
}
/// <summary>
/// Indicates how JSON text output is formatted.
/// </summary>
public virtual Formatting Formatting
{
get { return _formatting ?? JsonSerializerSettings.DefaultFormatting; }
set { _formatting = value; }
}
/// <summary>
/// Get or set how dates are written to JSON text.
/// </summary>
public virtual DateFormatHandling DateFormatHandling
{
get { return _dateFormatHandling ?? JsonSerializerSettings.DefaultDateFormatHandling; }
set { _dateFormatHandling = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling during serialization and deserialization.
/// </summary>
public virtual DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling ?? JsonSerializerSettings.DefaultDateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public virtual DateParseHandling DateParseHandling
{
get { return _dateParseHandling ?? JsonSerializerSettings.DefaultDateParseHandling; }
set { _dateParseHandling = value; }
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public virtual CultureInfo Culture
{
get { return _culture ?? JsonSerializerSettings.DefaultCulture; }
set { _culture = value; }
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public virtual int? MaxDepth
{
get { return _maxDepth; }
set
{
if (value <= 0)
throw new ArgumentException("Value must be positive.", "value");
_maxDepth = value;
_maxDepthSet = true;
}
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer"/> class.
/// </summary>
public JsonSerializer()
{
_referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling;
_missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling;
_nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling;
_defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling;
_objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling;
_preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling;
_constructorHandling = JsonSerializerSettings.DefaultConstructorHandling;
_typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling;
_context = JsonSerializerSettings.DefaultContext;
_binder = DefaultSerializationBinder.Instance;
}
/// <summary>
/// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param>
/// <returns>A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.</returns>
public static JsonSerializer Create(JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = new JsonSerializer();
if (settings != null)
{
if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
jsonSerializer.Converters.AddRange(settings.Converters);
// serializer specific
jsonSerializer.TypeNameHandling = settings.TypeNameHandling;
jsonSerializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat;
jsonSerializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
jsonSerializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
jsonSerializer.MissingMemberHandling = settings.MissingMemberHandling;
jsonSerializer.ObjectCreationHandling = settings.ObjectCreationHandling;
jsonSerializer.NullValueHandling = settings.NullValueHandling;
jsonSerializer.DefaultValueHandling = settings.DefaultValueHandling;
jsonSerializer.ConstructorHandling = settings.ConstructorHandling;
jsonSerializer.Context = settings.Context;
// reader/writer specific
// unset values won't override reader/writer set values
jsonSerializer._formatting = settings._formatting;
jsonSerializer._dateFormatHandling = settings._dateFormatHandling;
jsonSerializer._dateTimeZoneHandling = settings._dateTimeZoneHandling;
jsonSerializer._dateParseHandling = settings._dateParseHandling;
jsonSerializer._culture = settings._culture;
jsonSerializer._maxDepth = settings._maxDepth;
jsonSerializer._maxDepthSet = settings._maxDepthSet;
if (settings.Error != null)
jsonSerializer.Error += settings.Error;
if (settings.ContractResolver != null)
jsonSerializer.ContractResolver = settings.ContractResolver;
if (settings.ReferenceResolver != null)
jsonSerializer.ReferenceResolver = settings.ReferenceResolver;
if (settings.Binder != null)
jsonSerializer.Binder = settings.Binder;
}
return jsonSerializer;
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(TextReader reader, object target)
{
Populate(new JsonTextReader(reader), target);
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(JsonReader reader, object target)
{
PopulateInternal(reader, target);
}
internal virtual void PopulateInternal(JsonReader reader, object target)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
ValidationUtils.ArgumentNotNull(target, "target");
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
serializerReader.Populate(reader, target);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param>
/// <returns>The <see cref="Object"/> being deserialized.</returns>
public object Deserialize(JsonReader reader)
{
return Deserialize(reader, null);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="StringReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(TextReader reader, Type objectType)
{
return Deserialize(new JsonTextReader(reader), objectType);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns>
public T Deserialize<T>(JsonReader reader)
{
return (T)Deserialize(reader, typeof(T));
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(JsonReader reader, Type objectType)
{
return DeserializeInternal(reader, objectType);
}
internal virtual object DeserializeInternal(JsonReader reader, Type objectType)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
// set serialization options onto reader
CultureInfo previousCulture = null;
if (_culture != null && reader.Culture != _culture)
{
previousCulture = reader.Culture;
reader.Culture = _culture;
}
DateTimeZoneHandling? previousDateTimeZoneHandling = null;
if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling)
{
previousDateTimeZoneHandling = reader.DateTimeZoneHandling;
reader.DateTimeZoneHandling = _dateTimeZoneHandling.Value;
}
DateParseHandling? previousDateParseHandling = null;
if (_dateParseHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling)
{
previousDateParseHandling = reader.DateParseHandling;
reader.DateParseHandling = _dateParseHandling.Value;
}
int? previousMaxDepth = null;
if (_maxDepthSet && reader.MaxDepth != _maxDepth)
{
previousMaxDepth = reader.MaxDepth;
reader.MaxDepth = _maxDepth;
}
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
object value = serializerReader.Deserialize(reader, objectType);
// reset reader back to previous options
if (previousCulture != null)
reader.Culture = previousCulture;
if (previousDateTimeZoneHandling != null)
reader.DateTimeZoneHandling = previousDateTimeZoneHandling.Value;
if (previousDateParseHandling != null)
reader.DateParseHandling = previousDateParseHandling.Value;
if (_maxDepthSet)
reader.MaxDepth = previousMaxDepth;
return value;
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(TextWriter textWriter, object value)
{
Serialize(new JsonTextWriter(textWriter), value);
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>.
/// </summary>
/// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(JsonWriter jsonWriter, object value)
{
SerializeInternal(jsonWriter, value);
}
internal virtual void SerializeInternal(JsonWriter jsonWriter, object value)
{
ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter");
// set serialization options onto writer
Formatting? previousFormatting = null;
if (_formatting != null && jsonWriter.Formatting != _formatting)
{
previousFormatting = jsonWriter.Formatting;
jsonWriter.Formatting = _formatting.Value;
}
DateFormatHandling? previousDateFormatHandling = null;
if (_dateFormatHandling != null && jsonWriter.DateFormatHandling != _dateFormatHandling)
{
previousDateFormatHandling = jsonWriter.DateFormatHandling;
jsonWriter.DateFormatHandling = _dateFormatHandling.Value;
}
DateTimeZoneHandling? previousDateTimeZoneHandling = null;
if (_dateTimeZoneHandling != null && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling)
{
previousDateTimeZoneHandling = jsonWriter.DateTimeZoneHandling;
jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.Value;
}
JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this);
serializerWriter.Serialize(jsonWriter, value);
// reset writer back to previous options
if (previousFormatting != null)
jsonWriter.Formatting = previousFormatting.Value;
if (previousDateFormatHandling != null)
jsonWriter.DateFormatHandling = previousDateFormatHandling.Value;
if (previousDateTimeZoneHandling != null)
jsonWriter.DateTimeZoneHandling = previousDateTimeZoneHandling.Value;
}
internal JsonConverter GetMatchingConverter(Type type)
{
return GetMatchingConverter(_converters, type);
}
internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType)
{
#if DEBUG
ValidationUtils.ArgumentNotNull(objectType, "objectType");
#endif
if (converters != null)
{
for (int i = 0; i < converters.Count; i++)
{
JsonConverter converter = converters[i];
if (converter.CanConvert(objectType))
return converter;
}
}
return null;
}
internal void OnError(ErrorEventArgs e)
{
EventHandler<ErrorEventArgs> error = Error;
if (error != null)
error(this, e);
}
}
}
| |
/*
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 Adxstudio.Xrm.EntityList;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Adxstudio.Xrm.Web.UI.CrmEntityListView
{
/// <summary>
/// Settings for displaying a calendar.
/// </summary>
public class CalendarConfiguration
{
private string _initialDateString;
/// <summary>
/// Enumeration of the types of the calendar view that can be displayed.
/// </summary>
public enum CalendarView
{
/// <summary>
/// Display a full year view.
/// </summary>
Year = 756150000,
/// <summary>
/// Display a single month view.
/// </summary>
Month = 756150001,
/// <summary>
/// Display a single week view.
/// </summary>
Week = 756150002,
/// <summary>
/// Display a single day view.
/// </summary>
Day = 756150003
}
/// <summary>
/// Enumeration of the styles of the calendar.
/// </summary>
public enum CalendarStyle
{
/// <summary>
/// A full-sized calendar view will be rendered.
/// </summary>
Full = 756150000,
/// <summary>
/// Entities will be rendered as a list of events, with a supplementary calendar navigation element.
/// </summary>
List = 756150001,
}
/// <summary>
/// Enumeration of the time zone display modes.
/// </summary>
public enum TimeZoneDisplayMode
{
/// <summary>
/// User's local time
/// </summary>
UserLocalTimeZone = 756150000,
/// <summary>
/// Specific time zone.
/// </summary>
SpecificTimeZone = 756150001,
}
/// <summary>
/// Indicates whether the calendar is enabled or not.
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Indicates the start date/time of entity when rendered as an event. This field mapping is required for calendar view to function. Entities that do not have a value for this field will not be included in any calendar views.
/// </summary>
public string StartDateFieldName { get; set; }
/// <summary>
/// Indicates the end date/time of entity when rendered as an event.
/// </summary>
public string EndDateFieldName { get; set; }
/// <summary>
/// Field mapping for a short description/title of an event. This field mapping is required for calendar view to function. Entities that do not have a value for this field will not be included in any calendar views.
/// </summary>
public string SummaryFieldName { get; set; }
/// <summary>
/// Field mapping for a longer description of an event.
/// </summary>
public string DescriptionFieldName { get; set; }
/// <summary>
/// Field mapping for the organizer of an event. This can be a text field, or a lookup to a Contact record. By default, this field is only used by iCalendar exports.
/// </summary>
public string OrganizerFieldName { get; set; }
/// <summary>
/// Field mapping for the location of an event. By default, this field is only used by iCalendar exports.
/// </summary>
public string LocationFieldName { get; set; }
/// <summary>
/// Field mapping indicating whether an entity represents an "all day" event.
/// </summary>
public string IsAllDayFieldName { get; set; }
/// <summary>
/// The initial view to be shown when the user first loads the calendar. Default is "Month", but other options are "Day", "Year", and "Week".
/// </summary>
public CalendarView InitialView { get; set; }
/// <summary>
/// The string representing initial date on which the calendar view will be centered when the user first loads the page. This will be the current date by default when set to 'now'.
/// </summary>
public string InitialDateString
{
get { return string.IsNullOrWhiteSpace(_initialDateString) ? "now" : _initialDateString; }
set { _initialDateString = value; }
}
/// <summary>
/// Determines the style of user interface to be rendered. One of the following: Full calendar, Event list. Full calendar (default): A full-sized calendar view will be rendered. Event list: Entities will be rendered as a list of events, with a supplementary calendar navigation element.
/// </summary>
public CalendarStyle Style { get; set; }
/// <summary>
/// Determines the time zone display. One of the following: UserLocalTimeZone, SpecificTimeZone.
/// </summary>
public TimeZoneDisplayMode TimeZoneDisplay { get; set; }
/// <summary>
/// Standard name of a time zone. Used when TimeZoneDisplayMode is set to SpecificTimeZone.
/// </summary>
public string TimeZoneStandardName { get; set; }
/// <summary>
/// Constructor
/// </summary>
public CalendarConfiguration()
{
InitialView = CalendarView.Month;
Style = CalendarStyle.Full;
TimeZoneDisplay = TimeZoneDisplayMode.UserLocalTimeZone;
}
/// <summary>
/// Constructor used by The ViewConfiguration Class
/// </summary>
public CalendarConfiguration(OrganizationServiceContext serviceContext, bool calendarEnabled,
string calendarInitialDateString, OptionSetValue calendarInitialView,
OptionSetValue calendarStyle, OptionSetValue calendarTimeZoneDisplayMode,
int? calendarDisplayTimeZone, string calendarStartDateFieldName,
string calendarEndDateFieldName, string calendarSummaryFieldName,
string calendarDescriptionFieldName, string calendarOrganizerFieldName,
string calendarLocationFieldName, string calendarAllDayFieldName)
{
Enabled = calendarEnabled;
if (!string.IsNullOrWhiteSpace(calendarInitialDateString)) { InitialDateString = calendarInitialDateString; }
if (calendarInitialView != null)
{
if (Enum.IsDefined(typeof(CalendarView), calendarInitialView.Value))
{
InitialView = (CalendarView)calendarInitialView.Value;
}
else
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Calendar Initial View value '{0}' is not a valid value defined by CalendarConfiguration.CalendarView class.", calendarInitialView.Value));
}
}
if (calendarStyle != null)
{
if (Enum.IsDefined(typeof(CalendarStyle), calendarStyle.Value))
{
Style = (CalendarStyle)calendarStyle.Value;
}
else
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Calendar Style value '{0}' is not a valid value defined by CalendarConfiguration.CalendarStyle class.", calendarStyle.Value));
Style = CalendarStyle.Full;
}
}
if (calendarTimeZoneDisplayMode != null)
{
if (Enum.IsDefined(typeof(TimeZoneDisplayMode), calendarTimeZoneDisplayMode.Value))
{
TimeZoneDisplay = (TimeZoneDisplayMode)calendarTimeZoneDisplayMode.Value;
}
else
{
TimeZoneDisplay = TimeZoneDisplayMode.UserLocalTimeZone;
}
}
if (calendarDisplayTimeZone != null)
{
var calendarDisplayTimeZoneStandardName = EntityListFunctions.GetTimeZoneStandardName(serviceContext, calendarDisplayTimeZone.Value);
if (!string.IsNullOrWhiteSpace(calendarDisplayTimeZoneStandardName))
{
TimeZoneStandardName = calendarDisplayTimeZoneStandardName;
}
}
if (!string.IsNullOrWhiteSpace(calendarStartDateFieldName)) { StartDateFieldName = calendarStartDateFieldName; }
if (!string.IsNullOrWhiteSpace(calendarEndDateFieldName)) { EndDateFieldName = calendarEndDateFieldName; }
if (!string.IsNullOrWhiteSpace(calendarSummaryFieldName)) { SummaryFieldName = calendarSummaryFieldName; }
if (!string.IsNullOrWhiteSpace(calendarDescriptionFieldName)) { DescriptionFieldName = calendarDescriptionFieldName; }
if (!string.IsNullOrWhiteSpace(calendarOrganizerFieldName)) { OrganizerFieldName = calendarOrganizerFieldName; }
if (!string.IsNullOrWhiteSpace(calendarLocationFieldName)) { LocationFieldName = calendarLocationFieldName; }
if (!string.IsNullOrWhiteSpace(calendarAllDayFieldName)) { IsAllDayFieldName = calendarAllDayFieldName; }
}
}
}
| |
/* ====================================================================
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.XSSF.Model
{
using System.Collections.Generic;
using OpenXmlFormats.Spreadsheet;
using System;
using System.IO;
using NPOI.OpenXml4Net.OPC;
using System.Xml;
using System.Security;
using System.Text.RegularExpressions;
using System.Text;
/**
* Table of strings shared across all sheets in a workbook.
* <p>
* A workbook may contain thousands of cells Containing string (non-numeric) data. Furthermore this data is very
* likely to be repeated across many rows or columns. The goal of implementing a single string table that is shared
* across the workbook is to improve performance in opening and saving the file by only Reading and writing the
* repetitive information once.
* </p>
* <p>
* Consider for example a workbook summarizing information for cities within various countries. There may be a
* column for the name of the country, a column for the name of each city in that country, and a column
* Containing the data for each city. In this case the country name is repetitive, being duplicated in many cells.
* In many cases the repetition is extensive, and a tremendous savings is realized by making use of a shared string
* table when saving the workbook. When displaying text in the spreadsheet, the cell table will just contain an
* index into the string table as the value of a cell, instead of the full string.
* </p>
* <p>
* The shared string table Contains all the necessary information for displaying the string: the text, formatting
* properties, and phonetic properties (for East Asian languages).
* </p>
*
* @author Nick Birch
* @author Yegor Kozlov
*/
public class SharedStringsTable : POIXMLDocumentPart
{
/**
* Array of individual string items in the Shared String table.
*/
private List<CT_Rst> strings = new List<CT_Rst>();
/**
* Maps strings and their indexes in the <code>strings</code> arrays
*/
private Dictionary<String, int> stmap = new Dictionary<String, int>();
/**
* An integer representing the total count of strings in the workbook. This count does not
* include any numbers, it counts only the total of text strings in the workbook.
*/
private int count;
/**
* An integer representing the total count of unique strings in the Shared String Table.
* A string is unique even if it is a copy of another string, but has different formatting applied
* at the character level.
*/
private int uniqueCount;
private SstDocument _sstDoc;
public SharedStringsTable()
: base()
{
_sstDoc = new SstDocument();
_sstDoc.AddNewSst();
}
internal SharedStringsTable(PackagePart part, PackageRelationship rel)
: base(part, rel)
{
XmlDocument xml = ConvertStreamToXml(part.GetInputStream());
ReadFrom(xml);
}
public void ReadFrom(XmlDocument xml)
{
int cnt = 0;
_sstDoc = SstDocument.Parse(xml, NamespaceManager);
CT_Sst sst = _sstDoc.GetSst();
count = (int)sst.count;
uniqueCount = (int)sst.uniqueCount;
foreach (CT_Rst st in sst.si)
{
string key=GetKey(st);
if(key!=null && !stmap.ContainsKey(key))
stmap.Add(key, cnt);
strings.Add(st);
cnt++;
}
}
private String GetKey(CT_Rst st)
{
return st.XmlText;
}
/**
* Return a string item by index
*
* @param idx index of item to return.
* @return the item at the specified position in this Shared String table.
*/
public CT_Rst GetEntryAt(int idx)
{
return strings[idx];
}
/**
* Return an integer representing the total count of strings in the workbook. This count does not
* include any numbers, it counts only the total of text strings in the workbook.
*
* @return the total count of strings in the workbook
*/
public int Count
{
get
{
return count;
}
}
/**
* Returns an integer representing the total count of unique strings in the Shared String Table.
* A string is unique even if it is a copy of another string, but has different formatting applied
* at the character level.
*
* @return the total count of unique strings in the workbook
*/
public int UniqueCount
{
get
{
return uniqueCount;
}
}
/**
* Add an entry to this Shared String table (a new value is appened to the end).
*
* <p>
* If the Shared String table already Contains this <code>CT_Rst</code> bean, its index is returned.
* Otherwise a new entry is aded.
* </p>
*
* @param st the entry to add
* @return index the index of Added entry
*/
public int AddEntry(CT_Rst st)
{
String s = GetKey(st);
count++;
if (stmap.ContainsKey(s))
{
return stmap[s];
}
uniqueCount++;
//create a CT_Rst bean attached to this SstDocument and copy the argument CT_Rst into it
CT_Rst newSt = new CT_Rst();
_sstDoc.GetSst().si.Add(newSt);
newSt.Set(st);
int idx = strings.Count;
stmap[s] = idx;
strings.Add(newSt);
return idx;
}
/**
* Provide low-level access to the underlying array of CT_Rst beans
*
* @return array of CT_Rst beans
*/
public List<CT_Rst> Items
{
get
{
return strings;
}
}
/**
*
* this table out as XML.
*
* @param out The stream to write to.
* @throws IOException if an error occurs while writing.
*/
public void WriteTo(Stream out1)
{
// the following two lines turn off writing CDATA
// see Bugzilla 48936
//options.SetSaveCDataLengthThreshold(1000000);
//options.SetSaveCDataEntityCountThreshold(-1);
CT_Sst sst = _sstDoc.GetSst();
sst.count = count;
sst.uniqueCount = uniqueCount;
//re-create the sst table every time saving a workbook
_sstDoc.Save(out1);
}
protected override void Commit()
{
PackagePart part = GetPackagePart();
//Stream out1 = part.GetInputStream();
Stream out1 = part.GetOutputStream();
WriteTo(out1);
out1.Close();
}
}
}
| |
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using PlayFab.Json.Linq;
using PlayFab.Json.Utilities;
using System.Runtime.Serialization;
using System.Linq;
using UnityEngine;
namespace PlayFab.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private JsonContract _rootContract;
private readonly List<object> _serializeStack = new List<object>();
private JsonSerializerProxy _internalSerializer;
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
if (objectType != null)
_rootContract = Serializer._contractResolver.ResolveContract(objectType);
SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null);
}
private JsonSerializerProxy GetInternalSerializer()
{
if (_internalSerializer == null)
_internalSerializer = new JsonSerializerProxy(this);
return _internalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer._contractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.TypeCode == PrimitiveTypeCode.Bytes)
{
// if type name handling is enabled then wrap the base64 byte string in an object with the type name
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);
JsonWriter.WriteValue(writer, contract.TypeCode, value);
writer.WriteEndObject();
return;
}
}
JsonWriter.WriteValue(writer, contract.TypeCode, value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter;
if ((((converter = (member != null) ? member.Converter : null) != null)
|| ((converter = (containerProperty != null) ? containerProperty.ItemConverter : null) != null)
|| ((converter = (containerContract != null) ? containerContract.ItemConverter : null) != null)
|| ((converter = valueContract.Converter) != null)
|| ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null)
|| ((converter = valueContract.InternalConverter) != null))
&& converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract) valueContract;
if (!arrayContract.IsMultidimensionalArray)
SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
else
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract) valueContract;
SerializeDictionary(writer, (value is IDictionary) ? (IDictionary) value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
case JsonContractType.Dynamic:
SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Linq:
((JToken) value).WriteTo(writer, Serializer.Converters.ToArray());
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null && containerProperty != null)
isReference = containerProperty.ItemIsReference;
if (isReference == null && collectionContract != null)
isReference = collectionContract.ItemIsReference;
if (isReference == null)
isReference = contract.IsReference;
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
return false;
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
return false;
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.GetReferenceResolver().IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonProperty property)
{
if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return false;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
return false;
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
return true;
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
referenceLoopHandling = property.ReferenceLoopHandling;
if (referenceLoopHandling == null && containerProperty != null)
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
if (referenceLoopHandling == null && containerContract != null)
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
if (_serializeStack.IndexOf(value) != -1)
{
string message = "Self referencing loop detected";
if (property != null)
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
var selfRef = (value is Vector2 || value is Vector3 || value is Vector4 || value is Color || value is Color32)
? ReferenceLoopHandling.Ignore
: referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling);
switch (selfRef)
{
case ReferenceLoopHandling.Error:
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
return false;
case ReferenceLoopHandling.Serialize:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
return true;
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null);
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false);
writer.WriteValue(reference);
writer.WriteEndObject();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.GetReferenceResolver().GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
OnSerializing(writer, contract, value);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
}
private void OnSerializing(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerializing(value, Serializer._context);
}
private void OnSerialized(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerialized(value, Serializer._context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
if (contract.ExtensionDataGetter != null)
{
IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value);
if (extensionData != null)
{
foreach (KeyValuePair<object, object> e in extensionData)
{
JsonContract keyContract = GetContractSafe(e.Key);
JsonContract valueContract = GetContractSafe(e.Value);
bool escape;
string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape);
if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, e.Value);
}
else
{
if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, e.Value, valueContract, null, contract, member);
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
{
if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value))
{
if (property.PropertyContract == null)
property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
memberValue = property.ValueProvider.GetValue(value);
memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, property))
{
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
property.WritePropertyName(writer);
WriteReference(writer, memberValue);
return false;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
return false;
if (memberValue == null)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default;
if (resolvedRequired == Required.Always)
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
return true;
}
}
memberContract = null;
memberValue = null;
return false;
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null);
writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false);
writer.WriteValue(reference);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null);
writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false);
writer.WriteValue(typeName);
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
return;
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedCollection wrappedCollection = values as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
_serializeStack.Add(underlyingList);
bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingList);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, values);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, values);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = 0; i < values.GetLength(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth + 1);
else
throw;
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
}
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof (object));
return writeMetadataObject;
}
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
// only write non-dynamic properties that have an explicit attribute
if (property.HasMemberAttribute)
{
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
}
foreach (string memberName in value.GetDynamicMemberNames())
{
object memberValue;
if (contract.TryGetMember(value, memberName, out memberValue))
{
try
{
JsonContract valueContract = GetContractSafe(memberValue);
if (!ShouldWriteDynamicProperty(memberValue))
continue;
if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member))
{
string resolvedPropertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(memberName)
: memberName;
writer.WritePropertyName(resolvedPropertyName);
SerializeValue(writer, memberValue, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool ShouldWriteDynamicProperty(object memberValue)
{
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
return false;
if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) &&
(memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))))
return false;
return true;
}
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? Serializer._typeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
return true;
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.UnderlyingType != member.PropertyContract.CreatedType)
return true;
}
else if (containerContract != null)
{
if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
return true;
}
else if (_rootContract != null && _serializeStack.Count == 1)
{
if (contract.UnderlyingType != _rootContract.CreatedType)
return true;
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
if (contract.KeyContract == null)
contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
int initialDepth = writer.Top;
foreach (DictionaryEntry entry in values)
{
bool escape;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
propertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName, escape);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName, escape);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingDictionary);
}
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
string propertyName;
if (contract.ContractType == JsonContractType.Primitive)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(sw, (DateTime)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
else
{
escape = true;
return Convert.ToString(name, CultureInfo.InvariantCulture);
}
}
else if (TryConvertToString(name, name.GetType(), out propertyName))
{
escape = true;
return propertyName;
}
else
{
escape = true;
return name.ToString();
}
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
if (writer.WriteState == WriteState.Property)
writer.WriteNull();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
bool shouldSerialize = property.ShouldSerialize(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null);
return shouldSerialize;
}
private bool IsSpecified(JsonWriter writer, JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
bool isSpecified = property.GetIsSpecified(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null);
return isSpecified;
}
}
}
#endif
| |
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections.Generic;
namespace UMA.Editors
{
[CustomEditor(typeof(SlotLibrary))]
[CanEditMultipleObjects]
public class SlotLibraryEditor : Editor
{
private SerializedObject m_Object;
private SlotLibrary slotLibrary;
private SerializedProperty m_SlotDataAssetCount;
private const string kArraySizePath = "slotElementList.Array.size";
private const string kArrayData = "slotElementList.Array.data[{0}]";
private bool canUpdate;
private bool isDirty;
public void OnEnable()
{
m_Object = new SerializedObject(target);
slotLibrary = m_Object.targetObject as SlotLibrary;
m_SlotDataAssetCount = m_Object.FindProperty(kArraySizePath);
}
private SlotDataAsset[] GetSlotDataAssetArray()
{
int arrayCount = m_SlotDataAssetCount.intValue;
SlotDataAsset[] SlotDataAssetArray = new SlotDataAsset[arrayCount];
for (int i = 0; i < arrayCount; i++)
{
SlotDataAssetArray[i] = m_Object.FindProperty(string.Format(kArrayData, i)).objectReferenceValue as SlotDataAsset;
}
return SlotDataAssetArray;
}
private void SetSlotDataAsset(int index, SlotDataAsset slotElement)
{
m_Object.FindProperty(string.Format(kArrayData, index)).objectReferenceValue = slotElement;
isDirty = true;
}
private SlotDataAsset GetSlotDataAssetAtIndex(int index)
{
return m_Object.FindProperty(string.Format(kArrayData, index)).objectReferenceValue as SlotDataAsset;
}
private void AddSlotDataAsset(SlotDataAsset slotElement)
{
m_SlotDataAssetCount.intValue++;
SetSlotDataAsset(m_SlotDataAssetCount.intValue - 1, slotElement);
}
private void RemoveSlotDataAssetAtIndex(int index)
{
for (int i = index; i < m_SlotDataAssetCount.intValue - 1; i++)
{
SetSlotDataAsset(i, GetSlotDataAssetAtIndex(i + 1));
}
m_SlotDataAssetCount.intValue--;
}
private void DropAreaGUI(Rect dropArea)
{
var evt = Event.current;
if (evt.type == EventType.DragUpdated)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if (evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
for (int i = 0; i < draggedObjects.Length; i++)
{
if (draggedObjects[i])
{
SlotDataAsset tempSlotDataAsset = draggedObjects[i] as SlotDataAsset;
if (tempSlotDataAsset)
{
AddSlotDataAsset(tempSlotDataAsset);
continue;
}
var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForAssets(path);
}
}
}
}
}
}
private void RecursiveScanFoldersForAssets(string path)
{
var assetFiles = System.IO.Directory.GetFiles(path, "*.asset");
foreach (var assetFile in assetFiles)
{
var tempSlotDataAsset = AssetDatabase.LoadAssetAtPath(assetFile, typeof(SlotDataAsset)) as SlotDataAsset;
if (tempSlotDataAsset)
{
AddSlotDataAsset(tempSlotDataAsset);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForAssets(subFolder.Replace('\\', '/'));
}
}
public override void OnInspectorGUI()
{
m_Object.Update();
GUILayout.Label("slotElementList", EditorStyles.boldLabel);
SlotDataAsset[] slotElementList = GetSlotDataAssetArray();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Order by Name"))
{
canUpdate = false;
List<SlotDataAsset> SlotDataAssetTemp = slotElementList.ToList();
//Make sure there's no invalid data
for (int i = 0; i < SlotDataAssetTemp.Count; i++)
{
if (SlotDataAssetTemp[i] == null)
{
SlotDataAssetTemp.RemoveAt(i);
i--;
}
}
SlotDataAssetTemp.Sort((x, y) => x.name.CompareTo(y.name));
for (int i = 0; i < SlotDataAssetTemp.Count; i++)
{
SetSlotDataAsset(i, SlotDataAssetTemp[i]);
}
}
if (GUILayout.Button("Update List"))
{
isDirty = true;
canUpdate = false;
}
if (GUILayout.Button("Remove Duplicates"))
{
HashSet<SlotDataAsset> Slots = new HashSet<SlotDataAsset>();
foreach(SlotDataAsset osa in slotElementList)
{
Slots.Add(osa);
}
m_SlotDataAssetCount.intValue = Slots.Count;
for(int i=0;i<Slots.Count;i++)
{
SetSlotDataAsset(i,Slots.ElementAt(i));
}
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea, "Drag Slots here");
GUILayout.Space(20);
for (int i = 0; i < m_SlotDataAssetCount.intValue; i++)
{
GUILayout.BeginHorizontal();
SlotDataAsset result = EditorGUILayout.ObjectField(slotElementList[i], typeof(SlotDataAsset), true) as SlotDataAsset;
if (GUI.changed && canUpdate)
{
SetSlotDataAsset(i, result);
}
if (GUILayout.Button("-", GUILayout.Width(20.0f)))
{
canUpdate = false;
RemoveSlotDataAssetAtIndex(i);
}
GUILayout.EndHorizontal();
if (i == m_SlotDataAssetCount.intValue - 1)
{
canUpdate = true;
if (isDirty)
{
slotLibrary.UpdateDictionary();
isDirty = false;
}
}
}
DropAreaGUI(dropArea);
if (GUILayout.Button("Add SlotDataAsset"))
{
AddSlotDataAsset(null);
}
if (GUILayout.Button("Clear List"))
{
m_SlotDataAssetCount.intValue = 0;
}
if (GUILayout.Button("Remove Invalid Slot Data"))
{
RemoveInvalidSlotDataAsset(slotElementList);
}
m_Object.ApplyModifiedProperties();
}
private void RemoveInvalidSlotDataAsset(SlotDataAsset[] slotElementList)
{
for (int i = m_SlotDataAssetCount.intValue - 1; i >= 0; i--)
{
if (slotElementList[i] == null)
{
RemoveSlotDataAssetAtIndex(i);
}
}
}
}
}
| |
// 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.AcceptanceTestsBodyDateTimeRfc1123
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Datetimerfc1123.
/// </summary>
public static partial class Datetimerfc1123Extensions
{
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetNull(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetNullAsync(this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetInvalid(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetInvalidAsync(this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetOverflow(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetOverflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetOverflowAsync(this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOverflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetUnderflow(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUnderflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetUnderflowAsync(this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUnderflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutUtcMaxDateTime(this IDatetimerfc1123 operations, System.DateTime datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetimerfc1123)s).PutUtcMaxDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUtcMaxDateTimeAsync(this IDatetimerfc1123 operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUtcMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get max datetime value fri, 31 dec 9999 23:59:59 gmt
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetUtcLowercaseMaxDateTime(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcLowercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value fri, 31 dec 9999 23:59:59 gmt
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetUtcLowercaseMaxDateTimeAsync(this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetUtcUppercaseMaxDateTime(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcUppercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetUtcUppercaseMaxDateTimeAsync(this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutUtcMinDateTime(this IDatetimerfc1123 operations, System.DateTime datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetimerfc1123)s).PutUtcMinDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUtcMinDateTimeAsync(this IDatetimerfc1123 operations, System.DateTime datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUtcMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.DateTime? GetUtcMinDateTime(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcMinDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.DateTime?> GetUtcMinDateTimeAsync(this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUtcMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// ReSharper disable InconsistentNaming
using System;
using System.Threading;
using EasyNetQ.Loggers;
using NUnit.Framework;
namespace EasyNetQ.Tests.Integration
{
[TestFixture]
public class SchedulingTests
{
private IBus bus;
private ConsoleLogger logger;
[SetUp]
public void SetUp()
{
logger = new ConsoleLogger();
bus = RabbitHutch.CreateBus("host=localhost", x =>
x.Register<IEasyNetQLogger>(_ => logger));
}
[TearDown]
public void TearDown()
{
bus.Dispose();
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[Explicit("Needs an instance of RabbitMQ on localhost to work AND scheduler service running")]
public void Should_throw_exception_because_of_messageDelay()
{
var invitation = new PartyInvitation
{
Text = "Please come to my party",
Date = new DateTime(2011, 5, 24)
};
bus.FuturePublish(TimeSpan.FromMilliseconds(int.MaxValue), invitation);
}
[Test]
[Explicit("Needs an instance of RabbitMQ on localhost to work AND scheduler service running")]
public void Should_not_throw_exception_because_of_messageDelay()
{
var invitation = new PartyInvitation
{
Text = "Please come to my party",
Date = new DateTime(2011, 5, 24)
};
bus.FuturePublish(TimeSpan.FromMilliseconds(int.MaxValue - 1), invitation);
}
[Test]
[Explicit("Needs an instance of RabbitMQ on localhost to work")]
public void Should_be_able_to_schedule_a_message_2()
{
var autoResetEvent = new AutoResetEvent(false);
bus.Subscribe<PartyInvitation>("schedulingTest1", message =>
{
Console.WriteLine("Got scheduled message: {0}", message.Text);
autoResetEvent.Set();
});
var invitation = new PartyInvitation
{
Text = "Please come to my party",
Date = new DateTime(2011, 5, 24)
};
bus.FuturePublish(TimeSpan.FromSeconds(3), invitation);
if(! autoResetEvent.WaitOne(100000))
Assert.Fail();
}
[Test]
[Explicit("Needs an instance of RabbitMQ on localhost to work")]
public void High_volume_scheduling_test_2()
{
logger.Debug = false;
bus.Subscribe<PartyInvitation>("schedulingTest1", message =>
Console.WriteLine("Got scheduled message: {0}", message.Text));
var count = 0;
while (true)
{
var invitation = new PartyInvitation
{
Text = string.Format("Invitation {0}", count++),
Date = new DateTime(2011, 5, 24)
};
bus.FuturePublish(TimeSpan.FromSeconds(3), invitation);
Thread.Sleep(1);
}
}
/// <summary>
/// Tests the EasyNetQ.Scheduler.
/// 1. First run EasyNetQ.Scheduler.exe
/// 2. Run this test. You should see the test reporting that it's published a ScheduleMe message
/// and then the Scheduler reporting 'Got Schedule Message'. 3 seconds later you should see the
/// scheduler publish a PartyInvitation message and the test should report
/// 'Got scheduled message: Please come to my party'
/// </summary>
[Test]
[Explicit("Needs an instance of RabbitMQ on localhost to work AND scheduler service running")]
public void Should_be_able_to_schedule_a_message()
{
var autoResetEvent = new AutoResetEvent(false);
bus.Subscribe<PartyInvitation>("schedulingTest1", message =>
{
Console.WriteLine("Got scheduled message: {0}", message.Text);
autoResetEvent.Set();
});
var invitation = new PartyInvitation
{
Text = "Please come to my party",
Date = new DateTime(2011, 5, 24)
};
bus.FuturePublish(DateTime.UtcNow.AddSeconds(3), invitation);
autoResetEvent.WaitOne(10000);
}
/// <summary>
/// Based on Should_be_able_to_schedule_a_message(), but publishes 3 messages.
/// The second message has a different cancellation key than the others. The other messages are cancelled,
/// so the second message is the only one that should arrive.
/// </summary>
[Test]
[Explicit("Needs an instance of RabbitMQ on localhost to work AND scheduler service running")]
public void Should_be_able_to_cancel_a_message()
{
var messagesReceived = 0;
bus.Subscribe<PartyInvitation>("schedulingTest1", message =>
{
Console.WriteLine("Got scheduled message: {0}", message.Text);
messagesReceived++;
});
var invitation = new PartyInvitation
{
Text = "Please come to my party",
Date = new DateTime(2011, 5, 24)
};
bus.FuturePublish(DateTime.UtcNow.AddSeconds(3), "my_cancellation_key", invitation);
bus.FuturePublish(DateTime.UtcNow.AddSeconds(3), invitation);
bus.FuturePublish(DateTime.UtcNow.AddSeconds(3), "my_cancellation_key", invitation);
bus.CancelFuturePublish("my_cancellation_key");
Thread.Sleep(10000);
Assert.AreEqual(1, messagesReceived);
}
/// <summary>
/// Schedule thousands of messages
/// 1. First run EasyNetQ.Scheduler.exe
/// 2. Run this test.
/// </summary>
[Test]
[Explicit("Needs an instance of RabbitMQ on localhost to work AND scheduler service running")]
public void High_volume_scheduling_test()
{
logger.Debug = false;
bus.Subscribe<PartyInvitation>("schedulingTest1", message =>
Console.WriteLine("Got scheduled message: {0}", message.Text));
var count = 0;
while (true)
{
var invitation = new PartyInvitation
{
Text = string.Format("Invitation {0}", count++),
Date = new DateTime(2011, 5, 24)
};
bus.FuturePublish(DateTime.UtcNow.AddSeconds(3), invitation);
Thread.Sleep(1);
}
}
}
[Serializable]
public class PartyInvitation
{
public string Text { get; set; }
public DateTime Date { get; set; }
}
}
// ReSharper restore InconsistentNaming
| |
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace ClickHouse.Ado.Impl.ATG.IdentList {
internal class Token {
public int kind; // token kind
public int pos; // token position in bytes in the source text (starting at 0)
public int charPos; // token position in characters in the source text (starting at 0)
public int col; // token column (starting at 1)
public int line; // token line (starting at 1)
public string val; // token value
public Token next; // ML 2005-03-11 Tokens are kept in linked list
}
//-----------------------------------------------------------------------------------
// Buffer
//-----------------------------------------------------------------------------------
internal class Buffer {
// This Buffer supports the following cases:
// 1) seekable stream (file)
// a) whole stream in buffer
// b) part of stream in buffer
// 2) non seekable stream (network, console)
public const int EOF = char.MaxValue + 1;
const int MIN_BUFFER_LENGTH = 1024; // 1KB
const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB
byte[] buf; // input buffer
int bufStart; // position of first byte in buffer relative to input stream
int bufLen; // length of buffer
int fileLen; // length of input stream (may change if the stream is no file)
int bufPos; // current position in buffer
Stream stream; // input stream (seekable)
bool isUserStream; // was the stream opened by the user?
public Buffer (Stream s, bool isUserStream) {
stream = s; this.isUserStream = isUserStream;
if (stream.CanSeek) {
fileLen = (int) stream.Length;
bufLen = Math.Min(fileLen, MAX_BUFFER_LENGTH);
bufStart = Int32.MaxValue; // nothing in the buffer so far
} else {
fileLen = bufLen = bufStart = 0;
}
buf = new byte[(bufLen>0) ? bufLen : MIN_BUFFER_LENGTH];
if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start)
else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid
if (bufLen == fileLen && stream.CanSeek) Close();
}
protected Buffer(Buffer b) { // called in UTF8Buffer constructor
buf = b.buf;
bufStart = b.bufStart;
bufLen = b.bufLen;
fileLen = b.fileLen;
bufPos = b.bufPos;
stream = b.stream;
// keep destructor from closing the stream
b.stream = null;
isUserStream = b.isUserStream;
}
~Buffer() { Close(); }
protected void Close() {
if (!isUserStream && stream != null) {
#if NETSTANDARD15 || NETCOREAPP11
stream.Dispose();
#else
stream.Close();
#endif
stream = null;
}
}
public virtual int Read () {
if (bufPos < bufLen) {
return buf[bufPos++];
} else if (Pos < fileLen) {
Pos = Pos; // shift buffer start to Pos
return buf[bufPos++];
} else if (stream != null && !stream.CanSeek && ReadNextStreamChunk() > 0) {
return buf[bufPos++];
} else {
return EOF;
}
}
public int Peek () {
int curPos = Pos;
int ch = Read();
Pos = curPos;
return ch;
}
// beg .. begin, zero-based, inclusive, in byte
// end .. end, zero-based, exclusive, in byte
public string GetString (int beg, int end) {
int len = 0;
char[] buf = new char[end - beg];
int oldPos = Pos;
Pos = beg;
while (Pos < end) buf[len++] = (char) Read();
Pos = oldPos;
return new String(buf, 0, len);
}
public int Pos {
get { return bufPos + bufStart; }
set {
if (value >= fileLen && stream != null && !stream.CanSeek) {
// Wanted position is after buffer and the stream
// is not seek-able e.g. network or console,
// thus we have to read the stream manually till
// the wanted position is in sight.
while (value >= fileLen && ReadNextStreamChunk() > 0);
}
if (value < 0 || value > fileLen) {
throw new FatalError("buffer out of bounds access, position: " + value);
}
if (value >= bufStart && value < bufStart + bufLen) { // already in buffer
bufPos = value - bufStart;
} else if (stream != null) { // must be swapped in
stream.Seek(value, SeekOrigin.Begin);
bufLen = stream.Read(buf, 0, buf.Length);
bufStart = value; bufPos = 0;
} else {
// set the position to the end of the file, Pos will return fileLen.
bufPos = fileLen - bufStart;
}
}
}
// Read the next chunk of bytes from the stream, increases the buffer
// if needed and updates the fields fileLen and bufLen.
// Returns the number of bytes read.
private int ReadNextStreamChunk() {
int free = buf.Length - bufLen;
if (free == 0) {
// in the case of a growing input stream
// we can neither seek in the stream, nor can we
// foresee the maximum length, thus we must adapt
// the buffer size on demand.
byte[] newBuf = new byte[bufLen * 2];
Array.Copy(buf, newBuf, bufLen);
buf = newBuf;
free = bufLen;
}
int read = stream.Read(buf, bufLen, free);
if (read > 0) {
fileLen = bufLen = (bufLen + read);
return read;
}
// end of stream reached
return 0;
}
}
//-----------------------------------------------------------------------------------
// UTF8Buffer
//-----------------------------------------------------------------------------------
internal class UTF8Buffer: Buffer {
public UTF8Buffer(Buffer b): base(b) {}
public override int Read() {
int ch;
do {
ch = base.Read();
// until we find a utf8 start (0xxxxxxx or 11xxxxxx)
} while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EOF));
if (ch < 128 || ch == EOF) {
// nothing to do, first 127 chars are the same in ascii and utf8
// 0xxxxxxx or end of file character
} else if ((ch & 0xF0) == 0xF0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x07; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F; ch = base.Read();
int c4 = ch & 0x3F;
ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4;
} else if ((ch & 0xE0) == 0xE0) {
// 1110xxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x0F; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F;
ch = (((c1 << 6) | c2) << 6) | c3;
} else if ((ch & 0xC0) == 0xC0) {
// 110xxxxx 10xxxxxx
int c1 = ch & 0x1F; ch = base.Read();
int c2 = ch & 0x3F;
ch = (c1 << 6) | c2;
}
return ch;
}
}
//-----------------------------------------------------------------------------------
// Scanner
//-----------------------------------------------------------------------------------
internal class Scanner {
const char EOL = '\n';
const int eofSym = 0; /* pdt */
const int maxT = 3;
const int noSym = 3;
char valCh; // current input character (for token.val)
public Buffer buffer; // scanner buffer
Token t; // current token
int ch; // current input character
int pos; // byte position of current character
int charPos; // position by unicode characters starting with 0
int col; // column number of current character
int line; // line number of current character
int oldEols; // EOLs that appeared in a comment;
static readonly Dictionary<int,int> start; // maps first token character to start state
Token tokens; // list of tokens already peeked (first token is a dummy)
Token pt; // current peek token
char[] tval = new char[128]; // text of current token
int tlen; // length of current token
static Scanner() {
start = new Dictionary<int,int>(128);
for (int i = 97; i <= 122; ++i) start[i] = 1;
start[44] = 2;
start[Buffer.EOF] = -1;
}
public Scanner (string fileName) {
try {
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new Buffer(stream, false);
Init();
} catch (IOException) {
throw new FatalError("Cannot open file " + fileName);
}
}
public Scanner (Stream s) {
buffer = new Buffer(s, true);
Init();
}
void Init() {
pos = -1; line = 1; col = 0; charPos = -1;
oldEols = 0;
NextCh();
if (ch == 0xEF) { // check optional byte order mark for UTF-8
NextCh(); int ch1 = ch;
NextCh(); int ch2 = ch;
if (ch1 != 0xBB || ch2 != 0xBF) {
throw new FatalError(String.Format("illegal byte order mark: EF {0,2:X} {1,2:X}", ch1, ch2));
}
buffer = new UTF8Buffer(buffer); col = 0; charPos = -1;
NextCh();
}
pt = tokens = new Token(); // first token is a dummy
}
void NextCh() {
if (oldEols > 0) { ch = EOL; oldEols--; }
else {
pos = buffer.Pos;
// buffer reads unicode chars, if UTF8 has been detected
ch = buffer.Read(); col++; charPos++;
// replace isolated '\r' by '\n' in order to make
// eol handling uniform across Windows, Unix and Mac
if (ch == '\r' && buffer.Peek() != '\n') ch = EOL;
if (ch == EOL) { line++; col = 0; }
}
if (ch != Buffer.EOF) {
valCh = (char) ch;
ch = char.ToLower((char) ch);
}
}
void AddCh() {
if (tlen >= tval.Length) {
char[] newBuf = new char[2 * tval.Length];
Array.Copy(tval, 0, newBuf, 0, tval.Length);
tval = newBuf;
}
if (ch != Buffer.EOF) {
tval[tlen++] = valCh;
NextCh();
}
}
void CheckLiteral() {
switch (t.val.ToLower()) {
default: break;
}
}
Token NextToken() {
while (ch == ' ' ||
ch >= 9 && ch <= 10 || ch == 13
) NextCh();
int recKind = noSym;
int recEnd = pos;
t = new Token();
t.pos = pos; t.col = col; t.line = line; t.charPos = charPos;
int state;
if (start.ContainsKey(ch)) { state = (int) start[ch]; }
else { state = 0; }
tlen = 0; AddCh();
switch (state) {
case -1: { t.kind = eofSym; break; } // NextCh already done
case 0: {
if (recKind != noSym) {
tlen = recEnd - t.pos;
SetScannerBehindT();
}
t.kind = recKind; break;
} // NextCh already done
case 1:
recEnd = pos; recKind = 1;
if (ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 1;}
else {t.kind = 1; break;}
case 2:
{t.kind = 2; break;}
}
t.val = new String(tval, 0, tlen);
return t;
}
private void SetScannerBehindT() {
buffer.Pos = t.pos;
NextCh();
line = t.line; col = t.col; charPos = t.charPos;
for (int i = 0; i < tlen; i++) NextCh();
}
// get the next token (possibly a token already seen during peeking)
public Token Scan () {
if (tokens.next == null) {
return NextToken();
} else {
pt = tokens = tokens.next;
return tokens;
}
}
// peek for the next token, ignore pragmas
public Token Peek () {
do {
if (pt.next == null) {
pt.next = NextToken();
}
pt = pt.next;
} while (pt.kind > maxT); // skip pragmas
return pt;
}
// make sure that peeking starts at the current scan position
public void ResetPeek () { pt = tokens; }
} // end Scanner
}
| |
//
// Created by Shopify.
// Copyright (c) 2016 Shopify Inc. All rights reserved.
// Copyright (c) 2016 Xamarin Inc. All rights reserved.
//
// 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 CoreGraphics;
using Foundation;
using UIKit;
using Shopify.Buy;
namespace ShopifyiOSSample
{
public class ProductListViewController : UITableViewController, IUIViewControllerPreviewingDelegate
{
private readonly BuyClient client;
private readonly Collection collection;
private Product[] products;
private NSUrlSessionDataTask collectionTask;
private NSUrlSessionDataTask checkoutCreationTask;
private bool demoProductViewController;
private ThemeStyle themeStyle;
private UIColor[] themeTintColors;
private nint themeTintColorSelectedIndex;
private bool showsProductImageBackground;
private bool presentViewController;
private static Address Address {
get {
var address = new Address ();
address.Address1 = "150 Elgin Street";
address.Address2 = "8th Floor";
address.City = "Ottawa";
address.Company = "Shopify Inc.";
address.FirstName = "Egon";
address.LastName = "Spengler";
address.Phone = "1-555-555-5555";
address.CountryCode = "CA";
address.ProvinceCode = "ON";
address.Zip = "K1N5T5";
return address;
}
}
public ProductListViewController (BuyClient client, Collection collection)
: base (UITableViewStyle.Grouped)
{
this.client = client;
this.collection = collection;
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
if (checkoutCreationTask != null) {
checkoutCreationTask.Cancel ();
}
if (collectionTask != null) {
collectionTask.Cancel ();
}
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
if (collection != null) {
Title = collection.Title;
} else {
Title = "All Products";
}
TableView.RegisterClassForCellReuse (typeof(UITableViewCell), "Cell");
TableView.RegisterClassForCellReuse (typeof(ProductViewControllerToggleTableViewCell), "ProductViewControllerToggleCell");
TableView.RegisterClassForCellReuse (typeof(ProductViewControllerThemeStyleTableViewCell), "ThemeStyleCell");
TableView.RegisterClassForCellReuse (typeof(ProductViewControllerThemeTintColorTableViewCell), "ThemeTintColorCell");
TableView.RegisterClassForCellReuse (typeof(ProductViewControllerToggleTableViewCell), "ThemeShowsBackgroundToggleCell");
TableView.RegisterClassForCellReuse (typeof(ProductViewControllerToggleTableViewCell), "ProductViewControllerPresentViewControllerToggleCell");
themeTintColors = new [] {
UIColor.FromRGBA (0.48f, 0.71f, 0.36f, 1.0f),
UIColor.FromRGBA (0.88f, 0.06f, 0.05f, 1.0f),
UIColor.FromRGBA (0.02f, 0.54f, 1.0f, 1.0f)
};
themeTintColorSelectedIndex = 0;
showsProductImageBackground = true;
presentViewController = true;
if (collection != null) {
// If we're presenting with a collection, add the ability to sort
UIBarButtonItem sortBarButtonItem = new UIBarButtonItem ("Sort", UIBarButtonItemStyle.Plain, PresentCollectionSortOptions);
NavigationItem.RightBarButtonItem = sortBarButtonItem;
GetCollection (CollectionSort.Default);
} else {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
client.GetProductsPage (1, (products, page, reachedEnd, error) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
if (error == null && products != null) {
this.products = products;
TableView.ReloadData ();
} else {
Console.WriteLine ("Error fetching products: {0}", error);
}
});
}
}
private void PresentCollectionSortOptions (object sender, EventArgs e)
{
UIAlertController alertController = UIAlertController.Create ("Collection Sort", null, UIAlertControllerStyle.ActionSheet);
alertController.AddAction (UIAlertAction.Create ("Default", UIAlertActionStyle.Default, delegate {
GetCollection (CollectionSort.Default);
}));
alertController.AddAction (UIAlertAction.Create ("Best Selling", UIAlertActionStyle.Default, delegate {
GetCollection (CollectionSort.BestSelling);
}));
alertController.AddAction (UIAlertAction.Create ("Title - Ascending", UIAlertActionStyle.Default, delegate {
GetCollection (CollectionSort.TitleAscending);
}));
alertController.AddAction (UIAlertAction.Create ("Title - Descending", UIAlertActionStyle.Default, delegate {
GetCollection (CollectionSort.TitleDescending);
}));
alertController.AddAction (UIAlertAction.Create ("Price - Ascending", UIAlertActionStyle.Default, delegate {
GetCollection (CollectionSort.PriceAscending);
}));
alertController.AddAction (UIAlertAction.Create ("Price - Descending", UIAlertActionStyle.Default, delegate {
GetCollection (CollectionSort.PriceDescending);
}));
// Note: The BUYCollectionSort.CreatedAscending and BUYCollectionSort.CreatedDescending are currently not supported
if (TraitCollection.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) {
UIPopoverPresentationController popPresenter = alertController.PopoverPresentationController;
popPresenter.BarButtonItem = (UIBarButtonItem)sender;
}
alertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, null));
PresentViewController (alertController, true, null);
}
private void GetCollection (CollectionSort collectionSort)
{
if (collectionTask != null) {
collectionTask.Cancel ();
}
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
collectionTask = client.GetProductsPage (1, collection.CollectionId, collectionSort, (products, page, reachedEnd, error) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
if (error == null && products != null) {
this.products = products;
TableView.ReloadData ();
} else {
Console.WriteLine ("Error fetching products: {0}", error);
}
});
}
public override nint NumberOfSections (UITableView tableView)
{
return 2;
}
public override nint RowsInSection (UITableView tableView, nint section)
{
switch (section) {
case 0:
return demoProductViewController ? 5 : 1;
case 1:
return products == null ? 0 : products.Length;
default:
return 0;
}
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = null;
switch (indexPath.Section) {
case 0:
switch (indexPath.Row) {
case 0:
{
var toggleCell = (ProductViewControllerToggleTableViewCell)tableView.DequeueReusableCell ("ProductViewControllerToggleCell", indexPath);
toggleCell.ToggleSwitch.ValueChanged -= ToggleProductViewControllerDemo;
toggleCell.TextLabel.Text = "Demo BUYProductViewController";
toggleCell.ToggleSwitch.On = demoProductViewController;
toggleCell.ToggleSwitch.ValueChanged += ToggleProductViewControllerDemo;
cell = toggleCell;
}
break;
case 1:
{
var themeCell = (ProductViewControllerThemeStyleTableViewCell)TableView.DequeueReusableCell ("ThemeStyleCell", indexPath);
themeCell.SegmentedControl.ValueChanged -= ToggleProductViewControllerThemeStyle;
themeCell.SegmentedControl.SelectedSegment = (int)themeStyle;
themeCell.SegmentedControl.ValueChanged += ToggleProductViewControllerThemeStyle;
cell = themeCell;
}
break;
case 2:
{
var themeCell = (ProductViewControllerThemeTintColorTableViewCell)TableView.DequeueReusableCell ("ThemeTintColorCell", indexPath);
themeCell.SegmentedControl.ValueChanged -= ToggleProductViewControllerTintColorSelection;
themeCell.SegmentedControl.SelectedSegment = themeTintColorSelectedIndex;
themeCell.SegmentedControl.ValueChanged += ToggleProductViewControllerTintColorSelection;
cell = themeCell;
}
break;
case 3:
{
var toggleCell = (ProductViewControllerToggleTableViewCell)TableView.DequeueReusableCell ("ThemeShowsBackgroundToggleCell", indexPath);
toggleCell.ToggleSwitch.ValueChanged -= ToggleShowsProductImageBackground;
toggleCell.TextLabel.Text = "Product Image in Background";
toggleCell.ToggleSwitch.On = showsProductImageBackground;
toggleCell.ToggleSwitch.ValueChanged += ToggleShowsProductImageBackground;
cell = toggleCell;
}
break;
case 4:
{
var toggleCell = (ProductViewControllerToggleTableViewCell)TableView.DequeueReusableCell ("ProductViewControllerPresentViewControllerToggleCell", indexPath);
toggleCell.ToggleSwitch.ValueChanged -= TogglePresentViewController;
toggleCell.TextLabel.Text = "Modal Presentation";
toggleCell.ToggleSwitch.On = presentViewController;
toggleCell.ToggleSwitch.ValueChanged -= TogglePresentViewController;
cell = toggleCell;
}
break;
}
break;
case 1:
{
cell = TableView.DequeueReusableCell ("Cell", indexPath);
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
var product = products [indexPath.LongRow];
cell.TextLabel.Text = product.Title;
}
break;
}
return cell;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
if (indexPath.Section > 0) {
var product = products [indexPath.Row];
if (demoProductViewController) {
TableView.DeselectRow (indexPath, true);
DemoProductViewControllerWithProduct (product);
} else {
DemoNativeFlowWithProduct (product);
}
}
}
private void DemoNativeFlowWithProduct (Product product)
{
if (checkoutCreationTask != null && checkoutCreationTask.State == NSUrlSessionTaskState.Running) {
checkoutCreationTask.Cancel ();
}
var cart = new Cart ();
cart.AddVariant (product.Variants [0]);
var checkout = new Checkout (cart);
// Apply billing and shipping address, as well as email to the checkout
checkout.ShippingAddress = Address;
checkout.BillingAddress = Address;
checkout.Email = "[email protected]";
client.UrlScheme = "xamarinsample://";
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
checkoutCreationTask = client.CreateCheckout (checkout, (chkout, error) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
if (error == null && chkout != null) {
var shippingController = new ShippingRatesTableViewController (client, chkout);
NavigationController.PushViewController (shippingController, true);
} else {
Console.WriteLine ("Error creating checkout: {0}", error);
}
});
}
private void DemoProductViewControllerWithProduct (Product product)
{
var productViewController = GetProductViewController ();
productViewController.LoadProduct (product, (success, error) => {
if (error == null) {
if (presentViewController) {
productViewController.PresentPortraitInViewController (this);
} else {
NavigationController.PushViewController (productViewController, true);
}
}
});
}
private ProductViewController GetProductViewController ()
{
var theme = new Theme ();
theme.Style = themeStyle;
theme.TintColor = themeTintColors [themeTintColorSelectedIndex];
theme.ShowsProductImageBackground = showsProductImageBackground;
var productViewController = new ProductViewController (client, theme);
productViewController.MerchantId = AppDelegate.MERCHANT_ID;
return productViewController;
}
private void ToggleProductViewControllerDemo (object sender, EventArgs e)
{
demoProductViewController = ((UISwitch)sender).On;
TableView.ReloadSections (NSIndexSet.FromIndex (0), UITableViewRowAnimation.Automatic);
// // Add 3D Touch peek and pop for product previewing
// if (demoProductViewController == true && [[UITraitCollection class] respondsToSelector:@selector(traitCollectionWithForceTouchCapability:)] && self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
// [self registerForPreviewingWithDelegate:self sourceView:self.tableView];
// } else if ([[UITraitCollection class] respondsToSelector:@selector(traitCollectionWithForceTouchCapability:)] && self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
// [self registerForPreviewingWithDelegate:self sourceView:self.tableView];
// }
}
private void ToggleProductViewControllerThemeStyle (object sender, EventArgs e)
{
themeStyle = (ThemeStyle)(int)((UISegmentedControl)sender).SelectedSegment;
}
private void ToggleProductViewControllerTintColorSelection (object sender, EventArgs e)
{
themeTintColorSelectedIndex = ((UISegmentedControl)sender).SelectedSegment;
}
private void ToggleShowsProductImageBackground (object sender, EventArgs e)
{
showsProductImageBackground = ((UISwitch)sender).On;
}
private void TogglePresentViewController (object sender, EventArgs e)
{
presentViewController = ((UISwitch)sender).On;
}
public UIViewController GetViewControllerForPreview (IUIViewControllerPreviewing previewingContext, CGPoint location)
{
var indexPath = TableView.IndexPathForRowAtPoint (location);
var cell = TableView.CellAt (indexPath);
if (cell == null || demoProductViewController == false) {
return null;
}
var product = products [indexPath.Row];
var productViewController = GetProductViewController ();
productViewController.LoadProduct (product, null);
previewingContext.SourceRect = cell.Frame;
return productViewController;
}
public void CommitViewController (IUIViewControllerPreviewing previewingContext, UIViewController viewControllerToCommit)
{
if (presentViewController) {
PresentViewController (viewControllerToCommit, true, null);
} else {
NavigationController.PushViewController (viewControllerToCommit, true);
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Provides access to all native methods provided by <c>NativeExtension</c>.
/// An extra level of indirection is added to P/Invoke calls to allow intelligent loading
/// of the right configuration of the native extension based on current platform, architecture etc.
/// </summary>
internal class NativeMethods
{
#region Native methods
public readonly Delegates.grpcsharp_init_delegate grpcsharp_init;
public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown;
public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string;
public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create;
public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length;
public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled;
public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy;
public readonly Delegates.grpcsharp_request_call_context_create_delegate grpcsharp_request_call_context_create;
public readonly Delegates.grpcsharp_request_call_context_call_delegate grpcsharp_request_call_context_call;
public readonly Delegates.grpcsharp_request_call_context_method_delegate grpcsharp_request_call_context_method;
public readonly Delegates.grpcsharp_request_call_context_host_delegate grpcsharp_request_call_context_host;
public readonly Delegates.grpcsharp_request_call_context_deadline_delegate grpcsharp_request_call_context_deadline;
public readonly Delegates.grpcsharp_request_call_context_request_metadata_delegate grpcsharp_request_call_context_request_metadata;
public readonly Delegates.grpcsharp_request_call_context_destroy_delegate grpcsharp_request_call_context_destroy;
public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create;
public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release;
public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel;
public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status;
public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary;
public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming;
public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming;
public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming;
public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message;
public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client;
public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server;
public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message;
public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata;
public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside;
public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata;
public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials;
public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer;
public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy;
public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create;
public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string;
public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer;
public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy;
public readonly Delegates.grpcsharp_override_default_ssl_roots grpcsharp_override_default_ssl_roots;
public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create;
public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create;
public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release;
public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create;
public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create;
public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call;
public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state;
public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state;
public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target;
public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy;
public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event;
public readonly Delegates.grpcsharp_completion_queue_create_delegate grpcsharp_completion_queue_create;
public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown;
public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next;
public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck;
public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy;
public readonly Delegates.gprsharp_free_delegate gprsharp_free;
public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create;
public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add;
public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count;
public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key;
public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value;
public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full;
public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log;
public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin;
public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin;
public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create;
public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release;
public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create;
public readonly Delegates.grpcsharp_server_register_completion_queue_delegate grpcsharp_server_register_completion_queue;
public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port;
public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port;
public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start;
public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call;
public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls;
public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback;
public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy;
public readonly Delegates.grpcsharp_call_auth_context_delegate grpcsharp_call_auth_context;
public readonly Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate grpcsharp_auth_context_peer_identity_property_name;
public readonly Delegates.grpcsharp_auth_context_property_iterator_delegate grpcsharp_auth_context_property_iterator;
public readonly Delegates.grpcsharp_auth_property_iterator_next_delegate grpcsharp_auth_property_iterator_next;
public readonly Delegates.grpcsharp_auth_context_release_delegate grpcsharp_auth_context_release;
public readonly Delegates.gprsharp_now_delegate gprsharp_now;
public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future;
public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past;
public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type;
public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec;
public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback;
public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop;
#endregion
public NativeMethods(UnmanagedLibrary library)
{
this.grpcsharp_init = GetMethodDelegate<Delegates.grpcsharp_init_delegate>(library);
this.grpcsharp_shutdown = GetMethodDelegate<Delegates.grpcsharp_shutdown_delegate>(library);
this.grpcsharp_version_string = GetMethodDelegate<Delegates.grpcsharp_version_string_delegate>(library);
this.grpcsharp_batch_context_create = GetMethodDelegate<Delegates.grpcsharp_batch_context_create_delegate>(library);
this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_length_delegate>(library);
this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate>(library);
this.grpcsharp_batch_context_destroy = GetMethodDelegate<Delegates.grpcsharp_batch_context_destroy_delegate>(library);
this.grpcsharp_request_call_context_create = GetMethodDelegate<Delegates.grpcsharp_request_call_context_create_delegate>(library);
this.grpcsharp_request_call_context_call = GetMethodDelegate<Delegates.grpcsharp_request_call_context_call_delegate>(library);
this.grpcsharp_request_call_context_method = GetMethodDelegate<Delegates.grpcsharp_request_call_context_method_delegate>(library);
this.grpcsharp_request_call_context_host = GetMethodDelegate<Delegates.grpcsharp_request_call_context_host_delegate>(library);
this.grpcsharp_request_call_context_deadline = GetMethodDelegate<Delegates.grpcsharp_request_call_context_deadline_delegate>(library);
this.grpcsharp_request_call_context_request_metadata = GetMethodDelegate<Delegates.grpcsharp_request_call_context_request_metadata_delegate>(library);
this.grpcsharp_request_call_context_destroy = GetMethodDelegate<Delegates.grpcsharp_request_call_context_destroy_delegate>(library);
this.grpcsharp_composite_call_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_call_credentials_create_delegate>(library);
this.grpcsharp_call_credentials_release = GetMethodDelegate<Delegates.grpcsharp_call_credentials_release_delegate>(library);
this.grpcsharp_call_cancel = GetMethodDelegate<Delegates.grpcsharp_call_cancel_delegate>(library);
this.grpcsharp_call_cancel_with_status = GetMethodDelegate<Delegates.grpcsharp_call_cancel_with_status_delegate>(library);
this.grpcsharp_call_start_unary = GetMethodDelegate<Delegates.grpcsharp_call_start_unary_delegate>(library);
this.grpcsharp_call_start_client_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_client_streaming_delegate>(library);
this.grpcsharp_call_start_server_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_server_streaming_delegate>(library);
this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_duplex_streaming_delegate>(library);
this.grpcsharp_call_send_message = GetMethodDelegate<Delegates.grpcsharp_call_send_message_delegate>(library);
this.grpcsharp_call_send_close_from_client = GetMethodDelegate<Delegates.grpcsharp_call_send_close_from_client_delegate>(library);
this.grpcsharp_call_send_status_from_server = GetMethodDelegate<Delegates.grpcsharp_call_send_status_from_server_delegate>(library);
this.grpcsharp_call_recv_message = GetMethodDelegate<Delegates.grpcsharp_call_recv_message_delegate>(library);
this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_recv_initial_metadata_delegate>(library);
this.grpcsharp_call_start_serverside = GetMethodDelegate<Delegates.grpcsharp_call_start_serverside_delegate>(library);
this.grpcsharp_call_send_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_send_initial_metadata_delegate>(library);
this.grpcsharp_call_set_credentials = GetMethodDelegate<Delegates.grpcsharp_call_set_credentials_delegate>(library);
this.grpcsharp_call_get_peer = GetMethodDelegate<Delegates.grpcsharp_call_get_peer_delegate>(library);
this.grpcsharp_call_destroy = GetMethodDelegate<Delegates.grpcsharp_call_destroy_delegate>(library);
this.grpcsharp_channel_args_create = GetMethodDelegate<Delegates.grpcsharp_channel_args_create_delegate>(library);
this.grpcsharp_channel_args_set_string = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_string_delegate>(library);
this.grpcsharp_channel_args_set_integer = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_integer_delegate>(library);
this.grpcsharp_channel_args_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_args_destroy_delegate>(library);
this.grpcsharp_override_default_ssl_roots = GetMethodDelegate<Delegates.grpcsharp_override_default_ssl_roots>(library);
this.grpcsharp_ssl_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_credentials_create_delegate>(library);
this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_channel_credentials_create_delegate>(library);
this.grpcsharp_channel_credentials_release = GetMethodDelegate<Delegates.grpcsharp_channel_credentials_release_delegate>(library);
this.grpcsharp_insecure_channel_create = GetMethodDelegate<Delegates.grpcsharp_insecure_channel_create_delegate>(library);
this.grpcsharp_secure_channel_create = GetMethodDelegate<Delegates.grpcsharp_secure_channel_create_delegate>(library);
this.grpcsharp_channel_create_call = GetMethodDelegate<Delegates.grpcsharp_channel_create_call_delegate>(library);
this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_check_connectivity_state_delegate>(library);
this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_watch_connectivity_state_delegate>(library);
this.grpcsharp_channel_get_target = GetMethodDelegate<Delegates.grpcsharp_channel_get_target_delegate>(library);
this.grpcsharp_channel_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_destroy_delegate>(library);
this.grpcsharp_sizeof_grpc_event = GetMethodDelegate<Delegates.grpcsharp_sizeof_grpc_event_delegate>(library);
this.grpcsharp_completion_queue_create = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_delegate>(library);
this.grpcsharp_completion_queue_shutdown = GetMethodDelegate<Delegates.grpcsharp_completion_queue_shutdown_delegate>(library);
this.grpcsharp_completion_queue_next = GetMethodDelegate<Delegates.grpcsharp_completion_queue_next_delegate>(library);
this.grpcsharp_completion_queue_pluck = GetMethodDelegate<Delegates.grpcsharp_completion_queue_pluck_delegate>(library);
this.grpcsharp_completion_queue_destroy = GetMethodDelegate<Delegates.grpcsharp_completion_queue_destroy_delegate>(library);
this.gprsharp_free = GetMethodDelegate<Delegates.gprsharp_free_delegate>(library);
this.grpcsharp_metadata_array_create = GetMethodDelegate<Delegates.grpcsharp_metadata_array_create_delegate>(library);
this.grpcsharp_metadata_array_add = GetMethodDelegate<Delegates.grpcsharp_metadata_array_add_delegate>(library);
this.grpcsharp_metadata_array_count = GetMethodDelegate<Delegates.grpcsharp_metadata_array_count_delegate>(library);
this.grpcsharp_metadata_array_get_key = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_key_delegate>(library);
this.grpcsharp_metadata_array_get_value = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_delegate>(library);
this.grpcsharp_metadata_array_destroy_full = GetMethodDelegate<Delegates.grpcsharp_metadata_array_destroy_full_delegate>(library);
this.grpcsharp_redirect_log = GetMethodDelegate<Delegates.grpcsharp_redirect_log_delegate>(library);
this.grpcsharp_metadata_credentials_create_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate>(library);
this.grpcsharp_metadata_credentials_notify_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate>(library);
this.grpcsharp_ssl_server_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_server_credentials_create_delegate>(library);
this.grpcsharp_server_credentials_release = GetMethodDelegate<Delegates.grpcsharp_server_credentials_release_delegate>(library);
this.grpcsharp_server_create = GetMethodDelegate<Delegates.grpcsharp_server_create_delegate>(library);
this.grpcsharp_server_register_completion_queue = GetMethodDelegate<Delegates.grpcsharp_server_register_completion_queue_delegate>(library);
this.grpcsharp_server_add_insecure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_insecure_http2_port_delegate>(library);
this.grpcsharp_server_add_secure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_secure_http2_port_delegate>(library);
this.grpcsharp_server_start = GetMethodDelegate<Delegates.grpcsharp_server_start_delegate>(library);
this.grpcsharp_server_request_call = GetMethodDelegate<Delegates.grpcsharp_server_request_call_delegate>(library);
this.grpcsharp_server_cancel_all_calls = GetMethodDelegate<Delegates.grpcsharp_server_cancel_all_calls_delegate>(library);
this.grpcsharp_server_shutdown_and_notify_callback = GetMethodDelegate<Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate>(library);
this.grpcsharp_server_destroy = GetMethodDelegate<Delegates.grpcsharp_server_destroy_delegate>(library);
this.grpcsharp_call_auth_context = GetMethodDelegate<Delegates.grpcsharp_call_auth_context_delegate>(library);
this.grpcsharp_auth_context_peer_identity_property_name = GetMethodDelegate<Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate>(library);
this.grpcsharp_auth_context_property_iterator = GetMethodDelegate<Delegates.grpcsharp_auth_context_property_iterator_delegate>(library);
this.grpcsharp_auth_property_iterator_next = GetMethodDelegate<Delegates.grpcsharp_auth_property_iterator_next_delegate>(library);
this.grpcsharp_auth_context_release = GetMethodDelegate<Delegates.grpcsharp_auth_context_release_delegate>(library);
this.gprsharp_now = GetMethodDelegate<Delegates.gprsharp_now_delegate>(library);
this.gprsharp_inf_future = GetMethodDelegate<Delegates.gprsharp_inf_future_delegate>(library);
this.gprsharp_inf_past = GetMethodDelegate<Delegates.gprsharp_inf_past_delegate>(library);
this.gprsharp_convert_clock_type = GetMethodDelegate<Delegates.gprsharp_convert_clock_type_delegate>(library);
this.gprsharp_sizeof_timespec = GetMethodDelegate<Delegates.gprsharp_sizeof_timespec_delegate>(library);
this.grpcsharp_test_callback = GetMethodDelegate<Delegates.grpcsharp_test_callback_delegate>(library);
this.grpcsharp_test_nop = GetMethodDelegate<Delegates.grpcsharp_test_nop_delegate>(library);
}
/// <summary>
/// Gets singleton instance of this class.
/// </summary>
public static NativeMethods Get()
{
return NativeExtension.Get().NativeMethods;
}
static T GetMethodDelegate<T>(UnmanagedLibrary library)
where T : class
{
var methodName = RemoveStringSuffix(typeof(T).Name, "_delegate");
return library.GetNativeMethodDelegate<T>(methodName);
}
static string RemoveStringSuffix(string str, string toRemove)
{
if (!str.EndsWith(toRemove))
{
return str;
}
return str.Substring(0, str.Length - toRemove.Length);
}
/// <summary>
/// Delegate types for all published native methods. Declared under inner class to prevent scope pollution.
/// </summary>
public class Delegates
{
public delegate void grpcsharp_init_delegate();
public delegate void grpcsharp_shutdown_delegate();
public delegate IntPtr grpcsharp_version_string_delegate(); // returns not-owned const char*
public delegate BatchContextSafeHandle grpcsharp_batch_context_create_delegate();
public delegate IntPtr grpcsharp_batch_context_recv_initial_metadata_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_message_length_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_recv_message_to_buffer_delegate(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
public delegate StatusCode grpcsharp_batch_context_recv_status_on_client_status_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx, out UIntPtr detailsLength);
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx);
public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx);
public delegate RequestCallContextSafeHandle grpcsharp_request_call_context_create_delegate();
public delegate CallSafeHandle grpcsharp_request_call_context_call_delegate(RequestCallContextSafeHandle ctx);
public delegate IntPtr grpcsharp_request_call_context_method_delegate(RequestCallContextSafeHandle ctx, out UIntPtr methodLength);
public delegate IntPtr grpcsharp_request_call_context_host_delegate(RequestCallContextSafeHandle ctx, out UIntPtr hostLength);
public delegate Timespec grpcsharp_request_call_context_deadline_delegate(RequestCallContextSafeHandle ctx);
public delegate IntPtr grpcsharp_request_call_context_request_metadata_delegate(RequestCallContextSafeHandle ctx);
public delegate void grpcsharp_request_call_context_destroy_delegate(IntPtr ctx);
public delegate CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create_delegate(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
public delegate void grpcsharp_call_credentials_release_delegate(IntPtr credentials);
public delegate CallError grpcsharp_call_cancel_delegate(CallSafeHandle call);
public delegate CallError grpcsharp_call_cancel_with_status_delegate(CallSafeHandle call, StatusCode status, string description);
public delegate CallError grpcsharp_call_start_unary_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_start_client_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_start_server_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags,
MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_start_duplex_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_send_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, bool sendEmptyInitialMetadata);
public delegate CallError grpcsharp_call_send_close_from_client_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_send_status_from_server_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, StatusCode statusCode, byte[] statusMessage, UIntPtr statusMessageLen, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata,
byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags);
public delegate CallError grpcsharp_call_recv_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_recv_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_start_serverside_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_send_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate CallError grpcsharp_call_set_credentials_delegate(CallSafeHandle call, CallCredentialsSafeHandle credentials);
public delegate CStringSafeHandle grpcsharp_call_get_peer_delegate(CallSafeHandle call);
public delegate void grpcsharp_call_destroy_delegate(IntPtr call);
public delegate ChannelArgsSafeHandle grpcsharp_channel_args_create_delegate(UIntPtr numArgs);
public delegate void grpcsharp_channel_args_set_string_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
public delegate void grpcsharp_channel_args_set_integer_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
public delegate void grpcsharp_channel_args_destroy_delegate(IntPtr args);
public delegate void grpcsharp_override_default_ssl_roots(string pemRootCerts);
public delegate ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create_delegate(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
public delegate ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create_delegate(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
public delegate void grpcsharp_channel_credentials_release_delegate(IntPtr credentials);
public delegate ChannelSafeHandle grpcsharp_insecure_channel_create_delegate(string target, ChannelArgsSafeHandle channelArgs);
public delegate ChannelSafeHandle grpcsharp_secure_channel_create_delegate(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
public delegate CallSafeHandle grpcsharp_channel_create_call_delegate(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
public delegate ChannelState grpcsharp_channel_check_connectivity_state_delegate(ChannelSafeHandle channel, int tryToConnect);
public delegate void grpcsharp_channel_watch_connectivity_state_delegate(ChannelSafeHandle channel, ChannelState lastObservedState,
Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate CStringSafeHandle grpcsharp_channel_get_target_delegate(ChannelSafeHandle call);
public delegate void grpcsharp_channel_destroy_delegate(IntPtr channel);
public delegate int grpcsharp_sizeof_grpc_event_delegate();
public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_delegate();
public delegate void grpcsharp_completion_queue_shutdown_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_next_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_pluck_delegate(CompletionQueueSafeHandle cq, IntPtr tag);
public delegate void grpcsharp_completion_queue_destroy_delegate(IntPtr cq);
public delegate void gprsharp_free_delegate(IntPtr ptr);
public delegate MetadataArraySafeHandle grpcsharp_metadata_array_create_delegate(UIntPtr capacity);
public delegate void grpcsharp_metadata_array_add_delegate(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
public delegate UIntPtr grpcsharp_metadata_array_count_delegate(IntPtr metadataArray);
public delegate IntPtr grpcsharp_metadata_array_get_key_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr keyLength);
public delegate IntPtr grpcsharp_metadata_array_get_value_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr valueLength);
public delegate void grpcsharp_metadata_array_destroy_full_delegate(IntPtr array);
public delegate void grpcsharp_redirect_log_delegate(GprLogDelegate callback);
public delegate CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin_delegate(NativeMetadataInterceptor interceptor);
public delegate void grpcsharp_metadata_credentials_notify_from_plugin_delegate(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
public delegate ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create_delegate(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, bool forceClientAuth);
public delegate void grpcsharp_server_credentials_release_delegate(IntPtr credentials);
public delegate ServerSafeHandle grpcsharp_server_create_delegate(ChannelArgsSafeHandle args);
public delegate void grpcsharp_server_register_completion_queue_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq);
public delegate int grpcsharp_server_add_insecure_http2_port_delegate(ServerSafeHandle server, string addr);
public delegate int grpcsharp_server_add_secure_http2_port_delegate(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
public delegate void grpcsharp_server_start_delegate(ServerSafeHandle server);
public delegate CallError grpcsharp_server_request_call_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, RequestCallContextSafeHandle ctx);
public delegate void grpcsharp_server_cancel_all_calls_delegate(ServerSafeHandle server);
public delegate void grpcsharp_server_shutdown_and_notify_callback_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate void grpcsharp_server_destroy_delegate(IntPtr server);
public delegate AuthContextSafeHandle grpcsharp_call_auth_context_delegate(CallSafeHandle call);
public delegate IntPtr grpcsharp_auth_context_peer_identity_property_name_delegate(AuthContextSafeHandle authContext); // returns const char*
public delegate AuthContextSafeHandle.NativeAuthPropertyIterator grpcsharp_auth_context_property_iterator_delegate(AuthContextSafeHandle authContext);
public delegate IntPtr grpcsharp_auth_property_iterator_next_delegate(ref AuthContextSafeHandle.NativeAuthPropertyIterator iterator); // returns const auth_property*
public delegate void grpcsharp_auth_context_release_delegate(IntPtr authContext);
public delegate Timespec gprsharp_now_delegate(ClockType clockType);
public delegate Timespec gprsharp_inf_future_delegate(ClockType clockType);
public delegate Timespec gprsharp_inf_past_delegate(ClockType clockType);
public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, ClockType targetClock);
public delegate int gprsharp_sizeof_timespec_delegate();
public delegate CallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback);
public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.ServiceProcess;
using System.DirectoryServices;
using System.Linq;
using WebsitePanel.Setup.Web;
using Microsoft.Win32;
namespace WebsitePanel.Setup
{
/// <summary>
/// Utils class.
/// </summary>
public sealed class Utils
{
public const string AspNet40RegistrationToolx64 = @"Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe";
public const string AspNet40RegistrationToolx86 = @"Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe";
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private Utils()
{
}
#region Resources
/// <summary>
/// Get resource stream from assembly by specified resource name.
/// </summary>
/// <param name="resourceName">Name of the resource.</param>
/// <returns>Resource stream.</returns>
public static Stream GetResourceStream(string resourceName)
{
Assembly asm = typeof(Utils).Assembly;
Stream ret = asm.GetManifestResourceStream(resourceName);
return ret;
}
#endregion
#region Crypting
/// <summary>
/// Computes the SHA1 hash value
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string ComputeSHA1(string plainText)
{
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
HashAlgorithm hash = new SHA1Managed();
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
// Return the result.
return Convert.ToBase64String(hashBytes);
}
public static string CreateCryptoKey(int len)
{
byte[] bytes = new byte[len];
new RNGCryptoServiceProvider().GetBytes(bytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(string.Format("{0:X2}", bytes[i]));
}
return sb.ToString();
}
public static string Encrypt(string key, string str)
{
if (str == null)
return str;
// We are now going to create an instance of the
// Rihndael class.
RijndaelManaged RijndaelCipher = new RijndaelManaged();
byte[] plainText = System.Text.Encoding.Unicode.GetBytes(str);
byte[] salt = Encoding.ASCII.GetBytes(key.Length.ToString());
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(key, salt);
ICryptoTransform encryptor = RijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
// encode
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherBytes = memoryStream.ToArray();
// Close both streams
memoryStream.Close();
cryptoStream.Close();
// Return encrypted string
return Convert.ToBase64String(cipherBytes);
}
public static string Decrypt(string key, string Base64String)
{
var RijndaelCipher = new RijndaelManaged();
byte[] secretText = Convert.FromBase64String(Base64String);
byte[] salt = Encoding.ASCII.GetBytes(key.Length.ToString());
var secretKey = new PasswordDeriveBytes(key, salt);
var decryptor = RijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
var MemStream = new MemoryStream();
var DecryptoStream = new CryptoStream(MemStream, decryptor, CryptoStreamMode.Write);
DecryptoStream.Write(secretText, 0, secretText.Length);
DecryptoStream.FlushFinalBlock();
var Result = MemStream.ToArray();
MemStream.Close();
DecryptoStream.Close();
return Encoding.Unicode.GetString(Result);
}
public static string GetRandomString(int length)
{
string ptrn = "abcdefghjklmnpqrstwxyz0123456789";
StringBuilder sb = new StringBuilder();
byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert 4 bytes into a 32-bit integer value.
int seed = (randomBytes[0] & 0x7f) << 24 |
randomBytes[1] << 16 |
randomBytes[2] << 8 |
randomBytes[3];
Random rnd = new Random(seed);
for (int i = 0; i < length; i++)
sb.Append(ptrn[rnd.Next(ptrn.Length - 1)]);
return sb.ToString();
}
#endregion
#region Setup
public static Hashtable GetSetupParameters(object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
Hashtable args = obj as Hashtable;
if (args == null)
throw new ArgumentNullException("obj");
return args;
}
public static object GetSetupParameter(Hashtable args, string paramName)
{
if (args == null)
throw new ArgumentNullException("args");
//
if (args.ContainsKey(paramName) == false)
{
return String.Empty;
}
//
return args[paramName];
}
public static string GetStringSetupParameter(Hashtable args, string paramName)
{
object obj = GetSetupParameter(args, paramName);
if (obj == null)
return null;
if (!(obj is string))
throw new Exception(string.Format("Invalid type of '{0}' parameter", paramName));
return obj as string;
}
public static int GetInt32SetupParameter(Hashtable args, string paramName)
{
object obj = GetSetupParameter(args, paramName);
if (!(obj is int))
throw new Exception(string.Format("Invalid type of '{0}' parameter", paramName));
return (int)obj;
}
public static Version GetVersionSetupParameter(Hashtable args, string paramName)
{
object obj = GetSetupParameter(args, paramName);
if (!(obj is Version))
throw new Exception(string.Format("Invalid type of '{0}' parameter", paramName));
return obj as Version;
}
public static string ReplaceScriptVariable(string str, string variable, string value)
{
Regex re = new Regex("\\$\\{" + variable + "\\}+", RegexOptions.IgnoreCase);
return re.Replace(str, value);
}
#endregion
#region Type convertions
/// <summary>
/// Converts string to int
/// </summary>
/// <param name="value">String containing a number to convert</param>
/// <param name="defaultValue">Default value</param>
/// <returns>
///The Int32 number equivalent to the number contained in value.
/// </returns>
public static int ParseInt(string value, int defaultValue)
{
if (value != null && value.Length > 0)
{
try
{
return Int32.Parse(value);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
}
return defaultValue;
}
/// <summary>
/// ParseBool
/// </summary>
/// <param name="value">EventData</param>
/// <param name="defaultValue">Dafault value</param>
/// <returns>bool</returns>
public static bool ParseBool(string value, bool defaultValue)
{
if (value != null)
{
try
{
return bool.Parse(value);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
}
return defaultValue;
}
/// <summary>
/// Converts string to decimal
/// </summary>
/// <param name="value">String containing a number to convert</param>
/// <param name="defaultValue">Default value</param>
/// <returns>The Decimal number equivalent to the number contained in value.</returns>
public static decimal ParseDecimal(string value, decimal defaultValue)
{
if (value != null && !string.IsNullOrEmpty(value))
{
try
{
return Decimal.Parse(value);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
}
return defaultValue;
}
/// <summary>
/// Converts string to double
/// </summary>
/// <param name="value">String containing a number to convert</param>
/// <param name="defaultValue">Default value</param>
/// <returns>The double number equivalent to the number contained in value.</returns>
public static double ParseDouble(string value, double defaultValue)
{
if (value != null)
{
try
{
return double.Parse(value);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
}
return defaultValue;
}
#endregion
#region DB
/// <summary>
/// Converts db value to string
/// </summary>
/// <param name="val">EventData</param>
/// <returns>string</returns>
public static string GetDbString(object val)
{
string ret = string.Empty;
if ((val != null) && (val != DBNull.Value))
ret = (string)val;
return ret;
}
/// <summary>
/// Converts db value to short
/// </summary>
/// <param name="val">EventData</param>
/// <returns>short</returns>
public static short GetDbShort(object val)
{
short ret = 0;
if ((val != null) && (val != DBNull.Value))
ret = (short)val;
return ret;
}
/// <summary>
/// Converts db value to int
/// </summary>
/// <param name="val">EventData</param>
/// <returns>int</returns>
public static int GetDbInt32(object val)
{
int ret = 0;
if ((val != null) && (val != DBNull.Value))
ret = (int)val;
return ret;
}
/// <summary>
/// Converts db value to bool
/// </summary>
/// <param name="val">EventData</param>
/// <returns>bool</returns>
public static bool GetDbBool(object val)
{
bool ret = false;
if ((val != null) && (val != DBNull.Value))
ret = Convert.ToBoolean(val);
return ret;
}
/// <summary>
/// Converts db value to decimal
/// </summary>
/// <param name="val">EventData</param>
/// <returns>decimal</returns>
public static decimal GetDbDecimal(object val)
{
decimal ret = 0;
if ((val != null) && (val != DBNull.Value))
ret = (decimal)val;
return ret;
}
/// <summary>
/// Converts db value to datetime
/// </summary>
/// <param name="val">EventData</param>
/// <returns>DateTime</returns>
public static DateTime GetDbDateTime(object val)
{
DateTime ret = DateTime.MinValue;
if ((val != null) && (val != DBNull.Value))
ret = (DateTime)val;
return ret;
}
#endregion
#region Exceptions
public static bool IsThreadAbortException(Exception ex)
{
Exception innerException = ex;
while (innerException != null)
{
if (innerException is System.Threading.ThreadAbortException)
return true;
innerException = innerException.InnerException;
}
string str = ex.ToString();
return str.Contains("System.Threading.ThreadAbortException");
}
#endregion
#region Windows Firewall
public static bool IsWindowsFirewallEnabled()
{
int ret = RegistryUtils.GetRegistryKeyInt32Value(@"SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile", "EnableFirewall");
return (ret == 1);
}
public static bool IsWindowsFirewallExceptionsAllowed()
{
int ret = RegistryUtils.GetRegistryKeyInt32Value(@"SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile", "DoNotAllowExceptions");
return (ret != 1);
}
public static void OpenWindowsFirewallPort(string name, string port)
{
string path = Path.Combine(Environment.SystemDirectory, "netsh.exe");
string arguments = string.Format("firewall set portopening tcp {0} \"{1}\" enable", port, name);
RunProcess(path, arguments);
}
public static void OpenWindowsFirewallPortAdv(string RuleName, string Port)
{
string tool = Path.Combine(Environment.SystemDirectory, "netsh.exe");
string args = string.Format("advfirewall firewall add rule name=\"{0}\" dir=in action=allow protocol=tcp localport={1}", RuleName, Port);
RunProcess(tool, args);
}
#endregion
#region Processes & Services
public static int RunProcess(string path, string arguments)
{
Process process = null;
try
{
ProcessStartInfo info = new ProcessStartInfo(path, arguments);
info.WindowStyle = ProcessWindowStyle.Hidden;
process = Process.Start(info);
process.WaitForExit();
return process.ExitCode;
}
finally
{
if (process != null)
{
process.Close();
}
}
}
public static void StartService(string serviceName)
{
ServiceController sc = new ServiceController(serviceName);
// Start the service if the current status is stopped.
if (sc.Status == ServiceControllerStatus.Stopped)
{
// Start the service, and wait until its status is "Running".
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
}
}
public static void StopService(string serviceName)
{
ServiceController sc = new ServiceController(serviceName);
// Stop the service if the current status is not stopped.
if (sc.Status != ServiceControllerStatus.Stopped &&
sc.Status != ServiceControllerStatus.StopPending)
{
// Stop the service, and wait until its status is "Running".
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
}
}
#endregion
#region I/O
public static string GetSystemDrive()
{
return Path.GetPathRoot(Environment.SystemDirectory);
}
#endregion
public static bool IsWebDeployInstalled()
{
// TO-DO: Implement Web Deploy detection (x64/x86)
var isInstalled = false;
//
try
{
var msdeployRegKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\IIS Extensions\MSDeploy\2");
//
var keyValue = msdeployRegKey.GetValue("Install");
// We have found the required key in the registry hive
if (keyValue != null && keyValue.Equals(1))
{
isInstalled = true;
}
}
catch (Exception ex)
{
Log.WriteError("Could not retrieve Web Deploy key from the registry", ex);
}
//
return isInstalled;
}
public static bool IsWin64()
{
return (IntPtr.Size == 8);
}
public static void ShowConsoleErrorMessage(string format, params object[] args)
{
Console.WriteLine(String.Format(format, args));
}
public static string ResolveAspNet40RegistrationToolPath_Iis6(SetupVariables setupVariables)
{
// By default we fallback to the corresponding tool version based on the platform bitness
var util = Environment.Is64BitOperatingSystem ? AspNet40RegistrationToolx64 : AspNet40RegistrationToolx86;
// Choose appropriate tool version for IIS 6
if (setupVariables.IISVersion.Major == 6)
{
// Change to x86 tool version on x64 w/ "Enable32bitAppOnWin64" flag enabled
if (Environment.Is64BitOperatingSystem == true && Utils.IIS32Enabled())
{
util = AspNet40RegistrationToolx86;
}
}
// Build path to the tool
return Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), util);
}
/// <summary>
/// Beware: Web site component-dependent logic
/// </summary>
/// <param name="setupVariables"></param>
/// <returns></returns>
public static string ResolveAspNet40RegistrationToolPath_Iis7(SetupVariables setupVariables)
{
// By default we fallback to the corresponding tool version based on the platform bitness
var util = Environment.Is64BitOperatingSystem ? AspNet40RegistrationToolx64 : AspNet40RegistrationToolx86;
// Choose appropriate tool version for IIS 7
if (setupVariables.IISVersion.Major >= 7 && setupVariables.SetupAction == SetupActions.Update)
{
// Evaluate app pool settings on x64 platform only when update is running
if (Environment.Is64BitOperatingSystem == true)
{
// Change to x86 tool version if the component's app pool is in WOW64 mode
using (var srvman = new Microsoft.Web.Administration.ServerManager())
{
// Retrieve the component's app pool
var appPoolObj = srvman.ApplicationPools[setupVariables.WebApplicationPoolName];
// We are
if (appPoolObj == null)
{
throw new ArgumentException(String.Format("Could not find '{0}' web application pool", setupVariables.WebApplicationPoolName), "appPoolObj");
}
// Check app pool mode
else if (appPoolObj.Enable32BitAppOnWin64 == true)
{
util = AspNet40RegistrationToolx86;
}
}
}
}
// Build path to the tool
return Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), util);
}
public static bool CheckAspNet40Registered(SetupVariables setupVariables)
{
var regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\ASP.NET\\4.0.30319.0");
return (regkey != null);
}
public static string ExecAspNetRegistrationToolCommand(SetupVariables setupVariables, string arguments)
{
//
var util = (setupVariables.IISVersion.Major == 6) ? Utils.ResolveAspNet40RegistrationToolPath_Iis6(setupVariables) : Utils.ResolveAspNet40RegistrationToolPath_Iis7(setupVariables);
//
// Create a specific process start info set to redirect its standard output for further processing
ProcessStartInfo info = new ProcessStartInfo(util)
{
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardOutput = true,
Arguments = arguments
};
//
Log.WriteInfo(String.Format("Starting aspnet_regiis.exe {0}", info.Arguments));
//
var process = default(Process);
//
var psOutput = String.Empty;
//
try
{
// Start the process
process = Process.Start(info);
// Read the output
psOutput = process.StandardOutput.ReadToEnd();
// Wait for the completion
process.WaitForExit();
}
catch (Exception ex)
{
Log.WriteError("Could not execute ASP.NET Registration Tool command", ex);
}
finally
{
if (process != null)
process.Close();
}
// Trace output data for troubleshooting purposes
Log.WriteInfo(psOutput);
//
Log.WriteInfo(String.Format("Finished aspnet_regiis.exe {0}", info.Arguments));
//
return psOutput;
}
public static void RegisterAspNet40(Setup.SetupVariables setupVariables)
{
// Run ASP.NET Registration Tool command
ExecAspNetRegistrationToolCommand(setupVariables, arguments: (setupVariables.IISVersion.Major == 6) ? "-ir -enable" : "-ir");
}
public static WebExtensionStatus GetAspNetWebExtensionStatus_Iis6(SetupVariables setupVariables)
{
WebExtensionStatus status = WebExtensionStatus.Allowed;
if (setupVariables.IISVersion.Major == 6)
{
status = WebExtensionStatus.NotInstalled;
string path;
if (Utils.IsWin64() && !Utils.IIS32Enabled())
{
//64-bit
path = Path.Combine(OS.GetWindowsDirectory(), @"Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll");
}
else
{
//32-bit
path = Path.Combine(OS.GetWindowsDirectory(), @"Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll");
}
path = path.ToLower();
using (DirectoryEntry iis = new DirectoryEntry("IIS://LocalHost/W3SVC"))
{
PropertyValueCollection values = iis.Properties["WebSvcExtRestrictionList"];
for (int i = 0; i < values.Count; i++)
{
string val = values[i] as string;
if (!string.IsNullOrEmpty(val))
{
string strVal = val.ToString().ToLower();
if (strVal.Contains(path))
{
if (strVal[0] == '1')
{
status = WebExtensionStatus.Allowed;
}
else
{
status = WebExtensionStatus.Prohibited;
}
break;
}
}
}
}
}
return status;
}
public static void EnableAspNetWebExtension_Iis6()
{
Log.WriteStart("Enabling ASP.NET Web Service Extension");
//
var webExtensionName = (Utils.IsWin64() && Utils.IIS32Enabled()) ? "ASP.NET v4.0.30319 (32-bit)" : "ASP.NET v4.0.30319";
//
using (DirectoryEntry iisService = new DirectoryEntry("IIS://LocalHost/W3SVC"))
{
iisService.Invoke("EnableWebServiceExtension", webExtensionName);
iisService.CommitChanges();
}
//
Log.WriteEnd("Enabled ASP.NET Web Service Extension");
}
public static bool IIS32Enabled()
{
bool enabled = false;
using (DirectoryEntry obj = new DirectoryEntry("IIS://LocalHost/W3SVC/AppPools"))
{
object objProperty = GetObjectProperty(obj, "Enable32bitAppOnWin64");
if (objProperty != null)
{
enabled = (bool)objProperty;
}
}
return enabled;
}
public static void SetObjectProperty(DirectoryEntry oDE, string name, object value)
{
if (value != null)
{
if (oDE.Properties.Contains(name))
{
oDE.Properties[name][0] = value;
}
else
{
oDE.Properties[name].Add(value);
}
}
}
public static object GetObjectProperty(DirectoryEntry entry, string name)
{
if (entry.Properties.Contains(name))
return entry.Properties[name][0];
else
return null;
}
public static void OpenFirewallPort(string name, string port, Version iisVersion)
{
bool iis7 = (iisVersion.Major >= 7);
if (iis7)
{
if (Utils.IsWindowsFirewallEnabled() && Utils.IsWindowsFirewallExceptionsAllowed())
{
Log.WriteStart(String.Format("Opening port {0} in windows firewall", port));
Utils.OpenWindowsFirewallPortAdv(name, port);
Log.WriteEnd("Opened port in windows firewall");
InstallLog.AppendLine(String.Format("- Opened port {0} in Windows Firewall", port));
}
}
else
{
if (Utils.IsWindowsFirewallEnabled() &&
Utils.IsWindowsFirewallExceptionsAllowed())
{
//SetProgressText("Opening port in windows firewall...");
Log.WriteStart(String.Format("Opening port {0} in windows firewall", port));
Utils.OpenWindowsFirewallPort(name, port);
//update log
Log.WriteEnd("Opened port in windows firewall");
InstallLog.AppendLine(String.Format("- Opened port {0} in Windows Firewall", port));
}
}
}
public static string[] GetApplicationUrls(string ip, string domain, string port, string virtualDir)
{
List<string> urls = new List<string>();
// IP address, [port] and [virtualDir]
string url = ip;
if (String.IsNullOrEmpty(domain))
{
if (!String.IsNullOrEmpty(port) && port != "80")
url += ":" + port;
if (!String.IsNullOrEmpty(virtualDir))
url += "/" + virtualDir;
urls.Add(url);
}
// domain, [port] and [virtualDir]
if (!String.IsNullOrEmpty(domain))
{
url = domain;
if (!String.IsNullOrEmpty(port) && port != "80")
url += ":" + port;
if (!String.IsNullOrEmpty(virtualDir))
url += "/" + virtualDir;
urls.Add(url);
}
return urls.ToArray();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MultipleObjectsTransfer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement
{
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.DataMovement.TransferEnumerators;
using Microsoft.WindowsAzure.Storage.File;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Represents a multiple objects transfer operation.
/// </summary>
#if BINARY_SERIALIZATION
[Serializable]
#else
[KnownType(typeof(AzureBlobDirectoryLocation))]
[KnownType(typeof(AzureBlobLocation))]
[KnownType(typeof(AzureFileDirectoryLocation))]
[KnownType(typeof(AzureFileLocation))]
[KnownType(typeof(DirectoryLocation))]
[KnownType(typeof(FileLocation))]
// StreamLocation intentionally omitted because it is not serializable
[KnownType(typeof(UriLocation))]
[KnownType(typeof(SingleObjectTransfer))]
[DataContract]
#endif // BINARY_SERIALIZATION
internal abstract class MultipleObjectsTransfer : Transfer
{
/// <summary>
/// Serialization field name for transfer enumerator list continuation token.
/// </summary>
private const string ListContinuationTokenName = "ListContinuationToken";
/// <summary>
/// Serialization field name for sub transfers.
/// </summary>
private const string SubTransfersName = "SubTransfers";
/// <summary>
/// Internal directory transfer context instance.
/// </summary>
private DirectoryTransferContext dirTransferContext = null;
/// <summary>
/// List continuation token from which enumeration begins.
/// </summary>
#if !BINARY_SERIALIZATION
[DataMember]
#endif
private SerializableListContinuationToken enumerateContinuationToken;
/// <summary>
/// Lock object for enumeration continuation token.
/// </summary>
private object lockEnumerateContinuationToken = new object();
/// <summary>
/// Timeout used in reset event waiting.
/// </summary>
private TimeSpan EnumerationWaitTimeOut = TimeSpan.FromSeconds(10);
/// <summary>
/// Used to block enumeration when have enumerated enough transfer entries.
/// </summary>
private AutoResetEvent enumerationResetEvent;
/// <summary>
/// Stores enumerate exception.
/// </summary>
private Exception enumerateException;
/// <summary>
/// Number of outstandings tasks started by this transfer.
/// </summary>
private long outstandingTasks;
private ReaderWriterLockSlim progressUpdateLock = new ReaderWriterLockSlim();
/// <summary>
/// Job queue to invoke ShouldTransferCallback.
/// </summary>
private TaskQueue<Tuple<SingleObjectTransfer, TransferEntry>> shouldTransferQueue
= new TaskQueue<Tuple<SingleObjectTransfer, TransferEntry>>(TransferManager.Configurations.ParallelOperations * Constants.ListSegmentLengthMultiplier);
/// <summary>
/// Storres sub transfers.
/// </summary>
#if !BINARY_SERIALIZATION
[DataMember]
private TransferCollection<SingleObjectTransfer> serializeSubTransfers;
#endif
private TransferCollection<SingleObjectTransfer> subTransfers;
private TaskCompletionSource<object> allTransfersCompleteSource;
/// <summary>
/// Initializes a new instance of the <see cref="MultipleObjectsTransfer"/> class.
/// </summary>
/// <param name="source">Transfer source.</param>
/// <param name="dest">Transfer destination.</param>
/// <param name="transferMethod">Transfer method, see <see cref="TransferMethod"/> for detail available methods.</param>
public MultipleObjectsTransfer(TransferLocation source, TransferLocation dest, TransferMethod transferMethod)
: base(source, dest, transferMethod)
{
this.subTransfers = new TransferCollection<SingleObjectTransfer>();
this.subTransfers.OverallProgressTracker.Parent = this.ProgressTracker;
}
#if BINARY_SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="MultipleObjectsTransfer"/> class.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected MultipleObjectsTransfer(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.enumerateContinuationToken = (SerializableListContinuationToken)info.GetValue(ListContinuationTokenName, typeof(SerializableListContinuationToken));
if (context.Context is StreamJournal)
{
this.subTransfers = new TransferCollection<SingleObjectTransfer>();
}
else
{
this.subTransfers = (TransferCollection<SingleObjectTransfer>)info.GetValue(SubTransfersName, typeof(TransferCollection<SingleObjectTransfer>));
}
this.subTransfers.OverallProgressTracker.Parent = this.ProgressTracker;
}
#endif // BINARY_SERIALIZATION
#if !BINARY_SERIALIZATION
[OnSerializing]
private void OnSerializingCallback(StreamingContext context)
{
if (!IsStreamJournal)
{
this.serializeSubTransfers = this.subTransfers;
}
}
// Initialize a new MultipleObjectsTransfer object after deserialization
[OnDeserialized]
private void OnDeserializedCallback(StreamingContext context)
{
// Constructors and field initializers are not called by DCS, so initialize things here
progressUpdateLock = new ReaderWriterLockSlim();
lockEnumerateContinuationToken = new object();
EnumerationWaitTimeOut = TimeSpan.FromSeconds(10);
if (!IsStreamJournal)
{
this.subTransfers = this.serializeSubTransfers;
}
else
{
this.subTransfers = new TransferCollection<SingleObjectTransfer>();
}
this.subTransfers.OverallProgressTracker.Parent = this.ProgressTracker;
// DataContractSerializer doesn't invoke object's constructor, we should initialize member variables here.
shouldTransferQueue
= new TaskQueue<Tuple<SingleObjectTransfer, TransferEntry>>(TransferManager.Configurations.ParallelOperations * Constants.ListSegmentLengthMultiplier);
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="MultipleObjectsTransfer"/> class.
/// </summary>
/// <param name="other">Another <see cref="MultipleObjectsTransfer"/> object.</param>
protected MultipleObjectsTransfer(MultipleObjectsTransfer other)
: base(other)
{
other.progressUpdateLock?.EnterWriteLock();
this.ProgressTracker = other.ProgressTracker.Copy();
lock (other.lockEnumerateContinuationToken)
{
// copy enumerator
this.enumerateContinuationToken = other.enumerateContinuationToken;
// copy transfers
this.subTransfers = other.subTransfers.Copy();
}
this.subTransfers.OverallProgressTracker.Parent = this.ProgressTracker;
other.progressUpdateLock?.ExitWriteLock();
}
/// <summary>
/// Gets or sets the transfer context of this transfer.
/// </summary>
public override TransferContext Context
{
get
{
return this.dirTransferContext;
}
set
{
DirectoryTransferContext tempValue = value as DirectoryTransferContext;
if (tempValue == null)
{
throw new ArgumentException("Requires a DirectoryTransferContext instance", "value");
}
this.dirTransferContext = tempValue;
}
}
/// <summary>
/// Gets the directory transfer context of this transfer.
/// </summary>
public DirectoryTransferContext DirectoryContext
{
get
{
return this.dirTransferContext;
}
}
/// <summary>
/// Gets or sets the transfer enumerator for source location
/// </summary>
public ITransferEnumerator SourceEnumerator
{
get;
set;
}
/// <summary>
/// Gets or sets the maximum transfer concurrency
/// </summary>
public int MaxTransferConcurrency
{
get;
set;
}
#if BINARY_SERIALIZATION
/// <summary>
/// Serializes the object.
/// </summary>
/// <param name="info">Serialization info object.</param>
/// <param name="context">Streaming context.</param>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
// serialize enumerator
info.AddValue(ListContinuationTokenName, this.enumerateContinuationToken, typeof(SerializableListContinuationToken));
if (!(context.Context is StreamJournal))
{
// serialize sub transfers
info.AddValue(SubTransfersName, this.subTransfers, typeof(TransferCollection<SingleObjectTransfer>));
}
}
#endif // BINARY_SERIALIZATION
/// <summary>
/// Execute the transfer asynchronously.
/// </summary>
/// <param name="scheduler">Transfer scheduler</param>
/// <param name="cancellationToken">Token that can be used to cancel the transfer.</param>
/// <returns>A task representing the transfer operation.</returns>
public override async Task ExecuteAsync(TransferScheduler scheduler, CancellationToken cancellationToken)
{
this.ResetExecutionStatus();
this.Destination.Validate();
try
{
Task listTask = Task.Run(() => this.ListNewTransfers(cancellationToken));
await Task.Run(() => { this.EnumerateAndTransfer(scheduler, cancellationToken); });
await listTask;
}
finally
{
// wait for outstanding transfers to complete
await allTransfersCompleteSource.Task;
}
if (this.enumerateException != null)
{
throw this.enumerateException;
}
this.ProgressTracker.AddBytesTransferred(0);
}
protected abstract SingleObjectTransfer CreateTransfer(TransferEntry entry);
protected abstract void UpdateTransfer(Transfer transfer);
protected abstract void CreateParentDirectory(SingleObjectTransfer transfer);
protected override void Dispose(bool disposing)
{
if (disposing)
{
SpinWait sw = new SpinWait();
while (Interlocked.Read(ref this.outstandingTasks) != 0)
{
sw.SpinOnce();
}
if (this.enumerationResetEvent != null)
{
this.enumerationResetEvent.Dispose();
this.enumerationResetEvent = null;
}
if (this.shouldTransferQueue != null)
{
this.shouldTransferQueue.Dispose();
this.shouldTransferQueue = null;
}
if (null != this.progressUpdateLock)
{
this.progressUpdateLock.Dispose();
this.progressUpdateLock = null;
}
}
base.Dispose(disposing);
}
private void ListNewTransfers(CancellationToken cancellationToken)
{
// list new transfers
if (this.enumerateContinuationToken != null)
{
this.SourceEnumerator.EnumerateContinuationToken = this.enumerateContinuationToken.ListContinuationToken;
}
ShouldTransferCallback shouldTransferCallback = this.DirectoryContext?.ShouldTransferCallback;
try
{
var enumerator = this.SourceEnumerator.EnumerateLocation(cancellationToken).GetEnumerator();
while (true)
{
Utils.CheckCancellation(cancellationToken);
if (!enumerator.MoveNext())
{
break;
}
TransferEntry entry = enumerator.Current;
ErrorEntry errorEntry = entry as ErrorEntry;
if (errorEntry != null)
{
TransferException exception = errorEntry.Exception as TransferException;
if (null != exception)
{
throw exception;
}
else
{
throw new TransferException(
TransferErrorCode.FailToEnumerateDirectory,
errorEntry.Exception.GetExceptionMessage(),
errorEntry.Exception);
}
}
this.shouldTransferQueue.EnqueueJob(() =>
{
SingleObjectTransfer candidate = this.CreateTransfer(entry);
bool shouldTransfer = shouldTransferCallback == null || shouldTransferCallback(candidate.Source.Instance, candidate.Destination.Instance);
return new Tuple<SingleObjectTransfer, TransferEntry>(shouldTransfer ? candidate : null, entry);
});
}
}
finally
{
this.shouldTransferQueue.CompleteAdding();
}
}
private IEnumerable<SingleObjectTransfer> AllTransfers(CancellationToken cancellationToken)
{
if (null == this.Journal)
{
// return all existing transfers in subTransfers
foreach (var transfer in this.subTransfers.GetEnumerator())
{
Utils.CheckCancellation(cancellationToken);
transfer.Context = this.Context;
this.UpdateTransfer(transfer);
yield return transfer as SingleObjectTransfer;
}
}
else
{
foreach (var transfer in this.Journal.ListSubTransfers())
{
Utils.CheckCancellation(cancellationToken);
transfer.Context = this.Context;
this.UpdateTransfer(transfer);
this.subTransfers.AddTransfer(transfer, false);
yield return transfer;
}
}
while (true)
{
Utils.CheckCancellation(cancellationToken);
Tuple<SingleObjectTransfer, TransferEntry> pair;
try
{
pair = this.shouldTransferQueue.DequeueResult();
}
catch (InvalidOperationException)
{
// Task queue is empty and CompleteAdding. No more transfer to dequeue.
break;
}
catch (AggregateException aggregateException)
{
// Unwrap the AggregateException.
ExceptionDispatchInfo.Capture(aggregateException.Flatten().InnerExceptions[0]).Throw();
break;
}
SingleObjectTransfer transfer = pair.Item1;
TransferEntry entry = pair.Item2;
lock (this.lockEnumerateContinuationToken)
{
if (null != transfer)
{
this.subTransfers.AddTransfer(transfer);
}
this.enumerateContinuationToken = new SerializableListContinuationToken(entry.ContinuationToken);
}
if (null != transfer)
{
this.Journal?.AddSubtransfer(transfer);
}
this.Journal?.UpdateJournalItem(this);
if (null == transfer)
{
continue;
}
try
{
this.CreateParentDirectory(transfer);
}
catch (Exception ex)
{
transfer.OnTransferFailed(ex);
// Don't keep failed transfers in memory if they can be persisted to a journal.
if (null != this.Journal)
{
this.subTransfers.RemoveTransfer(transfer);
}
continue;
}
#if DEBUG
FaultInjectionPoint fip = new FaultInjectionPoint(FaultInjectionPoint.FIP_ThrowExceptionAfterEnumerated);
string fiValue;
string filePath = entry.RelativePath;
CloudBlob sourceBlob = transfer.Source.Instance as CloudBlob;
if (sourceBlob != null && sourceBlob.IsSnapshot)
{
filePath = Utils.AppendSnapShotTimeToFileName(filePath, sourceBlob.SnapshotTime);
}
if (fip.TryGetValue(out fiValue)
&& string.Equals(fiValue, filePath, StringComparison.OrdinalIgnoreCase))
{
throw new TransferException(TransferErrorCode.Unknown, "test exception thrown because of ThrowExceptionAfterEnumerated is enabled", null);
}
#endif
yield return transfer;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Needed to ensure exceptions are not thrown on threadpool threads.")]
private void EnumerateAndTransfer(TransferScheduler scheduler, CancellationToken cancellationToken)
{
Interlocked.Increment(ref this.outstandingTasks);
try
{
foreach (var transfer in this.AllTransfers(cancellationToken))
{
this.CheckAndPauseEnumeration(cancellationToken);
transfer.UpdateProgressLock(this.progressUpdateLock);
this.DoTransfer(transfer, scheduler, cancellationToken);
}
}
catch(StorageException e)
{
throw new TransferException(TransferErrorCode.FailToEnumerateDirectory, e.GetExceptionMessage(), e);
}
finally
{
if (Interlocked.Decrement(ref this.outstandingTasks) == 0)
{
// make sure transfer terminiate when there is no subtransfer.
this.allTransfersCompleteSource.SetResult(null);
}
}
}
private void CheckAndPauseEnumeration(CancellationToken cancellationToken)
{
// -1 because there's one outstanding task for list while this method is called.
if ((this.outstandingTasks - 1) > this.MaxTransferConcurrency)
{
while (!this.enumerationResetEvent.WaitOne(EnumerationWaitTimeOut)
&& !cancellationToken.IsCancellationRequested)
{
}
}
}
private void ResetExecutionStatus()
{
if (this.enumerationResetEvent != null)
{
this.enumerationResetEvent.Dispose();
}
this.enumerationResetEvent = new AutoResetEvent(true);
this.enumerateException = null;
this.allTransfersCompleteSource = new TaskCompletionSource<object>();
this.outstandingTasks = 0;
}
private async void DoTransfer(Transfer transfer, TransferScheduler scheduler, CancellationToken cancellationToken)
{
using (transfer)
{
bool hasError = false;
Interlocked.Increment(ref this.outstandingTasks);
try
{
await transfer.ExecuteAsync(scheduler, cancellationToken);
}
catch
{
// catch exception thrown from sub-transfer as it's already recorded
hasError = true;
}
finally
{
// Don't keep the failed transferring in memory, if the checkpoint is persist to a streamed journal,
// instead, should only keep them in the streamed journal.
if ((!hasError)
|| (null != this.Journal))
{
this.subTransfers.RemoveTransfer(transfer);
}
this.enumerationResetEvent.Set();
if (Interlocked.Decrement(ref this.outstandingTasks) == 0)
{
// all transfers are done
this.allTransfersCompleteSource.SetResult(null);
}
}
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Proxy.InfoPath
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/*
* 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.Xml.Serialization;
using System.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework
{
[Flags]
public enum AssetFlags : int
{
Normal = 0, // Immutable asset
Maptile = 1, // What it says
Rewritable = 2, // Content can be rewritten
Collectable = 4 // Can be GC'ed after some time
}
/// <summary>
/// Asset class. All Assets are reference by this class or a class derived from this class
/// </summary>
[Serializable]
public class AssetBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static readonly int MAX_ASSET_NAME = 64;
public static readonly int MAX_ASSET_DESC = 64;
/// <summary>
/// Data of the Asset
/// </summary>
private byte[] m_data;
/// <summary>
/// Meta Data of the Asset
/// </summary>
private AssetMetadata m_metadata;
// This is needed for .NET serialization!!!
// Do NOT "Optimize" away!
public AssetBase()
{
m_metadata = new AssetMetadata();
m_metadata.FullID = UUID.Zero;
m_metadata.ID = UUID.Zero.ToString();
m_metadata.Type = (sbyte)AssetType.Unknown;
m_metadata.CreatorID = String.Empty;
}
public AssetBase(UUID assetID, string name, sbyte assetType, string creatorID)
{
if (assetType == (sbyte)AssetType.Unknown)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}",
name, assetID, trace.ToString());
}
m_metadata = new AssetMetadata();
m_metadata.FullID = assetID;
m_metadata.Name = name;
m_metadata.Type = assetType;
m_metadata.CreatorID = creatorID;
}
public AssetBase(string assetID, string name, sbyte assetType, string creatorID)
{
if (assetType == (sbyte)AssetType.Unknown)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}",
name, assetID, trace.ToString());
}
m_metadata = new AssetMetadata();
m_metadata.ID = assetID;
m_metadata.Name = name;
m_metadata.Type = assetType;
m_metadata.CreatorID = creatorID;
}
public bool ContainsReferences
{
get
{
return
IsTextualAsset && (
Type != (sbyte)AssetType.Notecard
&& Type != (sbyte)AssetType.CallingCard
&& Type != (sbyte)AssetType.LSLText
&& Type != (sbyte)AssetType.Landmark);
}
}
public bool IsTextualAsset
{
get
{
return !IsBinaryAsset;
}
}
/// <summary>
/// Checks if this asset is a binary or text asset
/// </summary>
public bool IsBinaryAsset
{
get
{
return
(Type == (sbyte) AssetType.Animation ||
Type == (sbyte)AssetType.Gesture ||
Type == (sbyte)AssetType.Simstate ||
Type == (sbyte)AssetType.Unknown ||
Type == (sbyte)AssetType.Object ||
Type == (sbyte)AssetType.Sound ||
Type == (sbyte)AssetType.SoundWAV ||
Type == (sbyte)AssetType.Texture ||
Type == (sbyte)AssetType.TextureTGA ||
Type == (sbyte)AssetType.Folder ||
Type == (sbyte)AssetType.RootFolder ||
Type == (sbyte)AssetType.LostAndFoundFolder ||
Type == (sbyte)AssetType.SnapshotFolder ||
Type == (sbyte)AssetType.TrashFolder ||
Type == (sbyte)AssetType.ImageJPEG ||
Type == (sbyte) AssetType.ImageTGA ||
Type == (sbyte) AssetType.LSLBytecode);
}
}
public virtual byte[] Data
{
get { return m_data; }
set { m_data = value; }
}
/// <summary>
/// Asset UUID
/// </summary>
public UUID FullID
{
get { return m_metadata.FullID; }
set { m_metadata.FullID = value; }
}
/// <summary>
/// Asset MetaData ID (transferring from UUID to string ID)
/// </summary>
public string ID
{
get { return m_metadata.ID; }
set { m_metadata.ID = value; }
}
public string Name
{
get { return m_metadata.Name; }
set { m_metadata.Name = value; }
}
public string Description
{
get { return m_metadata.Description; }
set { m_metadata.Description = value; }
}
/// <summary>
/// (sbyte) AssetType enum
/// </summary>
public sbyte Type
{
get { return m_metadata.Type; }
set { m_metadata.Type = value; }
}
/// <summary>
/// Is this a region only asset, or does this exist on the asset server also
/// </summary>
public bool Local
{
get { return m_metadata.Local; }
set { m_metadata.Local = value; }
}
/// <summary>
/// Is this asset going to be saved to the asset database?
/// </summary>
public bool Temporary
{
get { return m_metadata.Temporary; }
set { m_metadata.Temporary = value; }
}
public string CreatorID
{
get { return m_metadata.CreatorID; }
set { m_metadata.CreatorID = value; }
}
public AssetFlags Flags
{
get { return m_metadata.Flags; }
set { m_metadata.Flags = value; }
}
[XmlIgnore]
public AssetMetadata Metadata
{
get { return m_metadata; }
set { m_metadata = value; }
}
public override string ToString()
{
return FullID.ToString();
}
}
[Serializable]
public class AssetMetadata
{
private UUID m_fullid;
private string m_id;
private string m_name = String.Empty;
private string m_description = String.Empty;
private DateTime m_creation_date;
private sbyte m_type = (sbyte)AssetType.Unknown;
private string m_content_type;
private byte[] m_sha1;
private bool m_local;
private bool m_temporary;
private string m_creatorid;
private AssetFlags m_flags;
public UUID FullID
{
get { return m_fullid; }
set { m_fullid = value; m_id = m_fullid.ToString(); }
}
public string ID
{
//get { return m_fullid.ToString(); }
//set { m_fullid = new UUID(value); }
get
{
if (String.IsNullOrEmpty(m_id))
m_id = m_fullid.ToString();
return m_id;
}
set
{
UUID uuid = UUID.Zero;
if (UUID.TryParse(value, out uuid))
{
m_fullid = uuid;
m_id = m_fullid.ToString();
}
else
m_id = value;
}
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public string Description
{
get { return m_description; }
set { m_description = value; }
}
public DateTime CreationDate
{
get { return m_creation_date; }
set { m_creation_date = value; }
}
public sbyte Type
{
get { return m_type; }
set { m_type = value; }
}
public string ContentType
{
get
{
if (!String.IsNullOrEmpty(m_content_type))
return m_content_type;
else
return SLUtil.SLAssetTypeToContentType(m_type);
}
set
{
m_content_type = value;
sbyte type = (sbyte)SLUtil.ContentTypeToSLAssetType(value);
if (type != -1)
m_type = type;
}
}
public byte[] SHA1
{
get { return m_sha1; }
set { m_sha1 = value; }
}
public bool Local
{
get { return m_local; }
set { m_local = value; }
}
public bool Temporary
{
get { return m_temporary; }
set { m_temporary = value; }
}
public string CreatorID
{
get { return m_creatorid; }
set { m_creatorid = value; }
}
public AssetFlags Flags
{
get { return m_flags; }
set { m_flags = value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
using NuGet.Resources;
namespace NuGet
{
public class InstallWalker : PackageWalker, IPackageOperationResolver
{
private readonly bool _ignoreDependencies;
private bool _allowPrereleaseVersions;
private readonly OperationLookup _operations;
private bool _isDowngrade;
// This acts as a "retainment" queue. It contains packages that are already installed but need to be kept during
// a package walk. This is to prevent those from being uninstalled in subsequent encounters.
private readonly HashSet<IPackage> _packagesToKeep = new HashSet<IPackage>(PackageEqualityComparer.IdAndVersion);
private IDictionary<string, IList<IPackage>> _packagesByDependencyOrder;
// this ctor is used for unit tests
internal InstallWalker(IPackageRepository localRepository,
IPackageRepository sourceRepository,
ILogger logger,
bool ignoreDependencies,
bool allowPrereleaseVersions,
DependencyVersion dependencyVersion)
: this(localRepository, sourceRepository, null, logger, ignoreDependencies, allowPrereleaseVersions, dependencyVersion)
{
}
public InstallWalker(IPackageRepository localRepository,
IPackageRepository sourceRepository,
FrameworkName targetFramework,
ILogger logger,
bool ignoreDependencies,
bool allowPrereleaseVersions,
DependencyVersion dependencyVersion) :
this(localRepository,
sourceRepository,
constraintProvider: NullConstraintProvider.Instance,
targetFramework: targetFramework,
logger: logger,
ignoreDependencies: ignoreDependencies,
allowPrereleaseVersions: allowPrereleaseVersions,
dependencyVersion: dependencyVersion)
{
}
public InstallWalker(IPackageRepository localRepository,
IPackageRepository sourceRepository,
IPackageConstraintProvider constraintProvider,
FrameworkName targetFramework,
ILogger logger,
bool ignoreDependencies,
bool allowPrereleaseVersions,
DependencyVersion dependencyVersion)
: base(targetFramework)
{
if (sourceRepository == null)
{
throw new ArgumentNullException("sourceRepository");
}
if (localRepository == null)
{
throw new ArgumentNullException("localRepository");
}
if (logger == null)
{
throw new ArgumentNullException("logger");
}
Repository = localRepository;
Logger = logger;
SourceRepository = sourceRepository;
_ignoreDependencies = ignoreDependencies;
ConstraintProvider = constraintProvider;
_operations = new OperationLookup();
_allowPrereleaseVersions = allowPrereleaseVersions;
DependencyVersion = dependencyVersion;
CheckDowngrade = true;
}
internal bool DisableWalkInfo
{
get;
set;
}
/// <summary>
/// Indicates if this object checks the downgrade case.
/// </summary>
/// <remarks>
/// Currently there is a concurrent issue: if there are multiple "nuget.exe install" running
/// concurrently, then checking local repository for existing packages to see
/// if current install is downgrade can generate file in use exception.
/// This property is a temporary workaround: it is set to false when
/// this object is called by "nuget.exe install/restore".
/// </remarks>
internal bool CheckDowngrade
{
get;
set;
}
protected override bool IgnoreWalkInfo
{
get
{
return DisableWalkInfo ? true : base.IgnoreWalkInfo;
}
}
protected ILogger Logger
{
get;
private set;
}
protected IPackageRepository Repository
{
get;
private set;
}
protected override bool IgnoreDependencies
{
get
{
return _ignoreDependencies;
}
}
protected override bool AllowPrereleaseVersions
{
get
{
return _allowPrereleaseVersions;
}
}
public bool AllowDowngradeFromPrerelease { get; set; }
protected IPackageRepository SourceRepository
{
get;
private set;
}
private IPackageConstraintProvider ConstraintProvider { get; set; }
protected IList<PackageOperation> Operations
{
get
{
return _operations.ToList();
}
}
protected virtual ConflictResult GetConflict(IPackage package)
{
var conflictingPackage = Marker.FindPackage(package.Id);
if (conflictingPackage != null)
{
return new ConflictResult(conflictingPackage, Marker, Marker);
}
return null;
}
protected override void OnBeforePackageWalk(IPackage package)
{
ConflictResult conflictResult = GetConflict(package);
if (conflictResult == null)
{
return;
}
// If the conflicting package is the same as the package being installed
// then no-op
if (PackageEqualityComparer.IdAndVersion.Equals(package, conflictResult.Package))
{
return;
}
// First we get a list of dependents for the installed package.
// Then we find the dependency in the foreach dependent that this installed package used to satisfy.
// We then check if the resolved package also meets that dependency and if it doesn't it's added to the list
// i.e. A1 -> C >= 1
// B1 -> C >= 1
// C2 -> []
// Given the above graph, if we upgrade from C1 to C2, we need to see if A and B can work with the new C
IEnumerable<IPackage> incompatiblePackages =
GetDependents(conflictResult)
.Select(
dependentPackage =>
new {dependentPackage, dependency = dependentPackage.FindDependency(package.Id, TargetFramework)})
.Where(t => t.dependency != null && !t.dependency.VersionSpec.Satisfies(package.Version))
.Select(t => t.dependentPackage).ToArray();
// If there were incompatible packages that we failed to update then we throw an exception
if (incompatiblePackages.Any() && !TryUpdate(incompatiblePackages, conflictResult, package, out incompatiblePackages))
{
throw CreatePackageConflictException(package, conflictResult.Package, incompatiblePackages);
}
else
{
if (!_isDowngrade && (package.Version < conflictResult.Package.Version))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
NuGetResources.NewerVersionAlreadyReferenced, package.Id));
}
Uninstall(conflictResult.Package, conflictResult.DependentsResolver, conflictResult.Repository);
}
}
private void Uninstall(IPackage package, IDependentsResolver dependentsResolver, IPackageRepository repository)
{
// If we explicitly want to uninstall this package, then remove it from the retainment queue.
_packagesToKeep.Remove(package);
// If this package isn't part of the current graph (i.e. hasn't been visited yet) and
// is marked for removal, then do nothing. This is so we don't get unnecessary duplicates.
if (!Marker.Contains(package) && _operations.Contains(package, PackageAction.Uninstall))
{
return;
}
// Uninstall the conflicting package. We set throw on conflicts to false since we've
// already decided that there were no conflicts based on the above code.
var resolver = new UninstallWalker(
repository,
dependentsResolver,
TargetFramework,
NullLogger.Instance,
removeDependencies: !IgnoreDependencies,
forceRemove: false)
{
DisableWalkInfo = this.DisableWalkInfo,
ThrowOnConflicts = false
};
foreach (var operation in resolver.ResolveOperations(package))
{
// If the operation is Uninstall, we don't want to uninstall the package if it is in the "retainment" queue.
if (operation.Action == PackageAction.Install || !_packagesToKeep.Contains(operation.Package))
{
_operations.AddOperation(operation);
}
}
}
private IPackage SelectDependency(IEnumerable<IPackage> dependencies)
{
return dependencies.SelectDependency(DependencyVersion);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We re-throw a more specific exception later on")]
private bool TryUpdate(IEnumerable<IPackage> dependents, ConflictResult conflictResult, IPackage package, out IEnumerable<IPackage> incompatiblePackages)
{
// Key dependents by id so we can look up the old package later
var dependentsLookup = dependents.ToDictionary(d => d.Id, StringComparer.OrdinalIgnoreCase);
var compatiblePackages = new Dictionary<IPackage, IPackage>();
// Initialize each compatible package to null
foreach (var dependent in dependents)
{
compatiblePackages[dependent] = null;
}
// Get compatible packages in one batch so we don't have to make requests for each one
var packages =
SourceRepository.FindCompatiblePackages(ConstraintProvider, dependentsLookup.Keys, package, TargetFramework,AllowPrereleaseVersions)
.GroupBy(p => p.Id)
.Select(g => new {g, oldPackage = dependentsLookup[g.Key]})
.Select(t =>
{
IEnumerable<IPackage> candidates = t.g.Where(
p => (p.Version > t.oldPackage.Version ))
.OrderBy(p => p.Version);
if (!AllowPrereleaseVersions && !t.oldPackage.IsReleaseVersion() && !candidates.Any() && AllowDowngradeFromPrerelease)
//changing from prerelease back to release and there are no candidates
{
candidates=t.g.OrderByDescending(p => p.Version).Take(1);//only latest version.
}
return new
{
OldPackage = t.oldPackage,
NewPackage =
SelectDependency(candidates)
};
});
foreach (var p in packages)
{
compatiblePackages[p.OldPackage] = p.NewPackage;
}
// Get all packages that have an incompatibility with the specified package i.e.
// We couldn't find a version in the repository that works with the specified package.
incompatiblePackages = compatiblePackages.Where(p => p.Value == null)
.Select(p => p.Key);
if (incompatiblePackages.Any())
{
return false;
}
IPackageConstraintProvider currentConstraintProvider = ConstraintProvider;
try
{
// Add a constraint for the incoming package so we don't try to update it by mistake.
// Scenario:
// A 1.0 -> B [1.0]
// B 1.0.1, B 1.5, B 2.0
// A 2.0 -> B (any version)
// We have A 1.0 and B 1.0 installed. When trying to update to B 1.0.1, we'll end up trying
// to find a version of A that works with B 1.0.1. The version in the above case is A 2.0.
// When we go to install A 2.0 we need to make sure that when we resolve it's dependencies that we stay within bounds
// i.e. when we resolve B for A 2.0 we want to keep the B 1.0.1 we've already chosen instead of trying to grab
// B 1.5 or B 2.0. In order to achieve this, we add a constraint for version of B 1.0.1 so we stay within those bounds for B.
// Respect all existing constraints plus an additional one that we specify based on the incoming package
var constraintProvider = new DefaultConstraintProvider();
constraintProvider.AddConstraint(package.Id, new VersionSpec(package.Version));
ConstraintProvider = new AggregateConstraintProvider(ConstraintProvider, constraintProvider);
// Mark the incoming package as visited so that we don't try walking the graph again
Marker.MarkVisited(package);
var failedPackages = new List<IPackage>();
// Update each of the existing packages to more compatible one
foreach (var pair in compatiblePackages)
{
try
{
//
// BUGBUG: What if the new package required license acceptance but the new dependency package did not?!
// When a dependency package that does not require license acceptance, like jQuery 1.7.1.1,
// is being updated to a version incompatible with its dependents, like jQuery 2.0.3 and its dependent Microsoft.jQuery.Unobtrusive.Ajax 2.0.20710.0
// Then, the dependent package is updated such that the new dependent package is compatible with the new dependency package
// In the example above, Microsoft.jQuery.Unobtrusive.Ajax 2.0.20710.0 will be updated to 2.0.30506.0. 2.0.30506.0 requires license acceptance
// But, the update happens anyways, just because, the user chose to update jQuery
//
// Remove the old package
Uninstall(pair.Key, conflictResult.DependentsResolver, conflictResult.Repository);
// Install the new package
Walk(pair.Value);
}
catch
{
// If we failed to update this package (most likely because of a conflict further up the dependency chain)
// we keep track of it so we can report an error about the top level package.
failedPackages.Add(pair.Key);
}
}
incompatiblePackages = failedPackages;
return !incompatiblePackages.Any();
}
finally
{
// Restore the current constraint provider
ConstraintProvider = currentConstraintProvider;
// Mark the package as processing again
Marker.MarkProcessing(package);
}
}
protected override void OnAfterPackageWalk(IPackage package)
{
if (!Repository.Exists(package))
{
// Don't add the package for installation if it already exists in the repository
_operations.AddOperation(new PackageOperation(package, PackageAction.Install));
}
else
{
// If we already added an entry for removing this package then remove it
// (it's equivalent for doing +P since we're removing a -P from the list)
_operations.RemoveOperation(package, PackageAction.Uninstall);
// and mark the package as being "retained".
_packagesToKeep.Add(package);
}
if (_packagesByDependencyOrder != null)
{
IList<IPackage> packages;
if (!_packagesByDependencyOrder.TryGetValue(package.Id, out packages))
{
_packagesByDependencyOrder[package.Id] = packages = new List<IPackage>();
}
packages.Add(package);
}
}
protected override IPackage ResolveDependency(PackageDependency dependency)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_AttemptingToRetrievePackageFromSource, dependency);
// First try to get a local copy of the package
// Bug1638: Include prereleases when resolving locally installed dependencies.
//Prerelease is included when we try to look at the local repository.
//In case of downgrade, we are going to look only at source repo and not local.
//That way we will downgrade dependencies when parent package is downgraded.
if (!_isDowngrade)
{
IPackage package = Repository.ResolveDependency(dependency, ConstraintProvider, allowPrereleaseVersions: true, preferListedPackages: false, dependencyVersion: DependencyVersion);
if (package != null)
{
return package;
}
}
// Next, query the source repo for the same dependency
IPackage sourcePackage = SourceRepository.ResolveDependency(dependency, ConstraintProvider, AllowPrereleaseVersions, preferListedPackages: true, dependencyVersion: DependencyVersion);
return sourcePackage;
}
protected override void OnDependencyResolveError(IPackage package, PackageDependency dependency)
{
IVersionSpec spec = ConstraintProvider.GetConstraint(dependency.Id);
string message = String.Empty;
if (spec != null)
{
message = String.Format(CultureInfo.CurrentCulture, NuGetResources.AdditonalConstraintsDefined, dependency.Id, VersionUtility.PrettyPrint(spec), ConstraintProvider.Source);
}
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,package+" : "+
NuGetResources.UnableToResolveDependency + message, dependency));
}
public IEnumerable<PackageOperation> ResolveOperations(IPackage package)
{
// The cases when we don't check downgrade is when this object is
// called to restore packages, e.g. by nuget.exe restore command.
// Otherwise, check downgrade is true, e.g. when user installs a package
// inside VS.
if (CheckDowngrade)
{
//Check if the package is installed. This is necessary to know if this is a fresh-install or a downgrade operation
IPackage packageUnderInstallation = Repository.FindPackage(package.Id);
if (packageUnderInstallation != null && packageUnderInstallation.Version > package.Version)
{
_isDowngrade = true;
}
}
else
{
_isDowngrade = false;
}
_operations.Clear();
Marker.Clear();
_packagesToKeep.Clear();
Walk(package);
return Operations.Reduce();
}
/// <summary>
/// Resolve operations for a list of packages clearing the package marker only once at the beginning. When the packages are interdependent, this method performs efficiently
/// Also, sets the packagesByDependencyOrder to the input packages, but in dependency order
/// NOTE: If package A 1.0 depends on package B 1.0 and A 2.0 does not depend on B 2.0; and, A 2.0 and B 2.0 are the input packages (likely from the updates tab in dialog)
/// then, the packagesbyDependencyOrder will have A followed by B. Since, A 2.0 does not depend on B 2.0. This is also true because GetConflict in this class
/// would only the PackageMarker and not the installed packages for information
/// </summary>
/// <param name="packages">The list of packages to resolve operations for. If from the dialog node, the list may be sorted, mostly, alphabetically</param>
/// <param name="packagesByDependencyOrder">Same set of packages returned in the dependency order</param>
/// <param name="allowPrereleaseVersionsBasedOnPackage">If true, allowPrereleaseVersion is determined based on package before walking that package. Otherwise, existing value is used</param>
/// <returns>
/// Returns a list of Package Operations to be performed for the installation of the packages passed
/// Also, the out parameter packagesByDependencyOrder would returned the packages passed in the dependency order
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "In addition to operations, need to return packagesByDependencyOrder.")]
public IList<PackageOperation> ResolveOperations(IEnumerable<IPackage> packages, out IList<IPackage> packagesByDependencyOrder, bool allowPrereleaseVersionsBasedOnPackage = false)
{
_packagesByDependencyOrder = new Dictionary<string, IList<IPackage>>();
_operations.Clear();
Marker.Clear();
_packagesToKeep.Clear();
Debug.Assert(Operations is List<PackageOperation>);
foreach (var package in packages)
{
if (!_operations.Contains(package, PackageAction.Install))
{
var allowPrereleaseVersions = _allowPrereleaseVersions;
try
{
if (allowPrereleaseVersionsBasedOnPackage)
{
// Update _allowPrereleaseVersions before walking a package if allowPrereleaseVersionsBasedOnPackage is set to true
// This is mainly used when bulk resolving operations for reinstalling packages
_allowPrereleaseVersions = _allowPrereleaseVersions || !package.IsReleaseVersion();
}
Walk(package);
}
finally
{
_allowPrereleaseVersions = allowPrereleaseVersions;
}
}
}
// Flatten the dictionary to create a list of all the packages. Only this item the packages visited first during the walk will appear on the list. Also, only retain distinct elements
IEnumerable<IPackage> allPackagesByDependencyOrder = _packagesByDependencyOrder.SelectMany(p => p.Value).Distinct();
// Only retain the packages for which the operations are being resolved for
packagesByDependencyOrder = allPackagesByDependencyOrder.Where(p => packages.Any(q => p.Id == q.Id && p.Version == q.Version)).ToList();
Debug.Assert(packagesByDependencyOrder.Count == packages.Count());
_packagesByDependencyOrder.Clear();
_packagesByDependencyOrder = null;
return Operations.Reduce();
}
private IEnumerable<IPackage> GetDependents(ConflictResult conflict)
{
// Skip all dependents that are marked for uninstall
IEnumerable<IPackage> packages = _operations.GetPackages(PackageAction.Uninstall);
return conflict.DependentsResolver.GetDependents(conflict.Package)
.Except<IPackage>(packages, PackageEqualityComparer.IdAndVersion);
}
private static InvalidOperationException CreatePackageConflictException(IPackage resolvedPackage, IPackage package, IEnumerable<IPackage> dependents)
{
if (dependents.Count() == 1)
{
return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
NuGetResources.ConflictErrorWithDependent, package.GetFullName(), resolvedPackage.GetFullName(), dependents.Single().Id));
}
return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
NuGetResources.ConflictErrorWithDependents, package.GetFullName(), resolvedPackage.GetFullName(), String.Join(", ",
dependents.Select(d => d.Id))));
}
/// <summary>
/// Operation lookup encapsulates an operation list and another efficient data structure for finding package operations
/// by package id, version and PackageAction.
/// </summary>
private class OperationLookup
{
private readonly List<PackageOperation> _operations = new List<PackageOperation>();
private readonly Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>> _operationLookup = new Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>>();
internal void Clear()
{
_operations.Clear();
_operationLookup.Clear();
}
internal IList<PackageOperation> ToList()
{
return _operations;
}
internal IEnumerable<IPackage> GetPackages(PackageAction action)
{
Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action);
if (dictionary != null)
{
return dictionary.Keys;
}
return Enumerable.Empty<IPackage>();
}
internal void AddOperation(PackageOperation operation)
{
Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(operation.Action, createIfNotExists: true);
if (!dictionary.ContainsKey(operation.Package))
{
dictionary.Add(operation.Package, operation);
_operations.Add(operation);
}
}
internal void RemoveOperation(IPackage package, PackageAction action)
{
Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action);
PackageOperation operation;
if (dictionary != null && dictionary.TryGetValue(package, out operation))
{
dictionary.Remove(package);
_operations.Remove(operation);
}
}
internal bool Contains(IPackage package, PackageAction action)
{
Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action);
return dictionary != null && dictionary.ContainsKey(package);
}
private Dictionary<IPackage, PackageOperation> GetPackageLookup(PackageAction action, bool createIfNotExists = false)
{
Dictionary<IPackage, PackageOperation> packages;
if (!_operationLookup.TryGetValue(action, out packages) && createIfNotExists)
{
packages = new Dictionary<IPackage, PackageOperation>(PackageEqualityComparer.IdAndVersion);
_operationLookup.Add(action, packages);
}
return packages;
}
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="PhotonView.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
//
// </summary>
// <author>[email protected]</author>
// ----------------------------------------------------------------------------
using System;
using UnityEngine;
using System.Reflection;
using System.Collections.Generic;
using ExitGames.Client.Photon;
#if UNITY_EDITOR
using UnityEditor;
#endif
public enum ViewSynchronization { Off, ReliableDeltaCompressed, Unreliable, UnreliableOnChange }
public enum OnSerializeTransform { OnlyPosition, OnlyRotation, OnlyScale, PositionAndRotation, All }
public enum OnSerializeRigidBody { OnlyVelocity, OnlyAngularVelocity, All }
/// <summary>
/// Options to define how Ownership Transfer is handled per PhotonView.
/// </summary>
/// <remarks>
/// This setting affects how RequestOwnership and TransferOwnership work at runtime.
/// </remarks>
public enum OwnershipOption
{
/// <summary>
/// Ownership is fixed. Instantiated objects stick with their creator, scene objects always belong to the Master Client.
/// </summary>
Fixed,
/// <summary>
/// Ownership can be taken away from the current owner who can't object.
/// </summary>
Takeover,
/// <summary>
/// Ownership can be requested with PhotonView.RequestOwnership but the current owner has to agree to give up ownership.
/// </summary>
/// <remarks>The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.</remarks>
Request
}
/// <summary>
/// PUN's NetworkView replacement class for networking. Use it like a NetworkView.
/// </summary>
/// \ingroup publicApi
[AddComponentMenu("Photon Networking/Photon View &v")]
public class PhotonView : Photon.MonoBehaviour
{
#if UNITY_EDITOR
[ContextMenu("Open PUN Wizard")]
void OpenPunWizard()
{
EditorApplication.ExecuteMenuItem("Window/Photon Unity Networking");
}
#endif
public int ownerId;
public int group = 0;
protected internal bool mixedModeIsReliable = false;
// NOTE: this is now an integer because unity won't serialize short (needed for instantiation). we SEND only a short though!
// NOTE: prefabs have a prefixBackup of -1. this is replaced with any currentLevelPrefix that's used at runtime. instantiated GOs get their prefix set pre-instantiation (so those are not -1 anymore)
public int prefix
{
get
{
if (this.prefixBackup == -1 && PhotonNetwork.networkingPeer != null)
{
this.prefixBackup = PhotonNetwork.networkingPeer.currentLevelPrefix;
}
return this.prefixBackup;
}
set { this.prefixBackup = value; }
}
// this field is serialized by unity. that means it is copied when instantiating a persistent obj into the scene
public int prefixBackup = -1;
/// <summary>
/// This is the instantiationData that was passed when calling PhotonNetwork.Instantiate* (if that was used to spawn this prefab)
/// </summary>
public object[] instantiationData
{
get
{
if (!this.didAwake)
{
// even though viewID and instantiationID are setup before the GO goes live, this data can't be set. as workaround: fetch it if needed
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
return this.instantiationDataField;
}
set { this.instantiationDataField = value; }
}
internal object[] instantiationDataField;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataSent = null;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataReceived = null;
public Component observed;
public ViewSynchronization synchronization;
public OnSerializeTransform onSerializeTransformOption = OnSerializeTransform.PositionAndRotation;
public OnSerializeRigidBody onSerializeRigidBodyOption = OnSerializeRigidBody.All;
/// <summary>Defines if ownership of this PhotonView is fixed, can be requested or simply taken.</summary>
/// <remarks>
/// Note that you can't edit this value at runtime.
/// The options are described in enum OwnershipOption.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public OwnershipOption ownershipTransfer = OwnershipOption.Fixed;
public List<Component> ObservedComponents;
Dictionary<Component, MethodInfo> m_OnSerializeMethodInfos = new Dictionary<Component, MethodInfo>();
#if UNITY_EDITOR
// Suppressing compiler warning "this variable is never used". Only used in the CustomEditor, only in Editor
#pragma warning disable 0414
[SerializeField]
bool ObservedComponentsFoldoutOpen = true;
#pragma warning restore 0414
#endif
[SerializeField]
private int viewIdField = 0;
/// <summary>
/// The ID of the PhotonView. Identifies it in a networked game (per room).
/// </summary>
/// <remarks>See: [Network Instantiation](@ref instantiateManual)</remarks>
public int viewID
{
get { return this.viewIdField; }
set
{
// if ID was 0 for an awakened PhotonView, the view should add itself into the networkingPeer.photonViewList after setup
bool viewMustRegister = this.didAwake && this.viewIdField == 0;
// TODO: decide if a viewID can be changed once it wasn't 0. most likely that is not a good idea
// check if this view is in networkingPeer.photonViewList and UPDATE said list (so we don't keep the old viewID with a reference to this object)
// PhotonNetwork.networkingPeer.RemovePhotonView(this, true);
this.ownerId = value / PhotonNetwork.MAX_VIEW_IDS;
this.viewIdField = value;
if (viewMustRegister)
{
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
}
//Debug.Log("Set viewID: " + value + " -> owner: " + this.ownerId + " subId: " + this.subId);
}
}
public int instantiationId; // if the view was instantiated with a GO, this GO has a instantiationID (first view's viewID)
/// <summary>True if the PhotonView was loaded with the scene (game object) or instantiated with InstantiateSceneObject.</summary>
/// <remarks>
/// Scene objects are not owned by a particular player but belong to the scene. Thus they don't get destroyed when their
/// creator leaves the game and the current Master Client can control them (whoever that is).
/// The ownerId is 0 (player IDs are 1 and up).
/// </remarks>
public bool isSceneView
{
get { return this.CreatorActorNr == 0; }
}
/// <summary>
/// The owner of a PhotonView is the player who created the GameObject with that view. Objects in the scene don't have an owner.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
///
/// Ownership can be transferred to another player with PhotonView.TransferOwnership or any player can request
/// ownership by calling the PhotonView's RequestOwnership method.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public PhotonPlayer owner
{
get
{
return PhotonPlayer.Find(this.ownerId);
}
}
public int OwnerActorNr
{
get { return this.ownerId; }
}
public bool isOwnerActive
{
get { return this.ownerId != 0 && PhotonNetwork.networkingPeer.mActors.ContainsKey(this.ownerId); }
}
public int CreatorActorNr
{
get { return this.viewIdField / PhotonNetwork.MAX_VIEW_IDS; }
}
/// <summary>
/// True if the PhotonView is "mine" and can be controlled by this client.
/// </summary>
/// <remarks>
/// PUN has an ownership concept that defines who can control and destroy each PhotonView.
/// True in case the owner matches the local PhotonPlayer.
/// True if this is a scene photonview on the Master client.
/// </remarks>
public bool isMine
{
get
{
return (this.ownerId == PhotonNetwork.player.ID) || (!this.isOwnerActive && PhotonNetwork.isMasterClient);
}
}
protected internal bool didAwake;
[SerializeField]
protected internal bool isRuntimeInstantiated;
protected internal bool removedFromLocalViewList;
internal MonoBehaviour[] RpcMonoBehaviours;
private MethodInfo OnSerializeMethodInfo;
private bool failedToFindOnSerialize;
/// <summary>Called by Unity on start of the application and does a setup the PhotonView.</summary>
protected internal void Awake()
{
if (this.viewID != 0)
{
// registration might be too late when some script (on this GO) searches this view BUT GetPhotonView() can search ALL in that case
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
this.didAwake = true;
}
/// <summary>
/// Depending on the PhotonView's ownershipTransfer setting, any client can request to become owner of the PhotonView.
/// </summary>
/// <remarks>
/// Requesting ownership can give you control over a PhotonView, if the ownershipTransfer setting allows that.
/// The current owner might have to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
///
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void RequestOwnership()
{
PhotonNetwork.networkingPeer.RequestOwnership(this.viewID, this.ownerId);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(PhotonPlayer newOwner)
{
this.TransferOwnership(newOwner.ID);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(int newOwnerId)
{
PhotonNetwork.networkingPeer.TransferOwnership(this.viewID, newOwnerId);
this.ownerId = newOwnerId; // immediately switch ownership locally, to avoid more updates sent from this client.
}
protected internal void OnDestroy()
{
if (!this.removedFromLocalViewList)
{
bool wasInList = PhotonNetwork.networkingPeer.LocalCleanPhotonView(this);
bool loading = false;
#if !UNITY_5 || UNITY_5_0 || UNITY_5_1
loading = Application.isLoadingLevel;
#endif
if (wasInList && !loading && this.instantiationId > 0 && !PhotonHandler.AppQuits && PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
{
Debug.Log("PUN-instantiated '" + this.gameObject.name + "' got destroyed by engine. This is OK when loading levels. Otherwise use: PhotonNetwork.Destroy().");
}
}
}
public void SerializeView(PhotonStream stream, PhotonMessageInfo info)
{
SerializeComponent(this.observed, stream, info);
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
SerializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
public void DeserializeView(PhotonStream stream, PhotonMessageInfo info)
{
DeserializeComponent(this.observed, stream, info);
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
DeserializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
protected internal void DeserializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
// Use incoming data according to observed type
if (component is MonoBehaviour)
{
ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyPosition:
trans.localPosition = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyRotation:
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyScale:
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.PositionAndRotation:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector3) stream.ReceiveNext();
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector3) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector2) stream.ReceiveNext();
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector2) stream.ReceiveNext();
break;
}
}
else
{
Debug.LogError("Type of observed is unknown when receiving.");
}
}
protected internal void SerializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
if (component is MonoBehaviour)
{
ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.OnlyPosition:
stream.SendNext(trans.localPosition);
break;
case OnSerializeTransform.OnlyRotation:
stream.SendNext(trans.localRotation);
break;
case OnSerializeTransform.OnlyScale:
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.PositionAndRotation:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else
{
Debug.LogError("Observed type is not serializable: " + component.GetType());
}
}
protected internal void ExecuteComponentOnSerialize(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component != null)
{
MethodInfo method = null;
bool found = this.m_OnSerializeMethodInfos.TryGetValue(component, out method);
if (!found)
{
bool foundMethod = NetworkingPeer.GetMethod(component as MonoBehaviour, PhotonNetworkingMessage.OnPhotonSerializeView.ToString(), out method);
if (foundMethod == false)
{
Debug.LogError("The observed monobehaviour (" + component.name + ") of this PhotonView does not implement OnPhotonSerializeView()!");
method = null;
}
this.m_OnSerializeMethodInfos.Add(component, method);
}
if (method != null)
{
method.Invoke(component, new object[] {stream, info});
}
}
}
/// <summary>
/// Can be used to refesh the list of MonoBehaviours on this GameObject while PhotonNetwork.UseRpcMonoBehaviourCache is true.
/// </summary>
/// <remarks>
/// Set PhotonNetwork.UseRpcMonoBehaviourCache to true to enable the caching.
/// Uses this.GetComponents<MonoBehaviour>() to get a list of MonoBehaviours to call RPCs on (potentially).
///
/// While PhotonNetwork.UseRpcMonoBehaviourCache is false, this method has no effect,
/// because the list is refreshed when a RPC gets called.
/// </remarks>
public void RefreshRpcMonoBehaviourCache()
{
this.RpcMonoBehaviours = this.GetComponents<MonoBehaviour>();
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="target">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonTargets target, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="target">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonTargets target, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, encrypt, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonPlayer targetPlayer, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonPlayer targetPlayer, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, encrypt, parameters);
}
public static PhotonView Get(Component component)
{
return component.GetComponent<PhotonView>();
}
public static PhotonView Get(GameObject gameObj)
{
return gameObj.GetComponent<PhotonView>();
}
public static PhotonView Find(int viewID)
{
return PhotonNetwork.networkingPeer.GetPhotonView(viewID);
}
public override string ToString()
{
return string.Format("View ({3}){0} on {1} {2}", this.viewID, (this.gameObject != null) ? this.gameObject.name : "GO==null", (this.isSceneView) ? "(scene)" : string.Empty, this.prefix);
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.IO.Serialization.Converters;
using osu.Game.Online.Rooms.RoomStatuses;
using osu.Game.Users;
using osu.Game.Utils;
namespace osu.Game.Online.Rooms
{
public class Room : IDeepCloneable<Room>
{
[Cached]
[JsonProperty("id")]
public readonly Bindable<long?> RoomID = new Bindable<long?>();
[Cached]
[JsonProperty("name")]
public readonly Bindable<string> Name = new Bindable<string>();
[Cached]
[JsonProperty("host")]
public readonly Bindable<User> Host = new Bindable<User>();
[Cached]
[JsonProperty("playlist")]
public readonly BindableList<PlaylistItem> Playlist = new BindableList<PlaylistItem>();
[Cached]
[JsonProperty("channel_id")]
public readonly Bindable<int> ChannelId = new Bindable<int>();
[Cached]
[JsonIgnore]
public readonly Bindable<RoomCategory> Category = new Bindable<RoomCategory>();
// Todo: osu-framework bug (https://github.com/ppy/osu-framework/issues/4106)
[JsonProperty("category")]
[JsonConverter(typeof(SnakeCaseStringEnumConverter))]
private RoomCategory category
{
get => Category.Value;
set => Category.Value = value;
}
[Cached]
[JsonIgnore]
public readonly Bindable<int?> MaxAttempts = new Bindable<int?>();
[Cached]
[JsonIgnore]
public readonly Bindable<RoomStatus> Status = new Bindable<RoomStatus>(new RoomStatusOpen());
[Cached]
[JsonIgnore]
public readonly Bindable<RoomAvailability> Availability = new Bindable<RoomAvailability>();
[Cached]
[JsonIgnore]
public readonly Bindable<MatchType> Type = new Bindable<MatchType>();
// Todo: osu-framework bug (https://github.com/ppy/osu-framework/issues/4106)
[JsonConverter(typeof(SnakeCaseStringEnumConverter))]
[JsonProperty("type")]
private MatchType type
{
get => Type.Value;
set => Type.Value = value;
}
[Cached]
[JsonIgnore]
public readonly Bindable<int?> MaxParticipants = new Bindable<int?>();
[Cached]
[JsonProperty("current_user_score")]
public readonly Bindable<PlaylistAggregateScore> UserScore = new Bindable<PlaylistAggregateScore>();
[JsonProperty("has_password")]
public readonly BindableBool HasPassword = new BindableBool();
[Cached]
[JsonProperty("recent_participants")]
public readonly BindableList<User> RecentParticipants = new BindableList<User>();
[Cached]
[JsonProperty("participant_count")]
public readonly Bindable<int> ParticipantCount = new Bindable<int>();
#region Properties only used for room creation request
[Cached(Name = nameof(Password))]
[JsonProperty("password")]
public readonly Bindable<string> Password = new Bindable<string>();
[Cached]
[JsonIgnore]
public readonly Bindable<TimeSpan?> Duration = new Bindable<TimeSpan?>();
[JsonProperty("duration")]
private int? duration
{
get => (int?)Duration.Value?.TotalMinutes;
set
{
if (value == null)
Duration.Value = null;
else
Duration.Value = TimeSpan.FromMinutes(value.Value);
}
}
#endregion
// Only supports retrieval for now
[Cached]
[JsonProperty("ends_at")]
public readonly Bindable<DateTimeOffset?> EndDate = new Bindable<DateTimeOffset?>();
// Todo: Find a better way to do this (https://github.com/ppy/osu-framework/issues/1930)
[JsonProperty("max_attempts", DefaultValueHandling = DefaultValueHandling.Ignore)]
private int? maxAttempts
{
get => MaxAttempts.Value;
set => MaxAttempts.Value = value;
}
public Room()
{
Password.BindValueChanged(p => HasPassword.Value = !string.IsNullOrEmpty(p.NewValue));
}
/// <summary>
/// Create a copy of this room without online information.
/// Should be used to create a local copy of a room for submitting in the future.
/// </summary>
public Room DeepClone()
{
var copy = new Room();
copy.CopyFrom(this);
copy.RoomID.Value = null;
return copy;
}
public void CopyFrom(Room other)
{
RoomID.Value = other.RoomID.Value;
Name.Value = other.Name.Value;
if (other.Category.Value != RoomCategory.Spotlight)
Category.Value = other.Category.Value;
if (other.Host.Value != null && Host.Value?.Id != other.Host.Value.Id)
Host.Value = other.Host.Value;
ChannelId.Value = other.ChannelId.Value;
Status.Value = other.Status.Value;
Availability.Value = other.Availability.Value;
HasPassword.Value = other.HasPassword.Value;
Type.Value = other.Type.Value;
MaxParticipants.Value = other.MaxParticipants.Value;
ParticipantCount.Value = other.ParticipantCount.Value;
EndDate.Value = other.EndDate.Value;
UserScore.Value = other.UserScore.Value;
if (EndDate.Value != null && DateTimeOffset.Now >= EndDate.Value)
Status.Value = new RoomStatusEnded();
other.RemoveExpiredPlaylistItems();
if (!Playlist.SequenceEqual(other.Playlist))
{
Playlist.Clear();
Playlist.AddRange(other.Playlist);
}
if (!RecentParticipants.SequenceEqual(other.RecentParticipants))
{
RecentParticipants.Clear();
RecentParticipants.AddRange(other.RecentParticipants);
}
}
public void RemoveExpiredPlaylistItems()
{
// Todo: This is not the best way/place to do this, but the intention is to display all playlist items when the room has ended,
// and display only the non-expired playlist items while the room is still active. In order to achieve this, all expired items are removed from the source Room.
// More refactoring is required before this can be done locally instead - DrawableRoomPlaylist is currently directly bound to the playlist to display items in the room.
if (!(Status.Value is RoomStatusEnded))
Playlist.RemoveAll(i => i.Expired);
}
public bool ShouldSerializeRoomID() => false;
public bool ShouldSerializeHost() => false;
public bool ShouldSerializeEndDate() => false;
}
}
| |
// This file is part of the Harvest Management library for LANDIS-II.
using Landis.Utilities;
using Landis.Library.SiteHarvest;
using Landis.SpatialModeling;
using System.Collections;
using System.Collections.Generic;
namespace Landis.Library.HarvestManagement
{
/// <summary>
/// A stand is a collection of sites and represent typical or average
/// forest management block sizes.
/// </summary>
public class Stand
: IEnumerable<ActiveSite>
{
private uint mapCode;
private uint repeatNumber;
private bool repeatHarvested;
private List<Location> siteLocations;
private double activeArea;
private ManagementArea mgmtArea;
private bool harvested;
private List<Stand> neighbors;
private List<Stand> ma_neighbors; //list for neighbors in different management areas
private ushort age;
private int yearAgeComputed;
private int setAsideUntil;
private int timeLastHarvested;
// for log, and for marking rejected prescriptions
private string prescriptionName;
private Prescription lastPrescription;
private int event_id; // for log
private double rank; // for log
//harvested_rank, used in log
private double harvested_rank; // for log
private Dictionary<string, List<Location>> setAsideSites; // List of all sites that should be harvested again in SingleRepeat, seperated by prescription
// tjs 2009.02.07 - Set by prescription to prevent recently
// damaged sites from being harvested
private int minTimeSinceDamage;
// tjs 2009.02.22 - Keep track of which prescriptions
// will not work with this stand. Used to prevent multiple
// attempts by a prescription to harvest a stand that
// will not meet the prescription's requirements. The
// prescription name is put on the list
List<string> rejectedPrescriptionNames;
public double LastAreaHarvested;
public int LastStandsHarvested;
//---------------------------------------------------------------------
/// <summary>
/// The code that designates which sites are in the stand in the stand
/// input map.
/// </summary>
public uint MapCode
{
get {
return mapCode;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Tracks how many times this stand has been repeat harvested by the current prescription
/// </summary>
public uint RepeatNumber
{
get
{
return repeatNumber;
}
}
/// <summary>
/// Increases how many times this stand has been repeat harvested
/// </summary>
public void IncrementRepeat()
{
this.repeatNumber++;
}
/// <summary>
/// Indicates if this stand was repeat harvested in the current timestep
/// </summary>
public bool RepeatHarvested
{
get
{
return this.repeatHarvested;
}
}
/// <summary>
/// Flips the flag indicating if the stand had a repeat harvest in the current time step
/// </summary>
public void SetRepeatHarvested()
{
this.repeatHarvested = !this.repeatHarvested;
}
/// <summary>
/// Resets the repeat number
/// </summary>
public void ResetRepeatNumber()
{
this.repeatNumber = 0;
}
/// <summary>
/// All the site locations in the stand, as specified in the stand map.
/// </summary>
public List<Location> AllLocations { get; private set; }
/// <summary>
/// Determines if a given active site has been set aside for single repeat
/// </summary>
public bool IsSiteSetAside(ActiveSite site, string name)
{
if (this.setAsideSites == null || !this.setAsideSites.ContainsKey(name) || this.setAsideSites[name].Count == 0)
{
return false;
}
return this.setAsideSites[name].Contains(site.Location);
}
/// <summary>
/// Adds a site to the list of set aside sites for single repeat
/// </summary>
public void SetSiteAside(ActiveSite site, string name)
{
if (!this.setAsideSites.ContainsKey(name))
{
this.setAsideSites.Add(name, new List<Location>());
}
this.setAsideSites[name].Add(site.Location);
}
/// <summary>
/// Removes a single site from the set aside list
/// </summary>
public void RemoveSetAsideSite(ActiveSite site, string name)
{
if (!this.setAsideSites.ContainsKey(name))
{
return;
}
this.setAsideSites[name].Remove(site.Location);
}
/// <summary>
/// Removes all sites from the set aside list
/// </summary>
public void ClearSetAsideSites(string name)
{
if (!this.setAsideSites.ContainsKey(name))
{
return;
}
this.setAsideSites[name].Clear();
}
//---------------------------------------------------------------------
/// <summary>
/// The list of locations in this stand where a site's land use allows
/// harvesting at the current timestep.
/// </summary>
public List<Location> SiteLocations {
get {
return siteLocations;
}
}
//---------------------------------------------------------------------
public int SiteCount
{
get {
return siteLocations.Count;
}
}
//---------------------------------------------------------------------
public List<ActiveSite> GetActiveSites() {
List<ActiveSite> sites = new List<ActiveSite>();
foreach (ActiveSite site in this) {
sites.Add(site);
}
return sites;
}
//---------------------------------------------------------------------
public double ActiveArea
{
get {
return activeArea;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The management area that the stand belongs to.
/// </summary>
public ManagementArea ManagementArea
{
get {
return mgmtArea;
}
internal set {
mgmtArea = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The stand's age, which is the mean of the oldest cohort on each
/// site within the stand.
/// </summary>
public ushort Age
{
get {
if (yearAgeComputed != Model.Core.CurrentTime)
{
age = ComputeAge();
yearAgeComputed = Model.Core.CurrentTime;
}
return age;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Set's or returns this stand's rank.
/// </summary>
public double Rank {
get {
return this.rank;
}
set {
this.rank = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Has the stand been harvested during the current timestep?
/// </summary>
public bool Harvested
{
get {
return harvested;
}
}
/// <summary>
/// Sets or returns the rank at which this stand was last harvested
/// </summary>
public double HarvestedRank {
get {
return this.harvested_rank;
}
set {
this.harvested_rank = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Return the time this stand was last harvested.
/// </summary>
public int TimeLastHarvested {
get {
return timeLastHarvested;
}
set {
timeLastHarvested = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Set by prescription to prevent recently
/// damaged sites from being harvested
/// </summary>
public int MinTimeSinceDamage {
get {
return minTimeSinceDamage;
}
set {
minTimeSinceDamage = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Return the time SINCE this stand was last harvested.
/// </summary>
public int TimeSinceLastHarvested {
get {
return Model.Core.CurrentTime - timeLastHarvested;
}
}
//---------------------------------------------------------------------
public IEnumerable<Stand> Neighbors
{
get {
return neighbors;
}
}
//---------------------------------------------------------------------
public IEnumerable<Stand> MaNeighbors
{
get {
return ma_neighbors;
}
}
//---------------------------------------------------------------------
public IEnumerable<string> RejectedPrescriptionNames {
get {
return rejectedPrescriptionNames;
}
}
//---------------------------------------------------------------------
public bool IsRejectedPrescriptionName(string name) {
bool
isRejected = false;
if(rejectedPrescriptionNames.Contains(name))
isRejected = true;
return isRejected;
}
//---------------------------------------------------------------------
/// <summary>
/// Has the stand been set aside by a repeat harvest? (or a stand adjacency constraint)
/// </summary>
public bool IsSetAside
{
get {
bool ret = (Model.Core.CurrentTime <= setAsideUntil);
return ret;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Returns the name of the prescription which damaged this stand
/// </summary>
public string PrescriptionName {
get {
return prescriptionName;
}
set {
prescriptionName = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Returns the prescription which damaged this stand
/// </summary>
public Prescription LastPrescription {
get {
return lastPrescription;
}
set {
lastPrescription = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Returns the event-id of this harvest
/// </summary>
public int EventId {
get {
return event_id;
}
set {
event_id = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The # of cohorts cut in the stand during its most recent harvest.
/// </summary>
public CohortCounts DamageTable { get; private set; }
//---------------------------------------------------------------------
/// <summary>
/// A new Stand Object, given a map code
/// </summary>
public Stand(uint mapCode)
{
this.mapCode = mapCode;
this.AllLocations = new List<Location>();
this.siteLocations = new List<Location>();
this.activeArea = Model.Core.CellArea;
this.mgmtArea = null;
this.neighbors = new List<Stand>();
this.ma_neighbors = new List<Stand>(); //new list for neighbors not in this management area
this.yearAgeComputed = Model.Core.StartTime;
this.setAsideUntil = Model.Core.StartTime;
this.timeLastHarvested = -1;
this.DamageTable = new CohortCounts();
this.rejectedPrescriptionNames = new List<string>();
this.setAsideSites = new Dictionary<string, List<Location>>();
this.repeatNumber = 0;
this.repeatHarvested = false;
}
//---------------------------------------------------------------------
private static RelativeLocation neighborAbove = new RelativeLocation(-1, 0);
private static RelativeLocation neighborLeft = new RelativeLocation( 0, -1);
private static RelativeLocation[] neighborsAboveAndLeft = new RelativeLocation[]{ neighborAbove, neighborLeft };
//---------------------------------------------------------------------
public void Add(ActiveSite site)
{
AllLocations.Add(site.Location);
this.activeArea = AllLocations.Count * Model.Core.CellArea;
//set site var
SiteVars.Stand[site] = this;
//loop- really just 2 locations, relative (-1, 0) and relative (0, -1)
foreach (RelativeLocation neighbor_loc in neighborsAboveAndLeft) {
//check this site for neighbors that are different
Site neighbor = site.GetNeighbor(neighbor_loc);
if (neighbor != null && neighbor.IsActive) {
//declare a stand with this site as its index.
Stand neighbor_stand = SiteVars.Stand[neighbor];
//check for non-null stand
//also, only allow stands in same management area to be called neighbors
if (neighbor_stand != null && this.ManagementArea == neighbor_stand.ManagementArea) {
//if neighbor_stand is different than this stand, then it is a true
//neighbor. add it as a neighbor and add 'this' as a neighbor of that.
if (this != neighbor_stand) {
//add neighbor_stand as a neighboring stand to this
AddNeighbor(neighbor_stand);
//add this as a neighboring stand to neighbor_stand
neighbor_stand.AddNeighbor(this);
}
}
//take into account other management areas just for stand-adjacency issue
else if (neighbor_stand != null && this.ManagementArea != neighbor_stand.ManagementArea) {
if (this != neighbor_stand) {
//add neighbor_stand as a ma-neighboring stand to this
AddMaNeighbor(neighbor_stand);
//add this as a ma-neighbor stand to neighbor_stand
neighbor_stand.AddMaNeighbor(this);
}
}
}
}
}
//---------------------------------------------------------------------
public ActiveSite GetRandomActiveSite {
get
{
if(siteLocations == null || siteLocations.Count == 0)
return new ActiveSite();
int random = (int)(Model.Core.GenerateUniform() * (siteLocations.Count - 1));
if(random < 0 || random > siteLocations.Count - 1)
return new ActiveSite();
return Model.Core.Landscape[siteLocations[random]];
}
}
//---------------------------------------------------------------------
public void DelistActiveSite(ActiveSite site) {
SiteVars.LandUseAllowHarvest[site] = false;
}
//---------------------------------------------------------------------
protected void AddNeighbor(Stand neighbor)
{
Require.ArgumentNotNull(neighbor);
if (! neighbors.Contains(neighbor))
neighbors.Add(neighbor);
}
//---------------------------------------------------------------------
protected void AddMaNeighbor(Stand neighbor) {
Require.ArgumentNotNull(neighbor);
if (! ma_neighbors.Contains(neighbor)) {
ma_neighbors.Add(neighbor);
}
}
//---------------------------------------------------------------------
public ushort ComputeAge()
{
double total = 0.0;
foreach (ActiveSite site in this) {
total += (double) SiteVars.GetMaxAge(site);
}
return (ushort) (total / (double) siteLocations.Count);
}
//---------------------------------------------------------------------
/// <summary>
/// Initializes the stand for the current timestep by resetting certain
/// harvest-related properties.
/// </summary>
public void InitializeForHarvesting()
{
harvested = false;
rejectedPrescriptionNames.Clear();
LastAreaHarvested = 0.0;
LastStandsHarvested = 0;
siteLocations.Clear();
foreach (Location location in AllLocations)
{
ActiveSite site = Model.Core.Landscape[location];
SiteVars.CohortsDamaged[site] = 0;
if (SiteVars.LandUseAllowHarvest[site])
siteLocations.Add(location);
}
activeArea = siteLocations.Count * Model.Core.CellArea;
}
//---------------------------------------------------------------------
/// <summary>
/// Marks a stand as harvested by setting its timeLastHarvested
/// and harvested as true
/// </summary>
public void MarkAsHarvested()
{
//reset timeLastHarvested to current time
this.timeLastHarvested = Model.Core.CurrentTime;
//mark stand as harvested
harvested = true;
}
//---------------------------------------------------------------------
/// <summary>
/// Adds prescription name to rejectedPrescriptionNames
/// sets prescription name to empty string
/// </summary>
public void RejectPrescriptionName(string name) {
if(!rejectedPrescriptionNames.Contains(name))
rejectedPrescriptionNames.Add(name);
prescriptionName = "";
}
//---------------------------------------------------------------------
/// <summary>
/// Sets the stand aside until a later time for a repeat harvest.
/// </summary>
/// <param name="year">
/// The calendar year until which the stand should be stand aside.
/// </param>
public void SetAsideUntil(int year) {
setAsideUntil = year;
}
/// <summary>
/// Update the damage_table for this stand
/// </summary>
/// <param name="siteCounts">
/// The number of cohorts cut for each species at the site that was
/// just harvested.
/// </param>
public void UpdateDamageTable(CohortCounts siteCounts)
{
DamageTable.IncrementCounts(siteCounts);
}
/// <summary>
///Clear the damage table of all data.
/// </summary>
public void ClearDamageTable() {
DamageTable.Reset();
}
//---------------------------------------------------------------------
IEnumerator<ActiveSite> IEnumerable<ActiveSite>.GetEnumerator()
{
foreach (Location location in siteLocations)
yield return Model.Core.Landscape[location];
}
//---------------------------------------------------------------------
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<ActiveSite>)this).GetEnumerator();
}
}
} // namespace Landis.Extensions.Harvest
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
// TPL namespaces
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public class TaskContinueWhenAllTests
{
#region Test Methods
// Test functionality of "bare" ContinueWhenAll overloads
[Fact]
public static void TestContinueWhenAll_bare()
{
int smallSize = 2;
int largeSize = 3;
Task[] smallTaskArray = null;
Task[] largeTaskArray = null;
Task<int>[] smallFutureArray = null;
Task<int>[] largeFutureArray = null;
Task tSmall;
Task tLarge;
for (int i = 0; i < 2; i++)
{
bool antecedentsAreFutures = (i == 0);
for (int j = 0; j < 2; j++)
{
bool continuationsAreFutures = (j == 0);
for (int x = 0; x < 2; x++)
{
bool useFutureFactory = (x == 0);
// This would be a nonsensical combination
if (useFutureFactory && !continuationsAreFutures) continue;
Debug.WriteLine(" Testing {0} = {3}.Factory.CWAll({1}, {2})",
continuationsAreFutures ? "Future" : "Task",
antecedentsAreFutures ? "Future[]" : "Task[]",
continuationsAreFutures ? "func" : "action",
useFutureFactory ? "Task<int>" : "Task");
// Set up our antecedents
if (antecedentsAreFutures)
{
makeCWAllFutureArrays(smallSize, largeSize, out smallFutureArray, out largeFutureArray);
if (continuationsAreFutures)
{
if (useFutureFactory)
{
// antecedentsAreFutures=true, continuationsAreFutures=true, useFutureFactory = true
tSmall = Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, (Task<int>[] finishedArray) => 10);
tLarge = Task<int>.Factory.ContinueWhenAll<int>(largeFutureArray, (Task<int>[] finishedArray) => 20);
}
else // useFutureFactory = false (use Task factory)
{
// antecedentsAreFutures=true, continuationsAreFutures=true, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, (Task<int>[] finishedArray) => 10);
tLarge = Task.Factory.ContinueWhenAll<int, int>(largeFutureArray, (Task<int>[] finishedArray) => 20);
}
}
else // continuationsAreFutures = false (continuations are Tasks)
{
// antecedentsAreFutures=true, continuationsAreFutures=false, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int>(smallFutureArray, (Task<int>[] finishedArray) => { });
tLarge = Task.Factory.ContinueWhenAll<int>(largeFutureArray, (Task<int>[] finishedArray) => { });
}
// Kick off the smallFutureArray
startTaskArray(smallFutureArray);
}
else // antecedentsAreFutures = false (antecedents are Tasks)
{
makeCWAllTaskArrays(smallSize, largeSize, out smallTaskArray, out largeTaskArray);
if (continuationsAreFutures)
{
if (useFutureFactory)
{
// antecedentsAreFutures=false, continuationsAreFutures=true, useFutureFactory = true
tSmall = Task<int>.Factory.ContinueWhenAll(smallTaskArray, (Task[] finishedArray) => 10);
tLarge = Task<int>.Factory.ContinueWhenAll(largeTaskArray, (Task[] finishedArray) => 20);
}
else // useFutureFactory = false (use TaskFactory)
{
// antecedentsAreFutures=false, continuationsAreFutures=true, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int>(smallTaskArray, (Task[] finishedArray) => 10);
tLarge = Task.Factory.ContinueWhenAll<int>(largeTaskArray, (Task[] finishedArray) => 20);
}
}
else // continuationsAreFutures = false (continuations are Tasks)
{
// antecedentsAreFutures=false, continuationsAreFutures=false, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll(smallTaskArray, (Task[] finishedArray) => { });
tLarge = Task.Factory.ContinueWhenAll(largeTaskArray, (Task[] finishedArray) => { });
}
// Kick off the smallTaskArray
startTaskArray(smallTaskArray);
}
// Verify correct behavior for starting small array
int result = 0;
Exception ex = null;
try
{
if (continuationsAreFutures) result = ((Task<int>)tSmall).Result;
else tSmall.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.Null(ex); // , "Did not expect exception from tSmall.Wait()")
Assert.True((result == 10) || (!continuationsAreFutures), "Expected valid result from tSmall");
Assert.False(tLarge.IsCompleted, "tLarge completed before its time");
//
// Now start the large array
//
if (antecedentsAreFutures) startTaskArray(largeFutureArray);
else startTaskArray(largeTaskArray);
result = 0;
try
{
if (continuationsAreFutures) result = ((Task<int>)tLarge).Result;
else tLarge.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.Null(ex); // , "Did not expect exception from tLarge.Wait()")
Assert.True((result == 20) || (!continuationsAreFutures), "Expected valid result from tLarge");
} // end x-loop (FutureFactory or TaskFactory)
} // end j-loop (continuations are futures or tasks)
}// end i-loop (antecedents are futures or tasks)
}
// Test functionality of ContinueWhenAll overloads w/ CancellationToken
[Fact]
public static void TestContinueWhenAll_CancellationToken()
{
int smallSize = 2;
int largeSize = 3;
Task[] smallTaskArray = null;
Task[] largeTaskArray = null;
Task<int>[] smallFutureArray = null;
Task<int>[] largeFutureArray = null;
Task tSmall;
Task tLarge;
for (int i = 0; i < 2; i++)
{
bool antecedentsAreFutures = (i == 0);
for (int j = 0; j < 2; j++)
{
bool continuationsAreFutures = (j == 0);
for (int k = 0; k < 2; k++)
{
bool preCanceledToken = (k == 0);
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
if (preCanceledToken) cts.Cancel();
for (int x = 0; x < 2; x++)
{
bool useFutureFactory = (x == 0);
// This would be a nonsensical combination
if (useFutureFactory && !continuationsAreFutures) continue;
Debug.WriteLine(" Testing {0} = {4}.Factory.CWAll({1}, {3}, ct({2}))",
continuationsAreFutures ? "Future" : "Task",
antecedentsAreFutures ? "Future[]" : "Task[]",
preCanceledToken ? "signaled" : "unsignaled",
continuationsAreFutures ? "func" : "action",
useFutureFactory ? "Task<int>" : "Task");
// Set up our antecedents
if (antecedentsAreFutures)
{
makeCWAllFutureArrays(smallSize, largeSize, out smallFutureArray, out largeFutureArray);
if (continuationsAreFutures)
{
if (useFutureFactory)
{
// antecedentsAreFutures=true, continuationsAreFutures=true, useFutureFactory = true
tSmall = Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, (Task<int>[] finishedArray) => 10, ct);
tLarge = Task<int>.Factory.ContinueWhenAll<int>(largeFutureArray, (Task<int>[] finishedArray) => 20, ct);
}
else // useFutureFactory = false (use Task factory)
{
// antecedentsAreFutures=true, continuationsAreFutures=true, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, (Task<int>[] finishedArray) => 10, ct);
tLarge = Task.Factory.ContinueWhenAll<int, int>(largeFutureArray, (Task<int>[] finishedArray) => 20, ct);
}
}
else // continuationsAreFutures = false (continuations are Tasks)
{
// antecedentsAreFutures=true, continuationsAreFutures=false, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int>(smallFutureArray, (Task<int>[] finishedArray) => { }, ct);
tLarge = Task.Factory.ContinueWhenAll<int>(largeFutureArray, (Task<int>[] finishedArray) => { }, ct);
}
// Kick off the smallFutureArray
startTaskArray(smallFutureArray);
}
else // antecedentsAreFutures = false (antecedents are Tasks)
{
makeCWAllTaskArrays(smallSize, largeSize, out smallTaskArray, out largeTaskArray);
if (continuationsAreFutures)
{
if (useFutureFactory)
{
// antecedentsAreFutures=false, continuationsAreFutures=true, useFutureFactory = true
tSmall = Task<int>.Factory.ContinueWhenAll(smallTaskArray, (Task[] finishedArray) => 10, ct);
tLarge = Task<int>.Factory.ContinueWhenAll(largeTaskArray, (Task[] finishedArray) => 20, ct);
}
else // useFutureFactory = false (use TaskFactory)
{
// antecedentsAreFutures=false, continuationsAreFutures=true, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int>(smallTaskArray, (Task[] finishedArray) => 10, ct);
tLarge = Task.Factory.ContinueWhenAll<int>(largeTaskArray, (Task[] finishedArray) => 20, ct);
}
}
else // continuationsAreFutures = false (continuations are Tasks)
{
// antecedentsAreFutures=false, continuationsAreFutures=false, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll(smallTaskArray, (Task[] finishedArray) => { }, ct);
tLarge = Task.Factory.ContinueWhenAll(largeTaskArray, (Task[] finishedArray) => { }, ct);
}
// Kick off the smallTaskArray
startTaskArray(smallTaskArray);
}
// Verify correct behavior for starting small array
int result = 0;
Exception ex = null;
try
{
if (continuationsAreFutures) result = ((Task<int>)tSmall).Result;
else tSmall.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.True(preCanceledToken == (ex != null), "Expected tSmall.Wait() exception only on preCanceledToken");
if (preCanceledToken)
{
if (ex != null)
{
Assert.True(
((ex is AggregateException) &&
(((AggregateException)ex).InnerExceptions[0].GetType() == typeof(TaskCanceledException))),
"Expected AE(TCE) on tSmall Cancellation, got " + ex.ToString());
}
Assert.True(tLarge.IsCompleted, "Expected tLarge to complete immediately on pre-canceled token");
CheckForCorrectCT(tSmall, ct);
}
else // !preCanceledToken
{
Assert.True((result == 10) || (!continuationsAreFutures), "Expected valid result from tSmall");
Assert.False(tLarge.IsCompleted, "tLarge completed before its time");
}
//
// Now start the large array
//
if (antecedentsAreFutures) startTaskArray(largeFutureArray);
else startTaskArray(largeTaskArray);
result = 0;
try
{
if (continuationsAreFutures) result = ((Task<int>)tLarge).Result;
else tLarge.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.True(preCanceledToken == (ex != null), "Expected tLarge.Wait() exception only on preCanceledToken");
if (preCanceledToken)
{
if (ex != null)
{
Assert.True(
((ex is AggregateException) &&
(((AggregateException)ex).InnerExceptions[0].GetType() == typeof(TaskCanceledException))),
"Expected AE(TCE) on tLarge cancellation, got " + ex.ToString());
}
CheckForCorrectCT(tLarge, ct);
}
else // !preCanceledToken
{
Assert.True((result == 20) || (!continuationsAreFutures), "Expected valid result from tLarge");
}
} // end x-loop (FutureFactory or TaskFactory)
} // end k-loop (preCanceled or not)
} // end j-loop (continuations are futures or tasks)
}// end i-loop (antecedents are futures or tasks)
}
// Test functionality of ContinueWhenAll overloads w/ TaskContinuationOptions
[Fact]
public static void TestContinueWhenAll_TaskContinuationOptions()
{
int smallSize = 2;
int largeSize = 3;
Task[] smallTaskArray = null;
Task[] largeTaskArray = null;
Task<int>[] smallFutureArray = null;
Task<int>[] largeFutureArray = null;
Task tSmall;
Task tLarge;
for (int i = 0; i < 2; i++)
{
bool antecedentsAreFutures = (i == 0);
for (int j = 0; j < 2; j++)
{
bool continuationsAreFutures = (j == 0);
for (int k = 0; k < 2; k++)
{
bool longRunning = (k == 0);
TaskContinuationOptions tco = longRunning ? TaskContinuationOptions.LongRunning : TaskContinuationOptions.None;
for (int x = 0; x < 2; x++)
{
bool useFutureFactory = (x == 0);
// This would be a nonsensical combination
if (useFutureFactory && !continuationsAreFutures) continue;
Debug.WriteLine(" Testing {0} = {3}.Factory.CWAll({1}, {2}, {4})",
continuationsAreFutures ? "Future" : "Task",
antecedentsAreFutures ? "Future[]" : "Task[]",
continuationsAreFutures ? "func" : "action",
useFutureFactory ? "Task<int>" : "Task",
tco);
// Set up our antecedents
if (antecedentsAreFutures)
{
makeCWAllFutureArrays(smallSize, largeSize, out smallFutureArray, out largeFutureArray);
if (continuationsAreFutures)
{
if (useFutureFactory)
{
// antecedentsAreFutures=true, continuationsAreFutures=true, useFutureFactory = true
tSmall = Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, (Task<int>[] finishedArray) => 10, tco);
tLarge = Task<int>.Factory.ContinueWhenAll<int>(largeFutureArray, (Task<int>[] finishedArray) => 20, tco);
}
else // useFutureFactory = false (use Task factory)
{
// antecedentsAreFutures=true, continuationsAreFutures=true, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, (Task<int>[] finishedArray) => 10, tco);
tLarge = Task.Factory.ContinueWhenAll<int, int>(largeFutureArray, (Task<int>[] finishedArray) => 20, tco);
}
}
else // continuationsAreFutures = false (continuations are Tasks)
{
// antecedentsAreFutures=true, continuationsAreFutures=false, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int>(smallFutureArray, (Task<int>[] finishedArray) => { }, tco);
tLarge = Task.Factory.ContinueWhenAll<int>(largeFutureArray, (Task<int>[] finishedArray) => { }, tco);
}
// Kick off the smallFutureArray
startTaskArray(smallFutureArray);
}
else // antecedentsAreFutures = false (antecedents are Tasks)
{
makeCWAllTaskArrays(smallSize, largeSize, out smallTaskArray, out largeTaskArray);
if (continuationsAreFutures)
{
if (useFutureFactory)
{
// antecedentsAreFutures=false, continuationsAreFutures=true, useFutureFactory = true
tSmall = Task<int>.Factory.ContinueWhenAll(smallTaskArray, (Task[] finishedArray) => 10, tco);
tLarge = Task<int>.Factory.ContinueWhenAll(largeTaskArray, (Task[] finishedArray) => 20, tco);
}
else // useFutureFactory = false (use TaskFactory)
{
// antecedentsAreFutures=false, continuationsAreFutures=true, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int>(smallTaskArray, (Task[] finishedArray) => 10, tco);
tLarge = Task.Factory.ContinueWhenAll<int>(largeTaskArray, (Task[] finishedArray) => 20, tco);
}
}
else // continuationsAreFutures = false (continuations are Tasks)
{
// antecedentsAreFutures=false, continuationsAreFutures=false, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll(smallTaskArray, (Task[] finishedArray) => { }, tco);
tLarge = Task.Factory.ContinueWhenAll(largeTaskArray, (Task[] finishedArray) => { }, tco);
}
// Kick off the smallTaskArray
startTaskArray(smallTaskArray);
}
// Verify correct behavior for starting small array
int result = 0;
Exception ex = null;
try
{
if (continuationsAreFutures) result = ((Task<int>)tSmall).Result;
else tSmall.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.Null(ex); // , "Did not expect exception from tSmall.Wait()")
Assert.True((result == 10) || (!continuationsAreFutures), "Expected valid result from tSmall");
Assert.False(tLarge.IsCompleted, "tLarge completed before its time");
Assert.Equal((tSmall.CreationOptions & TaskCreationOptions.LongRunning) != 0, longRunning);
Assert.True((tSmall.CreationOptions == TaskCreationOptions.None) || longRunning, "tSmall CreationOptions should be None unless longRunning is true");
//
// Now start the large array
//
if (antecedentsAreFutures) startTaskArray(largeFutureArray);
else startTaskArray(largeTaskArray);
result = 0;
try
{
if (continuationsAreFutures) result = ((Task<int>)tLarge).Result;
else tLarge.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.Null(ex); // , "Did not expect exception from tLarge.Wait()")
Assert.True((result == 20) || (!continuationsAreFutures), "Expected valid result from tLarge");
Assert.Equal((tLarge.CreationOptions & TaskCreationOptions.LongRunning) != 0, longRunning);
Assert.True((tLarge.CreationOptions == TaskCreationOptions.None) || longRunning, "tLarge CreationOptions should be None unless longRunning is true");
} // end x-loop (FutureFactory or TaskFactory)
} // end k-loop (TaskContinuationOptions are LongRunning or None)
} // end j-loop (continuations are futures or tasks)
}// end i-loop (antecedents are futures or tasks)
}
// Test functionality of "full up" ContinueWhenAll overloads
[Fact]
public static void TestCWAll_CancellationToken_TaskContinuation_TaskScheduler()
{
int smallSize = 2;
int largeSize = 3;
Task[] smallTaskArray = null;
Task[] largeTaskArray = null;
Task<int>[] smallFutureArray = null;
Task<int>[] largeFutureArray = null;
Task tSmall;
Task tLarge;
for (int i = 0; i < 2; i++)
{
bool antecedentsAreFutures = (i == 0);
for (int j = 0; j < 2; j++)
{
bool continuationsAreFutures = (j == 0);
for (int k = 0; k < 2; k++)
{
bool preCanceledToken = (k == 0);
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
if (preCanceledToken) cts.Cancel();
for (int x = 0; x < 2; x++)
{
bool useFutureFactory = (x == 0);
// This would be a nonsensical combination
if (useFutureFactory && !continuationsAreFutures) continue;
TaskContinuationOptions tco = TaskContinuationOptions.None; // for now
TaskScheduler ts = TaskScheduler.Default;
Debug.WriteLine(" Testing {0} = {4}.Factory.CWAll({1}, {3}, ct({2}), tco.None, ts.Default)",
continuationsAreFutures ? "Future" : "Task",
antecedentsAreFutures ? "Future[]" : "Task[]",
preCanceledToken ? "signaled" : "unsignaled",
continuationsAreFutures ? "func" : "action",
useFutureFactory ? "Task<int>" : "Task");
// Set up our antecedents
if (antecedentsAreFutures)
{
makeCWAllFutureArrays(smallSize, largeSize, out smallFutureArray, out largeFutureArray);
if (continuationsAreFutures)
{
if (useFutureFactory)
{
// antecedentsAreFutures=true, continuationsAreFutures=true, useFutureFactory = true
tSmall = Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, (Task<int>[] finishedArray) => 10, ct, tco, ts);
tLarge = Task<int>.Factory.ContinueWhenAll<int>(largeFutureArray, (Task<int>[] finishedArray) => 20, ct, tco, ts);
}
else // useFutureFactory = false (use Task factory)
{
// antecedentsAreFutures=true, continuationsAreFutures=true, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, (Task<int>[] finishedArray) => 10, ct, tco, ts);
tLarge = Task.Factory.ContinueWhenAll<int, int>(largeFutureArray, (Task<int>[] finishedArray) => 20, ct, tco, ts);
}
}
else // continuationsAreFutures = false (continuations are Tasks)
{
// antecedentsAreFutures=true, continuationsAreFutures=false, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int>(smallFutureArray, (Task<int>[] finishedArray) => { }, ct, tco, ts);
tLarge = Task.Factory.ContinueWhenAll<int>(largeFutureArray, (Task<int>[] finishedArray) => { }, ct, tco, ts);
}
// Kick off the smallFutureArray
startTaskArray(smallFutureArray);
}
else // antecedentsAreFutures = false (antecedents are Tasks)
{
makeCWAllTaskArrays(smallSize, largeSize, out smallTaskArray, out largeTaskArray);
if (continuationsAreFutures)
{
if (useFutureFactory)
{
// antecedentsAreFutures=false, continuationsAreFutures=true, useFutureFactory = true
tSmall = Task<int>.Factory.ContinueWhenAll(smallTaskArray, (Task[] finishedArray) => 10, ct, tco, ts);
tLarge = Task<int>.Factory.ContinueWhenAll(largeTaskArray, (Task[] finishedArray) => 20, ct, tco, ts);
}
else // useFutureFactory = false (use TaskFactory)
{
// antecedentsAreFutures=false, continuationsAreFutures=true, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll<int>(smallTaskArray, (Task[] finishedArray) => 10, ct, tco, ts);
tLarge = Task.Factory.ContinueWhenAll<int>(largeTaskArray, (Task[] finishedArray) => 20, ct, tco, ts);
}
}
else // continuationsAreFutures = false (continuations are Tasks)
{
// antecedentsAreFutures=false, continuationsAreFutures=false, useFutureFactory = false
tSmall = Task.Factory.ContinueWhenAll(smallTaskArray, (Task[] finishedArray) => { }, ct, tco, ts);
tLarge = Task.Factory.ContinueWhenAll(largeTaskArray, (Task[] finishedArray) => { }, ct, tco, ts);
}
// Kick off the smallTaskArray
startTaskArray(smallTaskArray);
}
// Verify correct behavior for starting small array
int result = 0;
Exception ex = null;
try
{
if (continuationsAreFutures) result = ((Task<int>)tSmall).Result;
else tSmall.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.True(preCanceledToken == (ex != null), "Expected tSmall.Wait() exception only on preCanceledToken");
if (preCanceledToken)
{
if (ex != null)
{
Assert.True(
((ex is AggregateException) &&
(((AggregateException)ex).InnerExceptions[0].GetType() == typeof(TaskCanceledException))),
"Expected AE(TCE) on tSmall Cancellation, got " + ex.ToString());
}
Assert.True(tLarge.IsCompleted, "Expected tLarge to complete immediately on pre-canceled token");
CheckForCorrectCT(tSmall, ct);
}
else // !preCanceledToken
{
Assert.True((result == 10) || (!continuationsAreFutures), "Expected valid result from tSmall");
Assert.False(tLarge.IsCompleted, "tLarge completed before its time");
}
//
// Now start the large array
//
if (antecedentsAreFutures) startTaskArray(largeFutureArray);
else startTaskArray(largeTaskArray);
result = 0;
try
{
if (continuationsAreFutures) result = ((Task<int>)tLarge).Result;
else tLarge.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.True(preCanceledToken == (ex != null), "Expected tLarge.Wait() exception only on preCanceledToken");
if (preCanceledToken)
{
if (ex != null)
{
Assert.True(
((ex is AggregateException) &&
(((AggregateException)ex).InnerExceptions[0].GetType() == typeof(TaskCanceledException))),
"Expected AE(TCE) on tLarge cancellation, got " + ex.ToString());
}
CheckForCorrectCT(tLarge, ct);
}
else // !preCanceledToken
{
Assert.True((result == 20) || (!continuationsAreFutures), "Expected valid result from tLarge");
}
} // end x-loop (FutureFactory or TaskFactory)
} // end k-loop (preCanceled or not)
} // end j-loop (continuations are futures or tasks)
}// end i-loop (antecedents are futures or tasks)
}
[Fact]
public static void RunContinueWhenAllTests_Exceptions()
{
int smallSize = 2;
int largeSize = 3;
Task[] largeTaskArray = null;
Task[] smallTaskArray;
Task<int>[] largeFutureArray = null;
Task<int>[] smallFutureArray;
// The remainder of this method will verify exceptional conditions
// Test that illegal LongRunning | ExecuteSynchronously combination results in an exception.
Task dummy = Task.Factory.StartNew(delegate { });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task.Factory.ContinueWhenAll(new Task[] { dummy }, _ => { }, TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously); });
dummy.Wait();
//
// Test exceptions when continuing from Task[] => Task
//
{
makeCWAllTaskArrays(smallSize, largeSize, out smallTaskArray, out largeTaskArray);
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll(smallTaskArray, delegate (Task[] finishedArray) { }, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task.Factory.ContinueWhenAll(smallTaskArray, delegate (Task[] finishedArray) { }, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll(smallTaskArray, (Action<Task[]>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll(smallTaskArray, (Action<Task[]>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll(smallTaskArray, (Action<Task[]>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll(smallTaskArray, (Action<Task[]>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll((Task[])null, delegate (Task[] finishedArray) { }); });
smallTaskArray[0] = null;
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAll(smallTaskArray, delegate (Task[] finishedArray) { }); });
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAll(new Task[] { }, delegate (Task[] finishedArray) { }); });
}
//
// Test exceptions from continuing from Task[] => Task<int> using TaskFactory
//
{
makeCWAllTaskArrays(smallSize, largeSize, out smallTaskArray, out largeTaskArray);
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallTaskArray, finishedArray => 10, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task.Factory.ContinueWhenAll<int>(smallTaskArray, finishedArray => 10, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallTaskArray, (Func<Task[], int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallTaskArray, (Func<Task[], int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallTaskArray, (Func<Task[], int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallTaskArray, (Func<Task[], int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>((Task[])null, finishedArray => 10); });
smallTaskArray[0] = null;
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAll<int>(smallTaskArray, finishedArray => 10); });
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAll<int>(new Task[] { }, finishedArray => 10); });
}
//
// Test exceptions from continuing from Task[] => Task<int> using FutureFactory
//
{
makeCWAllTaskArrays(smallSize, largeSize, out smallTaskArray, out largeTaskArray);
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll(smallTaskArray, finishedArray => 10, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task<int>.Factory.ContinueWhenAll(smallTaskArray, finishedArray => 10, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll(smallTaskArray, (Func<Task[], int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll(smallTaskArray, (Func<Task[], int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll(smallTaskArray, (Func<Task[], int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll(smallTaskArray, (Func<Task[], int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll((Task[])null, finishedArray => 10); });
smallTaskArray[0] = null;
Assert.Throws<ArgumentException>(
() => { Task<int>.Factory.ContinueWhenAll(smallTaskArray, finishedArray => 10); });
Assert.Throws<ArgumentException>(
() => { Task<int>.Factory.ContinueWhenAll(new Task[] { }, finishedArray => 10); });
}
//
// Test exceptions from continuing from Task<int>[] => Task
//
{
makeCWAllFutureArrays(smallSize, largeSize, out smallFutureArray, out largeFutureArray);
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallFutureArray, finishedArray => { }, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task.Factory.ContinueWhenAll<int>(smallFutureArray, finishedArray => { }, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallFutureArray, (Action<Task<int>[]>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallFutureArray, (Action<Task<int>[]>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallFutureArray, (Action<Task<int>[]>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>(smallFutureArray, (Action<Task<int>[]>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int>((Task<int>[])null, finishedArray => { }); });
smallFutureArray[0] = null;
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAll<int>(smallFutureArray, finishedArray => { }); });
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAll<int>(new Task<int>[] { }, finishedArray => { }); });
}
//
// Test exceptions from continuing from Task<int>[] => Task<int> using TaskFactory
//
{
makeCWAllFutureArrays(smallSize, largeSize, out smallFutureArray, out largeFutureArray);
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, finishedArray => 10, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, finishedArray => 10, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, (Func<Task[], int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, (Func<Task[], int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, (Func<Task[], int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, (Func<Task[], int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
Assert.Throws<ArgumentNullException>(
() => { Task.Factory.ContinueWhenAll<int, int>((Task<int>[])null, finishedArray => 10); });
smallFutureArray[0] = null;
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAll<int, int>(smallFutureArray, finishedArray => 10); });
Assert.Throws<ArgumentException>(
() => { Task.Factory.ContinueWhenAll<int, int>(new Task<int>[] { }, finishedArray => 10); });
}
//
// Test exceptions from continuing from Task<int>[] => Task<int> using FutureFactory
//
{
makeCWAllFutureArrays(smallSize, largeSize, out smallFutureArray, out largeFutureArray);
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, finishedArray => 10, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, finishedArray => 10, TaskContinuationOptions.NotOnFaulted); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, (Func<Task[], int>)null); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, (Func<Task[], int>)null, CancellationToken.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, (Func<Task[], int>)null, TaskContinuationOptions.None); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, (Func<Task[], int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); });
Assert.Throws<ArgumentNullException>(
() => { Task<int>.Factory.ContinueWhenAll<int>((Task<int>[])null, finishedArray => 10); });
smallFutureArray[0] = null;
Assert.Throws<ArgumentException>(
() => { Task<int>.Factory.ContinueWhenAll<int>(smallFutureArray, finishedArray => 10); });
Assert.Throws<ArgumentException>(
() => { Task<int>.Factory.ContinueWhenAll<int>(new Task<int>[] { }, finishedArray => 10); });
}
}
#endregion
#region Helper Methods / Classes
private static void CheckForCorrectCT(Task canceledTask, CancellationToken correctToken)
{
try
{
canceledTask.Wait();
Assert.True(false, string.Format(" > FAILED! Pre-canceled result did not throw from Wait()"));
}
catch (AggregateException ae)
{
ae.Flatten().Handle(e =>
{
var tce = e as TaskCanceledException;
if (tce == null)
{
Assert.True(false, string.Format(" > FAILED! Pre-canceled result threw non-TCE from Wait()"));
}
else if (tce.CancellationToken != correctToken)
{
Assert.True(false, string.Format(" > FAILED! Pre-canceled result threw TCE w/ wrong token"));
}
return true;
});
}
}
private static void makeCWAllFutureArrays(int smallSize, int largeSize, out Task<int>[] aSmall, out Task<int>[] aLarge)
{
aLarge = new Task<int>[largeSize];
aSmall = new Task<int>[smallSize];
for (int i = 0; i < largeSize; i++) aLarge[i] = new Task<int>(delegate { return 30; });
for (int i = 0; i < smallSize; i++) aSmall[i] = aLarge[i];
}
// used in ContinueWhenAll/ContinueWhenAny tests
private static void startTaskArray(Task[] tasks)
{
for (int i = 0; i < tasks.Length; i++)
{
if (tasks[i].Status == TaskStatus.Created) tasks[i].Start();
}
}
private static void makeCWAllTaskArrays(int smallSize, int largeSize, out Task[] aSmall, out Task[] aLarge)
{
aLarge = new Task[largeSize];
aSmall = new Task[smallSize];
for (int i = 0; i < largeSize; i++) aLarge[i] = new Task(delegate { });
for (int i = 0; i < smallSize; i++) aSmall[i] = aLarge[i];
}
#endregion
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpatialAnalysis.Geometry;
namespace SpatialAnalysis.CellularEnvironment
{
/// <summary>
/// This class analyzes the state of an agent in relation to the barriers.
/// </summary>
public class CollisionAnalyzer
{
/// <summary>
/// Reports if collision has occured
/// </summary>
public bool CollisionOccured { get; set; }
/// <summary>
/// Reports if the closest point to this location is the end point of an edge or not
/// </summary>
public bool IsClosestPointAnEndPoint { get; set; }
/// <summary>
/// The barrier
/// </summary>
public UVLine Barrrier { get; set; }
/// <summary>
/// The closest point on the barrier
/// </summary>
public UV ClosestPointOnBarrier { get; set; }
/// <summary>
/// the location of agent or target
/// </summary>
public UV Location { get; set; }
/// <summary>
/// Distance to the barrier
/// </summary>
public double DistanceToBarrier { get; set; }
/// <summary>
/// The normal vector at the closest point
/// </summary>
public UV NormalizedRepulsion { get; set; }
/// <summary>
/// Creats an instance of the CollisionAnalyzer. For internal use only.
/// </summary>
/// <param name="point">The agent or target location</param>
/// <param name="cell">The cell to which the point belongs</param>
/// <param name="cellularFloor">The CellularFloorBaseGeometry which includes the agent or target</param>
/// <param name="barrierType">Barrier type</param>
internal CollisionAnalyzer(UV point, Cell cell, CellularFloorBaseGeometry cellularFloor, BarrierType barrierType)
{
this.CollisionOccured = false;
this.Location = point;
Index index = cellularFloor.FindIndex(cell);
int I = index.I + 2;
//int I = index.I + 1;
I = Math.Min(I, cellularFloor.GridWidth - 1);
int J = index.J + 2;
//int J = index.J + 1;
J = Math.Min(J, cellularFloor.GridHeight - 1);
index.I = Math.Max(0, index.I - 1);
index.J = Math.Max(0, index.J - 1);
double DistanceSquared = double.PositiveInfinity;
for (int i = index.I; i <= I; i++)
{
for (int j = index.J; j <= J; j++)
{
switch (barrierType)
{
case BarrierType.Visual:
if (cellularFloor.Cells[i, j].VisualOverlapState == OverlapState.Outside)
{
foreach (int item in cellularFloor.Cells[i, j].VisualBarrierEdgeIndices)
{
double d = point.GetDistanceSquared(cellularFloor.VisualBarrierEdges[item]);
if (d < DistanceSquared)
{
DistanceSquared = d;
Barrrier = cellularFloor.VisualBarrierEdges[item];
}
}
}
break;
case BarrierType.Physical:
if (cellularFloor.Cells[i, j].PhysicalOverlapState != OverlapState.Outside)
{
foreach (int item in cellularFloor.Cells[i, j].PhysicalBarrierEdgeIndices)
{
double d = point.GetDistanceSquared(cellularFloor.PhysicalBarrierEdges[item]);
if (d < DistanceSquared)
{
DistanceSquared = d;
Barrrier = cellularFloor.PhysicalBarrierEdges[item];
}
}
}
break;
case BarrierType.Field:
if (cellularFloor.Cells[i, j].BarrierBufferOverlapState != OverlapState.Inside)
{
foreach (int item in cellularFloor.Cells[i, j].FieldBarrierEdgeIndices)
{
double d = point.GetDistanceSquared(cellularFloor.FieldBarrierEdges[item]);
if (d < DistanceSquared)
{
DistanceSquared = d;
Barrrier = cellularFloor.FieldBarrierEdges[item];
}
}
}
break;
}
}
}
if (!double.IsPositiveInfinity(DistanceSquared)
&& this.Barrrier != null)
{
bool isEndpoint = false;
this.ClosestPointOnBarrier = point.GetClosestPoint(this.Barrrier, ref isEndpoint);
this.IsClosestPointAnEndPoint = isEndpoint;
this.NormalizedRepulsion = this.Location - this.ClosestPointOnBarrier;
this.DistanceToBarrier = this.NormalizedRepulsion.GetLength();
this.NormalizedRepulsion /= this.DistanceToBarrier;
}
}
/// <summary>
/// Creats an instance of the CollisionAnalyzer.
/// </summary>
/// <param name="point">The agent or target location</param>
/// <param name="cellularFloor">The CellularFloorBaseGeometry which includes the agent or target</param>
/// <param name="barrierType">Barrier type</param>
/// <returns>An instance of the CollisionAnalyzer which can be null</returns>
public static CollisionAnalyzer GetCollidingEdge(UV point, CellularFloorBaseGeometry cellularFloor, BarrierType barrierType)
{
Cell cell = cellularFloor.FindCell(point);
if (cell == null)
{
return null;
}
switch (barrierType)
{
case BarrierType.Visual:
if (cell.VisualOverlapState == OverlapState.Inside)
{
return null;
}
break;
case BarrierType.Physical:
if (cell.PhysicalOverlapState == OverlapState.Inside)
{
return null;
}
break;
case BarrierType.Field:
if (cell.FieldOverlapState == OverlapState.Outside)
{
//cell.Visualize(MainDocument.TargetVisualizer, Cell.Size, Cell.Size, 0);
return null;
}
break;
case BarrierType.BarrierBuffer:
return null;
}
var colision = new CollisionAnalyzer(point, cell, cellularFloor, barrierType);
if (colision.Barrrier == null)
{
return null;
}
return colision;
}
//Offsets an edge towards a line
private static UVLine OffsetLine(UVLine edge, UV location, double offset)
{
UV vector = location - edge.Start;
UV edgeDirection = edge.End - edge.Start;
edgeDirection.Unitize();
UV vt = edgeDirection * edgeDirection.DotProduct(vector);
UV vp = vector - vt;
vp.Unitize();
UV start = edge.Start + vp * offset;
UV end = edge.End + vp * offset;
return new UVLine(start, end);
}
/// <summary>
/// Solves the ax^2 + bX + c = 0
/// </summary>
/// <param name="a">Coefficient of x^2</param>
/// <param name="b">Coefficient of x</param>
/// <param name="c">Constant parameter</param>
/// <returns></returns>
public static double[] QuadraticSolver(double a, double b, double c)
{
double delta = b * b - 4 * a * c;
if (delta < 0)
{
return null;
}
double deltaRoot = Math.Sqrt(delta);
return new double[2] { (-b - deltaRoot) / (2 * a), (-b + deltaRoot) / (2 * a) };
}
/// <summary>
/// Detects the collision that occurs between two states
/// </summary>
/// <param name="previous">Previous state</param>
/// <param name="current">Current state</param>
/// <param name="buffer">Offset buffer which is the radius of the body</param>
/// <param name="tolerance">Tolerance set by default to the main document's absolute tolerance factor</param>
/// <returns>An instance of the collision which can be null</returns>
public static ICollision GetCollision(CollisionAnalyzer previous, CollisionAnalyzer current, double buffer, double tolerance = OSMDocument.AbsoluteTolerance)
{
Trajectory trajectory = new Trajectory(current.Location, previous.Location);
List<ICollision> collisions = new List<ICollision>();
UVLine edgeBuffer1 = CollisionAnalyzer.OffsetLine(previous.Barrrier, previous.Location, buffer);
ICollision collisionWithEdgeBuffer1 = new GetCollisionWithEdge(trajectory, edgeBuffer1);
collisions.Add(collisionWithEdgeBuffer1);
ICollision collisionWithPreviousBarrierEndPoint = new GetCollisionWithEndPoint(trajectory, previous.Barrrier.End, buffer);
collisions.Add(collisionWithPreviousBarrierEndPoint);
ICollision collisionWithPreviousBarrierStartPoint = new GetCollisionWithEndPoint(trajectory, previous.Barrrier.Start, buffer);
collisions.Add(collisionWithPreviousBarrierStartPoint);
if (!previous.Barrrier.Equals(current.Barrrier))
{
UVLine edgeBuffer2 = CollisionAnalyzer.OffsetLine(current.Barrrier, previous.Location, buffer);
ICollision collisionWithEdgeBuffer2 = new GetCollisionWithEdge(trajectory, edgeBuffer2);
collisions.Add(collisionWithEdgeBuffer2);
if (current.Barrrier.End != previous.Barrrier.End && current.Barrrier.End != previous.Barrrier.Start)
{
ICollision collisionWithCurrentBarrierEndPoint = new GetCollisionWithEndPoint(trajectory, current.Barrrier.End, buffer);
collisions.Add(collisionWithCurrentBarrierEndPoint);
}
if (current.Barrrier.Start != previous.Barrrier.End && current.Barrrier.Start != previous.Barrrier.Start)
{
ICollision collisionWithCurrentBarrierStartPoint = new GetCollisionWithEndPoint(trajectory, current.Barrrier.Start, buffer);
collisions.Add(collisionWithCurrentBarrierStartPoint);
}
}
if (collisions.Count != 0)
{
collisions.Sort((a, b) => a.LengthToCollision.CompareTo(b.LengthToCollision));
ICollision firstCollision = collisions[0];
if (!double.IsInfinity(firstCollision.LengthToCollision))
{
//if (double.IsNaN(firstCollision.TimeStepRemainderProportion))
//{
// System.Windows.MessageBox.Show(double.NaN.ToString() + " caught!");
// GetCollision(previous, current, buffer, tolerance);
//}
return firstCollision;
}
}
return null;
}
}
/// <summary>
/// The trajectory of movement from one point to another
/// </summary>
public class Trajectory
{
/// <summary>
/// The trajectory line
/// </summary>
public UVLine TrajectoryLine { get; set; }
/// <summary>
/// The displacement length
/// </summary>
public double TrajectoryLength { get; set; }
/// <summary>
/// The displacement direction
/// </summary>
public UV TrajectoryNormalizedVector { get; set; }
/// <summary>
/// constructor
/// </summary>
/// <param name="start">Start point</param>
/// <param name="end">End point</param>
public Trajectory(UV start, UV end)
{
this.TrajectoryLine = new UVLine(start, end);
this.TrajectoryLength = UV.GetDistanceBetween(start, end);
this.TrajectoryNormalizedVector = (end - start) / this.TrajectoryLength;
}
}
/// <summary>
/// Collision data model
/// </summary>
public interface ICollision
{
/// <summary>
/// The timestep proportion after collision
/// </summary>
double TimeStepRemainderProportion { get; set; }
/// <summary>
/// Collision Point
/// </summary>
UV CollisionPoint { get; set; }
/// <summary>
/// Distance to the collision point
/// </summary>
double LengthToCollision { get; set; }
/// <summary>
/// Movement trajectory
/// </summary>
Trajectory DisplacementTrajectory { get; set; }
/// <summary>
/// Calculates the normal vector at the collision point
/// </summary>
/// <returns></returns>
UV GetCollisionNormal();
}
/// <summary>
/// Collision will end points of edges
/// </summary>
internal class GetCollisionWithEndPoint : ICollision
{
/// <summary>
/// Movement trajectory
/// </summary>
public Trajectory DisplacementTrajectory { get; set; }
/// <summary>
/// The timestep proportion after collision
/// </summary>
public double TimeStepRemainderProportion { get; set; }
/// <summary>
/// Collision Point
/// </summary>
public UV CollisionPoint { get; set; }
/// <summary>
/// Distance to the collision point
/// </summary>
public double LengthToCollision { get; set; }
/// <summary>
/// Edge end point
/// </summary>
public UV EndPoint { get; set; }
/// <summary>
/// Collision buffer
/// </summary>
public double Buffer { get; set; }
/// <summary>
/// Creates an instance of the collision
/// </summary>
/// <param name="displacementTrajectory">Displacement Trajectory</param>
/// <param name="endPoint">point at the end of an edge</param>
/// <param name="buffer">Buffer</param>
public GetCollisionWithEndPoint(Trajectory displacementTrajectory, UV endPoint, double buffer)
{
this.DisplacementTrajectory = displacementTrajectory;
this.Buffer = buffer;
//this.TrajectoryLine = trajectoryLine;
this.EndPoint = endPoint;
//create a vector that connects the start point of the line to the center of the circle
UV sO = this.EndPoint - this.DisplacementTrajectory.TrajectoryLine.Start;
double b = -2 * sO.DotProduct(this.DisplacementTrajectory.TrajectoryNormalizedVector);
double c = sO.GetLengthSquared() - this.Buffer * this.Buffer;
var results = CollisionAnalyzer.QuadraticSolver(1, b, c);
if (results == null)
{
this.LengthToCollision = double.PositiveInfinity;
}
else if (results[0] > this.DisplacementTrajectory.TrajectoryLength)
{
this.LengthToCollision = double.PositiveInfinity;
}
else
{
this.CollisionPoint = this.DisplacementTrajectory.TrajectoryLine.Start + this.DisplacementTrajectory.TrajectoryNormalizedVector * results[1];
this.TimeStepRemainderProportion = results[1] / this.DisplacementTrajectory.TrajectoryLength;
this.LengthToCollision = this.DisplacementTrajectory.TrajectoryLength - results[1];
}
}
/// <summary>
/// Calculates the normal at the collision point
/// </summary>
/// <returns>Normal vector</returns>
public UV GetCollisionNormal()
{
UV normal = this.CollisionPoint - this.EndPoint;
normal.Unitize();
return normal;
}
public override string ToString()
{
return string.Format("Length To Collision: {0}; Time-Step Proportion: {1}", this.LengthToCollision.ToString("0.0000000"), this.TimeStepRemainderProportion.ToString("0.0000000"));
}
}
/// <summary>
/// Collision will an edge
/// </summary>
internal class GetCollisionWithEdge : ICollision
{
/// <summary>
/// Movement trajectory
/// </summary>
public Trajectory DisplacementTrajectory { get; set; }
/// <summary>
/// The timestep proportion after collision
/// </summary>
public double TimeStepRemainderProportion { get; set; }
/// <summary>
/// Collision Point
/// </summary>
public UV CollisionPoint { get; set; }
/// <summary>
/// Distance to the collision point
/// </summary>
public double LengthToCollision { get; set; }
/// <summary>
/// The direction for offset buffer
/// </summary>
private UV BufferDirection { get; set; }
/// <summary>
/// Creates an instance of the collision
/// </summary>
/// <param name="displacementTrajectory">Displacement Trajectory</param>
/// <param name="bufferEdge">Barrier edge offseted according to buffer</param>
/// <param name="tolerance">Tolerance by default set to the tolerance absolute value of the main document</param>
public GetCollisionWithEdge(Trajectory displacementTrajectory, UVLine bufferEdge, double tolerance = OSMDocument.AbsoluteTolerance)
{
this.DisplacementTrajectory = displacementTrajectory;
this.BufferDirection = bufferEdge.End - bufferEdge.Start;
double? t = this.DisplacementTrajectory.TrajectoryLine.Intersection(bufferEdge, this.DisplacementTrajectory.TrajectoryLength, tolerance);
if (t == null)
{
this.LengthToCollision = double.PositiveInfinity;
return;
}
this.CollisionPoint = this.DisplacementTrajectory.TrajectoryLine.Start + t.Value * this.DisplacementTrajectory.TrajectoryNormalizedVector;
this.LengthToCollision = DisplacementTrajectory.TrajectoryLength - t.Value;
this.TimeStepRemainderProportion = t.Value / this.DisplacementTrajectory.TrajectoryLength;
}
/// <summary>
/// Calculates the normal at the collision point
/// </summary>
/// <returns>Normal Vector</returns>
public UV GetCollisionNormal()
{
this.BufferDirection.Unitize();
var Tt = this.BufferDirection * (this.BufferDirection.DotProduct(this.DisplacementTrajectory.TrajectoryNormalizedVector));
UV normal = Tt - this.DisplacementTrajectory.TrajectoryNormalizedVector;
normal.Unitize();
return -1 * normal;
}
public override string ToString()
{
return string.Format("Length To Collision: {0}; Time-Step Proportion: {1}", this.LengthToCollision.ToString("0.0000000"), this.TimeStepRemainderProportion.ToString("0.0000000"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryLogicalTests
{
//TODO: Need tests on the short-circuit and non-short-circuit nature of the two forms.
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolAndTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolAnd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolAndAlsoTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolAndAlso(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolOrTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolOrElseTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolOrElse(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyBoolAnd(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.And(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBoolAndAlso(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.AndAlso(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a && b, f());
}
private static void VerifyBoolOr(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.Or(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a | b, f());
}
private static void VerifyBoolOrElse(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.OrElse(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a || b, f());
}
#endregion
public static IEnumerable<object[]> AndAlso_TestData()
{
yield return new object[] { 5, 3, 1, true };
yield return new object[] { 0, 3, 0, false };
yield return new object[] { 5, 0, 0, true };
}
[Theory]
[PerCompilationType(nameof(AndAlso_TestData))]
public static void AndAlso_UserDefinedOperator(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.AndAlso(Expression.Constant(left), Expression.Constant(right));
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// AndAlso only evaluates the false operator of left
Assert.Equal(0, left.TrueCallCount);
Assert.Equal(1, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// AndAlso only evaluates the operator if left is not false
Assert.Equal(calledMethod ? 1 : 0, left.OperatorCallCount);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void AndAlso_UserDefinedOperator_HasMethodNotOperator(bool useInterpreter)
{
BinaryExpression expression = Expression.AndAlso(Expression.Constant(new NamedMethods(5)), Expression.Constant(new NamedMethods(3)));
Func<NamedMethods> lambda = Expression.Lambda<Func<NamedMethods>>(expression).Compile(useInterpreter);
Assert.Equal(1, lambda().Value);
}
[Theory]
[PerCompilationType(nameof(AndAlso_TestData))]
public static void AndAlso_Method(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
MethodInfo method = typeof(TrueFalseClass).GetMethod(nameof(TrueFalseClass.AndMethod));
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.AndAlso(Expression.Constant(left), Expression.Constant(right), method);
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// AndAlso only evaluates the false operator of left
Assert.Equal(0, left.TrueCallCount);
Assert.Equal(1, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// AndAlso only evaluates the method if left is not false
Assert.Equal(0, left.OperatorCallCount);
Assert.Equal(calledMethod ? 1 : 0, left.MethodCallCount);
}
public static IEnumerable<object[]> OrElse_TestData()
{
yield return new object[] { 5, 3, 5, false };
yield return new object[] { 0, 3, 3, true };
yield return new object[] { 5, 0, 5, false };
}
[Theory]
[PerCompilationType(nameof(OrElse_TestData))]
public static void OrElse_UserDefinedOperator(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.OrElse(Expression.Constant(left), Expression.Constant(right));
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// OrElse only evaluates the true operator of left
Assert.Equal(1, left.TrueCallCount);
Assert.Equal(0, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// OrElse only evaluates the operator if left is not true
Assert.Equal(calledMethod ? 1 : 0, left.OperatorCallCount);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void OrElse_UserDefinedOperator_HasMethodNotOperator(bool useInterpreter)
{
BinaryExpression expression = Expression.OrElse(Expression.Constant(new NamedMethods(0)), Expression.Constant(new NamedMethods(3)));
Func<NamedMethods> lambda = Expression.Lambda<Func<NamedMethods>>(expression).Compile(useInterpreter);
Assert.Equal(3, lambda().Value);
}
[Theory]
[PerCompilationType(nameof(OrElse_TestData))]
public static void OrElse_Method(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
MethodInfo method = typeof(TrueFalseClass).GetMethod(nameof(TrueFalseClass.OrMethod));
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.OrElse(Expression.Constant(left), Expression.Constant(right), method);
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// OrElse only evaluates the true operator of left
Assert.Equal(1, left.TrueCallCount);
Assert.Equal(0, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// OrElse only evaluates the method if left is not true
Assert.Equal(0, left.OperatorCallCount);
Assert.Equal(calledMethod ? 1 : 0, left.MethodCallCount);
}
[Fact]
public static void AndAlso_CannotReduce()
{
Expression exp = Expression.AndAlso(Expression.Constant(true), Expression.Constant(false));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void OrElse_CannotReduce()
{
Expression exp = Expression.OrElse(Expression.Constant(true), Expression.Constant(false));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void AndAlso_LeftNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.AndAlso(null, Expression.Constant(true)));
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.AndAlso(null, Expression.Constant(true), null));
}
[Fact]
public static void OrElse_LeftNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.OrElse(null, Expression.Constant(true)));
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.OrElse(null, Expression.Constant(true), null));
}
[Fact]
public static void AndAlso_RightNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.AndAlso(Expression.Constant(true), null));
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.AndAlso(Expression.Constant(true), null, null));
}
[Fact]
public static void OrElse_RightNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.OrElse(Expression.Constant(true), null));
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.OrElse(Expression.Constant(true), null, null));
}
[Fact]
public static void AndAlso_BinaryOperatorNotDefined_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("hello")));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("hello"), null));
}
[Fact]
public static void OrElse_BinaryOperatorNotDefined_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant("hello")));
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant("hello"), null));
}
public static IEnumerable<object[]> InvalidMethod_TestData()
{
yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.InstanceMethod)) };
yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticVoidMethod)) };
}
[Theory]
[ClassData(typeof(OpenGenericMethodsData))]
[MemberData(nameof(InvalidMethod_TestData))]
public static void InvalidMethod_ThrowsArgumentException(MethodInfo method)
{
AssertExtensions.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
AssertExtensions.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
[Theory]
[InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod0))]
[InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod1))]
[InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod3))]
public static void Method_DoesntHaveTwoParameters_ThrowsArgumentException(Type type, string methodName)
{
MethodInfo method = type.GetMethod(methodName);
AssertExtensions.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
AssertExtensions.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
[Fact]
public static void AndAlso_Method_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant("abc"), Expression.Constant(5), method));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method));
}
[Fact]
public static void OrElse_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant("abc"), Expression.Constant(5), method));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method));
}
[Fact]
public static void MethodParametersNotEqual_ThrowsArgumentException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Invalid1));
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant("abc"), method));
}
[Fact]
public static void Method_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Invalid2));
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
[Fact]
public static void MethodDeclaringTypeHasNoTrueFalseOperator_ThrowsArgumentException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid));
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
#if FEATURE_COMPILE
[Fact]
public static void AndAlso_NoMethod_NotStatic_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public, type, new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_NotStatic_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public, type, new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void AndAlso_NoMethod_VoidReturnType_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_VoidReturnType_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
AssertExtensions.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
public static void AndAlso_NoMethod_DoesntHaveTwoParameters_ThrowsInvalidOperationException(int parameterCount)
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, type, Enumerable.Repeat(type, parameterCount).ToArray());
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
public static void OrElse_NoMethod_DoesntHaveTwoParameters_ThrowsInvalidOperationException(int parameterCount)
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, type, Enumerable.Repeat(type, parameterCount).ToArray());
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void AndAlso_NoMethod_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, type, new Type[] { typeof(int), type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, type, new Type[] { typeof(int), type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void AndAlso_NoMethod_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
public static IEnumerable<object[]> Operator_IncorrectMethod_TestData()
{
// Does not return bool
TypeBuilder typeBuilder1 = GetTypeBuilder();
yield return new object[] { typeBuilder1, typeof(void), new Type[] { typeBuilder1 } };
// Parameter is not assignable from left
yield return new object[] { GetTypeBuilder(), typeof(bool), new Type[] { typeof(int) } };
// Has two parameters
TypeBuilder typeBuilder2 = GetTypeBuilder();
yield return new object[] { typeBuilder2, typeof(bool), new Type[] { typeBuilder2, typeBuilder2 } };
// Has no parameters
yield return new object[] { GetTypeBuilder(), typeof(bool), new Type[0] };
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void Method_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
MethodInfo createdMethod = createdType.GetMethod("Method");
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void Method_FalseOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[]parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
MethodInfo createdMethod = createdType.GetMethod("Method");
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void AndAlso_NoMethod_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void OrElse_NoMethod_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData("op_True")]
[InlineData("op_False")]
public static void Method_NoTrueFalseOperator_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder builder = module.DefineType("Type");
MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
MethodInfo createdMethod = createdType.GetMethod("Method");
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
}
[Theory]
[InlineData("op_True")]
[InlineData("op_False")]
public static void AndAlso_NoMethod_NoTrueFalseOperator_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder builder = module.DefineType("Type");
MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData("op_True")]
[InlineData("op_False")]
public static void OrElse_NoMethod_NoTrueFalseOperator_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder builder = module.DefineType("Type");
MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void Method_ParamsDontMatchOperator_ThrowsInvalidOperationException()
{
TypeBuilder builder = GetTypeBuilder();
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
MethodInfo createdMethod = createdType.GetMethod("Method");
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), createdMethod));
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), createdMethod));
}
[Fact]
public static void AndAlso_NoMethod_ParamsDontMatchOperator_ThrowsInvalidOperationException()
{
TypeBuilder builder = GetTypeBuilder();
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5)));
}
[Fact]
public static void OrElse_NoMethod_ParamsDontMatchOperator_ThrowsInvalidOperationException()
{
TypeBuilder builder = GetTypeBuilder();
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5)));
}
#endif
[Fact]
public static void ImplicitConversionToBool_ThrowsArgumentException()
{
MethodInfo method = typeof(ClassWithImplicitBoolOperator).GetMethod(nameof(ClassWithImplicitBoolOperator.ConversionMethod));
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(new ClassWithImplicitBoolOperator()), Expression.Constant(new ClassWithImplicitBoolOperator()), method));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(new ClassWithImplicitBoolOperator()), Expression.Constant(new ClassWithImplicitBoolOperator()), method));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void AndAlso_LeftIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
AssertExtensions.Throws<ArgumentException>("left", () => Expression.AndAlso(unreadableExpression, Expression.Constant(true)));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void AndAlso_RightIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
AssertExtensions.Throws<ArgumentException>("right", () => Expression.AndAlso(Expression.Constant(true), unreadableExpression));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void OrElse_LeftIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
AssertExtensions.Throws<ArgumentException>("left", () => Expression.OrElse(unreadableExpression, Expression.Constant(true)));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void OrElse_RightIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
AssertExtensions.Throws<ArgumentException>("right", () => Expression.OrElse(Expression.Constant(false), unreadableExpression));
}
[Fact]
public static void ToStringTest()
{
// NB: These were && and || in .NET 3.5 but shipped as AndAlso and OrElse in .NET 4.0; we kept the latter.
BinaryExpression e1 = Expression.AndAlso(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b"));
Assert.Equal("(a AndAlso b)", e1.ToString());
BinaryExpression e2 = Expression.OrElse(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b"));
Assert.Equal("(a OrElse b)", e2.ToString());
}
#if FEATURE_COMPILE
[Fact]
public static void AndAlsoGlobalMethod()
{
MethodInfo method = GlobalMethod(typeof(int), new[] { typeof(int), typeof(int) });
Assert.Throws<ArgumentException>(() => Expression.AndAlso(Expression.Constant(1), Expression.Constant(2), method));
}
[Fact]
public static void OrElseGlobalMethod()
{
MethodInfo method = GlobalMethod(typeof(int), new [] { typeof(int), typeof(int) });
Assert.Throws<ArgumentException>(() => Expression.OrElse(Expression.Constant(1), Expression.Constant(2), method));
}
private static TypeBuilder GetTypeBuilder()
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
return module.DefineType("Type");
}
private static MethodInfo GlobalMethod(Type returnType, Type[] parameterTypes)
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module");
MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, returnType, parameterTypes);
globalMethod.GetILGenerator().Emit(OpCodes.Ret);
module.CreateGlobalFunctions();
return module.GetMethod(globalMethod.Name);
}
#endif
public class NonGenericClass
{
public void InstanceMethod() { }
public static void StaticVoidMethod() { }
public static int StaticIntMethod0() => 0;
public static int StaticIntMethod1(int i) => 0;
public static int StaticIntMethod3(int i1, int i2, int i3) => 0;
public static int StaticIntMethod2Valid(int i1, int i2) => 0;
public static int StaticIntMethod2Invalid1(int i1, string i2) => 0;
public static string StaticIntMethod2Invalid2(int i1, int i2) => "abc";
}
public class TrueFalseClass
{
public int TrueCallCount { get; set; }
public int FalseCallCount { get; set; }
public int OperatorCallCount { get; set; }
public int MethodCallCount { get; set; }
public TrueFalseClass(int value) { Value = value; }
public int Value { get; }
public static bool operator true(TrueFalseClass c)
{
c.TrueCallCount++;
return c.Value != 0;
}
public static bool operator false(TrueFalseClass c)
{
c.FalseCallCount++;
return c.Value == 0;
}
public static TrueFalseClass operator &(TrueFalseClass c1, TrueFalseClass c2)
{
c1.OperatorCallCount++;
return new TrueFalseClass(c1.Value & c2.Value);
}
public static TrueFalseClass AndMethod(TrueFalseClass c1, TrueFalseClass c2)
{
c1.MethodCallCount++;
return new TrueFalseClass(c1.Value & c2.Value);
}
public static TrueFalseClass operator |(TrueFalseClass c1, TrueFalseClass c2)
{
c1.OperatorCallCount++;
return new TrueFalseClass(c1.Value | c2.Value);
}
public static TrueFalseClass OrMethod(TrueFalseClass c1, TrueFalseClass c2)
{
c1.MethodCallCount++;
return new TrueFalseClass(c1.Value | c2.Value);
}
}
public class NamedMethods
{
public NamedMethods(int value) { Value = value; }
public int Value { get; }
public static bool operator true(NamedMethods c) => c.Value != 0;
public static bool operator false(NamedMethods c) => c.Value == 0;
public static NamedMethods op_BitwiseAnd(NamedMethods c1, NamedMethods c2) => new NamedMethods(c1.Value & c2.Value);
public static NamedMethods op_BitwiseOr(NamedMethods c1, NamedMethods c2) => new NamedMethods(c1.Value | c2.Value);
}
public class ClassWithImplicitBoolOperator
{
public static ClassWithImplicitBoolOperator ConversionMethod(ClassWithImplicitBoolOperator bool1, ClassWithImplicitBoolOperator bool2)
{
return bool1;
}
public static implicit operator bool(ClassWithImplicitBoolOperator boolClass) => true;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.DDF
{
using System;
using NPOI.Util;
using System.Diagnostics;
public class SysIndexSource
{
internal static SysIndexSource[] Values()
{
return new SysIndexSource[] {
SysIndexSource.FILL_COLOR,
SysIndexSource.LINE_OR_FILL_COLOR,
SysIndexSource.SHADOW_COLOR,
SysIndexSource.CURRENT_OR_LAST_COLOR,
SysIndexSource.FILL_BACKGROUND_COLOR,
SysIndexSource.LINE_BACKGROUND_COLOR,
SysIndexSource.FILL_OR_LINE_COLOR
};
}
/* Use the fill color of the shape. */
public static SysIndexSource FILL_COLOR = new SysIndexSource(0xF0),
/* If the shape Contains a line, use the line color of the shape. Otherwise, use the fill color. */
LINE_OR_FILL_COLOR = new SysIndexSource(0xF1),
/* Use the line color of the shape. */
LINE_COLOR = new SysIndexSource(0xF2),
/* Use the shadow color of the shape. */
SHADOW_COLOR = new SysIndexSource(0xF3),
/* Use the current, or last-used, color. */
CURRENT_OR_LAST_COLOR = new SysIndexSource(0xF4),
/* Use the fill background color of the shape. */
FILL_BACKGROUND_COLOR = new SysIndexSource(0xF5),
/* Use the line background color of the shape. */
LINE_BACKGROUND_COLOR = new SysIndexSource(0xF6),
/* If the shape Contains a Fill, use the fill color of the shape. Otherwise, use the line color. */
FILL_OR_LINE_COLOR = new SysIndexSource(0xF7)
;
internal int value;
internal SysIndexSource(int value) { this.value = value; }
}
/**
* The following enum specifies values that indicate special procedural properties that
* are used to modify the color components of another color. These values are combined with
* those of the {@link SysIndexSource} enum or with a user-specified color.
* The first six values are mutually exclusive.
*/
public class SysIndexProcedure
{
internal static SysIndexProcedure[] Values()
{
return new SysIndexProcedure[] {
SysIndexProcedure.DARKEN_COLOR,
SysIndexProcedure.LIGHTEN_COLOR,
SysIndexProcedure.ADD_GRAY_LEVEL,
SysIndexProcedure.SUB_GRAY_LEVEL,
SysIndexProcedure.REVERSE_GRAY_LEVEL,
SysIndexProcedure.THRESHOLD,
SysIndexProcedure.INVERT_AFTER,
SysIndexProcedure.INVERT_HIGHBIT_AFTER
};
}
/*
* Darken the color by the value that is specified in the blue field.
* A blue value of 0xFF specifies that the color is to be left unChanged,
* whereas a blue value of 0x00 specifies that the color is to be completely darkened.
*/
public static SysIndexProcedure DARKEN_COLOR = new SysIndexProcedure(0x01),
/*
* Lighten the color by the value that is specified in the blue field.
* A blue value of 0xFF specifies that the color is to be left unChanged,
* whereas a blue value of 0x00 specifies that the color is to be completely lightened.
*/
LIGHTEN_COLOR = new SysIndexProcedure(0x02),
/*
* Add a gray level RGB value. The blue field Contains the gray level to Add:
* NewColor = SourceColor + gray
*/
ADD_GRAY_LEVEL = new SysIndexProcedure(0x03),
/*
* Subtract a gray level RGB value. The blue field Contains the gray level to subtract:
* NewColor = SourceColor - gray
*/
SUB_GRAY_LEVEL = new SysIndexProcedure(0x04),
/*
* Reverse-subtract a gray level RGB value. The blue field Contains the gray level from
* which to subtract:
* NewColor = gray - SourceColor
*/
REVERSE_GRAY_LEVEL = new SysIndexProcedure(0x05),
/*
* If the color component being modified is less than the parameter Contained in the blue
* field, Set it to the minimum intensity. If the color component being modified is greater
* than or equal to the parameter, Set it to the maximum intensity.
*/
THRESHOLD = new SysIndexProcedure(0x06),
/*
* After making other modifications, invert the color.
* This enum value is only for documentation and won't be directly returned.
*/
INVERT_AFTER = new SysIndexProcedure(0x20),
/*
* After making other modifications, invert the color by toggling just the high bit of each
* color channel.
* This enum value is only for documentation and won't be directly returned.
*/
INVERT_HIGHBIT_AFTER = new SysIndexProcedure(0x40)
;
internal BitField mask;
internal SysIndexProcedure(int mask)
{
this.mask = new BitField(mask);
}
}
/**
* An OfficeArtCOLORREF structure entry which also handles color extension opid data
*/
public class EscherColorRef
{
int opid = -1;
int colorRef = 0;
/*
* A bit that specifies whether the system color scheme will be used to determine the color.
* A value of 0x1 specifies that green and red will be treated as an unsigned 16-bit index
* into the system color table. Values less than 0x00F0 map directly to system colors.
*/
private static BitField FLAG_SYS_INDEX = new BitField(0x10000000);
/*
* A bit that specifies whether the current application-defined color scheme will be used
* to determine the color. A value of 0x1 specifies that red will be treated as an index
* into the current color scheme table. If this value is 0x1, green and blue MUST be 0x00.
*/
private static BitField FLAG_SCHEME_INDEX = new BitField(0x08000000);
/*
* A bit that specifies whether the color is a standard RGB color.
* 0x0 : The RGB color MAY use halftone dithering to display.
* 0x1 : The color MUST be a solid color.
*/
private static BitField FLAG_SYSTEM_RGB = new BitField(0x04000000);
/*
* A bit that specifies whether the current palette will be used to determine the color.
* A value of 0x1 specifies that red, green, and blue contain an RGB value that will be
* matched in the current color palette. This color MUST be solid.
*/
private static BitField FLAG_PALETTE_RGB = new BitField(0x02000000);
/*
* A bit that specifies whether the current palette will be used to determine the color.
* A value of 0x1 specifies that green and red will be treated as an unsigned 16-bit index into
* the current color palette. This color MAY be dithered. If this value is 0x1, blue MUST be 0x00.
*/
private static BitField FLAG_PALETTE_INDEX = new BitField(0x01000000);
/*
* An unsigned integer that specifies the intensity of the blue color channel. A value
* of 0x00 has the minimum blue intensity. A value of 0xFF has the maximum blue intensity.
*/
private static BitField FLAG_BLUE = new BitField(0x00FF0000);
/*
* An unsigned integer that specifies the intensity of the green color channel. A value
* of 0x00 has the minimum green intensity. A value of 0xFF has the maximum green intensity.
*/
private static BitField FLAG_GREEN = new BitField(0x0000FF00);
/*
* An unsigned integer that specifies the intensity of the red color channel. A value
* of 0x00 has the minimum red intensity. A value of 0xFF has the maximum red intensity.
*/
private static BitField FLAG_RED = new BitField(0x000000FF);
public EscherColorRef(int colorRef)
{
this.colorRef = colorRef;
}
public EscherColorRef(byte[] source, int start, int len)
{
Debug.Assert(len == 4 || len == 6);
int offset = start;
if (len == 6)
{
opid = LittleEndian.GetUShort(source, offset);
offset += 2;
}
colorRef = LittleEndian.GetInt(source, offset);
}
public bool HasSysIndexFlag()
{
return FLAG_SYS_INDEX.IsSet(colorRef);
}
public void SetSysIndexFlag(bool flag)
{
FLAG_SYS_INDEX.SetBoolean(colorRef, flag);
}
public bool HasSchemeIndexFlag()
{
return FLAG_SCHEME_INDEX.IsSet(colorRef);
}
public void SetSchemeIndexFlag(bool flag)
{
FLAG_SCHEME_INDEX.SetBoolean(colorRef, flag);
}
public bool HasSystemRGBFlag()
{
return FLAG_SYSTEM_RGB.IsSet(colorRef);
}
public void SetSystemRGBFlag(bool flag)
{
FLAG_SYSTEM_RGB.SetBoolean(colorRef, flag);
}
public bool HasPaletteRGBFlag()
{
return FLAG_PALETTE_RGB.IsSet(colorRef);
}
public void SetPaletteRGBFlag(bool flag)
{
FLAG_PALETTE_RGB.SetBoolean(colorRef, flag);
}
public bool HasPaletteIndexFlag()
{
return FLAG_PALETTE_INDEX.IsSet(colorRef);
}
public void SetPaletteIndexFlag(bool flag)
{
FLAG_PALETTE_INDEX.SetBoolean(colorRef, flag);
}
public int[] GetRGB()
{
int[] rgb = {
FLAG_RED.GetValue(colorRef),
FLAG_GREEN.GetValue(colorRef),
FLAG_BLUE.GetValue(colorRef)
};
return rgb;
}
/**
* @return {@link SysIndexSource} if {@link #hasSysIndexFlag()} is {@code true}, otherwise null
*/
public SysIndexSource GetSysIndexSource()
{
if (!HasSysIndexFlag()) return null;
int val = FLAG_RED.GetValue(colorRef);
foreach (SysIndexSource sis in SysIndexSource.Values())
{
if (sis.value == val) return sis;
}
return null;
}
/**
* Return the {@link SysIndexProcedure} - for invert flag use {@link #getSysIndexInvert()}
* @return {@link SysIndexProcedure} if {@link #hasSysIndexFlag()} is {@code true}, otherwise null
*/
public SysIndexProcedure GetSysIndexProcedure()
{
if (!HasSysIndexFlag()) return null;
int val = FLAG_RED.GetValue(colorRef);
foreach (SysIndexProcedure sip in SysIndexProcedure.Values())
{
if (sip == SysIndexProcedure.INVERT_AFTER || sip == SysIndexProcedure.INVERT_HIGHBIT_AFTER) continue;
if (sip.mask.IsSet(val)) return sip;
}
return null;
}
/**
* @return 0 for no invert flag, 1 for {@link SysIndexProcedure#INVERT_AFTER} and
* 2 for {@link SysIndexProcedure#INVERT_HIGHBIT_AFTER}
*/
public int GetSysIndexInvert()
{
if (!HasSysIndexFlag()) return 0;
int val = FLAG_GREEN.GetValue(colorRef);
if ((SysIndexProcedure.INVERT_AFTER.mask.IsSet(val))) return 1;
if ((SysIndexProcedure.INVERT_HIGHBIT_AFTER.mask.IsSet(val))) return 2;
return 0;
}
/**
* @return index of the scheme color or -1 if {@link #hasSchemeIndexFlag()} is {@code false}
*
* @see NPOI.HSLF.Record.ColorSchemeAtom#getColor(int)
*/
public int GetSchemeIndex()
{
if (!HasSchemeIndexFlag()) return -1;
return FLAG_RED.GetValue(colorRef);
}
/**
* @return index of current palette (color) or -1 if {@link #hasPaletteIndexFlag()} is {@code false}
*/
public int GetPaletteIndex()
{
if (!HasPaletteIndexFlag()) return -1;
return (FLAG_GREEN.GetValue(colorRef) << 8) & FLAG_RED.GetValue(colorRef);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using Internal.Runtime.CompilerServices;
namespace System
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
public readonly struct Memory<T>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is an array/string or an owned memory
// if (_index >> 31) == 1, object _object is an OwnedMemory<T>
// else, object _object is a T[] or a string. It can only be a string if the Memory<T> was created by
// using unsafe / marshaling code to reinterpret a ReadOnlyMemory<char> wrapped around a string as
// a Memory<T>.
private readonly object _object;
private readonly int _index;
private readonly int _length;
private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
_object = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = array;
_index = start;
_length = length;
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(OwnedMemory<T> owner, int index, int length)
{
if (owner == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory);
if (index < 0 || length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = owner;
_index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
_length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Memory(object obj, int index, int length)
{
// No validation performed; caller must provide any necessary validation.
_object = obj;
_index = index;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(T[] array) => new Memory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) =>
Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
//Debugger Display = {T[length]}
private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
/// <summary>
/// Returns an empty <see cref="Memory{T}"/>
/// </summary>
public static Memory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
return new Memory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
return new Memory<T>(_object, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public Span<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_index < 0)
{
return ((OwnedMemory<T>)_object).Span.Slice(_index & RemoveOwnedFlagBitMask, _length);
}
else if (typeof(T) == typeof(char) && _object is string s)
{
// This is dangerous, returning a writable span for a string that should be immutable.
// However, we need to handle the case where a ReadOnlyMemory<char> was created from a string
// and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code,
// in which case that's the dangerous operation performed by the dev, and we're just following
// suit here to make it work as best as possible.
return new Span<T>(ref Unsafe.As<char, T>(ref s.GetRawStringData()), s.Length).Slice(_index, _length);
}
else if (_object != null)
{
return new Span<T>((T[])_object, _index, _length);
}
else
{
return default;
}
}
}
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
public unsafe MemoryHandle Retain(bool pin = false)
{
MemoryHandle memoryHandle = default;
if (pin)
{
if (_index < 0)
{
memoryHandle = ((OwnedMemory<T>)_object).Pin();
memoryHandle.AddOffset((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>());
}
else if (typeof(T) == typeof(char) && _object is string s)
{
// This case can only happen if a ReadOnlyMemory<char> was created around a string
// and then that was cast to a Memory<char> using unsafe / marshaling code. This needs
// to work, however, so that code that uses a single Memory<char> field to store either
// a readable ReadOnlyMemory<char> or a writable Memory<char> can still be pinned and
// used for interop purposes.
GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref s.GetRawStringData()), _index);
memoryHandle = new MemoryHandle(null, pointer, handle);
}
else if (_object is T[] array)
{
var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index);
memoryHandle = new MemoryHandle(null, pointer, handle);
}
}
else
{
if (_index < 0)
{
((OwnedMemory<T>)_object).Retain();
memoryHandle = new MemoryHandle((OwnedMemory<T>)_object);
}
}
return memoryHandle;
}
/// <summary>
/// Get an array segment from the underlying memory.
/// If unable to get the array segment, return false with a default array segment.
/// </summary>
public bool TryGetArray(out ArraySegment<T> arraySegment)
{
if (_index < 0)
{
if (((OwnedMemory<T>)_object).TryGetArray(out var segment))
{
arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length);
return true;
}
}
else if (_object is T[] arr)
{
arraySegment = new ArraySegment<T>(arr, _index, _length);
return true;
}
arraySegment = default(ArraySegment<T>);
return false;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyMemory<T>)
{
return ((ReadOnlyMemory<T>)obj).Equals(this);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(Memory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return _object != null ? CombineHashCodes(_object.GetHashCode(), _index.GetHashCode(), _length.GetHashCode()) : 0;
}
private static int CombineHashCodes(int left, int right)
{
return ((left << 5) + left) ^ right;
}
private static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
}
}
| |
/*
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* 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.Management.Automation;
using Trisoft.ISHRemote.Objects;
using Trisoft.ISHRemote.Objects.Public;
using Trisoft.ISHRemote.Exceptions;
using Trisoft.ISHRemote.HelperClasses;
using System.Linq;
namespace Trisoft.ISHRemote.Cmdlets.Folder
{
/// <summary>
/// <para type="synopsis">The Get-IshFolder cmdlet retrieves metadata for the folders by providing one of the following input data:
/// - FolderPath string with the separated full folder path
/// - FolderIds array containing identifiers of the folders
/// - BaseFolder enum value referencing the specified root folder
/// - IshFolder[] array passed through the pipeline Query and Reference folders are not supported.</para>
/// <para type="description">The Get-IshFolder cmdlet retrieves metadata for the folders by providing one of the following input data:
/// - FolderPath string with the separated full folder path
/// - FolderIds array containing identifiers of the folders
/// - BaseFolder enum value referencing the specified root folder
/// - IshFolder[] array passed through the pipeline Query and Reference folders are not supported.</para>
/// </summary>
/// <example>
/// <code>
/// $ishSession = New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential Admin
/// Get-IshFolder -FolderPath "\General\__ISHRemote\Add-IshPublicationOutput\Pub"
/// </code>
/// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Returns the IshFolder object.</para>
/// </example>
/// <example>
/// <code>
/// $ishSession = New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential Admin
/// (Get-IshFolder -BaseFolder Data).name
/// </code>
/// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Returns the name of the root data folder, typically called 'General'.</para>
/// </example>
/// <example>
/// <code>
/// $ishSession = New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential "Admin"
/// $requestedMetadata = Set-IshMetadataFilterField -Name "FNAME" -Level "None"
/// $folderId = 7598 # provide a real folder identifier
/// $ishFolder = Get-IshFolder -FolderId $folderId -RequestedMetaData $requestedMetadata
/// $retrievedFolderName = $ishFolder.name
/// </code>
/// <para>Get folder name using Id with explicit requested metadata</para>
/// </example>
/// <example>
/// <code>
/// $ishSession = New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential "Admin"
/// $ishFolders = Get-IshFolder -FolderPath "General\Myfolder" -FolderTypeFilter @("ISHModule", "ISHMasterDoc", "ISHLibrary") -Recurse
/// </code>
/// <para>Get folders recursively with filtering on folder type</para>
/// </example>
[Cmdlet(VerbsCommon.Get, "IshFolder", SupportsShouldProcess = false)]
[OutputType(typeof(IshFolder))]
public sealed class GetIshFolder : FolderCmdlet
{
/// <summary>
/// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderIdGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderPathGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "BaseFolderGroup")]
[ValidateNotNullOrEmpty]
public IshSession IshSession { get; set; }
/// <summary>
/// <para type="description">Separated string with the full folder path, e.g. "General\Project\Topics"</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderPathGroup"), ValidateNotNull]
public string FolderPath { get; set; }
/// <summary>
/// <para type="description">Unique folder identifier</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderIdGroup"), ValidateNotNullOrEmpty, ValidateRange(1, long.MaxValue)]
public long FolderId { get; set; }
/// <summary>
/// <para type="description">The BaseFolder enumeration to get subfolders for the specified root folder</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "BaseFolderGroup"), ValidateNotNullOrEmpty]
public Enumerations.BaseFolder BaseFolder { get; set; }
/// <summary>
/// <para type="description">Folders for which to retrieve the metadata. This array can be passed through the pipeline or explicitly passed via the parameter.</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")]
[AllowEmptyCollection]
public IshFolder[] IshFolder { get; set; }
/// <summary>
/// <para type="description">The metadata fields to retrieve</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderIdGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderPathGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "BaseFolderGroup")]
[ValidateNotNullOrEmpty]
public IshField[] RequestedMetadata { get; set; }
/// <summary>
/// <para type="description">Perform recursive retrieval of the provided incoming folder(s)</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderIdGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderPathGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "BaseFolderGroup")]
public SwitchParameter Recurse { get; set; }
/// <summary>
/// <para type="description">Perform recursive retrieval of up to Depth of the provided incoming folder(s)</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderIdGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderPathGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "BaseFolderGroup")]
public int Depth
{
get { return _maxDepth; }
set { _maxDepth = value; }
}
/// <summary>
/// <para type="description">Recursive retrieval will loop all folder, this filter will only return folder matching the filter to the pipeline</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderIdGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderPathGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFolderGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "BaseFolderGroup")]
[ValidateNotNullOrEmpty]
public Enumerations.IshFolderType[] FolderTypeFilter { get; set; }
#region Private fields
/// <summary>
/// Initially holds incoming IshObject entries from the pipeline to correct the incorrect array-objects from Trisoft.Automation
/// </summary>
private readonly List<IshFolder> _retrievedIshFolders = new List<IshFolder>();
/// <summary>
/// Initially holds incoming folder id entries from the pipeline to correct the incorrect array-objects from Trisoft.Automation
/// </summary>
private readonly List<long> _retrievedFolderIds = new List<long>();
/// <summary>
/// Requested metadata to be shared across all (recursive) calls
/// </summary>
private IshFields _requestedMetadata;
/// <summary>
/// Initially set to max recursive depth we can handle
/// </summary>
private int _maxDepth = int.MaxValue;
#endregion
protected override void BeginProcessing()
{
if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); }
if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); }
WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}");
base.BeginProcessing();
}
/// <summary>
/// Process the Get-IshFolder commandlet.
/// </summary>
/// <exception cref="TrisoftAutomationException"></exception>
/// <exception cref="Exception"></exception>
protected override void ProcessRecord()
{
try
{
switch (ParameterSetName)
{
case "IshFolderGroup":
foreach (IshFolder ishFolder in IshFolder)
{
_retrievedIshFolders.Add(ishFolder);
}
break;
case "FolderIdGroup":
_retrievedFolderIds.Add(FolderId);
break;
}
}
catch (TrisoftAutomationException trisoftAutomationException)
{
ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null));
}
catch (Exception exception)
{
ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null));
}
}
/// <summary>
/// Process the Get-IshFolder commandlet.
/// </summary>
/// <exception cref="TrisoftAutomationException"></exception>
/// <exception cref="Exception"></exception>
/// <remarks>Writes an <see cref="IshFolder"/> object to the pipeline.</remarks>
protected override void EndProcessing()
{
try
{
// 1. Validating the input
WriteDebug("Validating");
List<IshFolder> returnIshFolders = new List<IshFolder>();
// 2. Doing Retrieve
WriteDebug("Retrieving");
_requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, new IshFields(RequestedMetadata), Enumerations.ActionMode.Read);
if (ParameterSetName == "IshFolderGroup" && _retrievedIshFolders.Count > 0)
{
var folderCardIds = _retrievedIshFolders.Select(ishFolder => Convert.ToInt64(ishFolder.IshFolderRef)).ToList();
WriteDebug($"Retrieving CardIds.length[{folderCardIds.Count}] RequestedMetadata.length[{_requestedMetadata.ToXml().Length}] 0/{folderCardIds.Count}");
// Devides the list of folder card ids in different lists that all have maximally MetadataBatchSize elements
List<List<long>> devidedFolderCardIdsList = DevideListInBatches<long>(folderCardIds, IshSession.MetadataBatchSize);
int currentFolderCardIdCount = 0;
foreach (List<long> folderCardIdBatch in devidedFolderCardIdsList)
{
// Process card ids in batches
string xmlIshFolders = IshSession.Folder25.RetrieveMetadataByIshFolderRefs(folderCardIdBatch.ToArray(), _requestedMetadata.ToXml());
IshFolders retrievedObjects = new IshFolders(xmlIshFolders);
returnIshFolders.AddRange(retrievedObjects.Folders);
currentFolderCardIdCount += folderCardIdBatch.Count;
WriteDebug($"Retrieving CardIds.length[{ folderCardIdBatch.Count}] RequestedMetadata.length[{ _requestedMetadata.ToXml().Length}] {currentFolderCardIdCount}/{folderCardIds.Count}");
}
}
else if (ParameterSetName == "FolderIdGroup" && _retrievedFolderIds.Count > 0)
{
WriteDebug($"Retrieving CardIds.length[{ _retrievedFolderIds.Count}] RequestedMetadata.length[{_requestedMetadata.ToXml().Length}] 0/{_retrievedFolderIds.Count}");
// Devides the list of folder card ids in different lists that all have maximally MetadataBatchSize elements
List<List<long>> devidedFolderCardIdsList = DevideListInBatches<long>(_retrievedFolderIds, IshSession.MetadataBatchSize);
int currentFolderCardIdCount = 0;
foreach (List<long> folderCardIdBatch in devidedFolderCardIdsList)
{
// Process card ids in batches
string xmlIshFolders = IshSession.Folder25.RetrieveMetadataByIshFolderRefs(folderCardIdBatch.ToArray(), _requestedMetadata.ToXml());
IshFolders retrievedObjects = new IshFolders(xmlIshFolders);
returnIshFolders.AddRange(retrievedObjects.Folders);
currentFolderCardIdCount += folderCardIdBatch.Count;
WriteDebug($"Retrieving CardIds.length[{folderCardIdBatch.Count}] RequestedMetadata.length[{_requestedMetadata.ToXml().Length}] {currentFolderCardIdCount}/{_retrievedFolderIds.Count}");
}
}
else if (ParameterSetName == "FolderPathGroup")
{
// Retrieve using provided parameter FolderPath
// Parse FolderPath input parameter: get basefolderName(1st element of an array)
string folderPath = FolderPath;
string[] folderPathElements = folderPath.Split(
new string[] { IshSession.FolderPathSeparator }, StringSplitOptions.RemoveEmptyEntries);
string baseFolderLabel = folderPathElements[0];
// remaining folder path elements
string[] folderPathTrisoft = new string[folderPathElements.Length - 1];
Array.Copy(folderPathElements, 1, folderPathTrisoft, 0, folderPathElements.Length - 1);
WriteDebug($"FolderPath[{ folderPath}]");
string xmlIshFolder = IshSession.Folder25.GetMetadata(
BaseFolderLabelToEnum(IshSession, baseFolderLabel),
folderPathTrisoft,
_requestedMetadata.ToXml());
IshFolders retrievedFolders = new IshFolders(xmlIshFolder, "ishfolder");
returnIshFolders.AddRange(retrievedFolders.Folders);
}
else if (ParameterSetName == "BaseFolderGroup")
{
// Retrieve using BaseFolder string (enumeration)
var baseFolder = EnumConverter.ToBaseFolder<Folder25ServiceReference.BaseFolder>(BaseFolder);
WriteDebug($"BaseFolder[{baseFolder}]");
string xmlIshFolders = IshSession.Folder25.GetMetadata(
baseFolder,
new string[0],
_requestedMetadata.ToXml());
IshFolders retrievedFolders = new IshFolders(xmlIshFolders, "ishfolder");
returnIshFolders.AddRange(retrievedFolders.Folders);
}
// 3b. Write it
if (!Recurse)
{
if (FolderTypeFilter == null)
{
WriteDebug($"returned object count[{returnIshFolders.Count}]");
WriteObject(IshSession, ISHType, returnIshFolders.ConvertAll(x => (IshBaseObject)x), true);
}
else
{
List<IshFolder> filteredIshFolders = new List<IshFolder>();
foreach (var returnIshFolder in returnIshFolders)
{
if (FolderTypeFilter.Contains(returnIshFolder.IshFolderType))
{
filteredIshFolders.Add(returnIshFolder);
}
else
{
string folderName = returnIshFolder.IshFields.GetFieldValue("FNAME", Enumerations.Level.None, Enumerations.ValueType.Value);
string folderpath = returnIshFolder.IshFields.GetFieldValue("FISHFOLDERPATH", Enumerations.Level.None, Enumerations.ValueType.Value);
WriteVerbose(folderpath.Replace(IshSession.Separator, IshSession.FolderPathSeparator) + IshSession.FolderPathSeparator + folderName + " skipped");
}
}
WriteDebug($"returned object count after filtering[{filteredIshFolders.Count}]");
WriteObject(IshSession, ISHType, filteredIshFolders.ConvertAll(x => (IshBaseObject)x), true);
}
}
else
{
WriteParentProgress("Recursive folder retrieve...", 0, returnIshFolders.Count);
foreach (IshFolder ishFolder in returnIshFolders)
{
WriteParentProgress("Recursive folder retrieve...", ++_parentCurrent, returnIshFolders.Count);
if (_maxDepth > 0)
{
RetrieveRecursive(ishFolder, 0, _maxDepth);
}
}
}
}
catch (TrisoftAutomationException trisoftAutomationException)
{
ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null));
}
catch (Exception exception)
{
ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null));
}
finally
{
base.EndProcessing();
}
}
private void RetrieveRecursive(IshFolder ishFolder, int currentDepth, int maxDepth)
{
// put them on the pipeline depth-first-traversel
string folderName = ishFolder.IshFields.GetFieldValue("FNAME", Enumerations.Level.None, Enumerations.ValueType.Value);
// only return IshFolder objects to the pipeline if the filter is either not set, or the current filter passes the filter criteria
if (FolderTypeFilter != null && FolderTypeFilter.Length > 0)
{
if (FolderTypeFilter.Contains<Enumerations.IshFolderType>(ishFolder.IshFolderType))
{
WriteVerbose(new string('>', currentDepth) + IshSession.FolderPathSeparator + folderName + IshSession.FolderPathSeparator);
WriteObject(IshSession, ISHType, ishFolder, true);
}
else
{
WriteVerbose(new string('>', currentDepth) + IshSession.FolderPathSeparator + folderName + IshSession.FolderPathSeparator + " skipped");
}
}
else
{
WriteVerbose(new string('>', currentDepth) + IshSession.FolderPathSeparator + folderName + IshSession.FolderPathSeparator);
WriteObject(IshSession, ISHType, ishFolder, true);
}
if (currentDepth < (maxDepth - 1))
{
WriteDebug($"RetrieveRecursive IshFolderRef[{ishFolder.IshFolderRef}] folderName[{folderName}] ({currentDepth}<{maxDepth})");
string xmlIshFolders = IshSession.Folder25.GetSubFoldersByIshFolderRef(ishFolder.IshFolderRef);
// GetSubFolders contains ishfolder for the parent folder + ishfolder inside for the subfolders
IshFolders retrievedFolders = new IshFolders(xmlIshFolders, "ishfolder/ishfolder");
if (retrievedFolders.Ids.Length > 0)
{
// Add the required fields (needed for pipe operations)
xmlIshFolders = IshSession.Folder25.RetrieveMetadataByIshFolderRefs(retrievedFolders.Ids,_requestedMetadata.ToXml());
retrievedFolders = new IshFolders(xmlIshFolders);
// sort them
++currentDepth;
IshFolder[] sortedFolders = retrievedFolders.SortedFolders;
WriteParentProgress("Recursive folder retrieve...", _parentCurrent, _parentTotal + sortedFolders.Count());
foreach (IshFolder retrievedIshFolder in sortedFolders)
{
WriteParentProgress("Recursive folder retrieve...", ++_parentCurrent, _parentTotal);
RetrieveRecursive(retrievedIshFolder, currentDepth, maxDepth);
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Linq.Expressions.Compiler
{
/// <summary>
/// Dynamic Language Runtime Compiler.
/// This part compiles lambdas.
/// </summary>
internal partial class LambdaCompiler
{
private static int s_counter;
internal void EmitConstantArray<T>(T[] array)
{
// Emit as runtime constant if possible
// if not, emit into IL
if (_method is DynamicMethod)
{
EmitConstant(array, typeof(T[]));
}
else if (_typeBuilder != null)
{
// store into field in our type builder, we will initialize
// the value only once.
FieldBuilder fb = CreateStaticField("ConstantArray", typeof(T[]));
Label l = _ilg.DefineLabel();
_ilg.Emit(OpCodes.Ldsfld, fb);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Bne_Un, l);
_ilg.EmitArray(array);
_ilg.Emit(OpCodes.Stsfld, fb);
_ilg.MarkLabel(l);
_ilg.Emit(OpCodes.Ldsfld, fb);
}
else
{
_ilg.EmitArray(array);
}
}
private void EmitClosureCreation(LambdaCompiler inner)
{
bool closure = inner._scope.NeedsClosure;
bool boundConstants = inner._boundConstants.Count > 0;
if (!closure && !boundConstants)
{
_ilg.EmitNull();
return;
}
// new Closure(constantPool, currentHoistedLocals)
if (boundConstants)
{
_boundConstants.EmitConstant(this, inner._boundConstants.ToArray(), typeof(object[]));
}
else
{
_ilg.EmitNull();
}
if (closure)
{
_scope.EmitGet(_scope.NearestHoistedLocals.SelfVariable);
}
else
{
_ilg.EmitNull();
}
_ilg.EmitNew(typeof(Closure).GetConstructor(new Type[] { typeof(object[]), typeof(object[]) }));
}
/// <summary>
/// Emits code which creates new instance of the delegateType delegate.
///
/// Since the delegate is getting closed over the "Closure" argument, this
/// cannot be used with virtual/instance methods (inner must be static method)
/// </summary>
private void EmitDelegateConstruction(LambdaCompiler inner)
{
Type delegateType = inner._lambda.Type;
DynamicMethod dynamicMethod = inner._method as DynamicMethod;
if (dynamicMethod != null)
{
// Emit MethodInfo.CreateDelegate instead because DynamicMethod is not in Windows 8 Profile
_boundConstants.EmitConstant(this, dynamicMethod, typeof(MethodInfo));
_ilg.EmitType(delegateType);
EmitClosureCreation(inner);
_ilg.Emit(OpCodes.Callvirt, typeof(MethodInfo).GetMethod("CreateDelegate", new Type[] { typeof(Type), typeof(object) }));
_ilg.Emit(OpCodes.Castclass, delegateType);
}
else
{
// new DelegateType(closure)
EmitClosureCreation(inner);
_ilg.Emit(OpCodes.Ldftn, (MethodInfo)inner._method);
_ilg.Emit(OpCodes.Newobj, (ConstructorInfo)(delegateType.GetMember(".ctor")[0]));
}
}
/// <summary>
/// Emits a delegate to the method generated for the LambdaExpression.
/// May end up creating a wrapper to match the requested delegate type.
/// </summary>
/// <param name="lambda">Lambda for which to generate a delegate</param>
///
private void EmitDelegateConstruction(LambdaExpression lambda)
{
// 1. Create the new compiler
LambdaCompiler impl;
if (_method is DynamicMethod)
{
impl = new LambdaCompiler(_tree, lambda);
}
else
{
// When the lambda does not have a name or the name is empty, generate a unique name for it.
string name = String.IsNullOrEmpty(lambda.Name) ? GetUniqueMethodName() : lambda.Name;
MethodBuilder mb = _typeBuilder.DefineMethod(name, MethodAttributes.Private | MethodAttributes.Static);
impl = new LambdaCompiler(_tree, lambda, mb);
}
// 2. emit the lambda
// Since additional ILs are always emitted after the lambda's body, should not emit with tail call optimization.
impl.EmitLambdaBody(_scope, false, CompilationFlags.EmitAsNoTail);
// 3. emit the delegate creation in the outer lambda
EmitDelegateConstruction(impl);
}
private static Type[] GetParameterTypes(LambdaExpression lambda)
{
return lambda.Parameters.Map(p => p.IsByRef ? p.Type.MakeByRefType() : p.Type);
}
private static string GetUniqueMethodName()
{
return "<ExpressionCompilerImplementationDetails>{" + Interlocked.Increment(ref s_counter) + "}lambda_method";
}
private void EmitLambdaBody()
{
// The lambda body is the "last" expression of the lambda
CompilationFlags tailCallFlag = _lambda.TailCall ? CompilationFlags.EmitAsTail : CompilationFlags.EmitAsNoTail;
EmitLambdaBody(null, false, tailCallFlag);
}
/// <summary>
/// Emits the lambda body. If inlined, the parameters should already be
/// pushed onto the IL stack.
/// </summary>
/// <param name="parent">The parent scope.</param>
/// <param name="inlined">true if the lambda is inlined; false otherwise.</param>
/// <param name="flags">
/// The emum to specify if the lambda is compiled with the tail call optimization.
/// </param>
private void EmitLambdaBody(CompilerScope parent, bool inlined, CompilationFlags flags)
{
_scope.Enter(this, parent);
if (inlined)
{
// The arguments were already pushed onto the IL stack.
// Store them into locals, popping in reverse order.
//
// If any arguments were ByRef, the address is on the stack and
// we'll be storing it into the variable, which has a ref type.
for (int i = _lambda.Parameters.Count - 1; i >= 0; i--)
{
_scope.EmitSet(_lambda.Parameters[i]);
}
}
// Need to emit the expression start for the lambda body
flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart);
if (_lambda.ReturnType == typeof(void))
{
EmitExpressionAsVoid(_lambda.Body, flags);
}
else
{
EmitExpression(_lambda.Body, flags);
}
// Return must be the last instruction in a CLI method.
// But if we're inlining the lambda, we want to leave the return
// value on the IL stack.
if (!inlined)
{
_ilg.Emit(OpCodes.Ret);
}
_scope.Exit();
// Validate labels
Debug.Assert(_labelBlock.Parent == null && _labelBlock.Kind == LabelScopeKind.Lambda);
foreach (LabelInfo label in _labelInfo.Values)
{
label.ValidateFinish();
}
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: Error.cs 566 2009-05-11 10:37:10Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Web;
using System.Xml;
using Thread = System.Threading.Thread;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
#endregion
/// <summary>
/// Represents a logical application error (as opposed to the actual
/// exception it may be representing).
/// </summary>
[ Serializable ]
public sealed class Error : ICloneable
{
private readonly Exception _exception;
private string _applicationName;
private string _hostName;
private string _typeName;
private string _source;
private string _message;
private string _detail;
private string _user;
private DateTime _time;
private int _statusCode;
private string _webHostHtmlMessage;
private NameValueCollection _serverVariables;
private NameValueCollection _queryString;
private NameValueCollection _form;
private NameValueCollection _cookies;
/// <summary>
/// Initializes a new instance of the <see cref="Error"/> class.
/// </summary>
public Error() {}
/// <summary>
/// Initializes a new instance of the <see cref="Error"/> class
/// from a given <see cref="Exception"/> instance.
/// </summary>
public Error(Exception e) :
this(e, null) {}
/// <summary>
/// Initializes a new instance of the <see cref="Error"/> class
/// from a given <see cref="Exception"/> instance and
/// <see cref="HttpContext"/> instance representing the HTTP
/// context during the exception.
/// </summary>
public Error(Exception e, HttpContext context)
{
if (e == null)
throw new ArgumentNullException("e");
_exception = e;
Exception baseException = e.GetBaseException();
//
// Load the basic information.
//
_hostName = Environment.MachineName;
_typeName = baseException.GetType().FullName;
_message = baseException.Message;
_source = baseException.Source;
_detail = e.ToString();
_user = Mask.NullString(Thread.CurrentPrincipal.Identity.Name);
_time = DateTime.Now;
//
// If this is an HTTP exception, then get the status code
// and detailed HTML message provided by the host.
//
HttpException httpException = e as HttpException;
if (httpException != null)
{
_statusCode = httpException.GetHttpCode();
_webHostHtmlMessage = Mask.NullString(httpException.GetHtmlErrorMessage());
}
//
// If the HTTP context is available, then capture the
// collections that represent the state request.
//
if (context != null)
{
HttpRequest request = context.Request;
_serverVariables = CopyCollection(request.ServerVariables);
_queryString = CopyCollection(request.QueryString);
_form = CopyCollection(request.Form);
_cookies = CopyCollection(request.Cookies);
}
}
/// <summary>
/// Gets the <see cref="Exception"/> instance used to initialize this
/// instance.
/// </summary>
/// <remarks>
/// This is a run-time property only that is not written or read
/// during XML serialization via <see cref="ErrorXml.Decode"/> and
/// <see cref="ErrorXml.Encode(Error,XmlWriter)"/>.
/// </remarks>
public Exception Exception
{
get { return _exception; }
}
/// <summary>
/// Gets or sets the name of application in which this error occurred.
/// </summary>
public string ApplicationName
{
get { return Mask.NullString(_applicationName); }
set { _applicationName = value; }
}
/// <summary>
/// Gets or sets name of host machine where this error occurred.
/// </summary>
public string HostName
{
get { return Mask.NullString(_hostName); }
set { _hostName = value; }
}
/// <summary>
/// Gets or sets the type, class or category of the error.
/// </summary>
public string Type
{
get { return Mask.NullString(_typeName); }
set { _typeName = value; }
}
/// <summary>
/// Gets or sets the source that is the cause of the error.
/// </summary>
public string Source
{
get { return Mask.NullString(_source); }
set { _source = value; }
}
/// <summary>
/// Gets or sets a brief text describing the error.
/// </summary>
public string Message
{
get { return Mask.NullString(_message); }
set { _message = value; }
}
/// <summary>
/// Gets or sets a detailed text describing the error, such as a
/// stack trace.
/// </summary>
public string Detail
{
get { return Mask.NullString(_detail); }
set { _detail = value; }
}
/// <summary>
/// Gets or sets the user logged into the application at the time
/// of the error.
/// </summary>
public string User
{
get { return Mask.NullString(_user); }
set { _user = value; }
}
/// <summary>
/// Gets or sets the date and time (in local time) at which the
/// error occurred.
/// </summary>
public DateTime Time
{
get { return _time; }
set { _time = value; }
}
/// <summary>
/// Gets or sets the HTTP status code of the output returned to the
/// client for the error.
/// </summary>
/// <remarks>
/// For cases where this value cannot always be reliably determined,
/// the value may be reported as zero.
/// </remarks>
public int StatusCode
{
get { return _statusCode; }
set { _statusCode = value; }
}
/// <summary>
/// Gets or sets the HTML message generated by the web host (ASP.NET)
/// for the given error.
/// </summary>
public string WebHostHtmlMessage
{
get { return Mask.NullString(_webHostHtmlMessage); }
set { _webHostHtmlMessage = value; }
}
/// <summary>
/// Gets a collection representing the Web server variables
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection ServerVariables
{
get { return FaultIn(ref _serverVariables); }
}
/// <summary>
/// Gets a collection representing the Web query string variables
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection QueryString
{
get { return FaultIn(ref _queryString); }
}
/// <summary>
/// Gets a collection representing the form variables captured as
/// part of diagnostic data for the error.
/// </summary>
public NameValueCollection Form
{
get { return FaultIn(ref _form); }
}
/// <summary>
/// Gets a collection representing the client cookies
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection Cookies
{
get { return FaultIn(ref _cookies); }
}
/// <summary>
/// Returns the value of the <see cref="Message"/> property.
/// </summary>
public override string ToString()
{
return this.Message;
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
object ICloneable.Clone()
{
//
// Make a base shallow copy of all the members.
//
Error copy = (Error) MemberwiseClone();
//
// Now make a deep copy of items that are mutable.
//
copy._serverVariables = CopyCollection(_serverVariables);
copy._queryString = CopyCollection(_queryString);
copy._form = CopyCollection(_form);
copy._cookies = CopyCollection(_cookies);
return copy;
}
private static NameValueCollection CopyCollection(NameValueCollection collection)
{
if (collection == null || collection.Count == 0)
return null;
return new NameValueCollection(collection);
}
private static NameValueCollection CopyCollection(HttpCookieCollection cookies)
{
if (cookies == null || cookies.Count == 0)
return null;
NameValueCollection copy = new NameValueCollection(cookies.Count);
for (int i = 0; i < cookies.Count; i++)
{
HttpCookie cookie = cookies[i];
//
// NOTE: We drop the Path and Domain properties of the
// cookie for sake of simplicity.
//
copy.Add(cookie.Name, cookie.Value);
}
return copy;
}
private static NameValueCollection FaultIn(ref NameValueCollection collection)
{
if (collection == null)
collection = new NameValueCollection();
return collection;
}
}
}
| |
// Copyright (c) 2002-2019 "Neo4j,"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// 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 System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Neo4j.Driver.Internal.Connector;
using Neo4j.Driver;
using static Neo4j.Driver.Internal.Throw.ObjectDisposedException;
namespace Neo4j.Driver.Internal.Routing
{
internal class LoadBalancer : IConnectionProvider, IClusterErrorHandler, IClusterConnectionPoolManager
{
private readonly IRoutingTableManager _routingTableManager;
private readonly ILoadBalancingStrategy _loadBalancingStrategy;
private readonly IClusterConnectionPool _clusterConnectionPool;
private readonly IDriverLogger _logger;
private int _closedMarker = 0;
public LoadBalancer(
IPooledConnectionFactory connectionFactory,
RoutingSettings routingSettings,
ConnectionPoolSettings poolSettings,
IDriverLogger logger)
{
_logger = logger;
_clusterConnectionPool =
new ClusterConnectionPool(Enumerable.Empty<Uri>(), connectionFactory, poolSettings, logger);
_routingTableManager = new RoutingTableManager(routingSettings, this, logger);
_loadBalancingStrategy = CreateLoadBalancingStrategy(_clusterConnectionPool, _logger);
}
// for test only
internal LoadBalancer(
IClusterConnectionPool clusterConnPool,
IRoutingTableManager routingTableManager)
{
var config = Config.DefaultConfig;
_logger = config.DriverLogger;
_clusterConnectionPool = clusterConnPool;
_routingTableManager = routingTableManager;
_loadBalancingStrategy = CreateLoadBalancingStrategy(clusterConnPool, _logger);
}
private bool IsClosed => _closedMarker > 0;
public async Task<IConnection> AcquireAsync(AccessMode mode, string database, Bookmark bookmark)
{
if (IsClosed)
{
ThrowObjectDisposedException();
}
var conn = await AcquireConnectionAsync(mode, database, bookmark).ConfigureAwait(false);
if (IsClosed)
{
ThrowObjectDisposedException();
}
return conn;
}
public Task OnConnectionErrorAsync(Uri uri, string database, Exception e)
{
_logger?.Info($"Server at {uri} is no longer available due to error: {e.Message}.");
_routingTableManager.ForgetServer(uri, database);
return _clusterConnectionPool.DeactivateAsync(uri);
}
public void OnWriteError(Uri uri, string database)
{
_routingTableManager.ForgetWriter(uri, database);
}
public Task AddConnectionPoolAsync(IEnumerable<Uri> uris)
{
return _clusterConnectionPool.AddAsync(uris);
}
public Task UpdateConnectionPoolAsync(IEnumerable<Uri> added, IEnumerable<Uri> removed)
{
return _clusterConnectionPool.UpdateAsync(added, removed);
}
public Task<IConnection> CreateClusterConnectionAsync(Uri uri)
{
return CreateClusterConnectionAsync(uri, AccessMode.Write, null, Bookmark.Empty);
}
public Task CloseAsync()
{
if (Interlocked.CompareExchange(ref _closedMarker, 1, 0) == 0)
{
_routingTableManager.Clear();
return _clusterConnectionPool.CloseAsync();
}
return Task.CompletedTask;
}
public async Task<IConnection> AcquireConnectionAsync(AccessMode mode, string database, Bookmark bookmark)
{
var routingTable = await _routingTableManager.EnsureRoutingTableForModeAsync(mode, database, bookmark)
.ConfigureAwait(false);
while (true)
{
Uri uri;
switch (mode)
{
case AccessMode.Read:
uri = _loadBalancingStrategy.SelectReader(routingTable.Readers, database);
break;
case AccessMode.Write:
uri = _loadBalancingStrategy.SelectWriter(routingTable.Writers, database);
break;
default:
throw new InvalidOperationException($"Unknown access mode {mode}");
}
if (uri == null)
{
// no server known to routingTable
break;
}
var conn =
await CreateClusterConnectionAsync(uri, mode, database, bookmark).ConfigureAwait(false);
if (conn != null)
{
return conn;
}
//else connection already removed by clusterConnection onError method
}
throw new SessionExpiredException($"Failed to connect to any {mode.ToString().ToLower()} server.");
}
private async Task<IConnection> CreateClusterConnectionAsync(Uri uri, AccessMode mode, string database,
Bookmark bookmark)
{
try
{
var conn = await _clusterConnectionPool.AcquireAsync(uri, mode, database, bookmark)
.ConfigureAwait(false);
if (conn != null)
{
return new ClusterConnection(conn, uri, this);
}
await OnConnectionErrorAsync(uri, database, new ArgumentException(
$"Routing table {_routingTableManager.RoutingTableFor(database)} contains a server {uri} " +
$"that is not known to cluster connection pool {_clusterConnectionPool}.")).ConfigureAwait(false);
}
catch (ServiceUnavailableException e)
{
await OnConnectionErrorAsync(uri, database, e).ConfigureAwait(false);
}
return null;
}
private void ThrowObjectDisposedException()
{
FailedToAcquireConnection(this);
}
public override string ToString()
{
return new StringBuilder(128)
.Append("LoadBalancer{")
.AppendFormat("routingTableManager={0}, ", _routingTableManager)
.AppendFormat("clusterConnectionPool={0}, ", _clusterConnectionPool)
.AppendFormat("closed={0}", IsClosed)
.Append("}")
.ToString();
}
private static ILoadBalancingStrategy CreateLoadBalancingStrategy(IClusterConnectionPool pool,
IDriverLogger logger)
{
return new LeastConnectedLoadBalancingStrategy(pool, logger);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace My1st5minApp.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Content Version
///<para>SObject Name: ContentVersion</para>
///<para>Custom Object: False</para>
///</summary>
public class SfContentVersion : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ContentVersion"; }
}
///<summary>
/// ContentVersion ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// ContentDocument ID
/// <para>Name: ContentDocumentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "contentDocumentId")]
[Updateable(false), Createable(true)]
public string ContentDocumentId { get; set; }
///<summary>
/// ReferenceTo: ContentDocument
/// <para>RelationshipName: ContentDocument</para>
///</summary>
[JsonProperty(PropertyName = "contentDocument")]
[Updateable(false), Createable(false)]
public SfContentDocument ContentDocument { get; set; }
///<summary>
/// Is Latest
/// <para>Name: IsLatest</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isLatest")]
[Updateable(false), Createable(false)]
public bool? IsLatest { get; set; }
///<summary>
/// Content URL
/// <para>Name: ContentUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "contentUrl")]
public string ContentUrl { get; set; }
///<summary>
/// Content Body ID
/// <para>Name: ContentBodyId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "contentBodyId")]
[Updateable(false), Createable(true)]
public string ContentBodyId { get; set; }
///<summary>
/// Version Number
/// <para>Name: VersionNumber</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "versionNumber")]
[Updateable(false), Createable(false)]
public string VersionNumber { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "title")]
public string Title { get; set; }
///<summary>
/// Description
/// <para>Name: Description</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
///<summary>
/// Reason For Change
/// <para>Name: ReasonForChange</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "reasonForChange")]
public string ReasonForChange { get; set; }
///<summary>
/// Prevent others from sharing and unsharing
/// <para>Name: SharingOption</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "sharingOption")]
public string SharingOption { get; set; }
///<summary>
/// File Privacy on Records
/// <para>Name: SharingPrivacy</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "sharingPrivacy")]
public string SharingPrivacy { get; set; }
///<summary>
/// Path On Client
/// <para>Name: PathOnClient</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "pathOnClient")]
[Updateable(false), Createable(true)]
public string PathOnClient { get; set; }
///<summary>
/// Rating Count
/// <para>Name: RatingCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "ratingCount")]
[Updateable(false), Createable(false)]
public int? RatingCount { get; set; }
///<summary>
/// Is Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Content Modified Date
/// <para>Name: ContentModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "contentModifiedDate")]
[Updateable(false), Createable(true)]
public DateTimeOffset? ContentModifiedDate { get; set; }
///<summary>
/// User ID
/// <para>Name: ContentModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "contentModifiedById")]
[Updateable(false), Createable(false)]
public string ContentModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: ContentModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "contentModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser ContentModifiedBy { get; set; }
///<summary>
/// Positive Rating Count
/// <para>Name: PositiveRatingCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "positiveRatingCount")]
[Updateable(false), Createable(false)]
public int? PositiveRatingCount { get; set; }
///<summary>
/// Negative Rating Count
/// <para>Name: NegativeRatingCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "negativeRatingCount")]
[Updateable(false), Createable(false)]
public int? NegativeRatingCount { get; set; }
///<summary>
/// Featured Content Boost
/// <para>Name: FeaturedContentBoost</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "featuredContentBoost")]
[Updateable(false), Createable(false)]
public int? FeaturedContentBoost { get; set; }
///<summary>
/// Featured Content Date
/// <para>Name: FeaturedContentDate</para>
/// <para>SF Type: date</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "featuredContentDate")]
[Updateable(false), Createable(false)]
public DateTime? FeaturedContentDate { get; set; }
///<summary>
/// Owner ID
/// <para>Name: OwnerId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "ownerId")]
public string OwnerId { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: Owner</para>
///</summary>
[JsonProperty(PropertyName = "owner")]
[Updateable(false), Createable(false)]
public SfUser Owner { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Tags
/// <para>Name: TagCsv</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "tagCsv")]
public string TagCsv { get; set; }
///<summary>
/// File Type
/// <para>Name: FileType</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "fileType")]
[Updateable(false), Createable(false)]
public string FileType { get; set; }
///<summary>
/// Publish Status
/// <para>Name: PublishStatus</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "publishStatus")]
[Updateable(false), Createable(false)]
public string PublishStatus { get; set; }
///<summary>
/// Version Data
/// <para>Name: VersionData</para>
/// <para>SF Type: base64</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "versionData")]
public string VersionData { get; set; }
///<summary>
/// Size
/// <para>Name: ContentSize</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "contentSize")]
[Updateable(false), Createable(false)]
public int? ContentSize { get; set; }
///<summary>
/// File Extension
/// <para>Name: FileExtension</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fileExtension")]
[Updateable(false), Createable(false)]
public string FileExtension { get; set; }
///<summary>
/// First Publish Location ID
/// <para>Name: FirstPublishLocationId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "firstPublishLocationId")]
[Updateable(false), Createable(true)]
public string FirstPublishLocationId { get; set; }
///<summary>
/// Content Origin
/// <para>Name: Origin</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "origin")]
[Updateable(false), Createable(true)]
public string Origin { get; set; }
///<summary>
/// Content Location
/// <para>Name: ContentLocation</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "contentLocation")]
[Updateable(false), Createable(true)]
public string ContentLocation { get; set; }
///<summary>
/// Text Preview
/// <para>Name: TextPreview</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "textPreview")]
[Updateable(false), Createable(false)]
public string TextPreview { get; set; }
///<summary>
/// External Document Info1
/// <para>Name: ExternalDocumentInfo1</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "externalDocumentInfo1")]
public string ExternalDocumentInfo1 { get; set; }
///<summary>
/// External Document Info2
/// <para>Name: ExternalDocumentInfo2</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "externalDocumentInfo2")]
public string ExternalDocumentInfo2 { get; set; }
///<summary>
/// External Data Source ID
/// <para>Name: ExternalDataSourceId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "externalDataSourceId")]
public string ExternalDataSourceId { get; set; }
///<summary>
/// ReferenceTo: ExternalDataSource
/// <para>RelationshipName: ExternalDataSource</para>
///</summary>
[JsonProperty(PropertyName = "externalDataSource")]
[Updateable(false), Createable(false)]
public SfExternalDataSource ExternalDataSource { get; set; }
///<summary>
/// Checksum
/// <para>Name: Checksum</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "checksum")]
[Updateable(false), Createable(false)]
public string Checksum { get; set; }
///<summary>
/// Major Version
/// <para>Name: IsMajorVersion</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isMajorVersion")]
[Updateable(false), Createable(true)]
public bool? IsMajorVersion { get; set; }
///<summary>
/// Asset File Enabled
/// <para>Name: IsAssetEnabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isAssetEnabled")]
[Updateable(false), Createable(true)]
public bool? IsAssetEnabled { get; set; }
}
}
| |
//---------------------------------------------------------------------------
// <copyright file="DocumentReference.cs" company="Microsoft">
// Copyright (C) 2004 by Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// Implements the DocumentReference element
//
// History:
// 05/13/2004 - Zhenbin Xu (ZhenbinX) - Created.
//
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
using MS.Internal;
using MS.Internal.AppModel;
using MS.Internal.Documents;
using MS.Internal.Utility;
using MS.Internal.Navigation;
using MS.Internal.PresentationFramework; // SecurityHelper
using System.Reflection;
using System.Windows; // DependencyID etc.
using System.Windows.Navigation;
using System.Windows.Markup;
using System.Windows.Threading; // Dispatcher
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Net;
using System.Security;
//=====================================================================
/// <summary>
/// DocumentReference is the class that references a Document.
/// Each document
/// </summary>
[UsableDuringInitialization(false)]
public sealed class DocumentReference : FrameworkElement, IUriContext
{
//--------------------------------------------------------------------
//
// Connstructors
//
//---------------------------------------------------------------------
#region Constructors
/// <summary>
/// Default DocumentReference constructor
/// </summary>
/// <remarks>
/// Automatic determination of current Dispatcher. Use alternative constructor
/// that accepts a Dispatcher for best performance.
/// </remarks>
public DocumentReference() : base()
{
_Init();
}
#endregion Constructors
//--------------------------------------------------------------------
//
// Public Methods
//
//---------------------------------------------------------------------
#region Public Methods
/// <summary>
/// Synchonrously download and parse the document based on the Source specification.
/// If a document was attached earlier and forceReload == false, the attached
/// document will be returned. forceReload == true results in downloading of the referenced
/// document based on Source specification, any previously attached document is ignored
/// in this case.
/// Regardless of forceReload, the document will be loaded based on Source specification if
/// it hasn't been loaded earlier.
/// </summary>
/// <param name="forceReload">Force reloading the document instead of using cached value</param>
/// <returns>The document tree</returns>
public FixedDocument GetDocument(bool forceReload)
{
DocumentsTrace.FixedDocumentSequence.IDF.Trace(string.Format("DocumentReference.GetDocument ({0}, {1})", Source == null ? new Uri("", UriKind.RelativeOrAbsolute) : Source, forceReload));
VerifyAccess();
FixedDocument idp = null;
if (_doc != null)
{
idp = _doc;
}
else
{
if (!forceReload)
{
idp = CurrentlyLoadedDoc;
}
if (idp == null)
{
FixedDocument idpReloaded = _LoadDocument();
if (idpReloaded != null)
{
DocumentsTrace.FixedDocumentSequence.IDF.Trace(string.Format("DocumentReference.GetDocument Loaded IDP {0}", idpReloaded.GetHashCode()));
// save the doc's identity
_docIdentity = idpReloaded;
idp = idpReloaded;
}
}
}
if (idp != null)
{
LogicalTreeHelper.AddLogicalChild(this.Parent, idp);
}
return idp;
}
/// <summary>
/// Attach a document to this DocumentReference
/// You can only attach a document if it is not attached before or it is not created from URI before.
/// </summary>
/// <param name="doc"></param>
public void SetDocument(FixedDocument doc)
{
VerifyAccess();
_docIdentity = null;
_doc = doc;
}
#endregion Public Methods
//--------------------------------------------------------------------
//
// Public Properties
//
//---------------------------------------------------------------------
#region Public Properties
/// <summary>
/// Dynamic Property to reference an external document stream.
/// </summary>
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(
"Source",
typeof(Uri),
typeof(DocumentReference),
new FrameworkPropertyMetadata(
(Uri) null,
new PropertyChangedCallback(OnSourceChanged)));
static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DocumentsTrace.FixedDocumentSequence.IDF.Trace(string.Format("DocumentReference.Source_Invaidated"));
DocumentReference docRef = (DocumentReference)d;
if (!object.Equals(e.OldValue, e.NewValue))
{
Uri oldSource = (Uri) e.OldValue;
Uri newSource = (Uri) e.NewValue;
DocumentsTrace.FixedDocumentSequence.IDF.Trace(string.Format("====Replace old doc {0} with new {1}",
oldSource == null ? "null" : oldSource.ToString(),
newSource == null? "null" : newSource.ToString()));
// drop loaded document if source changed
docRef._doc = null;
//
// #966803: Source change won't be a support scenario.
//
}
}
/// <summary>
/// Get/Set Source property that references an external page stream.
/// </summary>
public Uri Source
{
get { return (Uri) GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
#endregion Public Properties
#region IUriContext
/// <summary>
/// <see cref="IUriContext.BaseUri" />
/// </summary>
Uri IUriContext.BaseUri
{
get { return (Uri)GetValue(BaseUriHelper.BaseUriProperty); }
set { SetValue(BaseUriHelper.BaseUriProperty, value); }
}
#endregion IUriContext
//--------------------------------------------------------------------
//
// Public Events
//
//---------------------------------------------------------------------
#region Public Event
#endregion Public Event
//--------------------------------------------------------------------
//
// Internal Methods
//
//---------------------------------------------------------------------
#region Internal Methods
#if DEBUG
internal void Dump()
{
DocumentsTrace.FixedDocumentSequence.Content.Trace(string.Format(" This {0}", this.GetHashCode()));
DocumentsTrace.FixedDocumentSequence.Content.Trace(string.Format(" Source {0}", this.Source == null ? "null" : this.Source.ToString()));
DocumentsTrace.FixedDocumentSequence.Content.Trace(string.Format(" _doc {0}", _doc == null ? 0 : _doc.GetHashCode()));
DocumentsTrace.FixedDocumentSequence.Content.Trace(string.Format(" _docIdentity {0}", _docIdentity == null ? 0 : _docIdentity.GetHashCode()));
}
#endif
#endregion Internal Methods
//--------------------------------------------------------------------
//
// Internal Properties
//
//---------------------------------------------------------------------
#region Internal Properties
// return most recent result of GetDocument, if it is still alive
internal FixedDocument CurrentlyLoadedDoc
{
get
{
return _docIdentity;
}
}
#endregion Internal Properties
//--------------------------------------------------------------------
//
// private Properties
//
//---------------------------------------------------------------------
#region Private Properties
#endregion Private Properties
//--------------------------------------------------------------------
//
// Private Methods
//
//---------------------------------------------------------------------
#region Private Methods
private void _Init()
{
this.InheritanceBehavior = InheritanceBehavior.SkipToAppNow;
}
///<SecurityNote>
/// Critical as it access the base uri through GetUriToNavigate
///</SecurityNote>
[SecurityCritical]
private Uri _ResolveUri()
{
Uri uriToNavigate = this.Source;
if (uriToNavigate != null)
{
uriToNavigate = BindUriHelper.GetUriToNavigate(this, ((IUriContext)this).BaseUri, uriToNavigate);
}
return uriToNavigate;
}
// [....] load a document
///<SecurityNote>
/// Critical as it access the base uri through _resolveUri
/// TreatAsSafe since it does not disclose this
///</SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private FixedDocument _LoadDocument()
{
FixedDocument idp = null;
Uri uriToLoad = _ResolveUri();
if (uriToLoad != null)
{
ContentType mimeType = null;
Stream docStream = null;
docStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(uriToLoad, out mimeType);
if (docStream == null)
{
throw new ApplicationException(SR.Get(SRID.DocumentReferenceNotFound));
}
ParserContext pc = new ParserContext();
pc.BaseUri = uriToLoad;
if (BindUriHelper.IsXamlMimeType(mimeType))
{
XpsValidatingLoader loader = new XpsValidatingLoader();
idp = loader.Load(docStream, ((IUriContext)this).BaseUri, pc, mimeType) as FixedDocument;
}
else if (MS.Internal.MimeTypeMapper.BamlMime.AreTypeAndSubTypeEqual(mimeType))
{
idp = XamlReader.LoadBaml(docStream, pc, null, true) as FixedDocument;
}
else
{
throw new ApplicationException(SR.Get(SRID.DocumentReferenceUnsupportedMimeType));
}
idp.DocumentReference = this;
}
return idp;
}
#endregion Private Methods
//--------------------------------------------------------------------
//
// Private Fields
//
//---------------------------------------------------------------------
#region Private Fields
private FixedDocument _doc;
private FixedDocument _docIdentity; // used to cache the identity of the IDF so the IDF knows where it come from.
#endregion Private Fields
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Roslyn.Utilities;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Instrumentation;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// This class is used to resolve file references for the compilation.
/// It provides APIs to resolve:
/// (a) Metadata reference paths.
/// (b) Assembly names.
/// (c) Documentation files.
/// (d) XML document files.
/// </summary>
public class FileResolver
{
private readonly ImmutableArray<string> assemblySearchPaths;
private readonly string baseDirectory;
private readonly TouchedFileLogger touchedFiles;
/// <summary>
/// Default file resolver.
/// Does not create a new <see cref="TouchedFileLogger"/>.
/// </summary>
/// <remarks>
/// This resolver doesn't resolve any relative paths.
/// </remarks>
public static readonly FileResolver Default = new FileResolver(
assemblySearchPaths: ImmutableArray<string>.Empty,
baseDirectory: null,
touchedFiles: null);
/// <summary>
/// Initializes a new instance of the <see cref="FileResolver"/> class.
/// </summary>
/// <param name="assemblySearchPaths">An ordered set of fully qualified
/// paths which are searched when resolving assembly names.</param>
/// <param name="baseDirectory">Directory used when resolving relative paths.</param>
/// <param name="touchedFiles"></param>
public FileResolver(
ImmutableArray<string> assemblySearchPaths,
string baseDirectory,
TouchedFileLogger touchedFiles = null)
{
ValidateSearchPaths(assemblySearchPaths, "assemblySearchPaths");
if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute)
{
throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, "baseDirectory");
}
this.assemblySearchPaths = assemblySearchPaths;
this.baseDirectory = baseDirectory;
this.touchedFiles = touchedFiles;
}
/// <summary>
/// Initializes a new instance of the <see cref="FileResolver"/> class.
/// </summary>
/// <param name="assemblySearchPaths">An ordered set of fully qualified
/// paths which are searched when resolving assembly names.</param>
/// <param name="baseDirectory">Directory used when resolving relative paths.</param>
/// <param name="touchedFiles"></param>
public FileResolver(
IEnumerable<string> assemblySearchPaths,
string baseDirectory,
TouchedFileLogger touchedFiles = null)
: this(assemblySearchPaths.AsImmutableOrNull(), baseDirectory, touchedFiles)
{
}
internal static void ValidateSearchPaths(ImmutableArray<string> paths, string argName)
{
if (paths.IsDefault)
{
throw new ArgumentNullException(argName);
}
if (paths.Any(path => !PathUtilities.IsAbsolute(path)))
{
throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, argName);
}
}
/// <summary>
/// Search paths used when resolving metadata references.
/// </summary>
/// <remarks>
/// All search paths are absolute.
/// </remarks>
public ImmutableArray<string> AssemblySearchPaths
{
get { return this.assemblySearchPaths; }
}
/// <summary>
/// Directory used for resolution of relative paths.
/// A full directory path or null if not available.
/// </summary>
/// <remarks>
/// This directory is only used if the base directory isn't implied by the context within which the path is being resolved.
///
/// It is used, for example, when resolving a strong name key file specified in <see cref="System.Reflection.AssemblyKeyFileAttribute"/>,
/// or a metadata file path specified in <see cref="MetadataFileReference"/>.
///
/// Resolution of a relative path that needs the base directory fails if the base directory is null.
/// </remarks>
public string BaseDirectory
{
get { return baseDirectory; }
}
/// <summary>
/// Resolves file name against the <see cref="FileResolver"/>'s base
/// directory. Also logs the file as touched.
/// </summary>
internal string ResolveRelativePath(string path)
{
string resolved = FileUtilities.ResolveRelativePath(path, baseDirectory);
if (touchedFiles != null && resolved != null)
{
touchedFiles.AddRead(resolved);
}
return resolved;
}
/// <summary>
/// Resolves a metadata reference that is a path or an assembly name.
/// </summary>
/// <param name="assemblyDisplayNameOrPath">
/// Assembly name or file path.
/// <see cref="M:IsFilePath"/> is used to determine whether to consider this value an assembly name or a file path.
/// </param>
/// <param name="baseFilePath">
/// The base file path to use to resolve relative paths against.
/// Null to use the <see cref="BaseDirectory"/> as a base for relative paths.
/// </param>
/// <returns>
/// Normalized absolute path to the referenced file or null if it can't be resolved.
/// </returns>
public string ResolveMetadataReference(string assemblyDisplayNameOrPath, string baseFilePath = null)
{
string path;
if (!IsFilePath(assemblyDisplayNameOrPath))
{
path = ResolveAssemblyName(assemblyDisplayNameOrPath);
if (path == null)
{
return null;
}
}
else
{
path = assemblyDisplayNameOrPath;
}
return ResolveMetadataFileChecked(path, baseFilePath);
}
/// <summary>
/// Resolves given assembly name.
/// </summary>
/// <returns>Full path to an assembly file.</returns>
public virtual string ResolveAssemblyName(string displayName)
{
return null;
}
/// <summary>
/// Resolves a given reference path.
/// </summary>
/// <param name="path">Path to resolve.</param>
/// <param name="baseFilePath">
/// The base file path to use to resolve relative paths against.
/// Null to use the <see cref="BaseDirectory"/> as a base for relative paths.
/// </param>
/// <returns>
/// The resolved metadata reference path. A normalized absolute path or null.
/// </returns>
public virtual string ResolveMetadataFile(string path, string baseFilePath)
{
string resolvedPath = FileUtilities.ResolveRelativePath(path, baseFilePath, baseDirectory, assemblySearchPaths, FileExists);
if (!FileExists(resolvedPath))
{
return null;
}
return FileUtilities.NormalizeAbsolutePath(resolvedPath);
}
internal string ResolveMetadataFileChecked(string path, string baseFilePath)
{
string fullPath = ResolveMetadataFile(path, baseFilePath);
if (fullPath != null)
{
if (!PathUtilities.IsAbsolute(fullPath))
{
throw new InvalidOperationException(
String.Format(CodeAnalysisResources.PathReturnedByResolveMetadataFileMustBeAbsolute, GetType().FullName, fullPath));
}
if (touchedFiles != null)
{
touchedFiles.AddRead(fullPath);
}
}
return fullPath;
}
#region Source File Resolution // TODO: move to a separate type and make public
internal virtual string NormalizePath(string path, string basePath)
{
return FileUtilities.NormalizeRelativePath(path, basePath, baseDirectory) ?? path;
}
#endregion
#region XML Document resolution // TODO: move to a separate type and make public
/// <summary>
/// Resolves XML document file path.
/// </summary>
/// <param name="path">
/// Value of the "file" attribute of an <include> documentation comment element.
/// </param>
/// <param name="baseFilePath">
/// The base file path to use to resolve current-directory-relative paths against.
/// Null if not available.
/// </param>
/// <returns>Normalized XML document file path or null if not found.</returns>
public virtual string ResolveXmlFile(string path, string baseFilePath)
{
// Dev11: first look relative to the directory containing the file with the <include> element (baseFilepath)
// and then look look in the base directory (i.e. current working directory of the compiler).
string resolvedPath = FileUtilities.ResolveRelativePath(path, baseFilePath, baseDirectory);
if (!FileExists(resolvedPath))
{
resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory);
if (!FileExists(resolvedPath))
{
return null;
}
}
if (touchedFiles != null)
{
touchedFiles.AddRead(resolvedPath);
}
return FileUtilities.NormalizeAbsolutePath(resolvedPath);
}
/// <exception cref="ArgumentNullException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not a valid absolute path.</exception>
/// <exception cref="IOException">Error reading file <paramref name="fullPath"/>. See <see cref="Exception.InnerException"/> for details.</exception>
internal virtual Stream OpenRead(string fullPath)
{
CompilerPathUtilities.RequireAbsolutePath(fullPath, "fullPath");
try
{
// Use FileShare.Delete to support files that are opened with DeleteOnClose option.
return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
}
catch (Exception e) if (!(e is IOException))
{
throw new IOException(e.Message, e);
}
}
internal Stream OpenReadChecked(string fullPath)
{
var stream = OpenRead(fullPath);
if (stream == null || !stream.CanRead)
{
throw new InvalidOperationException(CodeAnalysisResources.FileResolverShouldReturnReadableNonNullStream);
}
return stream;
}
#endregion
// TODO (tomat): virtualized for testing, consider exposing as public API
internal virtual bool FileExists(string fullPath)
{
Debug.Assert(fullPath == null || PathUtilities.IsAbsolute(fullPath));
return File.Exists(fullPath);
}
/// <summary>
/// Determines whether an assembly reference is considered an assembly file path or an assembly name.
/// used, for example, on values of /r and #r.
/// </summary>
internal static bool IsFilePath(string assemblyDisplayNameOrPath)
{
Debug.Assert(assemblyDisplayNameOrPath != null);
string extension = PathUtilities.GetExtension(assemblyDisplayNameOrPath);
return string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase)
|| string.Equals(extension, ".exe", StringComparison.OrdinalIgnoreCase)
|| assemblyDisplayNameOrPath.IndexOf(PathUtilities.DirectorySeparatorChar) != -1
|| assemblyDisplayNameOrPath.IndexOf(PathUtilities.AltDirectorySeparatorChar) != -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.
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
using static System.Tests.Utf8TestUtilities;
namespace System.Tests
{
public unsafe partial class Utf8StringTests
{
[Fact]
public static void Ctor_ByteArrayOffset_Empty_ReturnsEmpty()
{
byte[] inputData = new byte[] { (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };
Assert.Same(Utf8String.Empty, new Utf8String(inputData, 3, 0));
}
[Fact]
public static void Ctor_ByteArrayOffset_ValidData_ReturnsOriginalContents()
{
byte[] inputData = new byte[] { (byte)'x', (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'x' };
Utf8String expected = u8("Hello");
var actual = new Utf8String(inputData, 1, 5);
Assert.Equal(expected, actual);
}
[Fact]
public static void Ctor_ByteArrayOffset_InvalidData_Throws()
{
byte[] inputData = new byte[] { (byte)'x', (byte)'H', (byte)'e', (byte)0xFF, (byte)'l', (byte)'o', (byte)'x' };
Assert.Throws<ArgumentException>(() => new Utf8String(inputData, 0, inputData.Length));
}
[Fact]
public static void Ctor_ByteArrayOffset_NullValue_Throws()
{
var exception = Assert.Throws<ArgumentNullException>(() => new Utf8String((byte[])null, 0, 0));
Assert.Equal("value", exception.ParamName);
}
[Fact]
public static void Ctor_ByteArrayOffset_InvalidStartIndexOrLength_Throws()
{
byte[] inputData = new byte[] { (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };
Assert.Throws<ArgumentOutOfRangeException>(() => new Utf8String(inputData, 1, 5));
}
[Fact]
public static void Ctor_BytePointer_Null_Throws()
{
var exception = Assert.Throws<ArgumentNullException>(() => new Utf8String((byte*)null));
Assert.Equal("value", exception.ParamName);
}
[Fact]
public static void Ctor_BytePointer_Empty_ReturnsEmpty()
{
byte[] inputData = new byte[] { 0 }; // standalone null byte
using (BoundedMemory<byte> boundedMemory = BoundedMemory.AllocateFromExistingData(inputData))
{
Assert.Same(Utf8String.Empty, new Utf8String((byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(boundedMemory.Span))));
}
}
[Fact]
public static void Ctor_BytePointer_ValidData_ReturnsOriginalContents()
{
byte[] inputData = new byte[] { (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'\0' };
using (BoundedMemory<byte> boundedMemory = BoundedMemory.AllocateFromExistingData(inputData))
{
Assert.Equal(u8("Hello"), new Utf8String((byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(boundedMemory.Span))));
}
}
[Fact]
public static void Ctor_BytePointer_InvalidData_Throws()
{
byte[] inputData = new byte[] { (byte)'H', (byte)'e', (byte)0xFF, (byte)'l', (byte)'o', (byte)'\0' };
using (BoundedMemory<byte> boundedMemory = BoundedMemory.AllocateFromExistingData(inputData))
{
Assert.Throws<ArgumentException>(() => new Utf8String((byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(boundedMemory.Span))));
}
}
[Fact]
public static void Ctor_ByteSpan_Empty_ReturnsEmpty()
{
Assert.Same(Utf8String.Empty, new Utf8String(ReadOnlySpan<byte>.Empty));
}
[Fact]
public static void Ctor_ByteSpan_ValidData_ReturnsOriginalContents()
{
byte[] inputData = new byte[] { (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };
Utf8String expected = u8("Hello");
var actual = new Utf8String(inputData.AsSpan());
Assert.Equal(expected, actual);
}
[Fact]
public static void Ctor_ByteSpan_InvalidData_Throws()
{
byte[] inputData = new byte[] { (byte)'H', (byte)'e', (byte)0xFF, (byte)'l', (byte)'o' };
Assert.Throws<ArgumentException>(() => new Utf8String(inputData.AsSpan()));
}
[Fact]
public static void Ctor_CharArrayOffset_Empty_ReturnsEmpty()
{
char[] inputData = "H\U00012345ello".ToCharArray(); // ok to have an empty slice in the middle of a multi-byte subsequence
Assert.Same(Utf8String.Empty, new Utf8String(inputData, 3, 0));
}
[Fact]
public static void Ctor_CharArrayOffset_ValidData_ReturnsAsUtf8()
{
char[] inputData = "H\U00012345\u07ffello".ToCharArray();
Utf8String expected = u8("\u07ffello");
var actual = new Utf8String(inputData, 3, 5);
Assert.Equal(expected, actual);
}
[Fact]
public static void Ctor_CharArrayOffset_InvalidData_Throws()
{
char[] inputData = "H\ud800ello".ToCharArray();
Assert.Throws<ArgumentException>(() => new Utf8String(inputData, 0, inputData.Length));
}
[Fact]
public static void Ctor_CharArrayOffset_NullValue_Throws()
{
var exception = Assert.Throws<ArgumentNullException>(() => new Utf8String((char[])null, 0, 0));
Assert.Equal("value", exception.ParamName);
}
[Fact]
public static void Ctor_CharArrayOffset_InvalidStartIndexOrLength_Throws()
{
char[] inputData = "Hello".ToCharArray();
Assert.Throws<ArgumentOutOfRangeException>(() => new Utf8String(inputData, 1, 5));
}
[Fact]
public static void Ctor_CharPointer_Null_Throws()
{
var exception = Assert.Throws<ArgumentNullException>(() => new Utf8String((char*)null));
Assert.Equal("value", exception.ParamName);
}
[Fact]
public static void Ctor_CharPointer_Empty_ReturnsEmpty()
{
char[] inputData = new char[] { '\0' }; // standalone null char
using (BoundedMemory<char> boundedMemory = BoundedMemory.AllocateFromExistingData(inputData))
{
Assert.Same(Utf8String.Empty, new Utf8String((char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(boundedMemory.Span))));
}
}
[Fact]
public static void Ctor_CharPointer_ValidData_ReturnsOriginalContents()
{
char[] inputData = "Hello\0".ToCharArray(); // need to manually null-terminate
using (BoundedMemory<char> boundedMemory = BoundedMemory.AllocateFromExistingData(inputData))
{
Assert.Equal(u8("Hello"), new Utf8String((char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(boundedMemory.Span))));
}
}
[Fact]
public static void Ctor_CharPointer_InvalidData_Throws()
{
char[] inputData = "He\ud800llo\0".ToCharArray(); // need to manually null-terminate
using (BoundedMemory<char> boundedMemory = BoundedMemory.AllocateFromExistingData(inputData))
{
Assert.Throws<ArgumentException>(() => new Utf8String((char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(boundedMemory.Span))));
}
}
[Fact]
public static void Ctor_CharSpan_Empty_ReturnsEmpty()
{
Assert.Same(Utf8String.Empty, new Utf8String(ReadOnlySpan<char>.Empty));
}
[Fact]
public static void Ctor_CharSpan_ValidData_ReturnsOriginalContents()
{
char[] inputData = "Hello".ToCharArray();
Utf8String expected = u8("Hello");
var actual = new Utf8String(inputData.AsSpan());
Assert.Equal(expected, actual);
}
[Fact]
public static void Ctor_CharSpan_InvalidData_Throws()
{
char[] inputData = "He\ud800llo".ToCharArray();
Assert.Throws<ArgumentException>(() => new Utf8String(inputData.AsSpan()));
}
[Fact]
public static void Ctor_String_Null_Throws()
{
var exception = Assert.Throws<ArgumentNullException>(() => new Utf8String((string)null));
Assert.Equal("value", exception.ParamName);
}
[Fact]
public static void Ctor_String_Empty_ReturnsEmpty()
{
Assert.Same(Utf8String.Empty, new Utf8String(string.Empty));
}
[Fact]
public static void Ctor_String_ValidData_ReturnsOriginalContents()
{
Assert.Equal(u8("Hello"), new Utf8String("Hello"));
}
[Fact]
public static void Ctor_String_InvalidData_Throws()
{
Assert.Throws<ArgumentException>(() => new Utf8String("He\uD800lo"));
}
[Fact]
public static void Ctor_NonValidating_FromByteSpan()
{
byte[] inputData = new byte[] { (byte)'x', (byte)'y', (byte)'z' };
Utf8String actual = Utf8String.UnsafeCreateWithoutValidation(inputData);
Assert.Equal(u8("xyz"), actual);
}
[Fact]
public static void Ctor_NonValidating_FromDelegate()
{
object expectedState = new object();
SpanAction<byte, object> spanAction = (span, actualState) =>
{
Assert.Same(expectedState, actualState);
Assert.NotEqual(0, span.Length); // shouldn't have been called for a zero-length span
for (int i = 0; i < span.Length; i++)
{
Assert.Equal(0, span[i]); // should've been zero-inited
span[i] = (byte)('a' + (i % 26)); // writes "abc...xyzabc...xyz..."
}
};
ArgumentException exception = Assert.Throws<ArgumentOutOfRangeException>(() => Utf8String.UnsafeCreateWithoutValidation(-1, expectedState, spanAction));
Assert.Equal("length", exception.ParamName);
exception = Assert.Throws<ArgumentNullException>(() => Utf8String.UnsafeCreateWithoutValidation(10, expectedState, action: null));
Assert.Equal("action", exception.ParamName);
Assert.Same(Utf8String.Empty, Utf8String.UnsafeCreateWithoutValidation(0, expectedState, spanAction));
Assert.Equal(u8("abcde"), Utf8String.UnsafeCreateWithoutValidation(5, expectedState, spanAction));
}
[Fact]
public static void Ctor_Validating_FromDelegate()
{
object expectedState = new object();
SpanAction<byte, object> spanAction = (span, actualState) =>
{
Assert.Same(expectedState, actualState);
Assert.NotEqual(0, span.Length); // shouldn't have been called for a zero-length span
for (int i = 0; i < span.Length; i++)
{
Assert.Equal(0, span[i]); // should've been zero-inited
span[i] = (byte)('a' + (i % 26)); // writes "abc...xyzabc...xyz..."
}
};
ArgumentException exception = Assert.Throws<ArgumentOutOfRangeException>(() => Utf8String.Create(-1, expectedState, spanAction));
Assert.Equal("length", exception.ParamName);
exception = Assert.Throws<ArgumentNullException>(() => Utf8String.Create(10, expectedState, action: null));
Assert.Equal("action", exception.ParamName);
Assert.Same(Utf8String.Empty, Utf8String.Create(0, expectedState, spanAction));
Assert.Equal(u8("abcde"), Utf8String.Create(5, expectedState, spanAction));
}
[Fact]
public static void Ctor_Validating_FromDelegate_ThrowsIfDelegateProvidesInvalidData()
{
SpanAction<byte, object> spanAction = (span, actualState) =>
{
span[0] = 0xFF; // never a valid UTF-8 byte
};
Assert.Throws<ArgumentException>(() => Utf8String.Create(10, new object(), spanAction));
}
[Fact]
public static void Ctor_CreateFromRelaxed_Utf16()
{
Assert.Same(Utf8String.Empty, Utf8String.CreateFromRelaxed(ReadOnlySpan<char>.Empty));
Assert.Equal(u8("xy\uFFFDz"), Utf8String.CreateFromRelaxed("xy\ud800z"));
}
[Fact]
public static void Ctor_CreateFromRelaxed_Utf8()
{
Assert.Same(Utf8String.Empty, Utf8String.CreateFromRelaxed(ReadOnlySpan<byte>.Empty));
Assert.Equal(u8("xy\uFFFDz"), Utf8String.CreateFromRelaxed(new byte[] { (byte)'x', (byte)'y', 0xF4, 0x80, 0x80, (byte)'z' }));
}
[Fact]
public static void Ctor_CreateRelaxed_FromDelegate()
{
object expectedState = new object();
SpanAction<byte, object> spanAction = (span, actualState) =>
{
Assert.Same(expectedState, actualState);
Assert.NotEqual(0, span.Length); // shouldn't have been called for a zero-length span
for (int i = 0; i < span.Length; i++)
{
Assert.Equal(0, span[i]); // should've been zero-inited
span[i] = 0xFF; // never a valid UTF-8 byte
}
};
ArgumentException exception = Assert.Throws<ArgumentOutOfRangeException>(() => Utf8String.CreateRelaxed(-1, expectedState, spanAction));
Assert.Equal("length", exception.ParamName);
exception = Assert.Throws<ArgumentNullException>(() => Utf8String.CreateRelaxed(10, expectedState, action: null));
Assert.Equal("action", exception.ParamName);
Assert.Same(Utf8String.Empty, Utf8String.CreateRelaxed(0, expectedState, spanAction));
Assert.Equal(u8("\uFFFD\uFFFD"), Utf8String.CreateRelaxed(2, expectedState, spanAction));
}
[Fact]
public static void Ctor_TryCreateFrom_Utf8()
{
Utf8String value;
// Empty string
Assert.True(Utf8String.TryCreateFrom(ReadOnlySpan<byte>.Empty, out value));
Assert.Same(Utf8String.Empty, value);
// Well-formed ASCII contents
Assert.True(Utf8String.TryCreateFrom(new byte[] { (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o' }, out value));
Assert.Equal(u8("Hello"), value);
// Well-formed non-ASCII contents
Assert.True(Utf8String.TryCreateFrom(new byte[] { 0xF0, 0x9F, 0x91, 0xBD }, out value)); // U+1F47D EXTRATERRESTRIAL ALIEN
Assert.Equal(u8("\U0001F47D"), value);
// Ill-formed contents
Assert.False(Utf8String.TryCreateFrom(new byte[] { 0xF0, 0x9F, 0x91, (byte)'x' }, out value));
Assert.Null(value);
}
[Fact]
public static void Ctor_TryCreateFrom_Utf16()
{
Utf8String value;
// Empty string
Assert.True(Utf8String.TryCreateFrom(ReadOnlySpan<char>.Empty, out value));
Assert.Same(Utf8String.Empty, value);
// Well-formed ASCII contents
Assert.True(Utf8String.TryCreateFrom("Hello", out value));
Assert.Equal(u8("Hello"), value);
// Well-formed non-ASCII contents
Assert.True(Utf8String.TryCreateFrom("\U0001F47D", out value)); // U+1F47D EXTRATERRESTRIAL ALIEN
Assert.Equal(u8("\U0001F47D"), value);
// Ill-formed contents
Assert.False(Utf8String.TryCreateFrom("\uD800x", out value));
Assert.Null(value);
}
}
}
| |
using System;
using System.Xml;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Drawing.Design;
using System.IO;
namespace InstallerLib
{
/// <summary>
/// A base component.
/// </summary>
[XmlChild(typeof(InstalledCheck))]
[XmlChild(typeof(InstalledCheckOperator))]
[XmlChild(typeof(DownloadDialog), Max = 1)]
[XmlChild(typeof(EmbedFile))]
[XmlChild(typeof(EmbedFolder))]
public abstract class Component : XmlClass
{
public Component(string type, string name)
{
m_type = type;
Template.Template_component tpl = Template.CurrentTemplate.component(name);
m_display_name = tpl.display_name;
}
#region Attributes
private string m_type;
[Description("Type of the component; can be 'cmd' for executing generic command line installation or 'msi' for installing Windows Installer MSI package or 'openfile' to open a file.")]
[Category("Component")]
[Required]
public string type
{
get { return m_type; }
}
private string m_os_filter;
[Description("Filter to install this component only on all operating systems equal or not equal to the id value(s) specified. Separate multiple operating system ids with comma (',') and use not symbol ('!') for NOT logic (es. '44,!45' ).")]
[Category("Operating System")]
public string os_filter
{
get { return m_os_filter; }
set { m_os_filter = value; }
}
private OperatingSystem m_os_filter_min;
[Description("Filter to install this component only on all operating systems greater or equal to the id value specified. For example to install a component only in Windows Server 2003 or later use 'winServer2003'.")]
[Category("Operating System")]
public OperatingSystem os_filter_min
{
get { return m_os_filter_min; }
set { m_os_filter_min = value; }
}
private OperatingSystem m_os_filter_max;
[Description("Filter to install this component only on all operating systems smaller or equal to the id value specified. For example to install a component preceding Windows Server 2003 use 'winXPMax'.")]
[Category("Operating System")]
public OperatingSystem os_filter_max
{
get { return m_os_filter_max; }
set { m_os_filter_max = value; }
}
private string m_os_type_filter;
[Description("Filter to install this component only on all operating system product types equal or not equal to the value(s) specified. Separate multiple operating system types with a comma (',') and use the not symbol ('!') for NOT logic (ex. '!workstation,!server' ).")]
[Category("Operating System")]
public string os_type_filter
{
get { return m_os_type_filter; }
set { m_os_type_filter = value; }
}
private string m_os_filter_lcid;
[Description("Filter to install this component only on all operating system languages equal or not equal to the LCID specified. Separate multiple LCID with comma (',') and use not symbol ('!') for NOT logic (eg. '1044,1033,!1038' ).")]
[Category("Operating System")]
public string os_filter_lcid
{
get { return m_os_filter_lcid; }
set { m_os_filter_lcid = value; }
}
private string m_installcompletemessage;
[Description("Message used after a component is successfully installed. To disable this message leave this property empty.")]
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
[Category("Install")]
public string installcompletemessage
{
get { return m_installcompletemessage; }
set { m_installcompletemessage = value; }
}
private string m_uninstallcompletemessage;
[Description("Message used after a component is been successfully uninstalled.")]
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
[Category("Uninstall")]
public string uninstallcompletemessage
{
get { return m_uninstallcompletemessage; }
set { m_uninstallcompletemessage = value; }
}
private bool m_mustreboot = false;
[Description("Indicates whether to reboot automatically after this component is installed or uninstalled successfully. Normally if the system must be restarted, the component tells this setup (with special return code) to stop and restart the system. Setting this option to 'true' forces a reboot without prompting.")]
[Category("Runtime")]
[Required]
public bool mustreboot
{
get { return m_mustreboot; }
set { m_mustreboot = value; }
}
private string m_failed_exec_command_continue;
[Description("Message to display after a component failed to install. The user is then asked whether installation can continue using this message. May contain one '%s' replaced by the description of the component.")]
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
[Category("Runtime")]
public string failed_exec_command_continue
{
get { return m_failed_exec_command_continue; }
set { m_failed_exec_command_continue = value; }
}
private string m_reboot_required;
[Description("Message used when this component signaled the installer that it requires a reboot.")]
[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
[Category("Runtime")]
public string reboot_required
{
get { return m_reboot_required; }
set { m_reboot_required = value; }
}
private bool m_must_reboot_required = false;
[Description("Component setting for reboot behavior. When 'true', installation won't continue after this component required a reboot.")]
[Category("Runtime")]
[Required]
public bool must_reboot_required
{
get { return m_must_reboot_required; }
set { m_must_reboot_required = value; }
}
private bool m_allow_continue_on_error = true;
[Description("Set to 'true' to prompt the user to continue when a component fails to install.")]
[Category("Runtime")]
[Required]
public bool allow_continue_on_error
{
get { return m_allow_continue_on_error; }
set { m_allow_continue_on_error = value; }
}
private bool m_default_continue_on_error = false;
[Description("The default value of whether to continue when a component fails to install.")]
[Category("Runtime")]
[Required]
public bool default_continue_on_error
{
get { return m_default_continue_on_error; }
set { m_default_continue_on_error = value; }
}
private string m_id;
[Description("Component identity. This value should be unique.")]
[Category("Component")]
[Required]
public string id
{
get { return m_id; }
set { m_id = value; OnDisplayChanged(); }
}
private string m_display_name;
[Description("Component display name. This value is used in some message to replace the '%s' string.")]
[Category("Component")]
[Required]
public string display_name
{
get { return m_display_name; }
set { m_display_name = value; OnDisplayChanged(); }
}
private string m_uninstall_display_name;
[Description("Optional display name of this component during uninstall. Defaults to 'display_name' when blank.")]
[Category("Component")]
public string uninstall_display_name
{
get { return m_uninstall_display_name; }
set { m_uninstall_display_name = value; OnDisplayChanged(); }
}
private bool m_required_install = true;
[Description("Indicates whether the component is required for a successful installation.")]
[Category("Component")]
[Required]
public bool required_install
{
get { return m_required_install; }
set { m_required_install = value; }
}
private bool m_required_uninstall = true;
[Description("Indicates whether the component is required for a successful uninstallation.")]
[Category("Component")]
[Required]
public bool required_uninstall
{
get { return m_required_uninstall; }
set { m_required_uninstall = value; }
}
private bool m_selected_install = true;
[Description("Indicates whether the component is selected by default during install.")]
[Category("Component")]
[Required]
public bool selected_install
{
get { return m_selected_install; }
set { m_selected_install = value; }
}
private bool m_selected_uninstall = true;
[Description("Indicates whether the component is selected by default during uninstall.")]
[Category("Component")]
[Required]
public bool selected_uninstall
{
get { return m_selected_uninstall; }
set { m_selected_uninstall = value; }
}
private string m_note;
[Description("Store any additional free-formed information in this field, not used by the setup.")]
[Category("Component")]
public string note
{
get { return m_note; }
set { m_note = value; }
}
// message for not matching the processor architecture filter
private string m_processor_architecture_filter;
[Description("Type of processor architecture (x86, mips, alpha, ppc, shx, arm, ia64, alpha64, msil, x64, ia32onwin64). Separate by commas, can use the NOT sign ('!') to exclude values. (eg. 'x86,x64' or '!x86').")]
[Category("Filters")]
public string processor_architecture_filter
{
get { return m_processor_architecture_filter; }
set { m_processor_architecture_filter = value; }
}
private string m_status_installed;
[Description("String used to indicate that this component is installed.")]
[Category("Component")]
public string status_installed
{
get { return m_status_installed; }
set { m_status_installed = value; }
}
private string m_status_notinstalled;
[Description("String used to indicate that this component is not installed.")]
[Category("Component")]
public string status_notinstalled
{
get { return m_status_notinstalled; }
set { m_status_notinstalled = value; }
}
private bool m_supports_install = true;
[Description("Indicates whether the component supports the install sequence.")]
[Category("Install")]
[Required]
public bool supports_install
{
get { return m_supports_install; }
set { m_supports_install = value; }
}
private bool m_supports_uninstall = false;
[Description("Indicates whether the component supports the uninstall sequence.")]
[Category("Uninstall")]
[Required]
public bool supports_uninstall
{
get { return m_supports_uninstall; }
set { m_supports_uninstall = value; }
}
private bool m_show_progress_dialog = true;
[Description("Set to 'true' to show the progress dialogs.")]
[Category("Component")]
[Required]
public bool show_progress_dialog
{
get { return m_show_progress_dialog; }
set { m_show_progress_dialog = value; }
}
private bool m_show_cab_dialog = true;
[Description("Set to 'true' to show the CAB extraction dialogs.")]
[Category("Component")]
[Required]
public bool show_cab_dialog
{
get { return m_show_cab_dialog; }
set { m_show_cab_dialog = value; }
}
private bool m_hide_component_if_installed = false;
[Description("Indicates whether the component is hidden if it's already installed. "
+ "The default value is 'false' so the component is displayed even if it's already installed.")]
[Category("Component")]
public bool hide_component_if_installed
{
get { return m_hide_component_if_installed; }
set { m_hide_component_if_installed = value; }
}
#endregion
#region Events
protected void OnDisplayChanged()
{
if (DisplayChanged != null)
{
DisplayChanged(this, EventArgs.Empty);
}
}
public event EventHandler DisplayChanged;
#endregion
#region XmlClass Members
public override string XmlTag
{
get { return "component"; }
}
#endregion
protected override void OnXmlWriteTag(XmlWriterEventArgs e)
{
e.XmlWriter.WriteAttributeString("id", string.IsNullOrEmpty(m_id) ? m_display_name : m_id);
e.XmlWriter.WriteAttributeString("display_name", m_display_name);
e.XmlWriter.WriteAttributeString("uninstall_display_name", m_uninstall_display_name);
e.XmlWriter.WriteAttributeString("os_filter", m_os_filter);
e.XmlWriter.WriteAttributeString("os_filter_min", (m_os_filter_min == OperatingSystem.winNone
? "" : Enum.GetName(typeof(OperatingSystem), m_os_filter_min)));
e.XmlWriter.WriteAttributeString("os_filter_max", (m_os_filter_max == OperatingSystem.winNone
? "" : Enum.GetName(typeof(OperatingSystem), m_os_filter_max)));
e.XmlWriter.WriteAttributeString("os_type_filter", m_os_type_filter);
e.XmlWriter.WriteAttributeString("os_filter_lcid", m_os_filter_lcid);
e.XmlWriter.WriteAttributeString("type", m_type);
e.XmlWriter.WriteAttributeString("installcompletemessage", m_installcompletemessage);
e.XmlWriter.WriteAttributeString("uninstallcompletemessage", m_uninstallcompletemessage);
e.XmlWriter.WriteAttributeString("mustreboot", m_mustreboot.ToString());
e.XmlWriter.WriteAttributeString("reboot_required", m_reboot_required);
e.XmlWriter.WriteAttributeString("must_reboot_required", m_must_reboot_required.ToString());
e.XmlWriter.WriteAttributeString("failed_exec_command_continue", m_failed_exec_command_continue);
e.XmlWriter.WriteAttributeString("allow_continue_on_error", m_allow_continue_on_error.ToString());
e.XmlWriter.WriteAttributeString("default_continue_on_error", m_default_continue_on_error.ToString());
e.XmlWriter.WriteAttributeString("required_install", m_required_install.ToString());
e.XmlWriter.WriteAttributeString("required_uninstall", m_required_uninstall.ToString());
e.XmlWriter.WriteAttributeString("selected_install", m_selected_install.ToString());
e.XmlWriter.WriteAttributeString("selected_uninstall", m_selected_uninstall.ToString());
e.XmlWriter.WriteAttributeString("note", m_note);
e.XmlWriter.WriteAttributeString("processor_architecture_filter", m_processor_architecture_filter);
e.XmlWriter.WriteAttributeString("status_installed", m_status_installed);
e.XmlWriter.WriteAttributeString("status_notinstalled", m_status_notinstalled);
e.XmlWriter.WriteAttributeString("supports_install", m_supports_install.ToString());
e.XmlWriter.WriteAttributeString("supports_uninstall", m_supports_uninstall.ToString());
// dialog options
e.XmlWriter.WriteAttributeString("show_progress_dialog", m_show_progress_dialog.ToString());
e.XmlWriter.WriteAttributeString("show_cab_dialog", m_show_cab_dialog.ToString());
e.XmlWriter.WriteAttributeString("hide_component_if_installed", m_hide_component_if_installed.ToString());
base.OnXmlWriteTag(e);
}
protected override void OnXmlReadTag(XmlElementEventArgs e)
{
// backwards compatible description < 1.8
ReadAttributeValue(e, "description", ref m_display_name);
ReadAttributeValue(e, "display_name", ref m_display_name);
ReadAttributeValue(e, "uninstall_display_name", ref m_uninstall_display_name);
ReadAttributeValue(e, "id", ref m_id);
if (string.IsNullOrEmpty(m_id)) m_id = m_display_name;
ReadAttributeValue(e, "installcompletemessage", ref m_installcompletemessage);
ReadAttributeValue(e, "uninstallcompletemessage", ref m_uninstallcompletemessage);
ReadAttributeValue(e, "mustreboot", ref m_mustreboot);
ReadAttributeValue(e, "reboot_required", ref m_reboot_required);
ReadAttributeValue(e, "must_reboot_required", ref m_must_reboot_required);
ReadAttributeValue(e, "failed_exec_command_continue", ref m_failed_exec_command_continue);
ReadAttributeValue(e, "allow_continue_on_error", ref m_allow_continue_on_error);
ReadAttributeValue(e, "default_continue_on_error", ref m_default_continue_on_error);
// required -> required_install and required_uninstall
if (!ReadAttributeValue(e, "required_install", ref m_required_install))
ReadAttributeValue(e, "required", ref m_required_install);
if (!ReadAttributeValue(e, "required_uninstall", ref m_required_uninstall))
m_required_uninstall = m_required_install;
// selected -> selected_install & selected_uninstall
if (!ReadAttributeValue(e, "selected_install", ref m_selected_install))
ReadAttributeValue(e, "selected", ref m_selected_install);
if (!ReadAttributeValue(e, "selected_uninstall", ref m_selected_uninstall))
m_selected_uninstall = m_selected_install;
// filters
ReadAttributeValue(e, "os_filter", ref m_os_filter);
ReadAttributeValue(e, "os_type_filter", ref m_os_type_filter);
ReadAttributeValue(e, "os_filter_lcid", ref m_os_filter_lcid);
string os_filter_greater = string.Empty;
if (ReadAttributeValue(e, "os_filter_greater", ref os_filter_greater) && !String.IsNullOrEmpty(os_filter_greater))
m_os_filter_min = (OperatingSystem)(int.Parse(os_filter_greater) + 1);
string os_filter_smaller = string.Empty;
if (ReadAttributeValue(e, "os_filter_smaller", ref os_filter_smaller) && !String.IsNullOrEmpty(os_filter_smaller))
m_os_filter_max = (OperatingSystem)(int.Parse(os_filter_smaller) - 1);
ReadAttributeValue(e, "os_filter_min", ref m_os_filter_min);
ReadAttributeValue(e, "os_filter_max", ref m_os_filter_max);
ReadAttributeValue(e, "note", ref m_note);
ReadAttributeValue(e, "processor_architecture_filter", ref m_processor_architecture_filter);
ReadAttributeValue(e, "status_installed", ref m_status_installed);
ReadAttributeValue(e, "status_notinstalled", ref m_status_notinstalled);
ReadAttributeValue(e, "supports_install", ref m_supports_install);
ReadAttributeValue(e, "supports_uninstall", ref m_supports_uninstall);
// dialog options
ReadAttributeValue(e, "show_progress_dialog", ref m_show_progress_dialog);
ReadAttributeValue(e, "show_cab_dialog", ref m_show_cab_dialog);
ReadAttributeValue(e, "hide_component_if_installed", ref m_hide_component_if_installed);
base.OnXmlReadTag(e);
}
public static Component CreateFromXml(XmlElement element)
{
Component l_Comp;
string xmltype = element.Attributes["type"].InnerText;
if (xmltype == "msi")
l_Comp = new ComponentMsi();
else if (xmltype == "msu")
l_Comp = new ComponentMsu();
else if (xmltype == "msp")
l_Comp = new ComponentMsp();
else if (xmltype == "cmd")
l_Comp = new ComponentCmd();
else if (xmltype == "openfile")
l_Comp = new ComponentOpenFile();
else if (xmltype == "exe")
l_Comp = new ComponentExe();
else
throw new Exception(string.Format("Invalid type: {0}", xmltype));
l_Comp.FromXml(element);
return l_Comp;
}
/// <summary>
/// Return files to embed for this component.
/// </summary>
/// <param name="parentid"></param>
/// <param name="supportdir"></param>
/// <returns></returns>
public override Dictionary<string, EmbedFileCollection> GetFiles(string parentid, string supportdir)
{
return base.GetFiles(id, supportdir);
}
}
}
| |
//
// Copyright (c) 2004-2020 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.
//
#define DEBUG
using NLog.Config;
namespace NLog.UnitTests.Common
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NLog.Common;
using Xunit;
using Xunit.Extensions;
public class InternalLoggerTests_Trace : NLogTestBase
{
[Theory]
[InlineData(null, null)]
[InlineData(false, null)]
[InlineData(null, false)]
[InlineData(false, false)]
public void ShouldNotLogInternalWhenLogToTraceIsDisabled(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace);
InternalLogger.Trace("Logger1 Hello");
Assert.Empty(mockTraceListener.Messages);
}
[Theory]
[InlineData(null, null)]
[InlineData(false, null)]
[InlineData(null, false)]
[InlineData(false, false)]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldNotLogInternalWhenLogLevelIsOff(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Off, internalLogToTrace, logToTrace);
InternalLogger.Trace("Logger1 Hello");
Assert.Empty(mockTraceListener.Messages);
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void VerifyInternalLoggerLevelFilter(bool? internalLogToTrace, bool? logToTrace)
{
foreach (LogLevel logLevelConfig in LogLevel.AllLevels)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(logLevelConfig, internalLogToTrace, logToTrace);
List<string> expected = new List<string>();
string input = "Logger1 Hello";
expected.Add(input);
InternalLogger.Trace(input);
InternalLogger.Debug(input);
InternalLogger.Info(input);
InternalLogger.Warn(input);
InternalLogger.Error(input);
InternalLogger.Fatal(input);
input += "No.{0}";
expected.Add(string.Format(input, 1));
InternalLogger.Trace(input, 1);
InternalLogger.Debug(input, 1);
InternalLogger.Info(input, 1);
InternalLogger.Warn(input, 1);
InternalLogger.Error(input, 1);
InternalLogger.Fatal(input, 1);
input += ", We come in {1}";
expected.Add(string.Format(input, 1, "Peace"));
InternalLogger.Trace(input, 1, "Peace");
InternalLogger.Debug(input, 1, "Peace");
InternalLogger.Info(input, 1, "Peace");
InternalLogger.Warn(input, 1, "Peace");
InternalLogger.Error(input, 1, "Peace");
InternalLogger.Fatal(input, 1, "Peace");
input += " and we are {2} to god";
expected.Add(string.Format(input, 1, "Peace", true));
InternalLogger.Trace(input, 1, "Peace", true);
InternalLogger.Debug(input, 1, "Peace", true);
InternalLogger.Info(input, 1, "Peace", true);
InternalLogger.Warn(input, 1, "Peace", true);
InternalLogger.Error(input, 1, "Peace", true);
InternalLogger.Fatal(input, 1, "Peace", true);
input += ", Please don't {3}";
expected.Add(string.Format(input, 1, "Peace", true, null));
InternalLogger.Trace(input, 1, "Peace", true, null);
InternalLogger.Debug(input, 1, "Peace", true, null);
InternalLogger.Info(input, 1, "Peace", true, null);
InternalLogger.Warn(input, 1, "Peace", true, null);
InternalLogger.Error(input, 1, "Peace", true, null);
InternalLogger.Fatal(input, 1, "Peace", true, null);
input += " the {4}";
expected.Add(string.Format(input, 1, "Peace", true, null, "Messenger"));
InternalLogger.Trace(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Debug(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Info(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Warn(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Error(input, 1, "Peace", true, null, "Messenger");
InternalLogger.Fatal(input, 1, "Peace", true, null, "Messenger");
Assert.Equal(expected.Count * (LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1), mockTraceListener.Messages.Count);
for (int i = 0; i < expected.Count; ++i)
{
int msgCount = LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1;
for (int j = 0; j < msgCount; ++j)
{
Assert.Contains(expected[i], mockTraceListener.Messages.First());
mockTraceListener.Messages.RemoveAt(0);
}
}
Assert.Empty(mockTraceListener.Messages);
}
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsTrace(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Trace, internalLogToTrace, logToTrace);
InternalLogger.Trace("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Trace Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsDebug(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Debug, internalLogToTrace, logToTrace);
InternalLogger.Debug("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Debug Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsInfo(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Info, internalLogToTrace, logToTrace);
InternalLogger.Info("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Info Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsWarn(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Warn, internalLogToTrace, logToTrace);
InternalLogger.Warn("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Warn Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsError(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Error, internalLogToTrace, logToTrace);
InternalLogger.Error("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Error Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
[Theory]
[InlineData(true, null)]
[InlineData(null, true)]
[InlineData(true, true)]
public void ShouldLogToTraceWhenInternalLogToTraceIsOnAndLogLevelIsFatal(bool? internalLogToTrace, bool? logToTrace)
{
var mockTraceListener = SetupTestConfiguration<MockTraceListener>(LogLevel.Fatal, internalLogToTrace, logToTrace);
InternalLogger.Fatal("Logger1 Hello");
Assert.Single(mockTraceListener.Messages);
Assert.Equal("NLog: Fatal Logger1 Hello" + Environment.NewLine, mockTraceListener.Messages.First());
}
#if !NETSTANDARD1_5
[Fact(Skip = "This test's not working - explenation is in documentation: https://msdn.microsoft.com/pl-pl/library/system.stackoverflowexception(v=vs.110).aspx#Anchor_5. To clarify if StackOverflowException should be thrown.")]
public void ShouldThrowStackOverFlowExceptionWhenUsingNLogTraceListener()
{
SetupTestConfiguration<NLogTraceListener>(LogLevel.Trace, true, null);
Assert.Throws<StackOverflowException>(() => Trace.WriteLine("StackOverFlowException"));
}
#endif
/// <summary>
/// Helper method to setup tests configuration
/// </summary>
/// <param name="logLevel">The <see cref="NLog.LogLevel"/> for the log event.</param>
/// <param name="internalLogToTrace">internalLogToTrace XML attribute value. If <c>null</c> attribute is omitted.</param>
/// <param name="logToTrace">Value of <see cref="InternalLogger.LogToTrace"/> property. If <c>null</c> property is not set.</param>
/// <returns><see cref="TraceListener"/> instance.</returns>
private T SetupTestConfiguration<T>(LogLevel logLevel, bool? internalLogToTrace, bool? logToTrace) where T : TraceListener
{
var internalLogToTraceAttribute = "";
if (internalLogToTrace.HasValue)
{
internalLogToTraceAttribute = $" internalLogToTrace='{internalLogToTrace.Value}'";
}
var xmlConfiguration = string.Format(XmlConfigurationFormat, logLevel, internalLogToTraceAttribute);
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(xmlConfiguration);
InternalLogger.IncludeTimestamp = false;
if (logToTrace.HasValue)
{
InternalLogger.LogToTrace = logToTrace.Value;
}
T traceListener;
if (typeof (T) == typeof (MockTraceListener))
{
traceListener = CreateMockTraceListener() as T;
}
else
{
traceListener = CreateNLogTraceListener() as T;
}
Trace.Listeners.Clear();
if (traceListener == null)
{
return null;
}
Trace.Listeners.Add(traceListener);
return traceListener;
}
private const string XmlConfigurationFormat = @"<nlog internalLogLevel='{0}'{1}>
<targets>
<target name='debug' type='Debug' layout='${{logger}} ${{level}} ${{message}}'/>
</targets>
<rules>
<logger name='*' level='{0}' writeTo='debug'/>
</rules>
</nlog>";
/// <summary>
/// Creates <see cref="MockTraceListener"/> instance.
/// </summary>
/// <returns><see cref="MockTraceListener"/> instance.</returns>
private static MockTraceListener CreateMockTraceListener()
{
return new MockTraceListener();
}
/// <summary>
/// Creates <see cref="NLogTraceListener"/> instance.
/// </summary>
/// <returns><see cref="NLogTraceListener"/> instance.</returns>
private static TraceListener CreateNLogTraceListener()
{
#if !NETSTANDARD1_5
return new NLogTraceListener {Name = "Logger1", ForceLogLevel = LogLevel.Trace};
#else
return null;
#endif
}
private class MockTraceListener : TraceListener
{
internal readonly List<string> Messages = new List<string>();
/// <summary>
/// When overridden in a derived class, writes the specified message to the listener you create in the derived class.
/// </summary>
/// <param name="message">A message to write. </param>
public override void Write(string message)
{
Messages.Add(message);
}
/// <summary>
/// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator.
/// </summary>
/// <param name="message">A message to write. </param>
public override void WriteLine(string message)
{
Messages.Add(message + Environment.NewLine);
}
}
}
}
| |
using EIDSS.Reports.Parameterized.Human.DToChangedD;
using EIDSS.Reports.Parameterized.Human.DToChangedD.DToChangedDDataSetTableAdapters;
namespace EIDSS.Reports.Parameterized.Human.ARM.Report
{
partial class FormN85FirstReport
{
#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(FormN85FirstReport));
this.m_Adapter = new EIDSS.Reports.Parameterized.Human.ARM.DataSet.FormN85FirstDataSetTableAdapters.FirstTableAdapter();
this.m_DataSet = new EIDSS.Reports.Parameterized.Human.ARM.DataSet.FormN85FirstDataSet();
this.ReportHeaderTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageHeaderTable = new DevExpress.XtraReports.UI.XRTable();
this.PageHeaderRow = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell52 = 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.DetailTable = new DevExpress.XtraReports.UI.XRTable();
this.DetailRow = new DevExpress.XtraReports.UI.XRTableRow();
this.DiagnosisCell = new DevExpress.XtraReports.UI.XRTableCell();
this.RowNumberCell = new DevExpress.XtraReports.UI.XRTableCell();
this.ICD10Cell = new DevExpress.XtraReports.UI.XRTableCell();
this.CasesOfRecordedDiseasesCell = new DevExpress.XtraReports.UI.XRTableCell();
this.IncludingWomenCell = new DevExpress.XtraReports.UI.XRTableCell();
this.IncludingUpTo18Cell = new DevExpress.XtraReports.UI.XRTableCell();
this.Including0_2AgeCell = new DevExpress.XtraReports.UI.XRTableCell();
this.Including3_6AgeCell = new DevExpress.XtraReports.UI.XRTableCell();
this.IncludingRuralTotalCell = new DevExpress.XtraReports.UI.XRTableCell();
this.IncludingRuralUpTo18Cell = new DevExpress.XtraReports.UI.XRTableCell();
this.RecordedLethalCell = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailHeaderSubBand = new DevExpress.XtraReports.UI.SubBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailBodySubBand = new DevExpress.XtraReports.UI.SubBand();
this.DetailPageBreakSubBand = new DevExpress.XtraReports.UI.SubBand();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ReportHeaderTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.PageHeaderTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// xrTable4
//
resources.ApplyResources(this.xrTable4, "xrTable4");
this.xrTable4.StylePriority.UseBorders = false;
this.xrTable4.StylePriority.UseFont = false;
this.xrTable4.StylePriority.UsePadding = false;
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UsePadding = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.SubBands.AddRange(new DevExpress.XtraReports.UI.SubBand[] {
this.DetailHeaderSubBand,
this.DetailBodySubBand,
this.DetailPageBreakSubBand});
this.Detail.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.Detail_BeforePrint);
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.PageHeaderTable});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.PrintOn = DevExpress.XtraReports.UI.PrintOnPages.AllPages;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.ReportHeaderTable});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
this.xrPageInfo1.StylePriority.UseTextAlignment = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UsePadding = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
//
// cellBaseCountry
//
this.cellBaseCountry.StylePriority.UseFont = false;
resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry");
//
// 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;
//
// m_Adapter
//
this.m_Adapter.ClearBeforeFill = true;
//
// m_DataSet
//
this.m_DataSet.DataSetName = "DataSet";
this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// ReportHeaderTable
//
this.ReportHeaderTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.ReportHeaderTable, "ReportHeaderTable");
this.ReportHeaderTable.Name = "ReportHeaderTable";
this.ReportHeaderTable.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.ReportHeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3,
this.xrTableRow6,
this.xrTableRow5,
this.xrTableRow4});
this.ReportHeaderTable.StylePriority.UseBorders = false;
this.ReportHeaderTable.StylePriority.UseFont = false;
this.ReportHeaderTable.StylePriority.UsePadding = false;
this.ReportHeaderTable.StylePriority.UseTextAlignment = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9});
this.xrTableRow3.Name = "xrTableRow3";
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
//
// xrTableCell9
//
this.xrTableCell9.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.StylePriority.UseBorders = false;
this.xrTableCell9.StylePriority.UseFont = false;
this.xrTableCell9.StylePriority.UseTextAlignment = false;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell22,
this.xrTableCell23,
this.xrTableCell24,
this.xrTableCell31,
this.xrTableCell27,
this.xrTableCell28});
this.xrTableRow6.Name = "xrTableRow6";
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
//
// xrTableCell22
//
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseFont = false;
//
// xrTableCell23
//
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseFont = false;
//
// xrTableCell24
//
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseFont = false;
//
// xrTableCell31
//
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Name = "xrTableCell31";
this.xrTableCell31.StylePriority.UseFont = false;
this.xrTableCell31.StylePriority.UseTextAlignment = false;
//
// xrTableCell27
//
this.xrTableCell27.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.StylePriority.UseBorders = false;
this.xrTableCell27.StylePriority.UseFont = false;
this.xrTableCell27.StylePriority.UseTextAlignment = false;
//
// xrTableCell28
//
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
this.xrTableCell28.Name = "xrTableCell28";
this.xrTableCell28.StylePriority.UseFont = false;
this.xrTableCell28.StylePriority.UseTextAlignment = false;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell15,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell32,
this.xrTableCell18,
this.xrTableCell29,
this.xrTableCell19,
this.xrTableCell20,
this.xrTableCell21});
this.xrTableRow5.Name = "xrTableRow5";
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
//
// xrTableCell15
//
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
this.xrTableCell15.StylePriority.UseFont = false;
this.xrTableCell15.StylePriority.UseTextAlignment = false;
//
// xrTableCell16
//
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseFont = false;
this.xrTableCell16.StylePriority.UseTextAlignment = false;
//
// xrTableCell17
//
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.StylePriority.UseFont = false;
this.xrTableCell17.StylePriority.UseTextAlignment = false;
//
// xrTableCell32
//
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Name = "xrTableCell32";
this.xrTableCell32.StylePriority.UseFont = false;
this.xrTableCell32.StylePriority.UseTextAlignment = false;
//
// xrTableCell18
//
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseFont = false;
this.xrTableCell18.StylePriority.UseTextAlignment = false;
//
// xrTableCell29
//
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.StylePriority.UseFont = false;
this.xrTableCell29.StylePriority.UseTextAlignment = false;
//
// xrTableCell19
//
this.xrTableCell19.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseBorders = false;
this.xrTableCell19.StylePriority.UseFont = false;
this.xrTableCell19.StylePriority.UseTextAlignment = false;
//
// xrTableCell20
//
this.xrTableCell20.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseBorders = false;
this.xrTableCell20.StylePriority.UseFont = false;
this.xrTableCell20.StylePriority.UseTextAlignment = false;
//
// xrTableCell21
//
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.xrTableCell21.StylePriority.UseFont = false;
this.xrTableCell21.StylePriority.UsePadding = false;
this.xrTableCell21.StylePriority.UseTextAlignment = false;
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell14,
this.xrTableCell10,
this.xrTableCell33,
this.xrTableCell8,
this.xrTableCell30,
this.xrTableCell26,
this.xrTableCell11,
this.xrTableCell25,
this.xrTableCell13,
this.xrTableCell12});
this.xrTableRow4.Name = "xrTableRow4";
this.xrTableRow4.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseBorders = false;
this.xrTableCell7.StylePriority.UseFont = false;
//
// xrTableCell14
//
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseFont = false;
//
// xrTableCell10
//
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Multiline = true;
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseBorders = false;
this.xrTableCell10.StylePriority.UseFont = false;
//
// xrTableCell33
//
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
this.xrTableCell33.Multiline = true;
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.StylePriority.UseFont = false;
//
// xrTableCell8
//
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseFont = false;
//
// xrTableCell30
//
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Multiline = true;
this.xrTableCell30.Name = "xrTableCell30";
this.xrTableCell30.StylePriority.UseFont = false;
//
// xrTableCell26
//
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Multiline = true;
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 0, 100F);
this.xrTableCell26.StylePriority.UseFont = false;
this.xrTableCell26.StylePriority.UsePadding = false;
//
// xrTableCell11
//
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 0, 100F);
this.xrTableCell11.StylePriority.UseFont = false;
this.xrTableCell11.StylePriority.UsePadding = false;
//
// xrTableCell25
//
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 0, 100F);
this.xrTableCell25.StylePriority.UseFont = false;
this.xrTableCell25.StylePriority.UsePadding = false;
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Multiline = true;
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 0, 100F);
this.xrTableCell13.StylePriority.UseFont = false;
this.xrTableCell13.StylePriority.UsePadding = false;
//
// xrTableCell12
//
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseFont = false;
//
// PageHeaderTable
//
resources.ApplyResources(this.PageHeaderTable, "PageHeaderTable");
this.PageHeaderTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.PageHeaderTable.Name = "PageHeaderTable";
this.PageHeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.PageHeaderRow});
this.PageHeaderTable.StylePriority.UseBackColor = false;
this.PageHeaderTable.StylePriority.UseBorders = false;
this.PageHeaderTable.StylePriority.UseFont = false;
this.PageHeaderTable.StylePriority.UsePadding = false;
this.PageHeaderTable.StylePriority.UseTextAlignment = false;
//
// PageHeaderRow
//
this.PageHeaderRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell47,
this.xrTableCell48,
this.xrTableCell49,
this.xrTableCell50,
this.xrTableCell51,
this.xrTableCell52,
this.xrTableCell53,
this.xrTableCell54,
this.xrTableCell55,
this.xrTableCell56,
this.xrTableCell57});
this.PageHeaderRow.Name = "PageHeaderRow";
this.PageHeaderRow.StylePriority.UseFont = false;
resources.ApplyResources(this.PageHeaderRow, "PageHeaderRow");
//
// xrTableCell47
//
resources.ApplyResources(this.xrTableCell47, "xrTableCell47");
this.xrTableCell47.Name = "xrTableCell47";
this.xrTableCell47.StylePriority.UseBorders = false;
this.xrTableCell47.StylePriority.UseFont = false;
//
// xrTableCell48
//
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
this.xrTableCell48.Name = "xrTableCell48";
this.xrTableCell48.StylePriority.UseFont = false;
//
// xrTableCell49
//
resources.ApplyResources(this.xrTableCell49, "xrTableCell49");
this.xrTableCell49.Name = "xrTableCell49";
this.xrTableCell49.StylePriority.UseBorders = false;
this.xrTableCell49.StylePriority.UseFont = false;
//
// xrTableCell50
//
resources.ApplyResources(this.xrTableCell50, "xrTableCell50");
this.xrTableCell50.Name = "xrTableCell50";
this.xrTableCell50.StylePriority.UseFont = false;
//
// xrTableCell51
//
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
this.xrTableCell51.Name = "xrTableCell51";
this.xrTableCell51.StylePriority.UseFont = false;
//
// xrTableCell52
//
resources.ApplyResources(this.xrTableCell52, "xrTableCell52");
this.xrTableCell52.Name = "xrTableCell52";
this.xrTableCell52.StylePriority.UseFont = false;
//
// xrTableCell53
//
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseFont = false;
//
// xrTableCell54
//
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
this.xrTableCell54.Name = "xrTableCell54";
this.xrTableCell54.StylePriority.UseFont = false;
//
// xrTableCell55
//
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
this.xrTableCell55.Name = "xrTableCell55";
this.xrTableCell55.StylePriority.UseFont = false;
//
// xrTableCell56
//
resources.ApplyResources(this.xrTableCell56, "xrTableCell56");
this.xrTableCell56.Multiline = true;
this.xrTableCell56.Name = "xrTableCell56";
this.xrTableCell56.StylePriority.UseFont = false;
//
// xrTableCell57
//
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
this.xrTableCell57.Name = "xrTableCell57";
this.xrTableCell57.StylePriority.UseFont = false;
//
// DetailTable
//
this.DetailTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.DetailTable, "DetailTable");
this.DetailTable.Name = "DetailTable";
this.DetailTable.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.DetailTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.DetailRow});
this.DetailTable.StylePriority.UseBorders = false;
this.DetailTable.StylePriority.UseFont = false;
this.DetailTable.StylePriority.UsePadding = false;
this.DetailTable.StylePriority.UseTextAlignment = false;
//
// DetailRow
//
this.DetailRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.DiagnosisCell,
this.RowNumberCell,
this.ICD10Cell,
this.CasesOfRecordedDiseasesCell,
this.IncludingWomenCell,
this.IncludingUpTo18Cell,
this.Including0_2AgeCell,
this.Including3_6AgeCell,
this.IncludingRuralTotalCell,
this.IncludingRuralUpTo18Cell,
this.RecordedLethalCell});
this.DetailRow.Name = "DetailRow";
this.DetailRow.StylePriority.UseFont = false;
resources.ApplyResources(this.DetailRow, "DetailRow");
//
// DiagnosisCell
//
this.DiagnosisCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.strDiagnosis")});
resources.ApplyResources(this.DiagnosisCell, "DiagnosisCell");
this.DiagnosisCell.Multiline = true;
this.DiagnosisCell.Name = "DiagnosisCell";
this.DiagnosisCell.StylePriority.UseBorders = false;
this.DiagnosisCell.StylePriority.UseFont = false;
this.DiagnosisCell.StylePriority.UseTextAlignment = false;
//
// RowNumberCell
//
this.RowNumberCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.strRowNumber")});
resources.ApplyResources(this.RowNumberCell, "RowNumberCell");
this.RowNumberCell.Name = "RowNumberCell";
this.RowNumberCell.StylePriority.UseFont = false;
//
// ICD10Cell
//
this.ICD10Cell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.strICD")});
resources.ApplyResources(this.ICD10Cell, "ICD10Cell");
this.ICD10Cell.Name = "ICD10Cell";
this.ICD10Cell.StylePriority.UseBorders = false;
this.ICD10Cell.StylePriority.UseFont = false;
//
// CasesOfRecordedDiseasesCell
//
this.CasesOfRecordedDiseasesCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.intCasesOfRecordedDiseasesTotal")});
resources.ApplyResources(this.CasesOfRecordedDiseasesCell, "CasesOfRecordedDiseasesCell");
this.CasesOfRecordedDiseasesCell.Name = "CasesOfRecordedDiseasesCell";
this.CasesOfRecordedDiseasesCell.StylePriority.UseFont = false;
//
// IncludingWomenCell
//
this.IncludingWomenCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.intIncludingWomen")});
resources.ApplyResources(this.IncludingWomenCell, "IncludingWomenCell");
this.IncludingWomenCell.Name = "IncludingWomenCell";
this.IncludingWomenCell.StylePriority.UseFont = false;
//
// IncludingUpTo18Cell
//
this.IncludingUpTo18Cell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.intIncludingUpTo18Age")});
resources.ApplyResources(this.IncludingUpTo18Cell, "IncludingUpTo18Cell");
this.IncludingUpTo18Cell.Name = "IncludingUpTo18Cell";
this.IncludingUpTo18Cell.StylePriority.UseFont = false;
//
// Including0_2AgeCell
//
this.Including0_2AgeCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.intIncluding0_2Age")});
resources.ApplyResources(this.Including0_2AgeCell, "Including0_2AgeCell");
this.Including0_2AgeCell.Name = "Including0_2AgeCell";
this.Including0_2AgeCell.StylePriority.UseFont = false;
//
// Including3_6AgeCell
//
this.Including3_6AgeCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.intIncluding3_6Age")});
resources.ApplyResources(this.Including3_6AgeCell, "Including3_6AgeCell");
this.Including3_6AgeCell.Name = "Including3_6AgeCell";
this.Including3_6AgeCell.StylePriority.UseFont = false;
//
// IncludingRuralTotalCell
//
this.IncludingRuralTotalCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.intIncludingRuralTotal")});
resources.ApplyResources(this.IncludingRuralTotalCell, "IncludingRuralTotalCell");
this.IncludingRuralTotalCell.Name = "IncludingRuralTotalCell";
this.IncludingRuralTotalCell.StylePriority.UseFont = false;
//
// IncludingRuralUpTo18Cell
//
this.IncludingRuralUpTo18Cell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.intIncludingRuralUpTo18Age")});
resources.ApplyResources(this.IncludingRuralUpTo18Cell, "IncludingRuralUpTo18Cell");
this.IncludingRuralUpTo18Cell.Multiline = true;
this.IncludingRuralUpTo18Cell.Name = "IncludingRuralUpTo18Cell";
this.IncludingRuralUpTo18Cell.StylePriority.UseFont = false;
//
// RecordedLethalCell
//
this.RecordedLethalCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.intRecordedLethalOutcomes")});
resources.ApplyResources(this.RecordedLethalCell, "RecordedLethalCell");
this.RecordedLethalCell.Name = "RecordedLethalCell";
this.RecordedLethalCell.StylePriority.UseFont = false;
//
// DetailHeaderSubBand
//
this.DetailHeaderSubBand.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.DetailHeaderSubBand, "DetailHeaderSubBand");
this.DetailHeaderSubBand.Name = "DetailHeaderSubBand";
//
// 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.Name = "xrTable1";
this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
this.xrTable1.StylePriority.UseBorders = false;
this.xrTable1.StylePriority.UseFont = false;
this.xrTable1.StylePriority.UsePadding = false;
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "FirstTable.strDiagnosis")});
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseBackColor = false;
this.xrTableCell1.StylePriority.UseBorders = false;
this.xrTableCell1.StylePriority.UseFont = false;
this.xrTableCell1.StylePriority.UseTextAlignment = false;
//
// DetailBodySubBand
//
this.DetailBodySubBand.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.DetailTable});
resources.ApplyResources(this.DetailBodySubBand, "DetailBodySubBand");
this.DetailBodySubBand.Name = "DetailBodySubBand";
//
// DetailPageBreakSubBand
//
resources.ApplyResources(this.DetailPageBreakSubBand, "DetailPageBreakSubBand");
this.DetailPageBreakSubBand.Name = "DetailPageBreakSubBand";
this.DetailPageBreakSubBand.PageBreak = DevExpress.XtraReports.UI.PageBreak.AfterBand;
//
// ReportFooter
//
this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable2});
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
//
// xrTable2
//
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2,
this.xrTableRow7,
this.xrTableRow8});
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2});
this.xrTableRow2.Name = "xrTableRow2";
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseFont = false;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell3});
this.xrTableRow7.Name = "xrTableRow7";
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
//
// xrTableCell3
//
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseFont = false;
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell4});
this.xrTableRow8.Name = "xrTableRow8";
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseFont = false;
//
// FormN85FirstReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.ReportFooter});
this.DataAdapter = this.m_Adapter;
this.DataMember = "FirstTable";
this.DataSource = this.m_DataSet;
this.Version = "15.1";
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.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ReportHeaderTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.PageHeaderTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private EIDSS.Reports.Parameterized.Human.ARM.DataSet.FormN85FirstDataSetTableAdapters.FirstTableAdapter m_Adapter;
private EIDSS.Reports.Parameterized.Human.ARM.DataSet.FormN85FirstDataSet m_DataSet;
private DevExpress.XtraReports.UI.XRTable ReportHeaderTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTable PageHeaderTable;
private DevExpress.XtraReports.UI.XRTableRow PageHeaderRow;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell47;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
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.XRTable DetailTable;
private DevExpress.XtraReports.UI.XRTableRow DetailRow;
private DevExpress.XtraReports.UI.XRTableCell DiagnosisCell;
private DevExpress.XtraReports.UI.XRTableCell RowNumberCell;
private DevExpress.XtraReports.UI.XRTableCell ICD10Cell;
private DevExpress.XtraReports.UI.XRTableCell CasesOfRecordedDiseasesCell;
private DevExpress.XtraReports.UI.XRTableCell IncludingWomenCell;
private DevExpress.XtraReports.UI.XRTableCell IncludingUpTo18Cell;
private DevExpress.XtraReports.UI.XRTableCell Including0_2AgeCell;
private DevExpress.XtraReports.UI.XRTableCell Including3_6AgeCell;
private DevExpress.XtraReports.UI.XRTableCell IncludingRuralTotalCell;
private DevExpress.XtraReports.UI.XRTableCell IncludingRuralUpTo18Cell;
private DevExpress.XtraReports.UI.XRTableCell RecordedLethalCell;
private DevExpress.XtraReports.UI.SubBand DetailHeaderSubBand;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.SubBand DetailBodySubBand;
private DevExpress.XtraReports.UI.SubBand DetailPageBreakSubBand;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsPaging
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for PagingOperations.
/// </summary>
public static partial class PagingOperationsExtensions
{
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetSinglePages(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetSinglePagesAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSinglePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesAsync(clientRequestId, pagingGetMultiplePagesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetOdataMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetOdataMultiplePagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetOdataMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetOdataMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesWithOffset(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesWithOffsetAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesWithOffsetAsync(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithOffsetWithHttpMessagesAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesRetryFirst(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesRetryFirstAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesRetrySecond(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesRetrySecondAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetSinglePagesFailure(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetSinglePagesFailureAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFailure(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFailureAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFailureUri(this IPagingOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFailureUriAsync(this IPagingOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFragmentNextLink(this IPagingOperations operations, string apiVersion, string tenant)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFragmentNextLinkAsync(apiVersion, tenant), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFragmentNextLinkAsync(this IPagingOperations operations, string apiVersion, string tenant, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFragmentNextLinkWithHttpMessagesAsync(apiVersion, tenant, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment with
/// parameters grouped
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFragmentWithGroupingNextLink(this IPagingOperations operations, CustomParameterGroup customParameterGroup)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFragmentWithGroupingNextLinkAsync(customParameterGroup), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment with
/// parameters grouped
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFragmentWithGroupingNextLinkAsync(this IPagingOperations operations, CustomParameterGroup customParameterGroup, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFragmentWithGroupingNextLinkWithHttpMessagesAsync(customParameterGroup, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> NextFragment(this IPagingOperations operations, string apiVersion, string tenant, string nextLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).NextFragmentAsync(apiVersion, tenant, nextLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> NextFragmentAsync(this IPagingOperations operations, string apiVersion, string tenant, string nextLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.NextFragmentWithHttpMessagesAsync(apiVersion, tenant, nextLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> NextFragmentWithGrouping(this IPagingOperations operations, string nextLink, CustomParameterGroup customParameterGroup)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).NextFragmentWithGroupingAsync(nextLink, customParameterGroup), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> NextFragmentWithGroupingAsync(this IPagingOperations operations, string nextLink, CustomParameterGroup customParameterGroup, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.NextFragmentWithGroupingWithHttpMessagesAsync(nextLink, customParameterGroup, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetSinglePagesNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetSinglePagesNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSinglePagesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetOdataMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetOdataMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetOdataMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetOdataMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesWithOffsetNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesWithOffsetNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesWithOffsetNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesRetryFirstNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesRetryFirstNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesRetrySecondNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesRetrySecondNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetSinglePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetSinglePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Product> GetMultiplePagesFailureUriNext(this IPagingOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Product>> GetMultiplePagesFailureUriNextAsync(this IPagingOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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 Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools.Project;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Navigation {
class HierarchyEventArgs : EventArgs {
private uint _itemId;
private string _fileName;
private IVsTextLines _buffer;
public HierarchyEventArgs(uint itemId, string canonicalName) {
_itemId = itemId;
_fileName = canonicalName;
}
public string CanonicalName {
get { return _fileName; }
}
public uint ItemID {
get { return _itemId; }
}
public IVsTextLines TextBuffer {
get { return _buffer; }
set { _buffer = value; }
}
}
internal abstract partial class LibraryManager : IDisposable, IVsRunningDocTableEvents {
internal class HierarchyListener : IVsHierarchyEvents, IDisposable {
private IVsHierarchy _hierarchy;
private uint _cookie;
private LibraryManager _manager;
public HierarchyListener(IVsHierarchy hierarchy, LibraryManager manager) {
Utilities.ArgumentNotNull("hierarchy", hierarchy);
Utilities.ArgumentNotNull("manager", manager);
_hierarchy = hierarchy;
_manager = manager;
}
protected IVsHierarchy Hierarchy {
get { return _hierarchy; }
}
#region Public Methods
public bool IsListening {
get { return (0 != _cookie); }
}
public void StartListening(bool doInitialScan) {
if (0 != _cookie) {
return;
}
ErrorHandler.ThrowOnFailure(
_hierarchy.AdviseHierarchyEvents(this, out _cookie));
if (doInitialScan) {
InternalScanHierarchy(VSConstants.VSITEMID_ROOT);
}
}
public void StopListening() {
InternalStopListening(true);
}
#endregion
#region IDisposable Members
public void Dispose() {
InternalStopListening(false);
_cookie = 0;
_hierarchy = null;
}
#endregion
#region IVsHierarchyEvents Members
public int OnInvalidateIcon(IntPtr hicon) {
// Do Nothing.
return VSConstants.S_OK;
}
public int OnInvalidateItems(uint itemidParent) {
// TODO: Find out if this event is needed.
return VSConstants.S_OK;
}
public int OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) {
// Check if the item is my language file.
string name;
if (!IsAnalyzableSource(itemidAdded, out name)) {
return VSConstants.S_OK;
}
// This item is a my language file, so we can notify that it is added to the hierarchy.
HierarchyEventArgs args = new HierarchyEventArgs(itemidAdded, name);
_manager.OnNewFile(_hierarchy, args);
return VSConstants.S_OK;
}
public int OnItemDeleted(uint itemid) {
// Notify that the item is deleted only if it is my language file.
string name;
if (!IsAnalyzableSource(itemid, out name)) {
return VSConstants.S_OK;
}
HierarchyEventArgs args = new HierarchyEventArgs(itemid, name);
_manager.OnDeleteFile(_hierarchy, args);
return VSConstants.S_OK;
}
public int OnItemsAppended(uint itemidParent) {
// TODO: Find out what this event is about.
return VSConstants.S_OK;
}
public int OnPropertyChanged(uint itemid, int propid, uint flags) {
if ((null == _hierarchy) || (0 == _cookie)) {
return VSConstants.S_OK;
}
string name;
if (!IsAnalyzableSource(itemid, out name)) {
return VSConstants.S_OK;
}
if (propid == (int)__VSHPROPID.VSHPROPID_IsNonMemberItem) {
_manager.IsNonMemberItemChanged(_hierarchy, new HierarchyEventArgs(itemid, name));
}
return VSConstants.S_OK;
}
#endregion
private bool InternalStopListening(bool throwOnError) {
if ((null == _hierarchy) || (0 == _cookie)) {
return false;
}
int hr = _hierarchy.UnadviseHierarchyEvents(_cookie);
if (throwOnError) {
ErrorHandler.ThrowOnFailure(hr);
}
_cookie = 0;
return ErrorHandler.Succeeded(hr);
}
/// <summary>
/// Do a recursive walk on the hierarchy to find all this language files in it.
/// It will generate an event for every file found.
/// </summary>
private void InternalScanHierarchy(uint itemId) {
uint currentItem = itemId;
while (VSConstants.VSITEMID_NIL != currentItem) {
// If this item is a my language file, then send the add item event.
string itemName;
if (IsAnalyzableSource(currentItem, out itemName)) {
HierarchyEventArgs args = new HierarchyEventArgs(currentItem, itemName);
_manager.OnNewFile(_hierarchy, args);
}
// NOTE: At the moment we skip the nested hierarchies, so here we look for the
// children of this node.
// Before looking at the children we have to make sure that the enumeration has not
// side effects to avoid unexpected behavior.
object propertyValue;
bool canScanSubitems = true;
int hr = _hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_HasEnumerationSideEffects, out propertyValue);
if ((VSConstants.S_OK == hr) && (propertyValue is bool)) {
canScanSubitems = !(bool)propertyValue;
}
// If it is allow to look at the sub-items of the current one, lets do it.
if (canScanSubitems) {
object child;
hr = _hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_FirstChild, out child);
if (VSConstants.S_OK == hr) {
// There is a sub-item, call this same function on it.
InternalScanHierarchy(GetItemId(child));
}
}
// Move the current item to its first visible sibling.
object sibling;
hr = _hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_NextSibling, out sibling);
if (VSConstants.S_OK != hr) {
currentItem = VSConstants.VSITEMID_NIL;
} else {
currentItem = GetItemId(sibling);
}
}
}
private bool IsAnalyzableSource(uint itemId, out string canonicalName) {
// Find out if this item is a physical file.
Guid typeGuid;
canonicalName = null;
int hr;
try {
hr = Hierarchy.GetGuidProperty(itemId, (int)__VSHPROPID.VSHPROPID_TypeGuid, out typeGuid);
} catch (System.Runtime.InteropServices.COMException) {
return false;
}
if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) ||
VSConstants.GUID_ItemType_PhysicalFile != typeGuid) {
// It is not a file, we can exit now.
return false;
}
// This item is a file; find if current language can recognize it.
hr = Hierarchy.GetCanonicalName(itemId, out canonicalName);
if (ErrorHandler.Failed(hr)) {
return false;
}
return (System.IO.Path.GetExtension(canonicalName).Equals(".xaml", StringComparison.OrdinalIgnoreCase)) ||
_manager._package.IsRecognizedFile(canonicalName);
}
/// <summary>
/// Gets the item id.
/// </summary>
/// <param name="variantValue">VARIANT holding an itemid.</param>
/// <returns>Item Id of the concerned node</returns>
private static uint GetItemId(object variantValue) {
if (variantValue == null)
return VSConstants.VSITEMID_NIL;
if (variantValue is int)
return (uint)(int)variantValue;
if (variantValue is uint)
return (uint)variantValue;
if (variantValue is short)
return (uint)(short)variantValue;
if (variantValue is ushort)
return (uint)(ushort)variantValue;
if (variantValue is long)
return (uint)(long)variantValue;
return VSConstants.VSITEMID_NIL;
}
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.VisualStudioTools.Navigation {
/// <summary>
/// Inplementation of the service that builds the information to expose to the symbols
/// navigation tools (class view or object browser) from the source files inside a
/// hierarchy.
/// </summary>
internal abstract partial class LibraryManager : IDisposable, IVsRunningDocTableEvents {
private readonly CommonPackage/*!*/ _package;
private readonly Dictionary<uint, TextLineEventListener> _documents;
private readonly Dictionary<IVsHierarchy, HierarchyInfo> _hierarchies = new Dictionary<IVsHierarchy, HierarchyInfo>();
private readonly Dictionary<ModuleId, LibraryNode> _files;
private readonly Library _library;
private readonly IVsEditorAdaptersFactoryService _adapterFactory;
private uint _objectManagerCookie;
private uint _runningDocTableCookie;
public LibraryManager(CommonPackage/*!*/ package) {
Contract.Assert(package != null);
_package = package;
_documents = new Dictionary<uint, TextLineEventListener>();
_library = new Library(new Guid(CommonConstants.LibraryGuid));
_library.LibraryCapabilities = (_LIB_FLAGS2)_LIB_FLAGS.LF_PROJECT;
_files = new Dictionary<ModuleId, LibraryNode>();
var model = ((IServiceContainer)package).GetService(typeof(SComponentModel)) as IComponentModel;
_adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>();
// Register our library now so it'll be available for find all references
RegisterLibrary();
}
public Library Library {
get { return _library; }
}
public virtual LibraryNode CreateFileLibraryNode(LibraryNode parent, HierarchyNode hierarchy, string name, string filename) {
return new LibraryNode(null, name, filename, LibraryNodeType.Namespaces);
}
private object GetPackageService(Type/*!*/ type) {
return ((System.IServiceProvider)_package).GetService(type);
}
private void RegisterForRDTEvents() {
if (0 != _runningDocTableCookie) {
return;
}
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null != rdt) {
// Do not throw here in case of error, simply skip the registration.
rdt.AdviseRunningDocTableEvents(this, out _runningDocTableCookie);
}
}
private void UnregisterRDTEvents() {
if (0 == _runningDocTableCookie) {
return;
}
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null != rdt) {
// Do not throw in case of error.
rdt.UnadviseRunningDocTableEvents(_runningDocTableCookie);
}
_runningDocTableCookie = 0;
}
#region ILibraryManager Members
public void RegisterHierarchy(IVsHierarchy hierarchy) {
if ((null == hierarchy) || _hierarchies.ContainsKey(hierarchy)) {
return;
}
RegisterLibrary();
var commonProject = hierarchy.GetProject().GetCommonProject();
HierarchyListener listener = new HierarchyListener(hierarchy, this);
var node = _hierarchies[hierarchy] = new HierarchyInfo(
listener,
new ProjectLibraryNode(commonProject)
);
_library.AddNode(node.ProjectLibraryNode);
listener.StartListening(true);
RegisterForRDTEvents();
}
private void RegisterLibrary() {
if (0 == _objectManagerCookie) {
IVsObjectManager2 objManager = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (null == objManager) {
return;
}
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
objManager.RegisterSimpleLibrary(_library, out _objectManagerCookie));
}
}
public void UnregisterHierarchy(IVsHierarchy hierarchy) {
if ((null == hierarchy) || !_hierarchies.ContainsKey(hierarchy)) {
return;
}
HierarchyInfo info = _hierarchies[hierarchy];
if (null != info) {
info.Listener.Dispose();
}
_hierarchies.Remove(hierarchy);
_library.RemoveNode(info.ProjectLibraryNode);
if (0 == _hierarchies.Count) {
UnregisterRDTEvents();
}
lock (_files) {
ModuleId[] keys = new ModuleId[_files.Keys.Count];
_files.Keys.CopyTo(keys, 0);
foreach (ModuleId id in keys) {
if (hierarchy.Equals(id.Hierarchy)) {
_library.RemoveNode(_files[id]);
_files.Remove(id);
}
}
}
// Remove the document listeners.
uint[] docKeys = new uint[_documents.Keys.Count];
_documents.Keys.CopyTo(docKeys, 0);
foreach (uint id in docKeys) {
TextLineEventListener docListener = _documents[id];
if (hierarchy.Equals(docListener.FileID.Hierarchy)) {
_documents.Remove(id);
docListener.Dispose();
}
}
}
public void RegisterLineChangeHandler(uint document,
TextLineChangeEvent lineChanged, Action<IVsTextLines> onIdle) {
_documents[document].OnFileChangedImmediate += delegate (object sender, TextLineChange[] changes, int fLast) {
lineChanged(sender, changes, fLast);
};
_documents[document].OnFileChanged += (sender, args) => onIdle(args.TextBuffer);
}
#endregion
#region Library Member Production
/// <summary>
/// Overridden in the base class to receive notifications of when a file should
/// be analyzed for inclusion in the library. The derived class should queue
/// the parsing of the file and when it's complete it should call FileParsed
/// with the provided LibraryTask and an IScopeNode which provides information
/// about the members of the file.
/// </summary>
protected virtual void OnNewFile(LibraryTask task) {
}
/// <summary>
/// Called by derived class when a file has been parsed. The caller should
/// provide the LibraryTask received from the OnNewFile call and an IScopeNode
/// which represents the contents of the library.
///
/// It is safe to call this method from any thread.
/// </summary>
protected void FileParsed(LibraryTask task) {
try {
var project = task.ModuleID.Hierarchy.GetProject().GetCommonProject();
HierarchyNode fileNode = fileNode = project.NodeFromItemId(task.ModuleID.ItemID);
HierarchyInfo parent;
if (fileNode == null || !_hierarchies.TryGetValue(task.ModuleID.Hierarchy, out parent)) {
return;
}
LibraryNode module = CreateFileLibraryNode(
parent.ProjectLibraryNode,
fileNode,
System.IO.Path.GetFileName(task.FileName),
task.FileName
);
// TODO: Creating the module tree should be done lazily as needed
// Currently we replace the entire tree and rely upon the libraries
// update count to invalidate the whole thing. We could do this
// finer grained and only update the changed nodes. But then we
// need to make sure we're not mutating lists which are handed out.
if (null != task.ModuleID) {
LibraryNode previousItem = null;
lock (_files) {
if (_files.TryGetValue(task.ModuleID, out previousItem)) {
_files.Remove(task.ModuleID);
parent.ProjectLibraryNode.RemoveNode(previousItem);
}
}
}
parent.ProjectLibraryNode.AddNode(module);
_library.Update();
if (null != task.ModuleID) {
lock (_files) {
_files.Add(task.ModuleID, module);
}
}
} catch (COMException) {
// we're shutting down and can't get the project
}
}
#endregion
#region Hierarchy Events
private void OnNewFile(object sender, HierarchyEventArgs args) {
IVsHierarchy hierarchy = sender as IVsHierarchy;
if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) {
return;
}
ITextBuffer buffer = null;
if (null != args.TextBuffer) {
buffer = _adapterFactory.GetDocumentBuffer(args.TextBuffer);
}
var id = new ModuleId(hierarchy, args.ItemID);
OnNewFile(new LibraryTask(args.CanonicalName, buffer, new ModuleId(hierarchy, args.ItemID)));
}
/// <summary>
/// Handles the delete event, checking to see if this is a project item.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void OnDeleteFile(object sender, HierarchyEventArgs args) {
IVsHierarchy hierarchy = sender as IVsHierarchy;
if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) {
return;
}
OnDeleteFile(hierarchy, args);
}
/// <summary>
/// Does a delete w/o checking if it's a non-meber item, for handling the
/// transition from member item to non-member item.
/// </summary>
private void OnDeleteFile(IVsHierarchy hierarchy, HierarchyEventArgs args) {
ModuleId id = new ModuleId(hierarchy, args.ItemID);
LibraryNode node = null;
lock (_files) {
if (_files.TryGetValue(id, out node)) {
_files.Remove(id);
HierarchyInfo parent;
if (_hierarchies.TryGetValue(hierarchy, out parent)) {
parent.ProjectLibraryNode.RemoveNode(node);
}
}
}
if (null != node) {
_library.RemoveNode(node);
}
}
private void IsNonMemberItemChanged(object sender, HierarchyEventArgs args) {
IVsHierarchy hierarchy = sender as IVsHierarchy;
if (null == hierarchy) {
return;
}
if (!IsNonMemberItem(hierarchy, args.ItemID)) {
OnNewFile(hierarchy, args);
} else {
OnDeleteFile(hierarchy, args);
}
}
/// <summary>
/// Checks whether this hierarchy item is a project member (on disk items from show all
/// files aren't considered project members).
/// </summary>
protected bool IsNonMemberItem(IVsHierarchy hierarchy, uint itemId) {
object val;
int hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_IsNonMemberItem, out val);
return ErrorHandler.Succeeded(hr) && (bool)val;
}
#endregion
#region IVsRunningDocTableEvents Members
public int OnAfterAttributeChange(uint docCookie, uint grfAttribs) {
if ((grfAttribs & (uint)(__VSRDTATTRIB.RDTA_MkDocument)) == (uint)__VSRDTATTRIB.RDTA_MkDocument) {
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (rdt != null) {
uint flags, readLocks, editLocks, itemid;
IVsHierarchy hier;
IntPtr docData = IntPtr.Zero;
string moniker;
int hr;
try {
hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out editLocks, out moniker, out hier, out itemid, out docData);
TextLineEventListener listner;
if (_documents.TryGetValue(docCookie, out listner)) {
listner.FileName = moniker;
}
} finally {
if (IntPtr.Zero != docData) {
Marshal.Release(docData);
}
}
}
}
return VSConstants.S_OK;
}
public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) {
return VSConstants.S_OK;
}
public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) {
return VSConstants.S_OK;
}
public int OnAfterSave(uint docCookie) {
return VSConstants.S_OK;
}
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) {
// Check if this document is in the list of the documents.
if (_documents.ContainsKey(docCookie)) {
return VSConstants.S_OK;
}
// Get the information about this document from the RDT.
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null != rdt) {
// Note that here we don't want to throw in case of error.
uint flags;
uint readLocks;
uint writeLoks;
string documentMoniker;
IVsHierarchy hierarchy;
uint itemId;
IntPtr unkDocData;
int hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out writeLoks,
out documentMoniker, out hierarchy, out itemId, out unkDocData);
try {
if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) || (IntPtr.Zero == unkDocData)) {
return VSConstants.S_OK;
}
// Check if the herarchy is one of the hierarchies this service is monitoring.
if (!_hierarchies.ContainsKey(hierarchy)) {
// This hierarchy is not monitored, we can exit now.
return VSConstants.S_OK;
}
// Check the file to see if a listener is required.
if (_package.IsRecognizedFile(documentMoniker)) {
return VSConstants.S_OK;
}
// Create the module id for this document.
ModuleId docId = new ModuleId(hierarchy, itemId);
// Try to get the text buffer.
IVsTextLines buffer = Marshal.GetObjectForIUnknown(unkDocData) as IVsTextLines;
// Create the listener.
TextLineEventListener listener = new TextLineEventListener(buffer, documentMoniker, docId);
// Set the event handler for the change event. Note that there is no difference
// between the AddFile and FileChanged operation, so we can use the same handler.
listener.OnFileChanged += new EventHandler<HierarchyEventArgs>(OnNewFile);
// Add the listener to the dictionary, so we will not create it anymore.
_documents.Add(docCookie, listener);
} finally {
if (IntPtr.Zero != unkDocData) {
Marshal.Release(unkDocData);
}
}
}
// Always return success.
return VSConstants.S_OK;
}
public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) {
if ((0 != dwEditLocksRemaining) || (0 != dwReadLocksRemaining)) {
return VSConstants.S_OK;
}
TextLineEventListener listener;
if (!_documents.TryGetValue(docCookie, out listener) || (null == listener)) {
return VSConstants.S_OK;
}
using (listener) {
_documents.Remove(docCookie);
// Now make sure that the information about this file are up to date (e.g. it is
// possible that Class View shows something strange if the file was closed without
// saving the changes).
HierarchyEventArgs args = new HierarchyEventArgs(listener.FileID.ItemID, listener.FileName);
OnNewFile(listener.FileID.Hierarchy, args);
}
return VSConstants.S_OK;
}
#endregion
public void OnIdle(IOleComponentManager compMgr) {
foreach (TextLineEventListener listener in _documents.Values) {
if (compMgr.FContinueIdle() == 0) {
break;
}
listener.OnIdle();
}
}
#region IDisposable Members
public void Dispose() {
// Dispose all the listeners.
foreach (var info in _hierarchies.Values) {
info.Listener.Dispose();
}
_hierarchies.Clear();
foreach (TextLineEventListener textListener in _documents.Values) {
textListener.Dispose();
}
_documents.Clear();
// Remove this library from the object manager.
if (0 != _objectManagerCookie) {
IVsObjectManager2 mgr = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (null != mgr) {
mgr.UnregisterLibrary(_objectManagerCookie);
}
_objectManagerCookie = 0;
}
// Unregister this object from the RDT events.
UnregisterRDTEvents();
}
#endregion
class HierarchyInfo {
public readonly HierarchyListener Listener;
public readonly ProjectLibraryNode ProjectLibraryNode;
public HierarchyInfo(HierarchyListener listener, ProjectLibraryNode projectLibNode) {
Listener = listener;
ProjectLibraryNode = projectLibNode;
}
}
}
}
| |
using System;
using System.Reflection;
using System.Collections;
using Server;
using Server.Network;
using Server.Menus;
using Server.Menus.Questions;
using Server.Targeting;
using Server.Commands;
using Server.Commands.Generic;
using CPA = Server.CommandPropertyAttribute;
/*
** modified properties gumps taken from RC0 properties gump scripts to support the special XmlSpawner properties gump
*/
namespace Server.Gumps
{
public class XmlPropertiesGump : Gump
{
private ArrayList m_List;
private int m_Page;
private Mobile m_Mobile;
private object m_Object;
private Stack m_Stack;
public static readonly bool OldStyle = PropsConfig.OldStyle;
public static readonly int GumpOffsetX = PropsConfig.GumpOffsetX;
public static readonly int GumpOffsetY = PropsConfig.GumpOffsetY;
public static readonly int TextHue = PropsConfig.TextHue;
public static readonly int TextOffsetX = PropsConfig.TextOffsetX;
public static readonly int OffsetGumpID = PropsConfig.OffsetGumpID;
public static readonly int HeaderGumpID = PropsConfig.HeaderGumpID;
public static readonly int EntryGumpID = PropsConfig.EntryGumpID;
public static readonly int BackGumpID = PropsConfig.BackGumpID;
public static readonly int SetGumpID = PropsConfig.SetGumpID;
public static readonly int SetWidth = PropsConfig.SetWidth;
public static readonly int SetOffsetX = PropsConfig.SetOffsetX, SetOffsetY = PropsConfig.SetOffsetY;
public static readonly int SetButtonID1 = PropsConfig.SetButtonID1;
public static readonly int SetButtonID2 = PropsConfig.SetButtonID2;
public static readonly int PrevWidth = PropsConfig.PrevWidth;
public static readonly int PrevOffsetX = PropsConfig.PrevOffsetX, PrevOffsetY = PropsConfig.PrevOffsetY;
public static readonly int PrevButtonID1 = PropsConfig.PrevButtonID1;
public static readonly int PrevButtonID2 = PropsConfig.PrevButtonID2;
public static readonly int NextWidth = PropsConfig.NextWidth;
public static readonly int NextOffsetX = PropsConfig.NextOffsetX, NextOffsetY = PropsConfig.NextOffsetY;
public static readonly int NextButtonID1 = PropsConfig.NextButtonID1;
public static readonly int NextButtonID2 = PropsConfig.NextButtonID2;
public static readonly int OffsetSize = PropsConfig.OffsetSize;
public static readonly int EntryHeight = PropsConfig.EntryHeight;
public static readonly int BorderSize = PropsConfig.BorderSize;
private static bool PrevLabel = OldStyle, NextLabel = OldStyle;
private static readonly int PrevLabelOffsetX = PrevWidth + 1;
private static readonly int PrevLabelOffsetY = 0;
private static readonly int NextLabelOffsetX = -29;
private static readonly int NextLabelOffsetY = 0;
private static readonly int NameWidth = 103;
private static readonly int ValueWidth = 82;
private static readonly int EntryCount = 66;
private static readonly int ColumnEntryCount = 22;
private static readonly int TypeWidth = NameWidth + OffsetSize + ValueWidth;
private static readonly int TotalWidth = OffsetSize + NameWidth + OffsetSize + ValueWidth + OffsetSize + SetWidth + OffsetSize;
private static readonly int TotalHeight = OffsetSize + ((EntryHeight + OffsetSize) * (EntryCount + 1));
private static readonly int BackWidth = BorderSize + TotalWidth + BorderSize;
private static readonly int BackHeight = BorderSize + TotalHeight + BorderSize;
public XmlPropertiesGump( Mobile mobile, object o ) : base( GumpOffsetX, GumpOffsetY )
{
m_Mobile = mobile;
m_Object = o;
m_List = BuildList();
Initialize( 0 );
}
public XmlPropertiesGump( Mobile mobile, object o, Stack stack, object parent ) : base( GumpOffsetX, GumpOffsetY )
{
m_Mobile = mobile;
m_Object = o;
m_Stack = stack;
m_List = BuildList();
if ( parent != null )
{
if ( m_Stack == null )
m_Stack = new Stack();
m_Stack.Push( parent );
}
Initialize( 0 );
}
public XmlPropertiesGump( Mobile mobile, object o, Stack stack, ArrayList list, int page ) : base( GumpOffsetX, GumpOffsetY )
{
m_Mobile = mobile;
m_Object = o;
m_List = list;
m_Stack = stack;
Initialize( page );
}
private void Initialize( int page )
{
m_Page = page;
int count = m_List.Count - (page * EntryCount);
if ( count < 0 )
count = 0;
else if ( count > EntryCount )
count = EntryCount;
int lastIndex = (page * EntryCount) + count - 1;
if ( lastIndex >= 0 && lastIndex < m_List.Count && m_List[lastIndex] == null )
--count;
int totalHeight = OffsetSize + ((EntryHeight + OffsetSize) * (ColumnEntryCount + 1));
AddPage( 0 );
AddBackground( 0, 0, TotalWidth*3 + BorderSize*2, BorderSize + totalHeight + BorderSize, BackGumpID );
AddImageTiled( BorderSize, BorderSize + EntryHeight, (TotalWidth - (OldStyle ? SetWidth + OffsetSize : 0))*3, totalHeight-EntryHeight, OffsetGumpID );
int x = BorderSize + OffsetSize;
int y = BorderSize /*+ OffsetSize*/;
int emptyWidth = TotalWidth - PrevWidth - NextWidth - (OffsetSize * 4) - (OldStyle ? SetWidth + OffsetSize : 0);
if(m_Object is Item)
AddLabelCropped( x + TextOffsetX, y, TypeWidth - TextOffsetX, EntryHeight, TextHue, ((Item)m_Object).Name );
int propcount = 0;
for ( int i = 0, index = page * EntryCount; i < count && index < m_List.Count; ++i, ++index )
{
// do the multi column display
int column = propcount/ColumnEntryCount;
if(propcount%ColumnEntryCount == 0)
y = BorderSize;
x = BorderSize + OffsetSize + column*(ValueWidth + NameWidth +OffsetSize*2 + SetOffsetX + SetWidth);
y += EntryHeight + OffsetSize;
object o = m_List[index];
if ( o == null )
{
AddImageTiled( x - OffsetSize, y, TotalWidth, EntryHeight, BackGumpID + 4 );
propcount++;
}
else
/*if ( o is Type )
{
Type type = (Type)o;
AddImageTiled( x, y, TypeWidth, EntryHeight, EntryGumpID );
AddLabelCropped( x + TextOffsetX, y, TypeWidth - TextOffsetX, EntryHeight, TextHue, type.Name );
x += TypeWidth + OffsetSize;
if ( SetGumpID != 0 )
AddImageTiled( x, y, SetWidth, EntryHeight, SetGumpID );
}
else
*/
if ( o is PropertyInfo )
{
propcount++;
PropertyInfo prop = (PropertyInfo)o;
// look for the default value of the equivalent property in the XmlSpawnerDefaults.DefaultEntry class
int huemodifier = TextHue;
FieldInfo finfo = null;
Server.Mobiles.XmlSpawnerDefaults.DefaultEntry de = new Server.Mobiles.XmlSpawnerDefaults.DefaultEntry();
Type ftype = de.GetType();
if(ftype != null)
finfo = ftype.GetField(prop.Name);
// is there an equivalent default field?
if(finfo != null){
// see if the value is different from the default
if(ValueToString(finfo.GetValue(de)) != ValueToString(prop))
{
huemodifier = 68;
}
}
AddImageTiled( x, y, NameWidth, EntryHeight, EntryGumpID );
AddLabelCropped( x + TextOffsetX, y, NameWidth - TextOffsetX, EntryHeight, huemodifier, prop.Name );
x += NameWidth + OffsetSize;
AddImageTiled( x, y, ValueWidth, EntryHeight, EntryGumpID );
AddLabelCropped( x + TextOffsetX, y, ValueWidth - TextOffsetX, EntryHeight, huemodifier, ValueToString( prop ) );
x += ValueWidth + OffsetSize;
if ( SetGumpID != 0 )
AddImageTiled( x, y, SetWidth, EntryHeight, SetGumpID );
CPA cpa = GetCPA( prop );
if ( prop.CanWrite && cpa != null && m_Mobile.AccessLevel >= cpa.WriteLevel )
AddButton( x + SetOffsetX, y + SetOffsetY, SetButtonID1, SetButtonID2, i + 3, GumpButtonType.Reply, 0 );
}
}
}
public static string[] m_BoolNames = new string[]{ "True", "False" };
public static object[] m_BoolValues = new object[]{ true, false };
public static string[] m_PoisonNames = new string[]{ "None", "Lesser", "Regular", "Greater", "Deadly", "Lethal" };
public static object[] m_PoisonValues = new object[]{ null, Poison.Lesser, Poison.Regular, Poison.Greater, Poison.Deadly, Poison.Lethal };
public override void OnResponse( NetState state, RelayInfo info )
{
Mobile from = state.Mobile;
if ( !BaseCommand.IsAccessible( from, m_Object ) )
{
from.SendMessage( "You may no longer access their properties." );
return;
}
switch ( info.ButtonID )
{
case 0: // Closed
{
if ( m_Stack != null && m_Stack.Count > 0 )
{
object obj = m_Stack.Pop();
from.SendGump( new XmlPropertiesGump( from, obj, m_Stack, null ) );
}
break;
}
case 1: // Previous
{
if ( m_Page > 0 )
from.SendGump( new XmlPropertiesGump( from, m_Object, m_Stack, m_List, m_Page - 1 ) );
break;
}
case 2: // Next
{
if ( (m_Page + 1) * EntryCount < m_List.Count )
from.SendGump( new XmlPropertiesGump( from, m_Object, m_Stack, m_List, m_Page + 1 ) );
break;
}
default:
{
int index = (m_Page * EntryCount) + (info.ButtonID - 3);
if ( index >= 0 && index < m_List.Count )
{
PropertyInfo prop = m_List[index] as PropertyInfo;
if ( prop == null )
return;
CPA attr = GetCPA( prop );
if ( !prop.CanWrite || attr == null || from.AccessLevel < attr.WriteLevel )
return;
Type type = prop.PropertyType;
if ( IsType( type, typeofMobile ) || IsType( type, typeofItem ) )
from.SendGump( new XmlSetObjectGump( prop, from, m_Object, m_Stack, type, m_Page, m_List ) );
else if ( IsType( type, typeofType ) )
from.Target = new XmlSetObjectTarget( prop, from, m_Object, m_Stack, type, m_Page, m_List );
else if ( IsType( type, typeofPoint3D ) )
from.SendGump( new XmlSetPoint3DGump( prop, from, m_Object, m_Stack, m_Page, m_List ) );
else if ( IsType( type, typeofPoint2D ) )
from.SendGump( new XmlSetPoint2DGump( prop, from, m_Object, m_Stack, m_Page, m_List ) );
else if ( IsType( type, typeofTimeSpan ) )
from.SendGump( new XmlSetTimeSpanGump( prop, from, m_Object, m_Stack, m_Page, m_List ) );
else if ( IsCustomEnum( type ) )
from.SendGump( new XmlSetCustomEnumGump( prop, from, m_Object, m_Stack, m_Page, m_List, GetCustomEnumNames( type ) ) );
else if ( IsType( type, typeofEnum ) )
from.SendGump( new XmlSetListOptionGump( prop, from, m_Object, m_Stack, m_Page, m_List, Enum.GetNames( type ), GetObjects( Enum.GetValues( type ) ) ) );
else if ( IsType( type, typeofBool ) )
from.SendGump( new XmlSetListOptionGump( prop, from, m_Object, m_Stack, m_Page, m_List, m_BoolNames, m_BoolValues ) );
else if ( IsType( type, typeofString ) || IsType( type, typeofReal ) || IsType( type, typeofNumeric ) )
from.SendGump( new XmlSetGump( prop, from, m_Object, m_Stack, m_Page, m_List ) );
else if ( IsType( type, typeofPoison ) )
from.SendGump( new XmlSetListOptionGump( prop, from, m_Object, m_Stack, m_Page, m_List, m_PoisonNames, m_PoisonValues ) );
else if ( IsType( type, typeofMap ) )
from.SendGump( new XmlSetListOptionGump( prop, from, m_Object, m_Stack, m_Page, m_List, Map.GetMapNames(), Map.GetMapValues() ) );
else if ( IsType( type, typeofSkills ) && m_Object is Mobile )
{
from.SendGump( new XmlPropertiesGump( from, m_Object, m_Stack, m_List, m_Page ) );
from.SendGump( new SkillsGump( from, (Mobile)m_Object ) );
}
else if ( HasAttribute( type, typeofPropertyObject, true ) )
from.SendGump( new XmlPropertiesGump( from, prop.GetValue( m_Object, null ), m_Stack, m_Object ) );
}
break;
}
}
}
private static object[] GetObjects( Array a )
{
object[] list = new object[a.Length];
for ( int i = 0; i < list.Length; ++i )
list[i] = a.GetValue( i );
return list;
}
private static bool IsCustomEnum( Type type )
{
return type.IsDefined( typeofCustomEnum, false );
}
private static string[] GetCustomEnumNames( Type type )
{
object[] attrs = type.GetCustomAttributes( typeofCustomEnum, false );
if ( attrs.Length == 0 )
return new string[0];
CustomEnumAttribute ce = attrs[0] as CustomEnumAttribute;
if ( ce == null )
return new string[0];
return ce.Names;
}
private static bool HasAttribute( Type type, Type check, bool inherit )
{
object[] objs = type.GetCustomAttributes( check, inherit );
return ( objs != null && objs.Length > 0 );
}
private static bool IsType( Type type, Type check )
{
return type == check || type.IsSubclassOf( check );
}
private static bool IsType( Type type, Type[] check )
{
for ( int i = 0; i < check.Length; ++i )
if ( IsType( type, check[i] ) )
return true;
return false;
}
private static Type typeofMobile = typeof( Mobile );
private static Type typeofItem = typeof( Item );
private static Type typeofType = typeof( Type );
private static Type typeofPoint3D = typeof( Point3D );
private static Type typeofPoint2D = typeof( Point2D );
private static Type typeofTimeSpan = typeof( TimeSpan );
private static Type typeofCustomEnum = typeof( CustomEnumAttribute );
private static Type typeofEnum = typeof( Enum );
private static Type typeofBool = typeof( Boolean );
private static Type typeofString = typeof( String );
private static Type typeofPoison = typeof( Poison );
private static Type typeofMap = typeof( Map );
private static Type typeofSkills = typeof( Skills );
private static Type typeofPropertyObject = typeof( PropertyObjectAttribute );
private static Type typeofNoSort = typeof( NoSortAttribute );
private static Type[] typeofReal = new Type[]
{
typeof( Single ),
typeof( Double )
};
private static Type[] typeofNumeric = new Type[]
{
typeof( Byte ),
typeof( Int16 ),
typeof( Int32 ),
typeof( Int64 ),
typeof( SByte ),
typeof( UInt16 ),
typeof( UInt32 ),
typeof( UInt64 )
};
private string ValueToString( PropertyInfo prop )
{
return ValueToString( m_Object, prop );
}
public static string ValueToString( object obj, PropertyInfo prop )
{
try
{
return ValueToString( prop.GetValue( obj, null ) );
}
catch ( Exception e )
{
return String.Format( "!{0}!", e.GetType() );
}
}
public static string ValueToString( object o )
{
if ( o == null )
{
return "-null-";
}
else if ( o is string )
{
return String.Format( "\"{0}\"", (string)o );
}
else if ( o is bool )
{
return o.ToString();
}
else if ( o is char )
{
return String.Format( "0x{0:X} '{1}'", (int)(char)o, (char)o );
}
else if ( o is Serial )
{
Serial s = (Serial)o;
if ( s.IsValid )
{
if ( s.IsItem )
{
return String.Format( "(I) 0x{0:X}", s.Value );
}
else if ( s.IsMobile )
{
return String.Format( "(M) 0x{0:X}", s.Value );
}
}
return String.Format( "(?) 0x{0:X}", s.Value );
}
else if ( o is byte || o is sbyte || o is short || o is ushort || o is int || o is uint || o is long || o is ulong )
{
return String.Format( "{0} (0x{0:X})", o );
}
else if ( o is double )
{
return o.ToString();
}
else if ( o is Mobile )
{
return String.Format( "(M) 0x{0:X} \"{1}\"", ((Mobile)o).Serial.Value, ((Mobile)o).Name );
}
else if ( o is Item )
{
return String.Format( "(I) 0x{0:X}", ((Item)o).Serial );
}
else if ( o is Type )
{
return ((Type)o).Name;
}
else
{
return o.ToString();
}
}
private ArrayList BuildList()
{
Type type = m_Object.GetType();
PropertyInfo[] props = type.GetProperties( BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public );
ArrayList groups = GetGroups( type, props );
ArrayList list = new ArrayList();
for ( int i = 0; i < groups.Count; ++i )
{
DictionaryEntry de = (DictionaryEntry)groups[i];
ArrayList groupList = (ArrayList)de.Value;
if ( !HasAttribute( (Type)de.Key, typeofNoSort, false ) )
groupList.Sort( PropertySorter.Instance );
if ( i != 0 )
list.Add( null );
list.Add( de.Key );
list.AddRange( groupList );
}
return list;
}
private static Type typeofCPA = typeof( CPA );
private static Type typeofObject = typeof( object );
private static CPA GetCPA( PropertyInfo prop )
{
object[] attrs = prop.GetCustomAttributes( typeofCPA, false );
if ( attrs.Length > 0 )
return attrs[0] as CPA;
else
return null;
}
private ArrayList GetGroups( Type objectType, PropertyInfo[] props )
{
Hashtable groups = new Hashtable();
for ( int i = 0; i < props.Length; ++i )
{
PropertyInfo prop = props[i];
if ( prop.CanRead )
{
CPA attr = GetCPA( prop );
if ( attr != null && m_Mobile.AccessLevel >= attr.ReadLevel )
{
Type type = prop.DeclaringType;
while ( true )
{
Type baseType = type.BaseType;
if ( baseType == null || baseType == typeofObject )
break;
if ( baseType.GetProperty( prop.Name, prop.PropertyType ) != null )
type = baseType;
else
break;
}
ArrayList list = (ArrayList)groups[type];
if ( list == null )
groups[type] = list = new ArrayList();
list.Add( prop );
}
}
}
ArrayList sorted = new ArrayList( groups );
sorted.Sort( new GroupComparer( objectType ) );
return sorted;
}
public static object GetObjectFromString( Type t, string s )
{
if ( t == typeof( string ) )
{
return s;
}
else if ( t == typeof( byte ) || t == typeof( sbyte ) || t == typeof( short ) || t == typeof( ushort ) || t == typeof( int ) || t == typeof( uint ) || t == typeof( long ) || t == typeof( ulong ) )
{
if ( s.StartsWith( "0x" ) )
{
if ( t == typeof( ulong ) || t == typeof( uint ) || t == typeof( ushort ) || t == typeof( byte ) )
{
return Convert.ChangeType( Convert.ToUInt64( s.Substring( 2 ), 16 ), t );
}
else
{
return Convert.ChangeType( Convert.ToInt64( s.Substring( 2 ), 16 ), t );
}
}
else
{
return Convert.ChangeType( s, t );
}
}
else if ( t == typeof( double ) || t == typeof( float ) )
{
return Convert.ChangeType( s, t );
}
else if ( t.IsDefined( typeof( ParsableAttribute ), false ) )
{
MethodInfo parseMethod = t.GetMethod( "Parse", new Type[]{ typeof( string ) } );
return parseMethod.Invoke( null, new object[]{ s } );
}
throw new Exception( "bad" );
}
private static string GetStringFromObject( object o )
{
if ( o == null )
{
return "-null-";
}
else if ( o is string )
{
return String.Format( "\"{0}\"", (string)o );
}
else if ( o is bool )
{
return o.ToString();
}
else if ( o is char )
{
return String.Format( "0x{0:X} '{1}'", (int)(char)o, (char)o );
}
else if ( o is Serial )
{
Serial s = (Serial)o;
if ( s.IsValid )
{
if ( s.IsItem )
{
return String.Format( "(I) 0x{0:X}", s.Value );
}
else if ( s.IsMobile )
{
return String.Format( "(M) 0x{0:X}", s.Value );
}
}
return String.Format( "(?) 0x{0:X}", s.Value );
}
else if ( o is byte || o is sbyte || o is short || o is ushort || o is int || o is uint || o is long || o is ulong )
{
return String.Format( "{0} (0x{0:X})", o );
}
else if ( o is Mobile )
{
return String.Format( "(M) 0x{0:X} \"{1}\"", ((Mobile)o).Serial.Value, ((Mobile)o).Name );
}
else if ( o is Item )
{
return String.Format( "(I) 0x{0:X}", ((Item)o).Serial );
}
else if ( o is Type )
{
return ((Type)o).Name;
}
else
{
return o.ToString();
}
}
private class PropertySorter : IComparer
{
public static readonly PropertySorter Instance = new PropertySorter();
private PropertySorter()
{
}
public int Compare( object x, object y )
{
if ( x == null && y == null )
return 0;
else if ( x == null )
return -1;
else if ( y == null )
return 1;
PropertyInfo a = x as PropertyInfo;
PropertyInfo b = y as PropertyInfo;
if ( a == null || b == null )
throw new ArgumentException();
return a.Name.CompareTo( b.Name );
}
}
private class GroupComparer : IComparer
{
private Type m_Start;
public GroupComparer( Type start )
{
m_Start = start;
}
private static Type typeofObject = typeof( Object );
private int GetDistance( Type type )
{
Type current = m_Start;
int dist;
for ( dist = 0; current != null && current != typeofObject && current != type; ++dist )
current = current.BaseType;
return dist;
}
public int Compare( object x, object y )
{
if ( x == null && y == null )
return 0;
else if ( x == null )
return -1;
else if ( y == null )
return 1;
if ( !(x is DictionaryEntry) || !(y is DictionaryEntry) )
throw new ArgumentException();
DictionaryEntry de1 = (DictionaryEntry)x;
DictionaryEntry de2 = (DictionaryEntry)y;
Type a = (Type)de1.Key;
Type b = (Type)de2.Key;
return GetDistance( a ).CompareTo( GetDistance( b ) );
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
namespace OpenSim.ApplicationPlugins.Rest.Inventory
{
public class RestAppearanceServices : IRest
{
// private static readonly int PARM_USERID = 0;
// private static readonly int PARM_PATH = 1;
// private bool enabled = false;
private string qPrefix = "appearance";
/// <summary>
/// The constructor makes sure that the service prefix is absolute
/// and the registers the service handler and the allocator.
/// </summary>
public RestAppearanceServices()
{
Rest.Log.InfoFormat("{0} User appearance services initializing", MsgId);
Rest.Log.InfoFormat("{0} Using REST Implementation Version {1}", MsgId, Rest.Version);
// If a relative path was specified for the handler's domain,
// add the standard prefix to make it absolute, e.g. /admin
if (!qPrefix.StartsWith(Rest.UrlPathSeparator))
{
Rest.Log.InfoFormat("{0} Domain is relative, adding absolute prefix", MsgId);
qPrefix = String.Format("{0}{1}{2}", Rest.Prefix, Rest.UrlPathSeparator, qPrefix);
qPrefix = String.Format("{0}{1}{2}", Rest.Prefix, Rest.UrlPathSeparator, qPrefix);
Rest.Log.InfoFormat("{0} Domain is now <{1}>", MsgId, qPrefix);
}
// Register interface using the absolute URI.
Rest.Plugin.AddPathHandler(DoAppearance,qPrefix,Allocate);
// Activate if everything went OK
// enabled = true;
Rest.Log.InfoFormat("{0} User appearance services initialization complete", MsgId);
}
/// <summary>
/// Post-construction, pre-enabled initialization opportunity
/// Not currently exploited.
/// </summary>
public void Initialize()
{
}
/// <summary>
/// Called by the plug-in to halt service processing. Local processing is
/// disabled.
/// </summary>
public void Close()
{
// enabled = false;
Rest.Log.InfoFormat("{0} User appearance services closing down", MsgId);
}
/// <summary>
/// This property is declared locally because it is used a lot and
/// brevity is nice.
/// </summary>
internal string MsgId
{
get { return Rest.MsgId; }
}
#region Interface
/// <summary>
/// The plugin (RestHandler) calls this method to allocate the request
/// state carrier for a new request. It is destroyed when the request
/// completes. All request-instance specific state is kept here. This
/// is registered when this service provider is registered.
/// </summary>
/// <param name=request>Inbound HTTP request information</param>
/// <param name=response>Outbound HTTP request information</param>
/// <param name=qPrefix>REST service domain prefix</param>
/// <returns>A RequestData instance suitable for this service</returns>
private RequestData Allocate(OSHttpRequest request, OSHttpResponse response, string prefix)
{
return (RequestData) new AppearanceRequestData(request, response, prefix);
}
/// <summary>
/// This method is registered with the handler when this service provider
/// is initialized. It is called whenever the plug-in identifies this service
/// provider as the best match for a given request.
/// It handles all aspects of inventory REST processing, i.e. /admin/inventory
/// </summary>
/// <param name=hdata>A consolidated HTTP request work area</param>
private void DoAppearance(RequestData hdata)
{
// !!! REFACTORIMG PROBLEM. This needs rewriting for 0.7
//AppearanceRequestData rdata = (AppearanceRequestData) hdata;
//Rest.Log.DebugFormat("{0} DoAppearance ENTRY", MsgId);
//// If we're disabled, do nothing.
//if (!enabled)
//{
// return;
//}
//// Now that we know this is a serious attempt to
//// access inventory data, we should find out who
//// is asking, and make sure they are authorized
//// to do so. We need to validate the caller's
//// identity before revealing anything about the
//// status quo. Authenticate throws an exception
//// via Fail if no identity information is present.
////
//// With the present HTTP server we can't use the
//// builtin authentication mechanisms because they
//// would be enforced for all in-bound requests.
//// Instead we look at the headers ourselves and
//// handle authentication directly.
//try
//{
// if (!rdata.IsAuthenticated)
// {
// rdata.Fail(Rest.HttpStatusCodeNotAuthorized,String.Format("user \"{0}\" could not be authenticated", rdata.userName));
// }
//}
//catch (RestException e)
//{
// if (e.statusCode == Rest.HttpStatusCodeNotAuthorized)
// {
// Rest.Log.WarnFormat("{0} User not authenticated", MsgId);
// Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
// }
// else
// {
// Rest.Log.ErrorFormat("{0} User authentication failed", MsgId);
// Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
// }
// throw (e);
//}
//Rest.Log.DebugFormat("{0} Authenticated {1}", MsgId, rdata.userName);
//// We can only get here if we are authorized
////
//// The requestor may have specified an UUID or
//// a conjoined FirstName LastName string. We'll
//// try both. If we fail with the first, UUID,
//// attempt, we try the other. As an example, the
//// URI for a valid inventory request might be:
////
//// http://<host>:<port>/admin/inventory/Arthur Dent
////
//// Indicating that this is an inventory request for
//// an avatar named Arthur Dent. This is ALL that is
//// required to designate a GET for an entire
//// inventory.
////
//// Do we have at least a user agent name?
//if (rdata.Parameters.Length < 1)
//{
// Rest.Log.WarnFormat("{0} Appearance: No user agent identifier specified", MsgId);
// rdata.Fail(Rest.HttpStatusCodeBadRequest, "no user identity specified");
//}
//// The first parameter MUST be the agent identification, either an UUID
//// or a space-separated First-name Last-Name specification. We check for
//// an UUID first, if anyone names their character using a valid UUID
//// that identifies another existing avatar will cause this a problem...
//try
//{
// rdata.uuid = new UUID(rdata.Parameters[PARM_USERID]);
// Rest.Log.DebugFormat("{0} UUID supplied", MsgId);
// rdata.userProfile = Rest.UserServices.GetUserProfile(rdata.uuid);
//}
//catch
//{
// string[] names = rdata.Parameters[PARM_USERID].Split(Rest.CA_SPACE);
// if (names.Length == 2)
// {
// Rest.Log.DebugFormat("{0} Agent Name supplied [2]", MsgId);
// rdata.userProfile = Rest.UserServices.GetUserProfile(names[0],names[1]);
// }
// else
// {
// Rest.Log.WarnFormat("{0} A Valid UUID or both first and last names must be specified", MsgId);
// rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid user identity");
// }
//}
//// If the user profile is null then either the server is broken, or the
//// user is not known. We always assume the latter case.
//if (rdata.userProfile != null)
//{
// Rest.Log.DebugFormat("{0} User profile obtained for agent {1} {2}",
// MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
//}
//else
//{
// Rest.Log.WarnFormat("{0} No user profile for {1}", MsgId, rdata.path);
// rdata.Fail(Rest.HttpStatusCodeNotFound, "unrecognized user identity");
//}
//// If we get to here, then we have effectively validated the user's
//switch (rdata.method)
//{
// case Rest.HEAD : // Do the processing, set the status code, suppress entity
// DoGet(rdata);
// rdata.buffer = null;
// break;
// case Rest.GET : // Do the processing, set the status code, return entity
// DoGet(rdata);
// break;
// case Rest.PUT : // Update named element
// DoUpdate(rdata);
// break;
// case Rest.POST : // Add new information to identified context.
// DoExtend(rdata);
// break;
// case Rest.DELETE : // Delete information
// DoDelete(rdata);
// break;
// default :
// Rest.Log.WarnFormat("{0} Method {1} not supported for {2}",
// MsgId, rdata.method, rdata.path);
// rdata.Fail(Rest.HttpStatusCodeMethodNotAllowed,
// String.Format("{0} not supported", rdata.method));
// break;
//}
}
#endregion Interface
#region method-specific processing
/// <summary>
/// This method implements GET processing for user's appearance.
/// </summary>
/// <param name=rdata>HTTP service request work area</param>
// private void DoGet(AppearanceRequestData rdata)
// {
// AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID);
//
// if (adata == null)
// {
// rdata.Fail(Rest.HttpStatusCodeNoContent,
// String.Format("appearance data not found for user {0} {1}",
// rdata.userProfile.FirstName, rdata.userProfile.SurName));
// }
// rdata.userAppearance = adata.ToAvatarAppearance(rdata.userProfile.ID);
//
// rdata.initXmlWriter();
//
// FormatUserAppearance(rdata);
//
// // Indicate a successful request
//
// rdata.Complete();
//
// // Send the response to the user. The body will be implicitly
// // constructed from the result of the XML writer.
//
// rdata.Respond(String.Format("Appearance {0} Normal completion", rdata.method));
// }
/// <summary>
/// POST adds NEW information to the user profile database.
/// This effectively resets the appearance before applying those
/// characteristics supplied in the request.
/// </summary>
// private void DoExtend(AppearanceRequestData rdata)
// {
//
// bool created = false;
// bool modified = false;
// string newnode = String.Empty;
//
// Rest.Log.DebugFormat("{0} POST ENTRY", MsgId);
//
// //AvatarAppearance old = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID);
//
// rdata.userAppearance = new AvatarAppearance();
//
// // Although the following behavior is admitted by HTTP I am becoming
// // increasingly doubtful that it is appropriate for REST. If I attempt to
// // add a new record, and it already exists, then it seems to me that the
// // attempt should fail, rather than update the existing record.
// AvatarData adata = null;
// if (GetUserAppearance(rdata))
// {
// modified = rdata.userAppearance != null;
// created = !modified;
// adata = new AvatarData(rdata.userAppearance);
// Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata);
// // Rest.UserServices.UpdateUserProfile(rdata.userProfile);
// }
// else
// {
// created = true;
// adata = new AvatarData(rdata.userAppearance);
// Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata);
// // Rest.UserServices.UpdateUserProfile(rdata.userProfile);
// }
//
// if (created)
// {
// newnode = String.Format("{0} {1}", rdata.userProfile.FirstName,
// rdata.userProfile.SurName);
// // Must include a location header with a URI that identifies the new resource.
//
// rdata.AddHeader(Rest.HttpHeaderLocation,String.Format("http://{0}{1}:{2}{3}{4}",
// rdata.hostname,rdata.port,rdata.path,Rest.UrlPathSeparator, newnode));
// rdata.Complete(Rest.HttpStatusCodeCreated);
//
// }
// else
// {
// if (modified)
// {
// rdata.Complete(Rest.HttpStatusCodeOK);
// }
// else
// {
// rdata.Complete(Rest.HttpStatusCodeNoContent);
// }
// }
//
// rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method));
//
// }
/// <summary>
/// This updates the user's appearance. not all aspects need to be provided,
/// only those supplied will be changed.
/// </summary>
// private void DoUpdate(AppearanceRequestData rdata)
// {
//
// // REFACTORING PROBLEM This was commented out. It doesn't work for 0.7
//
// //bool created = false;
// //bool modified = false;
//
//
// //rdata.userAppearance = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID);
//
// //// If the user exists then this is considered a modification regardless
// //// of what may, or may not be, specified in the payload.
//
// //if (rdata.userAppearance != null)
// //{
// // modified = true;
// // Rest.AvatarServices.UpdateUserAppearance(rdata.userProfile.ID, rdata.userAppearance);
// // Rest.UserServices.UpdateUserProfile(rdata.userProfile);
// //}
//
// //if (created)
// //{
// // rdata.Complete(Rest.HttpStatusCodeCreated);
// //}
// //else
// //{
// // if (modified)
// // {
// // rdata.Complete(Rest.HttpStatusCodeOK);
// // }
// // else
// // {
// // rdata.Complete(Rest.HttpStatusCodeNoContent);
// // }
// //}
//
// rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method));
//
// }
/// <summary>
/// Delete the specified user's appearance. This actually performs a reset
/// to the default avatar appearance, if the info is already there.
/// Existing ownership is preserved. All prior updates are lost and can not
/// be recovered.
/// </summary>
// private void DoDelete(AppearanceRequestData rdata)
// {
// AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID);
//
// if (adata != null)
// {
// AvatarAppearance old = adata.ToAvatarAppearance(rdata.userProfile.ID);
// rdata.userAppearance = new AvatarAppearance();
// rdata.userAppearance.Owner = old.Owner;
// adata = new AvatarData(rdata.userAppearance);
//
// Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata);
//
// rdata.Complete();
// }
// else
// {
//
// rdata.Complete(Rest.HttpStatusCodeNoContent);
// }
//
// rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method));
// }
#endregion method-specific processing
private bool GetUserAppearance(AppearanceRequestData rdata)
{
XmlReader xml;
bool indata = false;
rdata.initXmlReader();
xml = rdata.reader;
while (xml.Read())
{
switch (xml.NodeType)
{
case XmlNodeType.Element :
switch (xml.Name)
{
case "Appearance" :
if (xml.MoveToAttribute("Height"))
{
rdata.userAppearance.AvatarHeight = (float) Convert.ToDouble(xml.Value);
indata = true;
}
// if (xml.MoveToAttribute("Owner"))
// {
// rdata.userAppearance.Owner = (UUID)xml.Value;
// indata = true;
// }
if (xml.MoveToAttribute("Serial"))
{
rdata.userAppearance.Serial = Convert.ToInt32(xml.Value);
indata = true;
}
if (xml.MoveToAttribute("XML3D"))
{
rdata.userAppearance.XML3D = xml.Value;
indata = true;
}
break;
/*
case "Body" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.BodyItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.BodyAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Skin" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.SkinItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.SkinAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Hair" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.HairItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.HairAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Eyes" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.EyesItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.EyesAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Shirt" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.ShirtItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.ShirtAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Pants" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.PantsItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.PantsAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Shoes" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.ShoesItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.ShoesAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Socks" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.SocksItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.SocksAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Jacket" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.JacketItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.JacketAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Gloves" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.GlovesItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.GlovesAsset = (UUID)xml.Value;
indata = true;
}
break;
case "UnderShirt" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.UnderShirtItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.UnderShirtAsset = (UUID)xml.Value;
indata = true;
}
break;
case "UnderPants" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.UnderPantsItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.UnderPantsAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Skirt" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.SkirtItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.SkirtAsset = (UUID)xml.Value;
indata = true;
}
break;
*/
case "Attachment" :
{
int ap;
UUID asset;
UUID item;
if (xml.MoveToAttribute("AtPoint"))
{
ap = Convert.ToInt32(xml.Value);
if (xml.MoveToAttribute("Asset"))
{
asset = new UUID(xml.Value);
if (xml.MoveToAttribute("Asset"))
{
item = new UUID(xml.Value);
rdata.userAppearance.SetAttachment(ap, item, asset);
indata = true;
}
}
}
}
break;
case "Texture" :
if (xml.MoveToAttribute("Default"))
{
rdata.userAppearance.Texture = new Primitive.TextureEntry(new UUID(xml.Value));
indata = true;
}
break;
case "Face" :
{
uint index;
if (xml.MoveToAttribute("Index"))
{
index = Convert.ToUInt32(xml.Value);
if (xml.MoveToAttribute("Id"))
{
rdata.userAppearance.Texture.CreateFace(index).TextureID = new UUID(xml.Value);
indata = true;
}
}
}
break;
case "VisualParameters" :
{
xml.ReadContentAsBase64(rdata.userAppearance.VisualParams,
0, rdata.userAppearance.VisualParams.Length);
indata = true;
}
break;
}
break;
}
}
return indata;
}
private void FormatPart(AppearanceRequestData rdata, string part, UUID item, UUID asset)
{
if (item != UUID.Zero || asset != UUID.Zero)
{
rdata.writer.WriteStartElement(part);
if (item != UUID.Zero)
{
rdata.writer.WriteAttributeString("Item",item.ToString());
}
if (asset != UUID.Zero)
{
rdata.writer.WriteAttributeString("Asset",asset.ToString());
}
rdata.writer.WriteEndElement();
}
}
private void FormatUserAppearance(AppearanceRequestData rdata)
{
Rest.Log.DebugFormat("{0} FormatUserAppearance", MsgId);
if (rdata.userAppearance != null)
{
Rest.Log.DebugFormat("{0} FormatUserAppearance: appearance object exists", MsgId);
rdata.writer.WriteStartElement("Appearance");
rdata.writer.WriteAttributeString("Height", rdata.userAppearance.AvatarHeight.ToString());
// if (rdata.userAppearance.Owner != UUID.Zero)
// rdata.writer.WriteAttributeString("Owner", rdata.userAppearance.Owner.ToString());
rdata.writer.WriteAttributeString("Serial", rdata.userAppearance.Serial.ToString());
rdata.writer.WriteAttributeString("XML3D", rdata.userAppearance.XML3D);
/*
FormatPart(rdata, "Body", rdata.userAppearance.BodyItem, rdata.userAppearance.BodyAsset);
FormatPart(rdata, "Skin", rdata.userAppearance.SkinItem, rdata.userAppearance.SkinAsset);
FormatPart(rdata, "Hair", rdata.userAppearance.HairItem, rdata.userAppearance.HairAsset);
FormatPart(rdata, "Eyes", rdata.userAppearance.EyesItem, rdata.userAppearance.EyesAsset);
FormatPart(rdata, "Shirt", rdata.userAppearance.ShirtItem, rdata.userAppearance.ShirtAsset);
FormatPart(rdata, "Pants", rdata.userAppearance.PantsItem, rdata.userAppearance.PantsAsset);
FormatPart(rdata, "Skirt", rdata.userAppearance.SkirtItem, rdata.userAppearance.SkirtAsset);
FormatPart(rdata, "Shoes", rdata.userAppearance.ShoesItem, rdata.userAppearance.ShoesAsset);
FormatPart(rdata, "Socks", rdata.userAppearance.SocksItem, rdata.userAppearance.SocksAsset);
FormatPart(rdata, "Jacket", rdata.userAppearance.JacketItem, rdata.userAppearance.JacketAsset);
FormatPart(rdata, "Gloves", rdata.userAppearance.GlovesItem, rdata.userAppearance.GlovesAsset);
FormatPart(rdata, "UnderShirt", rdata.userAppearance.UnderShirtItem, rdata.userAppearance.UnderShirtAsset);
FormatPart(rdata, "UnderPants", rdata.userAppearance.UnderPantsItem, rdata.userAppearance.UnderPantsAsset);
*/
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting attachments", MsgId);
rdata.writer.WriteStartElement("Attachments");
List<AvatarAttachment> attachments = rdata.userAppearance.GetAttachments();
foreach (AvatarAttachment attach in attachments)
{
rdata.writer.WriteStartElement("Attachment");
rdata.writer.WriteAttributeString("AtPoint", attach.AttachPoint.ToString());
rdata.writer.WriteAttributeString("Item", attach.ItemID.ToString());
rdata.writer.WriteAttributeString("Asset", attach.AssetID.ToString());
rdata.writer.WriteEndElement();
}
rdata.writer.WriteEndElement();
Primitive.TextureEntry texture = rdata.userAppearance.Texture;
if (texture != null && (texture.DefaultTexture != null || texture.FaceTextures != null))
{
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting textures", MsgId);
rdata.writer.WriteStartElement("Texture");
if (texture.DefaultTexture != null)
{
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting default texture", MsgId);
rdata.writer.WriteAttributeString("Default",
texture.DefaultTexture.TextureID.ToString());
}
if (texture.FaceTextures != null)
{
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting face textures", MsgId);
for (int i=0; i<texture.FaceTextures.Length;i++)
{
if (texture.FaceTextures[i] != null)
{
rdata.writer.WriteStartElement("Face");
rdata.writer.WriteAttributeString("Index", i.ToString());
rdata.writer.WriteAttributeString("Id",
texture.FaceTextures[i].TextureID.ToString());
rdata.writer.WriteEndElement();
}
}
}
rdata.writer.WriteEndElement();
}
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting visual parameters", MsgId);
rdata.writer.WriteStartElement("VisualParameters");
rdata.writer.WriteBase64(rdata.userAppearance.VisualParams,0,
rdata.userAppearance.VisualParams.Length);
rdata.writer.WriteEndElement();
rdata.writer.WriteFullEndElement();
}
Rest.Log.DebugFormat("{0} FormatUserAppearance: completed", MsgId);
return;
}
#region appearance RequestData extension
internal class AppearanceRequestData : RequestData
{
/// <summary>
/// These are the inventory specific request/response state
/// extensions.
/// </summary>
internal UUID uuid = UUID.Zero;
internal UserProfileData userProfile = null;
internal AvatarAppearance userAppearance = null;
internal AppearanceRequestData(OSHttpRequest request, OSHttpResponse response, string prefix)
: base(request, response, prefix)
{
}
}
#endregion Appearance RequestData extension
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XmlDiff;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
using XmlCoreTest.Common;
namespace XLinqTests
{
public class SaveWithWriter : XLinqTestCase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+SaveWithWriter
// Test Case
#region Constants
private const string BaseSaveFileName = "baseSave.xml";
private const string TestSaveFileName = "testSave";
private const string xml = "<PurchaseOrder><Item price=\"100\">Motor<![CDATA[cdata]]><elem>innertext</elem>text<?pi pi pi?></Item></PurchaseOrder>";
private const string xmlForXElementWriteContent = "<Item price=\"100\">Motor<![CDATA[cdata]]><elem>innertext</elem>text<?pi pi pi?></Item>";
#endregion
#region Fields
private readonly XmlDiff _diff;
#endregion
#region Constructors and Destructors
public SaveWithWriter()
{
_diff = new XmlDiff();
}
#endregion
#region Public Methods and Operators
public static string[] GetExpectedXml()
{
string[] xml = { "text", "", " ", "<!--comment1 comment1 -->", "<!---->", "<!-- -->", "<?pi1 pi1 pi1 ?>", "<?pi1?>", "<?pi1 ?>", "<![CDATA[cdata cdata ]]>", "<![CDATA[]]>", "<![CDATA[ ]]>", "<elem attr=\"val\">text<!--comm--><?pi hffgg?><![CDATA[jfggr]]></elem>" };
return xml;
}
public static object[] GetObjects()
{
object[] objects = { new XText("text"), new XText(""), new XText(" "), new XComment("comment1 comment1 "), new XComment(""), new XComment(" "), new XProcessingInstruction("pi1", "pi1 pi1 "), new XProcessingInstruction("pi1", ""), new XProcessingInstruction("pi1", " "), new XCData("cdata cdata "), new XCData(""), new XCData(" "), new XElement("elem", new XAttribute("attr", "val"), new XText("text"), new XComment("comm"), new XProcessingInstruction("pi", "hffgg"), new XCData("jfggr")) };
return objects;
}
public override void AddChildren()
{
AddChild(new TestVariation(writer_5) { Attribute = new VariationAttribute("Write and valIdate XDocumentType") { Priority = 0 } });
AddChild(new TestVariation(writer_18) { Attribute = new VariationAttribute("WriteTo after WriteState = Error") { Param = "WriteTo", Priority = 2 } });
AddChild(new TestVariation(writer_18) { Attribute = new VariationAttribute("Save after WriteState = Error") { Param = "Save", Priority = 2 } });
AddChild(new TestVariation(writer_20) { Attribute = new VariationAttribute("XDocument: Null parameters for Save") { Priority = 1 } });
AddChild(new TestVariation(writer_21) { Attribute = new VariationAttribute("XElement: Null parameters for Save") { Priority = 1 } });
AddChild(new TestVariation(writer_23) { Attribute = new VariationAttribute("XDocument: Null parameters for WriteTo") { Priority = 1 } });
AddChild(new TestVariation(writer_24) { Attribute = new VariationAttribute("XElement: Null parameters for WriteTo") { Priority = 1 } });
}
public Encoding[] GetEncodings()
{
Encoding[] encodings = { Encoding.UTF8
//Encoding.Unicode,
//Encoding.BigEndianUnicode,
};
return encodings;
}
//[Variation(Priority = 2, Desc = "Save after WriteState = Error", Param = "Save")]
//[Variation(Priority = 2, Desc = "WriteTo after WriteState = Error", Param = "WriteTo")]
public void writer_18()
{
var doc = new XDocument();
foreach (Encoding encoding in GetEncodings())
{
foreach (XmlWriter w in GetXmlWriters(encoding))
{
try
{
if (Variation.Param.ToString() == "Save")
{
doc.Save(w);
}
else
{
doc.WriteTo(w);
}
throw new TestException(TestResult.Failed, "");
}
catch (Exception ex)
{
if (!(ex is InvalidOperationException) && !(ex is ArgumentException))
{
throw;
}
TestLog.Equals(w.WriteState, WriteState.Error, "Error in WriteState");
try
{
if (Variation.Param.ToString() == "Save")
{
doc.Save(w);
}
else
{
doc.WriteTo(w);
}
throw new TestException(TestResult.Failed, "");
}
catch (InvalidOperationException)
{
}
}
finally
{
w.Dispose();
}
}
}
}
//[Variation(Priority = 1, Desc = "XDocument: Null parameters for Save")]
public void writer_20()
{
var doc = new XDocument(new XElement("PurchaseOrder"));
//save with TextWriter
try
{
doc.Save((TextWriter)null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
doc.Save((TextWriter)null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
}
try
{
doc.Save((TextWriter)null, SaveOptions.DisableFormatting);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
doc.Save((TextWriter)null, SaveOptions.DisableFormatting);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
}
try
{
doc.Save((TextWriter)null, SaveOptions.None);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
doc.Save((TextWriter)null, SaveOptions.None);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
}
//save with XmlWriter
try
{
doc.Save((XmlWriter)null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
try
{
doc.Save((XmlWriter)null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
}
}
//[Variation(Priority = 1, Desc = "XElement: Null parameters for Save")]
public void writer_21()
{
var doc = new XElement(new XElement("PurchaseOrder"));
//save with TextWriter
try
{
doc.Save((TextWriter)null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
try
{
doc.Save((TextWriter)null, SaveOptions.DisableFormatting);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
try
{
doc.Save((TextWriter)null, SaveOptions.None);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
//save with XmlWriter
try
{
doc.Save((XmlWriter)null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
}
//[Variation(Priority = 1, Desc = "XDocument: Null parameters for WriteTo")]
public void writer_23()
{
var doc = new XDocument(new XElement("PurchaseOrder"));
try
{
doc.WriteTo(null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
}
//[Variation(Priority = 1, Desc = "XElement: Null parameters for WriteTo")]
public void writer_24()
{
var doc = new XElement(new XElement("PurchaseOrder"));
try
{
doc.WriteTo(null);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentNullException)
{
}
}
//[Variation(Priority = 0, Desc = "Write and valIdate XDocumentType")]
public void writer_5()
{
string expectedXml = "<!DOCTYPE root PUBLIC \"\" \"\"[<!ELEMENT root ANY>]>";
var doc = new XDocumentType("root", "", "", "<!ELEMENT root ANY>");
TestToStringAndXml(doc, expectedXml);
var ws = new XmlWriterSettings();
ws.ConformanceLevel = ConformanceLevel.Document;
ws.OmitXmlDeclaration = true;
// Set to true when FileIO is ok
ws.CloseOutput = false;
// Use a file to replace this when FileIO is ok
var m = new MemoryStream();
using (XmlWriter wr = XmlWriter.Create(m, ws))
{
doc.WriteTo(wr);
}
m.Position = 0;
using (TextReader r = new StreamReader(m))
{
string actualXml = r.ReadToEnd();
TestLog.Compare(expectedXml, actualXml, "XDocumentType writeTo method failed");
}
}
#endregion
//
// helpers
//
#region Methods
private string GenerateTestFileName(int index)
{
string filename = String.Format("{0}{1}.xml", TestSaveFileName, index);
try
{
FilePathUtil.getStream(filename);
}
catch (Exception)
{
FilePathUtil.addStream(filename, new MemoryStream());
}
return filename;
}
private List<XmlWriter> GetXmlWriters(Encoding encoding)
{
return GetXmlWriters(encoding, ConformanceLevel.Document);
}
private List<XmlWriter> GetXmlWriters(Encoding encoding, ConformanceLevel conformanceLevel)
{
var xmlWriters = new List<XmlWriter>();
int count = 0;
var s = new XmlWriterSettings();
s.CheckCharacters = true;
s.Encoding = encoding;
var ws = new XmlWriterSettings();
ws.CheckCharacters = false;
// Set it to true when FileIO is ok
ws.CloseOutput = false;
ws.Encoding = encoding;
s.ConformanceLevel = conformanceLevel;
ws.ConformanceLevel = conformanceLevel;
TextWriter tw = new StreamWriter(FilePathUtil.getStream(GenerateTestFileName(count++)));
xmlWriters.Add(new CoreXml.Test.XLinq.CustomWriter(tw, ws)); // CustomWriter
xmlWriters.Add(XmlWriter.Create(FilePathUtil.getStream(GenerateTestFileName(count++)), s)); // Factory XmlWriter
xmlWriters.Add(XmlWriter.Create(FilePathUtil.getStream(GenerateTestFileName(count++)), ws)); // Factory Writer
return xmlWriters;
}
private void SaveBaseline(string xml)
{
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
sw.Write(xml);
sw.Flush();
FilePathUtil.addStream(BaseSaveFileName, ms);
}
private void SaveWithFile(Object doc)
{
string file0 = GenerateTestFileName(0);
string file1 = GenerateTestFileName(1);
string file2 = GenerateTestFileName(2);
foreach (Encoding encoding in GetEncodings())
{
if (doc is XDocument)
{
((XDocument)doc).Save(FilePathUtil.getStream(file0));
((XDocument)doc).Save(FilePathUtil.getStream(file1), SaveOptions.DisableFormatting);
((XDocument)doc).Save(FilePathUtil.getStream(file2), SaveOptions.None);
}
else if (doc is XElement)
{
((XElement)doc).Save(FilePathUtil.getStream(file0));
((XElement)doc).Save(FilePathUtil.getStream(file1), SaveOptions.DisableFormatting);
((XElement)doc).Save(FilePathUtil.getStream(file2), SaveOptions.None);
}
else
{
TestLog.Compare(false, "Wrong object");
}
TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file0)), "Save failed:encoding " + encoding);
TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file1)), "Save(preserveWhitespace true) failed:encoding " + encoding);
TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file2)), "Save(preserveWhitespace false) " + encoding);
}
}
private void SaveWithTextWriter(Object doc)
{
string file0 = GenerateTestFileName(0);
string file1 = GenerateTestFileName(1);
string file2 = GenerateTestFileName(2);
foreach (Encoding encoding in GetEncodings())
{
using (TextWriter w0 = new StreamWriter(FilePathUtil.getStream(file0)))
using (TextWriter w1 = new StreamWriter(FilePathUtil.getStream(file1)))
using (TextWriter w2 = new StreamWriter(FilePathUtil.getStream(file2)))
{
if (doc is XDocument)
{
((XDocument)doc).Save(w0);
((XDocument)doc).Save(w1, SaveOptions.DisableFormatting);
((XDocument)doc).Save(w2, SaveOptions.None);
}
else if (doc is XElement)
{
((XElement)doc).Save(w0);
((XElement)doc).Save(w1, SaveOptions.DisableFormatting);
((XElement)doc).Save(w2, SaveOptions.None);
}
else
{
TestLog.Compare(false, "Wrong object");
}
w0.Dispose();
w1.Dispose();
w2.Dispose();
TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file0)), "TextWriter failed:encoding " + encoding);
TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file1)), "TextWriter(preserveWhtsp=true) failed:encoding " + encoding);
TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file2)), "TextWriter(preserveWhtsp=false) failed:encoding " + encoding);
}
}
}
private void SaveWithXmlWriter(Object doc)
{
foreach (Encoding encoding in GetEncodings())
{
List<XmlWriter> xmlWriters = GetXmlWriters(encoding);
try
{
for (int i = 0; i < xmlWriters.Count; ++i)
{
if (doc is XDocument)
{
((XDocument)doc).Save(xmlWriters[i]);
}
else if (doc is XElement)
{
((XElement)doc).Save(xmlWriters[i]);
}
else
{
TestLog.Compare(false, "Wrong object");
}
xmlWriters[i].Dispose();
if (doc is XDocument)
{
((XDocument)doc).Save(FilePathUtil.getStream(GenerateTestFileName(i)));
}
else if (doc is XElement)
{
((XElement)doc).Save(FilePathUtil.getStream(GenerateTestFileName(i)));
}
else
{
TestLog.Compare(false, "Wrong object");
}
TestLog.Skip("ReEnable this when FileIO is OK");
}
}
finally
{
for (int i = 0; i < xmlWriters.Count; ++i)
{
xmlWriters[i].Dispose();
}
}
}
}
private void TestToStringAndXml(Object doc, string expectedXml)
{
string toString = doc.ToString();
string xml = String.Empty;
if (doc is XDocument)
{
xml = ((XDocument)doc).ToString(SaveOptions.DisableFormatting);
}
else if (doc is XElement)
{
xml = ((XElement)doc).ToString(SaveOptions.DisableFormatting);
}
else if (doc is XText)
{
xml = ((XText)doc).ToString(SaveOptions.DisableFormatting);
}
else if (doc is XCData)
{
xml = ((XCData)doc).ToString(SaveOptions.DisableFormatting);
}
else if (doc is XComment)
{
xml = ((XComment)doc).ToString(SaveOptions.DisableFormatting);
}
else if (doc is XProcessingInstruction)
{
xml = ((XProcessingInstruction)doc).ToString(SaveOptions.DisableFormatting);
}
else if (doc is XDocumentType)
{
xml = ((XDocumentType)doc).ToString(SaveOptions.DisableFormatting);
}
else
{
TestLog.Compare(false, "Wrong object");
}
TestLog.Compare(toString, expectedXml, "Test ToString failed");
TestLog.Compare(xml, expectedXml, "Test .ToString(SaveOptions.DisableFormatting) failed");
}
#endregion
}
}
| |
using YAF.Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Util.Automaton
{
/*
* 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>
/// Just holds a set of <see cref="T:int[]"/> states, plus a corresponding
/// <see cref="T:int[]"/> count per state. Used by
/// <see cref="BasicOperations.Determinize(Automaton)"/>.
/// <para/>
/// NOTE: This was SortedIntSet in Lucene
/// </summary>
internal sealed class SortedInt32Set
{
internal int[] values;
internal int[] counts;
internal int upto;
private int hashCode;
// If we hold more than this many states, we switch from
// O(N^2) linear ops to O(N log(N)) TreeMap
private const int TREE_MAP_CUTOVER = 30;
private readonly IDictionary<int, int> map = new JCG.SortedDictionary<int, int>();
private bool useTreeMap;
internal State state;
public SortedInt32Set(int capacity)
{
values = new int[capacity];
counts = new int[capacity];
}
// Adds this state to the set
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Incr(int num)
{
if (useTreeMap)
{
int key = num;
if (!map.TryGetValue(key, out int val))
{
map[key] = 1;
}
else
{
map[key] = 1 + val;
}
return;
}
if (upto == values.Length)
{
values = ArrayUtil.Grow(values, 1 + upto);
counts = ArrayUtil.Grow(counts, 1 + upto);
}
for (int i = 0; i < upto; i++)
{
if (values[i] == num)
{
counts[i]++;
return;
}
else if (num < values[i])
{
// insert here
int j = upto - 1;
while (j >= i)
{
values[1 + j] = values[j];
counts[1 + j] = counts[j];
j--;
}
values[i] = num;
counts[i] = 1;
upto++;
return;
}
}
// append
values[upto] = num;
counts[upto] = 1;
upto++;
if (upto == TREE_MAP_CUTOVER)
{
useTreeMap = true;
for (int i = 0; i < upto; i++)
{
map[values[i]] = counts[i];
}
}
}
// Removes this state from the set, if count decrs to 0
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Decr(int num)
{
if (useTreeMap)
{
int count = map[num];
if (count == 1)
{
map.Remove(num);
}
else
{
map[num] = count - 1;
}
// Fall back to simple arrays once we touch zero again
if (map.Count == 0)
{
useTreeMap = false;
upto = 0;
}
return;
}
for (int i = 0; i < upto; i++)
{
if (values[i] == num)
{
counts[i]--;
if (counts[i] == 0)
{
int limit = upto - 1;
while (i < limit)
{
values[i] = values[i + 1];
counts[i] = counts[i + 1];
i++;
}
upto = limit;
}
return;
}
}
if (Debugging.AssertsEnabled) Debugging.Assert(false);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ComputeHash()
{
if (useTreeMap)
{
if (map.Count > values.Length)
{
int size = ArrayUtil.Oversize(map.Count, RamUsageEstimator.NUM_BYTES_INT32);
values = new int[size];
counts = new int[size];
}
hashCode = map.Count;
upto = 0;
foreach (int state in map.Keys)
{
hashCode = 683 * hashCode + state;
values[upto++] = state;
}
}
else
{
hashCode = upto;
for (int i = 0; i < upto; i++)
{
hashCode = 683 * hashCode + values[i];
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FrozenInt32Set ToFrozenInt32Set() // LUCENENET specific
{
int[] c = new int[upto];
Array.Copy(values, 0, c, 0, upto);
return new FrozenInt32Set(c, this.hashCode, this.state);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FrozenInt32Set Freeze(State state)
{
int[] c = new int[upto];
Array.Copy(values, 0, c, 0, upto);
return new FrozenInt32Set(c, hashCode, state);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return hashCode;
}
public override bool Equals(object obj)
{
if (obj is null)
{
return false;
}
if (!(obj is SortedInt32Set other)) // LUCENENET specific - don't compare against FrozenInt32Set
{
return false;
}
if (hashCode != other.hashCode)
{
return false;
}
if (other.values.Length != upto)
{
return false;
}
for (int i = 0; i < upto; i++)
{
if (other.values[i] != values[i])
{
return false;
}
}
return true;
}
public override string ToString()
{
StringBuilder sb = (new StringBuilder()).Append('[');
for (int i = 0; i < upto; i++)
{
if (i > 0)
{
sb.Append(' ');
}
sb.Append(values[i]).Append(':').Append(counts[i]);
}
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// NOTE: This was FrozenIntSet in Lucene
/// </summary>
public struct FrozenInt32Set : IEquatable<FrozenInt32Set>
{
internal int[] values;
internal int hashCode;
internal State state;
public FrozenInt32Set(int[] values, int hashCode, State state)
{
this.values = values;
this.hashCode = hashCode;
this.state = state;
}
public FrozenInt32Set(int num, State state)
{
this.values = new int[] { num };
this.state = state;
this.hashCode = 683 + num;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return hashCode;
}
public override bool Equals(object obj)
{
if (obj is null)
{
return false;
}
if (obj is FrozenInt32Set other)
{
if (hashCode != other.hashCode)
{
return false;
}
if (other.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other.values[i] != values[i])
{
return false;
}
}
return true;
}
return false;
}
public bool Equals(FrozenInt32Set other) // LUCENENET specific - implemented IEquatable<FrozenInt32Set>
{
if (hashCode != other.hashCode)
{
return false;
}
if (other.values.Length != values.Length)
{
return false;
}
for (int i = 0; i < values.Length; i++)
{
if (other.values[i] != values[i])
{
return false;
}
}
return true;
}
public override string ToString()
{
StringBuilder sb = (new StringBuilder()).Append('[');
for (int i = 0; i < values.Length; i++)
{
if (i > 0)
{
sb.Append(' ');
}
sb.Append(values[i]);
}
sb.Append(']');
return sb.ToString();
}
}
}
}
| |
// 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.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// A class that provides a simple, lightweight implementation of thread-local lazy-initialization, where a value is initialized once per accessing
// thread; this provides an alternative to using a ThreadStatic static variable and having
// to check the variable prior to every access to see if it's been initialized.
//
//
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.Threading
{
/// <summary>
/// Provides thread-local storage of data.
/// </summary>
/// <typeparam name="T">Specifies the type of data stored per-thread.</typeparam>
/// <remarks>
/// <para>
/// With the exception of <see cref="Dispose()"/>, all public and protected members of
/// <see cref="ThreadLocal{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(SystemThreading_ThreadLocalDebugView<>))]
[DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")]
[HostProtection(Synchronization = true, ExternalThreading = true)]
public class ThreadLocal<T> : IDisposable
{
// a delegate that returns the created value, if null the created value will be default(T)
private Func<T> m_valueFactory;
//
// ts_slotArray is a table of thread-local values for all ThreadLocal<T> instances
//
// So, when a thread reads ts_slotArray, it gets back an array of *all* ThreadLocal<T> values for this thread and this T.
// The slot relevant to this particular ThreadLocal<T> instance is determined by the m_idComplement instance field stored in
// the ThreadLocal<T> instance.
//
[ThreadStatic]
static LinkedSlotVolatile[] ts_slotArray;
[ThreadStatic]
static FinalizationHelper ts_finalizationHelper;
// Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish
// between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or
// possibly due to a memory model issue in user code.
private int m_idComplement;
// This field is set to true when the constructor completes. That is helpful for recognizing whether a constructor
// threw an exception - either due to invalid argument or due to a thread abort. Finally, the field is set to false
// when the instance is disposed.
private volatile bool m_initialized;
// IdManager assigns and reuses slot IDs. Additionally, the object is also used as a global lock.
private static IdManager s_idManager = new IdManager();
// A linked list of all values associated with this ThreadLocal<T> instance.
// We create a dummy head node. That allows us to remove any (non-dummy) node without having to locate the m_linkedSlot field.
private LinkedSlot m_linkedSlot = new LinkedSlot(null);
// Whether the Values property is supported
private bool m_trackAllValues;
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance.
/// </summary>
public ThreadLocal()
{
Initialize(null, false);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance.
/// </summary>
/// <param name="trackAllValues">Whether to track all values set on the instance and expose them through the Values property.</param>
public ThreadLocal(bool trackAllValues)
{
Initialize(null, trackAllValues);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the
/// specified <paramref name="valueFactory"/> function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when
/// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic).
/// </exception>
public ThreadLocal(Func<T> valueFactory)
{
if (valueFactory == null)
throw new ArgumentNullException(nameof(valueFactory));
Initialize(valueFactory, false);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the
/// specified <paramref name="valueFactory"/> function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when
/// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized.
/// </param>
/// <param name="trackAllValues">Whether to track all values set on the instance and expose them via the Values property.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic).
/// </exception>
public ThreadLocal(Func<T> valueFactory, bool trackAllValues)
{
if (valueFactory == null)
throw new ArgumentNullException(nameof(valueFactory));
Initialize(valueFactory, trackAllValues);
}
private void Initialize(Func<T> valueFactory, bool trackAllValues)
{
m_valueFactory = valueFactory;
m_trackAllValues = trackAllValues;
// Assign the ID and mark the instance as initialized. To avoid leaking IDs, we assign the ID and set m_initialized
// in a finally block, to avoid a thread abort in between the two statements.
try { }
finally
{
m_idComplement = ~s_idManager.GetId();
// As the last step, mark the instance as fully initialized. (Otherwise, if m_initialized=false, we know that an exception
// occurred in the constructor.)
m_initialized = true;
}
}
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
~ThreadLocal()
{
// finalizer to return the type combination index to the pool
Dispose(false);
}
#region IDisposable Members
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
/// <param name="disposing">
/// A Boolean value that indicates whether this method is being called due to a call to <see cref="Dispose()"/>.
/// </param>
/// <remarks>
/// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
int id;
lock (s_idManager)
{
id = ~m_idComplement;
m_idComplement = 0;
if (id < 0 || !m_initialized)
{
Contract.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
// Handle double Dispose calls or disposal of an instance whose constructor threw an exception.
return;
}
m_initialized = false;
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
LinkedSlotVolatile[] slotArray = linkedSlot.SlotArray;
if (slotArray == null)
{
// The thread that owns this slotArray has already finished.
continue;
}
// Remove the reference from the LinkedSlot to the slot table.
linkedSlot.SlotArray = null;
// And clear the references from the slot table to the linked slot and the value so that
// both can get garbage collected.
slotArray[id].Value.Value = default(T);
slotArray[id].Value = null;
}
}
m_linkedSlot = null;
s_idManager.ReturnId(id);
}
#endregion
/// <summary>Creates and returns a string representation of this instance for the current thread.</summary>
/// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see cref="Value"/>.</returns>
/// <exception cref="T:System.NullReferenceException">
/// The <see cref="Value"/> for the current thread is a null reference (Nothing in Visual Basic).
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// The initialization function referenced <see cref="Value"/> in an improper manner.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
/// <remarks>
/// Calling this method forces initialization for the current thread, as is the
/// case with accessing <see cref="Value"/> directly.
/// </remarks>
public override string ToString()
{
return Value.ToString();
}
/// <summary>
/// Gets or sets the value of this instance for the current thread.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The initialization function referenced <see cref="Value"/> in an improper manner.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
/// <remarks>
/// If this instance was not previously initialized for the current thread,
/// accessing <see cref="Value"/> will attempt to initialize it. If an initialization function was
/// supplied during the construction, that initialization will happen by invoking the function
/// to retrieve the initial value for <see cref="Value"/>. Otherwise, the default value of
/// <typeparamref name="T"/> will be used.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Value
{
get
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
LinkedSlot slot;
int id = ~m_idComplement;
//
// Attempt to get the value using the fast path
//
if (slotArray != null // Has the slot array been initialized?
&& id >= 0 // Is the ID non-negative (i.e., instance is not disposed)?
&& id < slotArray.Length // Is the table large enough?
&& (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID?
&& m_initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)?
)
{
// We verified that the instance has not been disposed *after* we got a reference to the slot.
// This guarantees that we have a reference to the right slot.
//
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// will not be reordered before the read of slotArray[id].
return slot.Value;
}
return GetValueSlow();
}
set
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
LinkedSlot slot;
int id = ~m_idComplement;
//
// Attempt to set the value using the fast path
//
if (slotArray != null // Has the slot array been initialized?
&& id >= 0 // Is the ID non-negative (i.e., instance is not disposed)?
&& id < slotArray.Length // Is the table large enough?
&& (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID?
&& m_initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)?
)
{
// We verified that the instance has not been disposed *after* we got a reference to the slot.
// This guarantees that we have a reference to the right slot.
//
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// will not be reordered before the read of slotArray[id].
slot.Value = value;
}
else
{
SetValueSlow(value, slotArray);
}
}
}
private T GetValueSlow()
{
// If the object has been disposed, the id will be -1.
int id = ~m_idComplement;
if (id < 0)
{
throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
}
Debugger.NotifyOfCrossThreadDependency();
// Determine the initial value
T value;
if (m_valueFactory == null)
{
value = default(T);
}
else
{
value = m_valueFactory();
if (IsValueCreated)
{
throw new InvalidOperationException(Environment.GetResourceString("ThreadLocal_Value_RecursiveCallsToValue"));
}
}
// Since the value has been previously uninitialized, we also need to set it (according to the ThreadLocal semantics).
Value = value;
return value;
}
private void SetValueSlow(T value, LinkedSlotVolatile[] slotArray)
{
int id = ~m_idComplement;
// If the object has been disposed, id will be -1.
if (id < 0)
{
throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
}
// If a slot array has not been created on this thread yet, create it.
if (slotArray == null)
{
slotArray = new LinkedSlotVolatile[GetNewTableSize(id + 1)];
ts_finalizationHelper = new FinalizationHelper(slotArray, m_trackAllValues);
ts_slotArray = slotArray;
}
// If the slot array is not big enough to hold this ID, increase the table size.
if (id >= slotArray.Length)
{
GrowTable(ref slotArray, id + 1);
ts_finalizationHelper.SlotArray = slotArray;
ts_slotArray = slotArray;
}
// If we are using the slot in this table for the first time, create a new LinkedSlot and add it into
// the linked list for this ThreadLocal instance.
if (slotArray[id].Value == null)
{
CreateLinkedSlot(slotArray, id, value);
}
else
{
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// that follows will not be reordered before the read of slotArray[id].
LinkedSlot slot = slotArray[id].Value;
// It is important to verify that the ThreadLocal instance has not been disposed. The check must come
// after capturing slotArray[id], but before assigning the value into the slot. This ensures that
// if this ThreadLocal instance was disposed on another thread and another ThreadLocal instance was
// created, we definitely won't assign the value into the wrong instance.
if (!m_initialized)
{
throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
}
slot.Value = value;
}
}
/// <summary>
/// Creates a LinkedSlot and inserts it into the linked list for this ThreadLocal instance.
/// </summary>
private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value)
{
// Create a LinkedSlot
var linkedSlot = new LinkedSlot(slotArray);
// Insert the LinkedSlot into the linked list maintained by this ThreadLocal<> instance and into the slot array
lock (s_idManager)
{
// Check that the instance has not been disposed. It is important to check this under a lock, since
// Dispose also executes under a lock.
if (!m_initialized)
{
throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
}
LinkedSlot firstRealNode = m_linkedSlot.Next;
//
// Insert linkedSlot between nodes m_linkedSlot and firstRealNode.
// (m_linkedSlot is the dummy head node that should always be in the front.)
//
linkedSlot.Next = firstRealNode;
linkedSlot.Previous = m_linkedSlot;
linkedSlot.Value = value;
if (firstRealNode != null)
{
firstRealNode.Previous = linkedSlot;
}
m_linkedSlot.Next = linkedSlot;
// Assigning the slot under a lock prevents a race condition with Dispose (dispose also acquires the lock).
// Otherwise, it would be possible that the ThreadLocal instance is disposed, another one gets created
// with the same ID, and the write would go to the wrong instance.
slotArray[id].Value = linkedSlot;
}
}
/// <summary>
/// Gets a list for all of the values currently stored by all of the threads that have accessed this instance.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
public IList<T> Values
{
get
{
if (!m_trackAllValues)
{
throw new InvalidOperationException(Environment.GetResourceString("ThreadLocal_ValuesNotAvailable"));
}
var list = GetValuesAsList(); // returns null if disposed
if (list == null) throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
return list;
}
}
/// <summary>Gets all of the threads' values in a list.</summary>
private List<T> GetValuesAsList()
{
List<T> valueList = new List<T>();
int id = ~m_idComplement;
if (id == -1)
{
return null;
}
// Walk over the linked list of slots and gather the values associated with this ThreadLocal instance.
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
// We can safely read linkedSlot.Value. Even if this ThreadLocal has been disposed in the meantime, the LinkedSlot
// objects will never be assigned to another ThreadLocal instance.
valueList.Add(linkedSlot.Value);
}
return valueList;
}
/// <summary>Gets the number of threads that have data in this instance.</summary>
private int ValuesCountForDebugDisplay
{
get
{
int count = 0;
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
count++;
}
return count;
}
}
/// <summary>
/// Gets whether <see cref="Value"/> is initialized on the current thread.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
public bool IsValueCreated
{
get
{
int id = ~m_idComplement;
if (id < 0)
{
throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
}
LinkedSlotVolatile[] slotArray = ts_slotArray;
return slotArray != null && id < slotArray.Length && slotArray[id].Value != null;
}
}
/// <summary>Gets the value of the ThreadLocal<T> for debugging display purposes. It takes care of getting
/// the value for the current thread in the ThreadLocal mode.</summary>
internal T ValueForDebugDisplay
{
get
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
int id = ~m_idComplement;
LinkedSlot slot;
if (slotArray == null || id >= slotArray.Length || (slot = slotArray[id].Value) == null || !m_initialized)
return default(T);
return slot.Value;
}
}
/// <summary>Gets the values of all threads that accessed the ThreadLocal<T>.</summary>
internal List<T> ValuesForDebugDisplay // same as Values property, but doesn't throw if disposed
{
get { return GetValuesAsList(); }
}
/// <summary>
/// Resizes a table to a certain length (or larger).
/// </summary>
private void GrowTable(ref LinkedSlotVolatile[] table, int minLength)
{
Contract.Assert(table.Length < minLength);
// Determine the size of the new table and allocate it.
int newLen = GetNewTableSize(minLength);
LinkedSlotVolatile[] newTable = new LinkedSlotVolatile[newLen];
//
// The lock is necessary to avoid a race with ThreadLocal.Dispose. GrowTable has to point all
// LinkedSlot instances referenced in the old table to reference the new table. Without locking,
// Dispose could use a stale SlotArray reference and clear out a slot in the old array only, while
// the value continues to be referenced from the new (larger) array.
//
lock (s_idManager)
{
for (int i = 0; i < table.Length; i++)
{
LinkedSlot linkedSlot = table[i].Value;
if (linkedSlot != null && linkedSlot.SlotArray != null)
{
linkedSlot.SlotArray = newTable;
newTable[i] = table[i];
}
}
}
table = newTable;
}
/// <summary>
/// Chooses the next larger table size
/// </summary>
private static int GetNewTableSize(int minSize)
{
if ((uint)minSize > Array.MaxArrayLength)
{
// Intentionally return a value that will result in an OutOfMemoryException
return int.MaxValue;
}
Contract.Assert(minSize > 0);
//
// Round up the size to the next power of 2
//
// The algorithm takes three steps:
// input -> subtract one -> propagate 1-bits to the right -> add one
//
// Let's take a look at the 3 steps in both interesting cases: where the input
// is (Example 1) and isn't (Example 2) a power of 2.
//
// Example 1: 100000 -> 011111 -> 011111 -> 100000
// Example 2: 011010 -> 011001 -> 011111 -> 100000
//
int newSize = minSize;
// Step 1: Decrement
newSize--;
// Step 2: Propagate 1-bits to the right.
newSize |= newSize >> 1;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
// Step 3: Increment
newSize++;
// Don't set newSize to more than Array.MaxArrayLength
if ((uint)newSize > Array.MaxArrayLength)
{
newSize = Array.MaxArrayLength;
}
return newSize;
}
/// <summary>
/// A wrapper struct used as LinkedSlotVolatile[] - an array of LinkedSlot instances, but with volatile semantics
/// on array accesses.
/// </summary>
private struct LinkedSlotVolatile
{
internal volatile LinkedSlot Value;
}
/// <summary>
/// A node in the doubly-linked list stored in the ThreadLocal instance.
///
/// The value is stored in one of two places:
///
/// 1. If SlotArray is not null, the value is in SlotArray.Table[id]
/// 2. If SlotArray is null, the value is in FinalValue.
/// </summary>
private sealed class LinkedSlot
{
internal LinkedSlot(LinkedSlotVolatile[] slotArray)
{
SlotArray = slotArray;
}
// The next LinkedSlot for this ThreadLocal<> instance
internal volatile LinkedSlot Next;
// The previous LinkedSlot for this ThreadLocal<> instance
internal volatile LinkedSlot Previous;
// The SlotArray that stores this LinkedSlot at SlotArray.Table[id].
internal volatile LinkedSlotVolatile[] SlotArray;
// The value for this slot.
internal T Value;
}
/// <summary>
/// A manager class that assigns IDs to ThreadLocal instances
/// </summary>
private class IdManager
{
// The next ID to try
private int m_nextIdToTry = 0;
// Stores whether each ID is free or not. Additionally, the object is also used as a lock for the IdManager.
private List<bool> m_freeIds = new List<bool>();
internal int GetId()
{
lock (m_freeIds)
{
int availableId = m_nextIdToTry;
while (availableId < m_freeIds.Count)
{
if (m_freeIds[availableId]) { break; }
availableId++;
}
if (availableId == m_freeIds.Count)
{
m_freeIds.Add(false);
}
else
{
m_freeIds[availableId] = false;
}
m_nextIdToTry = availableId + 1;
return availableId;
}
}
// Return an ID to the pool
internal void ReturnId(int id)
{
lock (m_freeIds)
{
m_freeIds[id] = true;
if (id < m_nextIdToTry) m_nextIdToTry = id;
}
}
}
/// <summary>
/// A class that facilitates ThreadLocal cleanup after a thread exits.
///
/// After a thread with an associated thread-local table has exited, the FinalizationHelper
/// is reponsible for removing back-references to the table. Since an instance of FinalizationHelper
/// is only referenced from a single thread-local slot, the FinalizationHelper will be GC'd once
/// the thread has exited.
///
/// The FinalizationHelper then locates all LinkedSlot instances with back-references to the table
/// (all those LinkedSlot instances can be found by following references from the table slots) and
/// releases the table so that it can get GC'd.
/// </summary>
private class FinalizationHelper
{
internal LinkedSlotVolatile[] SlotArray;
private bool m_trackAllValues;
internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues)
{
SlotArray = slotArray;
m_trackAllValues = trackAllValues;
}
~FinalizationHelper()
{
LinkedSlotVolatile[] slotArray = SlotArray;
Contract.Assert(slotArray != null);
for (int i = 0; i < slotArray.Length; i++)
{
LinkedSlot linkedSlot = slotArray[i].Value;
if (linkedSlot == null)
{
// This slot in the table is empty
continue;
}
if (m_trackAllValues)
{
// Set the SlotArray field to null to release the slot array.
linkedSlot.SlotArray = null;
}
else
{
// Remove the LinkedSlot from the linked list. Once the FinalizationHelper is done, all back-references to
// the table will be have been removed, and so the table can get GC'd.
lock (s_idManager)
{
if (linkedSlot.Next != null)
{
linkedSlot.Next.Previous = linkedSlot.Previous;
}
// Since the list uses a dummy head node, the Previous reference should never be null.
Contract.Assert(linkedSlot.Previous != null);
linkedSlot.Previous.Next = linkedSlot.Next;
}
}
}
}
}
}
/// <summary>A debugger view of the ThreadLocal<T> to surface additional debugging properties and
/// to ensure that the ThreadLocal<T> does not become initialized if it was not already.</summary>
internal sealed class SystemThreading_ThreadLocalDebugView<T>
{
//The ThreadLocal object being viewed.
private readonly ThreadLocal<T> m_tlocal;
/// <summary>Constructs a new debugger view object for the provided ThreadLocal object.</summary>
/// <param name="tlocal">A ThreadLocal object to browse in the debugger.</param>
public SystemThreading_ThreadLocalDebugView(ThreadLocal<T> tlocal)
{
m_tlocal = tlocal;
}
/// <summary>Returns whether the ThreadLocal object is initialized or not.</summary>
public bool IsValueCreated
{
get { return m_tlocal.IsValueCreated; }
}
/// <summary>Returns the value of the ThreadLocal object.</summary>
public T Value
{
get
{
return m_tlocal.ValueForDebugDisplay;
}
}
/// <summary>Return all values for all threads that have accessed this instance.</summary>
public List<T> Values
{
get
{
return m_tlocal.ValuesForDebugDisplay;
}
}
}
}
| |
using System;
using System.Collections;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.Kisa;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Ntt;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Cms
{
/**
* General class for generating a CMS enveloped-data message.
*
* A simple example of usage.
*
* <pre>
* CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator();
*
* fact.addKeyTransRecipient(cert);
*
* CMSEnvelopedData data = fact.generate(content, algorithm, "BC");
* </pre>
*/
public class CmsEnvelopedGenerator
{
// Note: These tables are complementary: If rc2Table[i]==j, then rc2Ekb[j]==i
internal static readonly short[] rc2Table =
{
0xbd, 0x56, 0xea, 0xf2, 0xa2, 0xf1, 0xac, 0x2a, 0xb0, 0x93, 0xd1, 0x9c, 0x1b, 0x33, 0xfd, 0xd0,
0x30, 0x04, 0xb6, 0xdc, 0x7d, 0xdf, 0x32, 0x4b, 0xf7, 0xcb, 0x45, 0x9b, 0x31, 0xbb, 0x21, 0x5a,
0x41, 0x9f, 0xe1, 0xd9, 0x4a, 0x4d, 0x9e, 0xda, 0xa0, 0x68, 0x2c, 0xc3, 0x27, 0x5f, 0x80, 0x36,
0x3e, 0xee, 0xfb, 0x95, 0x1a, 0xfe, 0xce, 0xa8, 0x34, 0xa9, 0x13, 0xf0, 0xa6, 0x3f, 0xd8, 0x0c,
0x78, 0x24, 0xaf, 0x23, 0x52, 0xc1, 0x67, 0x17, 0xf5, 0x66, 0x90, 0xe7, 0xe8, 0x07, 0xb8, 0x60,
0x48, 0xe6, 0x1e, 0x53, 0xf3, 0x92, 0xa4, 0x72, 0x8c, 0x08, 0x15, 0x6e, 0x86, 0x00, 0x84, 0xfa,
0xf4, 0x7f, 0x8a, 0x42, 0x19, 0xf6, 0xdb, 0xcd, 0x14, 0x8d, 0x50, 0x12, 0xba, 0x3c, 0x06, 0x4e,
0xec, 0xb3, 0x35, 0x11, 0xa1, 0x88, 0x8e, 0x2b, 0x94, 0x99, 0xb7, 0x71, 0x74, 0xd3, 0xe4, 0xbf,
0x3a, 0xde, 0x96, 0x0e, 0xbc, 0x0a, 0xed, 0x77, 0xfc, 0x37, 0x6b, 0x03, 0x79, 0x89, 0x62, 0xc6,
0xd7, 0xc0, 0xd2, 0x7c, 0x6a, 0x8b, 0x22, 0xa3, 0x5b, 0x05, 0x5d, 0x02, 0x75, 0xd5, 0x61, 0xe3,
0x18, 0x8f, 0x55, 0x51, 0xad, 0x1f, 0x0b, 0x5e, 0x85, 0xe5, 0xc2, 0x57, 0x63, 0xca, 0x3d, 0x6c,
0xb4, 0xc5, 0xcc, 0x70, 0xb2, 0x91, 0x59, 0x0d, 0x47, 0x20, 0xc8, 0x4f, 0x58, 0xe0, 0x01, 0xe2,
0x16, 0x38, 0xc4, 0x6f, 0x3b, 0x0f, 0x65, 0x46, 0xbe, 0x7e, 0x2d, 0x7b, 0x82, 0xf9, 0x40, 0xb5,
0x1d, 0x73, 0xf8, 0xeb, 0x26, 0xc7, 0x87, 0x97, 0x25, 0x54, 0xb1, 0x28, 0xaa, 0x98, 0x9d, 0xa5,
0x64, 0x6d, 0x7a, 0xd4, 0x10, 0x81, 0x44, 0xef, 0x49, 0xd6, 0xae, 0x2e, 0xdd, 0x76, 0x5c, 0x2f,
0xa7, 0x1c, 0xc9, 0x09, 0x69, 0x9a, 0x83, 0xcf, 0x29, 0x39, 0xb9, 0xe9, 0x4c, 0xff, 0x43, 0xab
};
// internal static readonly short[] rc2Ekb =
// {
// 0x5d, 0xbe, 0x9b, 0x8b, 0x11, 0x99, 0x6e, 0x4d, 0x59, 0xf3, 0x85, 0xa6, 0x3f, 0xb7, 0x83, 0xc5,
// 0xe4, 0x73, 0x6b, 0x3a, 0x68, 0x5a, 0xc0, 0x47, 0xa0, 0x64, 0x34, 0x0c, 0xf1, 0xd0, 0x52, 0xa5,
// 0xb9, 0x1e, 0x96, 0x43, 0x41, 0xd8, 0xd4, 0x2c, 0xdb, 0xf8, 0x07, 0x77, 0x2a, 0xca, 0xeb, 0xef,
// 0x10, 0x1c, 0x16, 0x0d, 0x38, 0x72, 0x2f, 0x89, 0xc1, 0xf9, 0x80, 0xc4, 0x6d, 0xae, 0x30, 0x3d,
// 0xce, 0x20, 0x63, 0xfe, 0xe6, 0x1a, 0xc7, 0xb8, 0x50, 0xe8, 0x24, 0x17, 0xfc, 0x25, 0x6f, 0xbb,
// 0x6a, 0xa3, 0x44, 0x53, 0xd9, 0xa2, 0x01, 0xab, 0xbc, 0xb6, 0x1f, 0x98, 0xee, 0x9a, 0xa7, 0x2d,
// 0x4f, 0x9e, 0x8e, 0xac, 0xe0, 0xc6, 0x49, 0x46, 0x29, 0xf4, 0x94, 0x8a, 0xaf, 0xe1, 0x5b, 0xc3,
// 0xb3, 0x7b, 0x57, 0xd1, 0x7c, 0x9c, 0xed, 0x87, 0x40, 0x8c, 0xe2, 0xcb, 0x93, 0x14, 0xc9, 0x61,
// 0x2e, 0xe5, 0xcc, 0xf6, 0x5e, 0xa8, 0x5c, 0xd6, 0x75, 0x8d, 0x62, 0x95, 0x58, 0x69, 0x76, 0xa1,
// 0x4a, 0xb5, 0x55, 0x09, 0x78, 0x33, 0x82, 0xd7, 0xdd, 0x79, 0xf5, 0x1b, 0x0b, 0xde, 0x26, 0x21,
// 0x28, 0x74, 0x04, 0x97, 0x56, 0xdf, 0x3c, 0xf0, 0x37, 0x39, 0xdc, 0xff, 0x06, 0xa4, 0xea, 0x42,
// 0x08, 0xda, 0xb4, 0x71, 0xb0, 0xcf, 0x12, 0x7a, 0x4e, 0xfa, 0x6c, 0x1d, 0x84, 0x00, 0xc8, 0x7f,
// 0x91, 0x45, 0xaa, 0x2b, 0xc2, 0xb1, 0x8f, 0xd5, 0xba, 0xf2, 0xad, 0x19, 0xb2, 0x67, 0x36, 0xf7,
// 0x0f, 0x0a, 0x92, 0x7d, 0xe3, 0x9d, 0xe9, 0x90, 0x3e, 0x23, 0x27, 0x66, 0x13, 0xec, 0x81, 0x15,
// 0xbd, 0x22, 0xbf, 0x9f, 0x7e, 0xa9, 0x51, 0x4b, 0x4c, 0xfb, 0x02, 0xd3, 0x70, 0x86, 0x31, 0xe7,
// 0x3b, 0x05, 0x03, 0x54, 0x60, 0x48, 0x65, 0x18, 0xd2, 0xcd, 0x5f, 0x32, 0x88, 0x0e, 0x35, 0xfd
// };
// TODO Create named constants for all of these
public static readonly string DesEde3Cbc = PkcsObjectIdentifiers.DesEde3Cbc.Id;
public static readonly string RC2Cbc = PkcsObjectIdentifiers.RC2Cbc.Id;
public const string IdeaCbc = "1.3.6.1.4.1.188.7.1.1.2";
public const string Cast5Cbc = "1.2.840.113533.7.66.10";
public static readonly string Aes128Cbc = NistObjectIdentifiers.IdAes128Cbc.Id;
public static readonly string Aes192Cbc = NistObjectIdentifiers.IdAes192Cbc.Id;
public static readonly string Aes256Cbc = NistObjectIdentifiers.IdAes256Cbc.Id;
public static readonly string Camellia128Cbc = NttObjectIdentifiers.IdCamellia128Cbc.Id;
public static readonly string Camellia192Cbc = NttObjectIdentifiers.IdCamellia192Cbc.Id;
public static readonly string Camellia256Cbc = NttObjectIdentifiers.IdCamellia256Cbc.Id;
public static readonly string SeedCbc = KisaObjectIdentifiers.IdSeedCbc.Id;
public static readonly string DesEde3Wrap = PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id;
public static readonly string Aes128Wrap = NistObjectIdentifiers.IdAes128Wrap.Id;
public static readonly string Aes192Wrap = NistObjectIdentifiers.IdAes192Wrap.Id;
public static readonly string Aes256Wrap = NistObjectIdentifiers.IdAes256Wrap.Id;
public static readonly string Camellia128Wrap = NttObjectIdentifiers.IdCamellia128Wrap.Id;
public static readonly string Camellia192Wrap = NttObjectIdentifiers.IdCamellia192Wrap.Id;
public static readonly string Camellia256Wrap = NttObjectIdentifiers.IdCamellia256Wrap.Id;
public static readonly string SeedWrap = KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap.Id;
public static readonly string ECDHSha1Kdf = X9ObjectIdentifiers.DHSinglePassStdDHSha1KdfScheme.Id;
public static readonly string ECMqvSha1Kdf = X9ObjectIdentifiers.MqvSinglePassSha1KdfScheme.Id;
internal readonly IList recipientInfoGenerators = Platform.CreateArrayList();
internal readonly SecureRandom rand;
internal CmsAttributeTableGenerator unprotectedAttributeGenerator = null;
public CmsEnvelopedGenerator()
: this(new SecureRandom())
{
}
/// <summary>Constructor allowing specific source of randomness</summary>
/// <param name="rand">Instance of <c>SecureRandom</c> to use.</param>
public CmsEnvelopedGenerator(
SecureRandom rand)
{
this.rand = rand;
}
public CmsAttributeTableGenerator UnprotectedAttributeGenerator
{
get { return this.unprotectedAttributeGenerator; }
set { this.unprotectedAttributeGenerator = value; }
}
/**
* add a recipient.
*
* @param cert recipient's public key certificate
* @exception ArgumentException if there is a problem with the certificate
*/
public void AddKeyTransRecipient(
X509Certificate cert)
{
KeyTransRecipientInfoGenerator ktrig = new KeyTransRecipientInfoGenerator();
ktrig.RecipientCert = cert;
recipientInfoGenerators.Add(ktrig);
}
/**
* add a recipient
*
* @param key the public key used by the recipient
* @param subKeyId the identifier for the recipient's public key
* @exception ArgumentException if there is a problem with the key
*/
public void AddKeyTransRecipient(
AsymmetricKeyParameter pubKey,
byte[] subKeyId)
{
KeyTransRecipientInfoGenerator ktrig = new KeyTransRecipientInfoGenerator();
ktrig.RecipientPublicKey = pubKey;
ktrig.SubjectKeyIdentifier = new DerOctetString(subKeyId);
recipientInfoGenerators.Add(ktrig);
}
/**
* add a KEK recipient.
* @param key the secret key to use for wrapping
* @param keyIdentifier the byte string that identifies the key
*/
public void AddKekRecipient(
string keyAlgorithm, // TODO Remove need for this parameter
KeyParameter key,
byte[] keyIdentifier)
{
AddKekRecipient(keyAlgorithm, key, new KekIdentifier(keyIdentifier, null, null));
}
/**
* add a KEK recipient.
* @param key the secret key to use for wrapping
* @param keyIdentifier the byte string that identifies the key
*/
public void AddKekRecipient(
string keyAlgorithm, // TODO Remove need for this parameter
KeyParameter key,
KekIdentifier kekIdentifier)
{
KekRecipientInfoGenerator kekrig = new KekRecipientInfoGenerator();
kekrig.KekIdentifier = kekIdentifier;
kekrig.KeyEncryptionKeyOID = keyAlgorithm;
kekrig.KeyEncryptionKey = key;
recipientInfoGenerators.Add(kekrig);
}
public void AddPasswordRecipient(
CmsPbeKey pbeKey,
string kekAlgorithmOid)
{
Pbkdf2Params p = new Pbkdf2Params(pbeKey.Salt, pbeKey.IterationCount);
PasswordRecipientInfoGenerator prig = new PasswordRecipientInfoGenerator();
prig.KeyDerivationAlgorithm = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbkdf2, p);
prig.KeyEncryptionKeyOID = kekAlgorithmOid;
prig.KeyEncryptionKey = pbeKey.GetEncoded(kekAlgorithmOid);
recipientInfoGenerators.Add(prig);
}
/**
* Add a key agreement based recipient.
*
* @param agreementAlgorithm key agreement algorithm to use.
* @param senderPrivateKey private key to initialise sender side of agreement with.
* @param senderPublicKey sender public key to include with message.
* @param recipientCert recipient's public key certificate.
* @param cekWrapAlgorithm OID for key wrapping algorithm to use.
* @exception SecurityUtilityException if the algorithm requested cannot be found
* @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
*/
public void AddKeyAgreementRecipient(
string agreementAlgorithm,
IAsymmetricKeyParameter senderPrivateKey,
IAsymmetricKeyParameter senderPublicKey,
X509Certificate recipientCert,
string cekWrapAlgorithm)
{
IList recipientCerts = Platform.CreateArrayList(1);
recipientCerts.Add(recipientCert);
AddKeyAgreementRecipients(agreementAlgorithm, senderPrivateKey, senderPublicKey,
recipientCerts, cekWrapAlgorithm);
}
/**
* Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure).
*
* @param agreementAlgorithm key agreement algorithm to use.
* @param senderPrivateKey private key to initialise sender side of agreement with.
* @param senderPublicKey sender public key to include with message.
* @param recipientCerts recipients' public key certificates.
* @param cekWrapAlgorithm OID for key wrapping algorithm to use.
* @exception SecurityUtilityException if the algorithm requested cannot be found
* @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
*/
public void AddKeyAgreementRecipients(
string agreementAlgorithm,
IAsymmetricKeyParameter senderPrivateKey,
IAsymmetricKeyParameter senderPublicKey,
ICollection recipientCerts,
string cekWrapAlgorithm)
{
if (!senderPrivateKey.IsPrivate)
throw new ArgumentException(@"Expected private key", "senderPrivateKey");
if (senderPublicKey.IsPrivate)
throw new ArgumentException(@"Expected public key", "senderPublicKey");
/* TODO
* "a recipient X.509 version 3 certificate that contains a key usage extension MUST
* assert the keyAgreement bit."
*/
KeyAgreeRecipientInfoGenerator karig = new KeyAgreeRecipientInfoGenerator();
karig.KeyAgreementOID = new DerObjectIdentifier(agreementAlgorithm);
karig.KeyEncryptionOID = new DerObjectIdentifier(cekWrapAlgorithm);
karig.RecipientCerts = recipientCerts;
karig.SenderKeyPair = new AsymmetricCipherKeyPair(senderPublicKey, senderPrivateKey);
recipientInfoGenerators.Add(karig);
}
protected internal virtual AlgorithmIdentifier GetAlgorithmIdentifier(
string encryptionOid,
KeyParameter encKey,
Asn1Encodable asn1Params,
out ICipherParameters cipherParameters)
{
Asn1Object asn1Object;
if (asn1Params != null)
{
asn1Object = asn1Params.ToAsn1Object();
cipherParameters = ParameterUtilities.GetCipherParameters(
encryptionOid, encKey, asn1Object);
}
else
{
asn1Object = DerNull.Instance;
cipherParameters = encKey;
}
return new AlgorithmIdentifier(
new DerObjectIdentifier(encryptionOid),
asn1Object);
}
protected internal virtual Asn1Encodable GenerateAsn1Parameters(
string encryptionOid,
byte[] encKeyBytes)
{
Asn1Encodable asn1Params = null;
try
{
if (encryptionOid.Equals(RC2Cbc))
{
byte[] iv = new byte[8];
rand.NextBytes(iv);
// TODO Is this detailed repeat of Java version really necessary?
int effKeyBits = encKeyBytes.Length * 8;
int parameterVersion;
if (effKeyBits < 256)
{
parameterVersion = rc2Table[effKeyBits];
}
else
{
parameterVersion = effKeyBits;
}
asn1Params = new RC2CbcParameter(parameterVersion, iv);
}
else
{
asn1Params = ParameterUtilities.GenerateParameters(encryptionOid, rand);
}
}
catch (SecurityUtilityException)
{
// No problem... no parameters generated
}
return asn1Params;
}
}
}
| |
// Adopted from the great article: http://www.codeproject.com/Articles/17890/Do-Anything-With-ID
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace ManagedBass
{
/// <summary>
/// Reads ID3v2 Tags.
/// </summary>
public class ID3v2Tag
{
enum TextEncodings
{
Ascii,
Utf16,
Utf16Be,
Utf8
}
IntPtr _ptr;
readonly Version _versionInfo;
/// <summary>
/// Reads tags from an <see cref="IntPtr"/> to an ID3v2 block.
/// </summary>
public ID3v2Tag(IntPtr Pointer)
{
_ptr = Pointer;
if (ReadText(3, TextEncodings.Ascii) != "ID3") // If don't contain ID3v2 tag
throw new DataMisalignedException("ID3v2 info not found");
_versionInfo = new Version(2, ReadByte(), ReadByte()); // Read ID3v2 version
_ptr += 1; // Flags are skipped
ReadAllFrames(ReadSize());
}
/// <summary>
/// Reads tags from a Channel.
/// </summary>
public ID3v2Tag(int Channel) : this(Bass.ChannelGetTags(Channel, TagType.ID3v2)) { }
void ReadAllFrames(int Length)
{
// If ID3v2 is ID3v2.2 FrameID, FrameLength of Frames is 3 byte
// otherwise it's 4 character
var frameIdLen = _versionInfo.Minor == 2 ? 3 : 4;
// Minimum frame size is 10 because frame header is 10 byte
while (Length > 10)
{
// check for padding( 00 bytes )
var buf = ReadByte();
if (buf == 0)
{
Length--;
continue;
}
// if readed byte is not zero. it must read as FrameID
_ptr -= 1;
// ---------- Read Frame Header -----------------------
var frameId = ReadText(frameIdLen, TextEncodings.Ascii);
var frameLength = Convert.ToInt32(ReadUInt(frameIdLen));
if (frameIdLen == 4)
ReadUInt(2);
//Issue 78 Fix: Dbond (2020-07-16)
//add saftey check to make sure we can't read past the overall header length
//protecting against an invalid frame value.
frameLength = Math.Min(frameLength, Length - 10); //header space left is length - header size.. (10 bytes)
var added = AddFrame(frameId, frameLength);
// if don't read this frame, we must go forward to read next frame
if (!added)
_ptr += frameLength;
Length -= frameLength + 10;
}
}
bool AddFrame(string FrameID, int Length)
{
if (FrameID == null || !IsValidFrameID(FrameID))
return false;
if (FrameID[0] == 'T' || FrameID[0] == 'W') // Is Text Frame
{
var isUrl = FrameID[0] == 'W';
TextEncodings textEncoding;
if (isUrl) textEncoding = TextEncodings.Ascii;
else
{
textEncoding = (TextEncodings)ReadByte();
Length--;
if (!Enum.IsDefined(typeof(TextEncodings), textEncoding))
return false;
}
var text = ReadText(Length, textEncoding);
AddTextFrame(FrameID, text);
return true;
}
switch (FrameID)
{
case "POPM":
ReadText(Length, TextEncodings.Ascii, ref Length, true); // Skip Email Address
var rating = ReadByte().ToString(); // Read Rating
if (--Length > 8)
return false;
_ptr += Length; // Skip Counter value
AddTextFrame("POPM", rating);
return true;
case "COM":
case "COMM":
var TextEncoding = (TextEncodings)ReadByte();
Length--;
if (!Enum.IsDefined(typeof(TextEncodings), TextEncoding))
return false;
_ptr += 3;
Length -= 3;
ReadText(Length, TextEncoding, ref Length, true); // Skip Description
AddTextFrame("COMM", ReadText(Length, TextEncoding));
return true;
case "APIC":
var textEncoding = (TextEncodings)ReadByte();
Length--;
if (!Enum.IsDefined(typeof(TextEncodings), textEncoding))
return false;
var mimeType = ReadText(Length, TextEncodings.Ascii, ref Length, true);
var pictureType = (PictureTypes)ReadByte();
Length--;
ReadText(Length, textEncoding, ref Length, true); // Skip Description
var data = new byte[Length];
Read(data, 0, Length);
PictureFrames.Add(new PictureTag
{
Data = data,
MimeType = mimeType,
PictureType = pictureType
});
return true;
}
return false;
}
static bool IsValidFrameID(string FrameID)
{
if (FrameID == null || (FrameID.Length != 3 && FrameID.Length != 4))
return false;
return FrameID.Cast<char>().All(ch => char.IsUpper(ch) || char.IsDigit(ch));
}
// Multiple values for text tags are separated by ';'.
void AddTextFrame(string Key, string Value)
{
if (TextFrames.ContainsKey(Key))
TextFrames[Key] += ";" + Value;
else TextFrames.Add(Key, Value);
}
/// <summary>
/// Dictionary of Text frames.
/// </summary>
public Dictionary<string, string> TextFrames { get; } = new Dictionary<string, string>();
/// <summary>
/// List of Picture tags.
/// </summary>
public List<PictureTag> PictureFrames { get; } = new List<PictureTag>();
#region Streaming
string ReadText(int MaxLength, TextEncodings TEncoding)
{
var i = 0;
return ReadText(MaxLength, TEncoding, ref i, false);
}
string ReadText(int MaxLength, TextEncodings TEncoding, ref int ReadedLength, bool DetectEncoding)
{
if (MaxLength <= 0)
return "";
var bytesRead = 0;
using (var mStream = new MemoryStream())
{
if (DetectEncoding && MaxLength >= 3)
{
var buffer = new byte[3];
Read(buffer, 0, buffer.Length);
if (buffer[0] == 0xFF && buffer[1] == 0xFE)
{
// FF FE
TEncoding = TextEncodings.Utf16; // UTF-16 (LE)
_ptr -= 1;
bytesRead += 1;
MaxLength -= 2;
}
else if (buffer[0] == 0xFE && buffer[1] == 0xFF)
{
// FE FF
TEncoding = TextEncodings.Utf16Be;
_ptr -= 1;
bytesRead += 1;
MaxLength -= 2;
}
else if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF)
{
// EF BB BF
TEncoding = TextEncodings.Utf8;
MaxLength -= 3;
}
{
_ptr -= 3;
bytesRead += 3;
}
}
var is2ByteSeprator = TEncoding == TextEncodings.Utf16 || TEncoding == TextEncodings.Utf16Be;
while (MaxLength > 0)
{
var buf = ReadByte();
if (buf != 0) // if it's data byte
mStream.WriteByte(buf);
else // if Buf == 0
{
if (is2ByteSeprator)
{
var temp = ReadByte();
if (temp == 0)
break;
mStream.WriteByte(buf);
mStream.WriteByte(temp);
MaxLength--;
}
else break;
}
MaxLength--;
}
if (MaxLength < 0)
_ptr += MaxLength;
ReadedLength -= bytesRead;
return GetEncoding(TEncoding).GetString(mStream.ToArray(), 0, (int)mStream.Length);
}
}
byte ReadByte()
{
var rByte = new byte[1];
Read(rByte, 0, 1);
return rByte[0];
}
uint ReadUInt(int Length)
{
if (Length > 4 || Length < 1)
throw new ArgumentOutOfRangeException(nameof(Length), "ReadUInt method can read 1-4 byte(s)");
byte[] buf = new byte[Length],
rBuf = new byte[4];
Read(buf, 0, Length);
buf.CopyTo(rBuf, 4 - buf.Length);
Array.Reverse(rBuf);
return BitConverter.ToUInt32(rBuf, 0);
}
int ReadSize()
{
/* ID3 Size is like:
* 0XXXXXXXb 0XXXXXXXb 0XXXXXXXb 0XXXXXXXb (b means binary)
* the zero bytes must ignore, so we have 28 bits number = 0x1000 0000 (maximum)
* it's equal to 256MB
*/
return ReadByte() * 0x200000 + ReadByte() * 0x4000 + ReadByte() * 0x80 + ReadByte();
}
static Encoding GetEncoding(TextEncodings TEncoding)
{
switch (TEncoding)
{
case TextEncodings.Utf16:
return Encoding.Unicode;
case TextEncodings.Utf16Be:
return Encoding.GetEncoding("UTF-16BE");
default:
return Encoding.UTF8;
}
}
void Read(byte[] Buffer, int Offset, int Count)
{
Marshal.Copy(_ptr, Buffer, Offset, Count);
_ptr += Count;
}
#endregion
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Threading;
using dnlib.DotNet.MD;
using dnlib.Threading;
namespace dnlib.DotNet {
/// <summary>
/// A high-level representation of a row in the TypeRef table
/// </summary>
public abstract class TypeRef : ITypeDefOrRef, IHasCustomAttribute, IMemberRefParent, IResolutionScope {
/// <summary>
/// The row id in its table
/// </summary>
protected uint rid;
/// <summary>
/// The owner module
/// </summary>
protected ModuleDef module;
#if THREAD_SAFE
readonly Lock theLock = Lock.Create();
#endif
/// <inheritdoc/>
public MDToken MDToken {
get { return new MDToken(Table.TypeRef, rid); }
}
/// <inheritdoc/>
public uint Rid {
get { return rid; }
set { rid = value; }
}
/// <inheritdoc/>
public int TypeDefOrRefTag {
get { return 1; }
}
/// <inheritdoc/>
public int HasCustomAttributeTag {
get { return 2; }
}
/// <inheritdoc/>
public int MemberRefParentTag {
get { return 1; }
}
/// <inheritdoc/>
public int ResolutionScopeTag {
get { return 3; }
}
/// <inheritdoc/>
int IGenericParameterProvider.NumberOfGenericParameters {
get { return 0; }
}
/// <inheritdoc/>
string IType.TypeName {
get { return FullNameCreator.Name(this, false); }
}
/// <inheritdoc/>
public string ReflectionName {
get { return FullNameCreator.Name(this, true); }
}
/// <inheritdoc/>
string IType.Namespace {
get { return FullNameCreator.Namespace(this, false); }
}
/// <inheritdoc/>
public string ReflectionNamespace {
get { return FullNameCreator.Namespace(this, true); }
}
/// <inheritdoc/>
public string FullName {
get { return FullNameCreator.FullName(this, false); }
}
/// <inheritdoc/>
public string ReflectionFullName {
get { return FullNameCreator.FullName(this, true); }
}
/// <inheritdoc/>
public string AssemblyQualifiedName {
get { return FullNameCreator.AssemblyQualifiedName(this); }
}
/// <inheritdoc/>
public IAssembly DefinitionAssembly {
get { return FullNameCreator.DefinitionAssembly(this); }
}
/// <inheritdoc/>
public IScope Scope {
get { return FullNameCreator.Scope(this); }
}
/// <inheritdoc/>
public ITypeDefOrRef ScopeType {
get { return this; }
}
/// <summary>
/// Always returns <c>false</c> since a <see cref="TypeRef"/> does not contain any
/// <see cref="GenericVar"/> or <see cref="GenericMVar"/>.
/// </summary>
public bool ContainsGenericParameter {
get { return false; }
}
/// <inheritdoc/>
public ModuleDef Module {
get { return module; }
}
/// <summary>
/// From column TypeRef.ResolutionScope
/// </summary>
public IResolutionScope ResolutionScope {
get {
if (!resolutionScope_isInitialized)
InitializeResolutionScope();
return resolutionScope;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
resolutionScope = value;
resolutionScope_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected IResolutionScope resolutionScope;
/// <summary/>
protected bool resolutionScope_isInitialized;
void InitializeResolutionScope() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (resolutionScope_isInitialized)
return;
resolutionScope = GetResolutionScope_NoLock();
resolutionScope_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="resolutionScope"/></summary>
protected virtual IResolutionScope GetResolutionScope_NoLock() {
return null;
}
/// <summary>
/// From column TypeRef.Name
/// </summary>
public UTF8String Name {
get { return name; }
set { name = value; }
}
/// <summary>Name</summary>
protected UTF8String name;
/// <summary>
/// From column TypeRef.Namespace
/// </summary>
public UTF8String Namespace {
get { return @namespace; }
set { @namespace = value; }
}
/// <summary>Name</summary>
protected UTF8String @namespace;
/// <summary>
/// Gets all custom attributes
/// </summary>
public CustomAttributeCollection CustomAttributes {
get {
if (customAttributes == null)
InitializeCustomAttributes();
return customAttributes;
}
}
/// <summary/>
protected CustomAttributeCollection customAttributes;
/// <summary>Initializes <see cref="customAttributes"/></summary>
protected virtual void InitializeCustomAttributes() {
Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null);
}
/// <inheritdoc/>
public bool HasCustomAttributes {
get { return CustomAttributes.Count > 0; }
}
/// <summary>
/// <c>true</c> if it's nested within another <see cref="TypeRef"/>
/// </summary>
public bool IsNested {
get { return DeclaringType != null; }
}
/// <inheritdoc/>
public bool IsValueType {
get {
var td = Resolve();
return td != null && td.IsValueType;
}
}
/// <inheritdoc/>
public bool IsPrimitive {
get { return this.IsPrimitive(); }
}
/// <summary>
/// Gets the declaring type, if any
/// </summary>
public TypeRef DeclaringType {
get { return ResolutionScope as TypeRef; }
}
/// <inheritdoc/>
ITypeDefOrRef IMemberRef.DeclaringType {
get { return DeclaringType; }
}
bool IIsTypeOrMethod.IsType {
get { return true; }
}
bool IIsTypeOrMethod.IsMethod {
get { return false; }
}
bool IMemberRef.IsField {
get { return false; }
}
bool IMemberRef.IsTypeSpec {
get { return false; }
}
bool IMemberRef.IsTypeRef {
get { return true; }
}
bool IMemberRef.IsTypeDef {
get { return false; }
}
bool IMemberRef.IsMethodSpec {
get { return false; }
}
bool IMemberRef.IsMethodDef {
get { return false; }
}
bool IMemberRef.IsMemberRef {
get { return false; }
}
bool IMemberRef.IsFieldDef {
get { return false; }
}
bool IMemberRef.IsPropertyDef {
get { return false; }
}
bool IMemberRef.IsEventDef {
get { return false; }
}
bool IMemberRef.IsGenericParam {
get { return false; }
}
/// <summary>
/// Resolves the type
/// </summary>
/// <returns>A <see cref="TypeDef"/> instance or <c>null</c> if it couldn't be resolved</returns>
public TypeDef Resolve() {
return Resolve(null);
}
/// <summary>
/// Resolves the type
/// </summary>
/// <param name="sourceModule">The module that needs to resolve the type or <c>null</c></param>
/// <returns>A <see cref="TypeDef"/> instance or <c>null</c> if it couldn't be resolved</returns>
public TypeDef Resolve(ModuleDef sourceModule) {
if (module == null)
return null;
return module.Context.Resolver.Resolve(this, sourceModule);
}
/// <summary>
/// Resolves the type
/// </summary>
/// <returns>A <see cref="TypeDef"/> instance</returns>
/// <exception cref="TypeResolveException">If the type couldn't be resolved</exception>
public TypeDef ResolveThrow() {
return ResolveThrow(null);
}
/// <summary>
/// Resolves the type
/// </summary>
/// <param name="sourceModule">The module that needs to resolve the type or <c>null</c></param>
/// <returns>A <see cref="TypeDef"/> instance</returns>
/// <exception cref="TypeResolveException">If the type couldn't be resolved</exception>
public TypeDef ResolveThrow(ModuleDef sourceModule) {
var type = Resolve(sourceModule);
if (type != null)
return type;
throw new TypeResolveException(string.Format("Could not resolve type: {0} ({1})", this, DefinitionAssembly));
}
/// <summary>
/// Gets the top-most (non-nested) <see cref="TypeRef"/>
/// </summary>
/// <param name="typeRef">Input</param>
/// <returns>The non-nested <see cref="TypeRef"/> or <c>null</c></returns>
internal static TypeRef GetNonNestedTypeRef(TypeRef typeRef) {
if (typeRef == null)
return null;
for (int i = 0; i < 1000; i++) {
var next = typeRef.ResolutionScope as TypeRef;
if (next == null)
return typeRef;
typeRef = next;
}
return null; // Here if eg. the TypeRef has an infinite loop
}
/// <inheritdoc/>
public override string ToString() {
return FullName;
}
}
/// <summary>
/// A TypeRef row created by the user and not present in the original .NET file
/// </summary>
public class TypeRefUser : TypeRef {
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">Owner module</param>
/// <param name="name">Type name</param>
public TypeRefUser(ModuleDef module, UTF8String name)
: this(module, UTF8String.Empty, name) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">Owner module</param>
/// <param name="namespace">Type namespace</param>
/// <param name="name">Type name</param>
public TypeRefUser(ModuleDef module, UTF8String @namespace, UTF8String name)
: this(module, @namespace, name, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">Owner module</param>
/// <param name="namespace">Type namespace</param>
/// <param name="name">Type name</param>
/// <param name="resolutionScope">Resolution scope (a <see cref="ModuleDef"/>,
/// <see cref="ModuleRef"/>, <see cref="AssemblyRef"/> or <see cref="TypeRef"/>)</param>
public TypeRefUser(ModuleDef module, UTF8String @namespace, UTF8String name, IResolutionScope resolutionScope) {
this.module = module;
this.resolutionScope = resolutionScope;
this.resolutionScope_isInitialized = true;
this.name = name;
this.@namespace = @namespace;
}
}
/// <summary>
/// Created from a row in the TypeRef table
/// </summary>
sealed class TypeRefMD : TypeRef, IMDTokenProviderMD {
/// <summary>The module where this instance is located</summary>
readonly ModuleDefMD readerModule;
readonly uint origRid;
readonly uint resolutionScopeCodedToken;
/// <inheritdoc/>
public uint OrigRid {
get { return origRid; }
}
/// <inheritdoc/>
protected override IResolutionScope GetResolutionScope_NoLock() {
return readerModule.ResolveResolutionScope(resolutionScopeCodedToken);
}
/// <inheritdoc/>
protected override void InitializeCustomAttributes() {
var list = readerModule.MetaData.GetCustomAttributeRidList(Table.TypeRef, origRid);
var tmp = new CustomAttributeCollection((int)list.Length, list, (list2, index) => readerModule.ReadCustomAttribute(((RidList)list2)[index]));
Interlocked.CompareExchange(ref customAttributes, tmp, null);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="readerModule">The module which contains this <c>TypeRef</c> row</param>
/// <param name="rid">Row ID</param>
/// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception>
/// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception>
public TypeRefMD(ModuleDefMD readerModule, uint rid) {
#if DEBUG
if (readerModule == null)
throw new ArgumentNullException("readerModule");
if (readerModule.TablesStream.TypeRefTable.IsInvalidRID(rid))
throw new BadImageFormatException(string.Format("TypeRef rid {0} does not exist", rid));
#endif
this.origRid = rid;
this.rid = rid;
this.readerModule = readerModule;
this.module = readerModule;
uint resolutionScope, name;
uint @namespace = readerModule.TablesStream.ReadTypeRefRow(origRid, out resolutionScope, out name);
this.name = readerModule.StringsStream.ReadNoNull(name);
this.@namespace = readerModule.StringsStream.ReadNoNull(@namespace);
this.resolutionScopeCodedToken = resolutionScope;
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Autodesk;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.Loads.CS
{
/// <summary>
/// Deal the LoadCase class which give methods to connect Revit and the user operation on the form
/// </summary>
public class LoadCaseDeal
{
// Private Members
Autodesk.Revit.ApplicationServices.Application m_revit; // Store the reference of revit application
Loads m_dataBuffer;
List<string> m_newLoadNaturesName; //store all the new nature's name that should be added
// Methods
/// <summary>
/// Default constructor of LoadCaseDeal
/// </summary>
public LoadCaseDeal(Loads dataBuffer)
{
m_dataBuffer = dataBuffer;
m_revit = dataBuffer.RevitApplication;
m_newLoadNaturesName = new List<string>();
m_newLoadNaturesName.Add("EQ1");
m_newLoadNaturesName.Add("EQ2");
m_newLoadNaturesName.Add("W1");
m_newLoadNaturesName.Add("W2");
m_newLoadNaturesName.Add("W3");
m_newLoadNaturesName.Add("W4");
m_newLoadNaturesName.Add("Other");
}
/// <summary>
/// prepare data for the dialog
/// </summary>
public void PrepareData()
{
//Create seven Load Natures first
if (!CreateLoadNatures())
{
return;
}
//get all the categories of load cases
UIApplication uiapplication = new UIApplication(m_revit);
Categories categories = uiapplication.ActiveUIDocument.Document.Settings.Categories;
Category category = categories.get_Item(BuiltInCategory.OST_LoadCases);
CategoryNameMap categoryNameMap = category.SubCategories;
System.Collections.IEnumerator iter = categoryNameMap.GetEnumerator();
iter.Reset();
while (iter.MoveNext())
{
Category temp = iter.Current as Category;
if (null == temp)
{
continue;
}
m_dataBuffer.LoadCasesCategory.Add(temp);
}
//get all the loadnatures name
IList<Element> elements = new FilteredElementCollector(uiapplication.ActiveUIDocument.Document).OfClass(typeof(LoadNature)).ToElements();
foreach (Element e in elements)
{
LoadNature nature = e as LoadNature;
if (null != nature)
{
m_dataBuffer.LoadNatures.Add(nature);
LoadNaturesMap newLoadNaturesMap = new LoadNaturesMap(nature);
m_dataBuffer.LoadNaturesMap.Add(newLoadNaturesMap);
}
}
elements = new FilteredElementCollector(uiapplication.ActiveUIDocument.Document).OfClass(typeof(LoadCase)).ToElements();
foreach (Element e in elements)
{
//get all the loadcases
LoadCase loadCase = e as LoadCase;
if (null != loadCase)
{
m_dataBuffer.LoadCases.Add(loadCase);
LoadCasesMap newLoadCaseMap = new LoadCasesMap(loadCase);
m_dataBuffer.LoadCasesMap.Add(newLoadCaseMap);
}
}
}
/// <summary>
/// create some load case natures named EQ1, EQ2, W1, W2, W3, W4, Other
/// </summary>
/// <returns></returns>
private bool CreateLoadNatures()
{
//try to add some new load natures
try
{
UIApplication uiapplication = new UIApplication(m_revit);
for (int i = 0; i < m_newLoadNaturesName.Count; i++)
{
string temp = m_newLoadNaturesName[i];
uiapplication.ActiveUIDocument.Document.Create.NewLoadNature(temp);
}
}
catch (Exception e)
{
m_dataBuffer.ErrorInformation += e.ToString();
return false;
}
return true;
}
/// <summary>
/// add a new load nature
/// </summary>
/// <param name="index">the selected nature's index in the nature map</param>
/// <returns></returns>
public bool AddLoadNature(int index)
{
string natureName = null; //the load nature's name to be added
bool isUnique = false; // check if the name is unique
LoadNaturesMap myLoadNature = null;
//try to get out the loadnature from the map
try
{
myLoadNature = m_dataBuffer.LoadNaturesMap[index];
}
catch (Exception e)
{
m_dataBuffer.ErrorInformation += e.ToString();
return false;
}
//Can not get the load nature
if (null == myLoadNature)
{
m_dataBuffer.ErrorInformation += "Can't find the nature";
return false;
}
//check if the name is unique
natureName = myLoadNature.LoadNaturesName;
while (!isUnique)
{
natureName += "(1)";
isUnique = IsNatureNameUnique(natureName);
}
//try to create a load nature
try
{
UIApplication uiapplication = new UIApplication(m_revit);
LoadNature newLoadNature = uiapplication.ActiveUIDocument.Document.Create.NewLoadNature(natureName);
if (null == newLoadNature)
{
m_dataBuffer.ErrorInformation += "Create Failed";
return false;
}
//add the load nature into the list and maps
m_dataBuffer.LoadNatures.Add(newLoadNature);
LoadNaturesMap newMap = new LoadNaturesMap(newLoadNature);
m_dataBuffer.LoadNaturesMap.Add(newMap);
}
catch (Exception e)
{
m_dataBuffer.ErrorInformation += e.ToString();
return false;
}
return true;
}
/// <summary>
/// Duplicate a new load case
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public bool DuplicateLoadCase(int index)
{
LoadCasesMap myLoadCase = null;
bool isUnique = false;
string caseName = null;
//try to get the load case from the map
try
{
myLoadCase = m_dataBuffer.LoadCasesMap[index];
}
catch (Exception e)
{
m_dataBuffer.ErrorInformation += e.ToString();
return false;
}
//get nothing
if (null == myLoadCase)
{
m_dataBuffer.ErrorInformation += "Can not find the load case";
return false;
}
//check the name
caseName = myLoadCase.LoadCasesName;
while (!isUnique)
{
caseName += "(1)";
isUnique = IsCaseNameUnique(caseName);
}
//get the selected case's nature
Category caseCategory = null;
LoadNature caseNature = null;
Autodesk.Revit.DB.ElementId categoryId = myLoadCase.LoadCasesCategoryId;
Autodesk.Revit.DB.ElementId natureId = myLoadCase.LoadCasesNatureId;
UIApplication uiapplication = new UIApplication(m_revit);
caseNature = uiapplication.ActiveUIDocument.Document.get_Element(natureId) as LoadNature;
//get the selected case's category
Categories categories = uiapplication.ActiveUIDocument.Document.Settings.Categories;
Category category = categories.get_Item(BuiltInCategory.OST_LoadCases);
CategoryNameMap categoryNameMap = category.SubCategories;
System.Collections.IEnumerator iter = categoryNameMap.GetEnumerator();
iter.Reset();
while (iter.MoveNext())
{
Category tempC = iter.Current as Category;
if (null != tempC && (categoryId.IntegerValue == tempC.Id.IntegerValue))
{
caseCategory = tempC;
break;
}
}
//check if lack of the information
if (null == caseNature || null == caseCategory || null == caseName)
{
m_dataBuffer.ErrorInformation += "Can't find the load case";
return false;
}
//try to create a load case
try
{
LoadCase newLoadCase = uiapplication.ActiveUIDocument.Document.Create.NewLoadCase(caseName, caseNature, caseCategory);
if (null == newLoadCase)
{
m_dataBuffer.ErrorInformation += "Create Load Case Failed";
return false;
}
//add the new case into list and map
m_dataBuffer.LoadCases.Add(newLoadCase);
LoadCasesMap newLoadCaseMap = new LoadCasesMap(newLoadCase);
m_dataBuffer.LoadCasesMap.Add(newLoadCaseMap);
}
catch (Exception e)
{
m_dataBuffer.ErrorInformation += e.ToString();
return false;
}
return true;
}
/// <summary>
/// check if the case's name is unique
/// </summary>
/// <param name="name">the name to be checked</param>
/// <returns>true will be returned if the name is unique</returns>
public bool IsCaseNameUnique(string name)
{
//compare the name with the name of each case in the map
for (int i = 0; i < m_dataBuffer.LoadCasesMap.Count; i++)
{
string nameTemp = m_dataBuffer.LoadCasesMap[i].LoadCasesName;
if (name == nameTemp)
{
return false;
}
}
return true;
}
/// <summary>
/// check if the nature's name is unique
/// </summary>
/// <param name="name">the name to be checked</param>
/// <returns>true will be returned if the name is unique</returns>
public bool IsNatureNameUnique(string name)
{
//compare the name with the name of each nature in the map
for (int i = 0; i < m_dataBuffer.LoadNatures.Count; i++)
{
string nameTemp = m_dataBuffer.LoadNaturesMap[i].LoadNaturesName;
if (name == nameTemp)
{
return false;
}
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Opswat.Metadefender.Core.Client;
using Opswat.Metadefender.Core.Client.Exceptions;
using Newtonsoft.Json;
/**
* Main class for the REST API client
*/
namespace Opswat.Metadefender.Core.Client
{
public class MetadefenderCoreClient
{
private HttpConnector httpConnector = new HttpConnector();
private string apiEndPointUrl;
private string sessionId = null;
// default user_agent for fileScan-s
private string user_agent = null;
/**
* Constructor for the client.
* If you use this constructor, you wont be logged in. (You can use several api calls without authentication)
* @param apiEndPointUrl Format: protocol://host:port Example value: http://localhost:8008
*/
public MetadefenderCoreClient(string apiEndPointUrl)
{
this.apiEndPointUrl = apiEndPointUrl;
}
/**
* Constructs a rest client with an api key, to access protected resources.
*
* @param apiEndPointUrl Format: protocol://host:port Example value: http://localhost:8008
* @param apiKey valid api key
*/
public MetadefenderCoreClient(string apiEndPointUrl, string apiKey)
{
this.apiEndPointUrl = apiEndPointUrl;
sessionId = apiKey;
}
/**
* Constructs a rest client with an api authentication.
*
* @param apiEndPointUrl Format: protocol://host:port Example value: http://localhost:8008
* @param userName username to login with
* @param password password to login with
* @throws MetadefenderClientException if the provided user/pass is not valid.
*/
public MetadefenderCoreClient(string apiEndPointUrl, string userName, string password)
{
this.apiEndPointUrl = apiEndPointUrl;
Login(userName, password);
}
/**
* You can set your custom HttpConnector instance to use for making all the requests to the API endpoint.
* This can be handy if You want to handle special connection issues yourself.
*
* @param httpConnector your custom HttpConnector
*/
public void SetHttpConnector(HttpConnector httpConnector)
{
if (httpConnector == null)
{
throw new ArgumentNullException("httpConnector cannot be null");
}
this.httpConnector = httpConnector;
}
/**
* For setting a default user agent string for all file scan api calls.
* @param user_agent custom user agent string
*/
public void SetUserAgent(string user_agent)
{
this.user_agent = user_agent;
}
/**
* If you successfully log in with username/password you will get a session id.
*
* @return The current session id.
*/
public string GetSessionId()
{
return sessionId;
}
/**
* Initiate a new session for using protected REST APIs.
*
* @see <a href="http://software.opswat.com/metascan/Documentation/Metascan_v4/documentation/user_guide_metascan_developer_guide_login.html" target="_blank">REST API doc</a>
*
* @param userName username to login with
* @param password password to login with
* @throws MetadefenderClientException
*/
public void Login(string userName, string password)
{
Requests.Login loginRequest = new Requests.Login();
loginRequest.user = userName;
loginRequest.password = password;
string requestStr = JsonConvert.SerializeObject(loginRequest);
MemoryStream requestStream = new MemoryStream(Encoding.UTF8.GetBytes(requestStr));
HttpConnector.HttpResponse response = httpConnector.SendRequest(apiEndPointUrl + "/login", "POST", requestStream, null);
if (response.responseCode == 200)
{
try
{
Responses.Login loginResponse = JsonConvert.DeserializeObject<Responses.Login>(response.response);
if (loginResponse != null)
{
sessionId = loginResponse.session_id;
}
else
{
ThrowRequestError(response);
}
}
catch (JsonSerializationException)
{
ThrowRequestError(response);
}
}
else
{
ThrowRequestError(response);
}
}
/**
* Get the current session state.
*
* @return TRUE if the current session is valid, FALSE otherwise.
* @throws MetadefenderClientException
*/
public bool ValidateCurrentSession()
{
if (string.IsNullOrEmpty(sessionId))
{
return false;
}
HttpConnector.HttpResponse response =
httpConnector.SendRequest(apiEndPointUrl + "/version", "GET", null, GetLoggedInHeader());
return response.responseCode == 200;
}
/**
* Scan is done asynchronously and each scan request is tracked by data id of which result can be retrieved by API Fetch Scan Result.
*
* @see <a href="http://software.opswat.com/metascan/Documentation/Metascan_v4/documentation/user_guide_metascan_developer_guide_scan_file.html" target="_blank">REST API doc</a>
*
* @param inputStream Stream of data (file) to scan. Required
* @param fileScanOptions Optional file scan options. Can be NULL.
* @return unique data id for this file scan
*/
public string ScanFile(Stream inputStream, FileScanOptions fileScanOptions)
{
if (inputStream == null)
{
throw new MetadefenderClientException("Stream cannot be null");
}
if ((fileScanOptions != null && fileScanOptions.GetUserAgent() == null) && user_agent != null)
{
fileScanOptions.SetUserAgent(user_agent);
}
if (fileScanOptions == null && user_agent != null)
{
fileScanOptions = new FileScanOptions().SetUserAgent(user_agent);
}
Dictionary<string, string> headers = (fileScanOptions == null) ? null : fileScanOptions.GetOptions();
HttpConnector.HttpResponse response =
httpConnector.SendRequest(apiEndPointUrl + "/file", "POST", inputStream, headers);
if (response.responseCode == 200)
{
try
{
Responses.ScanRequest scanRequest = JsonConvert.DeserializeObject<Responses.ScanRequest>(response.response);
if (scanRequest != null)
{
return scanRequest.data_id;
}
else
{
ThrowRequestError(response);
return null;
}
}
catch (JsonSerializationException)
{
ThrowRequestError(response);
return null;
}
}
else
{
ThrowRequestError(response);
return null;
}
}
/**
* Scan file in synchron mode.
* Note: this method call will block your thread until the file scan finishes.
*
* @param inputStream input stream to scan
* @param fileScanOptions optional file scan options
* @param pollingInterval polling time in millis
* @param timeout timeout in millis
* @return FileScanResult
* @throws MetadefenderClientException
*/
public Responses.FileScanResult ScanFileSync(Stream inputStream, FileScanOptions fileScanOptions, int initialPollingInterval, int maximumPollingInterval, int timeout)
{
int pollingInterval = initialPollingInterval;
string data_id = ScanFile(inputStream, fileScanOptions);
var t = Task<Responses.FileScanResult>.Run(() =>
{
Responses.FileScanResult fileScanResult;
do
{
fileScanResult = FetchScanResult(data_id);
if (!fileScanResult.IsScanFinished())
{
Thread.Sleep(pollingInterval);
pollingInterval = Math.Min(pollingInterval * 2, maximumPollingInterval);
}
}
while (!fileScanResult.IsScanFinished());
return fileScanResult;
});
Task.WhenAny(t, Task.Delay(timeout));
if (t.Wait(timeout))
{
return t.Result;
}
else
{
throw new TimeoutException();
}
}
/**
* Retrieve scan results.
*
* @see <a href="http://software.opswat.com/metascan/Documentation/Metascan_v4/documentation/user_guide_metascan_developer_guide_fetch_scan_result.html" target="_blank"v>REST API doc</a>
*
* @param data_id Unique file scan id. Required.
* @return File scan result object
* @throws MetadefenderClientException
*/
public Responses.FileScanResult FetchScanResult(string data_id)
{
if (string.IsNullOrEmpty(data_id))
{
throw new MetadefenderClientException("data_id is required");
}
HttpConnector.HttpResponse response = httpConnector.SendRequest(apiEndPointUrl + "/file/" + data_id, "GET");
if (response.responseCode == 200)
{
return GetObjectFromJson<Responses.FileScanResult>(response.response);
}
else
{
ThrowRequestError(response);
return null;
}
}
/**
* Fetch Scan Result by File Hash
*
* @see <a href="http://software.opswat.com/metascan/Documentation/Metascan_v4/documentation/user_guide_metascan_developer_guide_fetch_scan_result_by_file_hash.html" target="_blank">REST API doc</a>
*
* @param hash {md5|sha1|sha256 hash}
* @return File scan result object
* @throws MetadefenderClientException
*/
public Responses.FileScanResult FetchScanResultByHash(string hash)
{
if (string.IsNullOrEmpty(hash))
{
throw new MetadefenderClientException("Hash is required");
}
HttpConnector.HttpResponse response = httpConnector.SendRequest(apiEndPointUrl + "/hash/" + hash, "GET");
if (response.responseCode == 200)
{
Responses.FileScanResult fileScanResult = GetObjectFromJson<Responses.FileScanResult>(response.response);
if (fileScanResult == null)
{
ThrowRequestError(response);
}
return fileScanResult;
}
else
{
ThrowRequestError(response);
return null;
}
}
/**
* You need to be logged in to access this API point.
*
* @see <a href="http://software.opswat.com/metascan/Documentation/Metascan_v4/documentation/user_guide_metascan_developer_guide_getlicense.html" target="_blank">REST API doc</a>
*
* @return License object
* @throws MetadefenderClientException
*/
public Responses.License GetCurrentLicenseInformation()
{
CheckSession();
HttpConnector.HttpResponse response = httpConnector.SendRequest(apiEndPointUrl + "/admin/license", "GET", null,
GetLoggedInHeader());
if (response.responseCode == 200)
{
return GetObjectFromJson<Responses.License>(response.response);
}
else
{
ThrowRequestError(response);
return null;
}
}
/**
* Fetching Engine/Database Versions
* The response is an array of engines with database information.
*
* @see <a href="http://software.opswat.com/metascan/Documentation/Metascan_v4/documentation/user_guide_metascan_developer_guide_fetching_engine_database_versions.html" target="_blank">REST API doc</a>
*
* @return List of Engine versions
* @throws MetadefenderClientException
*/
public List<Responses.EngineVersion> GetEngineVersions()
{
HttpConnector.HttpResponse response = httpConnector.SendRequest(apiEndPointUrl + "/stat/engines", "GET");
if (response.responseCode == 200)
{
return GetObjectFromJson<List<Responses.EngineVersion>>(response.response);
}
else
{
ThrowRequestError(response);
return null;
}
}
/**
* You need to be logged in to access this API point.
*
* @return ApiVersion object
* @throws MetadefenderClientException
*/
public Responses.ApiVersion GetVersion()
{
CheckSession();
HttpConnector.HttpResponse response =
httpConnector.SendRequest(apiEndPointUrl + "/version", "GET", null, GetLoggedInHeader());
if (response.responseCode == 200)
{
return GetObjectFromJson<Responses.ApiVersion>(response.response);
}
else
{
ThrowRequestError(response);
return null;
}
}
/**
* Fetching Available Scan Rules
*
* @see <a href="http://software.opswat.com/metascan/Documentation/Metascan_v4/documentation/user_guide_metascan_developer_guide_fetching_available_scan_workflows.html" target="_blank">REST API doc</a>
*
* @return List of Scan rules
* @throws MetadefenderClientException
*/
public List<Responses.ScanRule> GetAvailableScanRules()
{
HttpConnector.HttpResponse response = httpConnector.SendRequest(apiEndPointUrl + "/file/rules", "GET");
if (response.responseCode == 200)
{
return GetObjectFromJson<List<Responses.ScanRule>>(response.response);
}
else
{
ThrowRequestError(response);
return null;
}
}
/**
* You need to be logged in to access this API point.
*
* Destroy session for not using protected REST APIs.
*
* @see <a href="http://software.opswat.com/metascan/Documentation/Metascan_v4/documentation/user_guide_metascan_developer_guide_logout.html" target="_blank">REST API doc</a>
* @throws MetadefenderClientException
*/
public void Logout()
{
CheckSession();
HttpConnector.HttpResponse response =
httpConnector.SendRequest(apiEndPointUrl + "/logout", "POST", null, GetLoggedInHeader());
sessionId = null;
if (response.responseCode != 200)
{
ThrowRequestError(response);
}
}
//////// Private utils methods:
private Dictionary<string, string> GetLoggedInHeader()
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers["apikey"] = sessionId;
return headers;
}
/**
* Generic error handling for API request where response code != 200
* @param response actual API response
* @throws MetadefenderClientException
*/
private void ThrowRequestError(HttpConnector.HttpResponse response)
{
try
{
Responses.Error error = JsonConvert.DeserializeObject<Responses.Error>(response.response);
if (error != null)
{
throw new MetadefenderClientException(error.err, response.responseCode);
}
else
{
throw new MetadefenderClientException("", response.responseCode);
}
}
catch (JsonSerializationException)
{
throw new MetadefenderClientException("", response.responseCode);
}
}
/**
* Reusable util method for current session exist check
* @throws MetadefenderClientException if session is empty
*/
private void CheckSession()
{
if (string.IsNullOrEmpty(sessionId))
{
throw new MetadefenderClientException("You need to be logged in to access this API point.");
}
}
private T GetObjectFromJson<T>(string json) where T : class
{
try
{
T ret = JsonConvert.DeserializeObject<T>(json);
if (ret != null)
{
return ret;
}
else
{
throw new MetadefenderClientException("Error serializing Json: " + json);
}
}
catch (JsonSerializationException e)
{
throw new MetadefenderClientException("Error: " + e.Message + " Json: " + json);
}
}
}
}
| |
//
// NowPlayingContents.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.ServiceStack;
using Hyena;
namespace Banshee.NowPlaying
{
public class NowPlayingContents : Table, IDisposable
{
private static Widget video_display;
public static void CreateVideoDisplay ()
{
if (video_display == null) {
video_display = new XOverlayVideoDisplay ();
}
}
private Widget substitute_audio_display;
private bool video_display_initial_shown = false;
private EventBox video_event;
private TrackInfoDisplay track_info_display;
public NowPlayingContents () : base (1, 1, false)
{
NoShowAll = true;
CreateVideoDisplay ();
video_event = new EventBox ();
video_event.VisibleWindow = false;
video_event.CanFocus = true;
video_event.AboveChild = true;
video_event.Add (video_display);
video_event.Events |= Gdk.EventMask.PointerMotionMask |
Gdk.EventMask.ButtonPressMask |
Gdk.EventMask.ButtonMotionMask |
Gdk.EventMask.KeyPressMask |
Gdk.EventMask.KeyReleaseMask;
//TODO stop tracking mouse when no more in menu
video_event.ButtonPressEvent += OnButtonPress;
video_event.ButtonReleaseEvent += OnButtonRelease;
video_event.MotionNotifyEvent += OnMouseMove;
video_event.KeyPressEvent += OnKeyPress;
IVideoDisplay ivideo_display = video_display as IVideoDisplay;
if (ivideo_display != null) {
ivideo_display.IdleStateChanged += OnVideoDisplayIdleStateChanged;
}
Attach (video_event, 0, 1, 0, 1,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Expand | AttachOptions.Fill, 0, 0);
track_info_display = new NowPlayingTrackInfoDisplay ();
Attach (track_info_display, 0, 1, 0, 1,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Expand | AttachOptions.Fill, 0, 0);
video_event.ShowAll ();
}
internal void SetSubstituteAudioDisplay (Widget widget)
{
if (substitute_audio_display != null) {
Remove (substitute_audio_display);
}
substitute_audio_display = widget;
if (widget != null) {
Attach (widget, 0, 1, 0, 1,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Expand | AttachOptions.Fill, 0, 0);
}
CheckIdle ();
}
public override void Dispose ()
{
video_event.ButtonPressEvent -= OnButtonPress;
video_event.ButtonReleaseEvent -= OnButtonRelease;
video_event.MotionNotifyEvent -= OnMouseMove;
video_event.KeyPressEvent -= OnKeyPress;
IVideoDisplay ivideo_display = video_display as IVideoDisplay;
if (ivideo_display != null) {
ivideo_display.IdleStateChanged -= OnVideoDisplayIdleStateChanged;
}
if (video_display != null) {
video_display = null;
}
base.Dispose ();
}
protected override void OnShown ()
{
base.OnShown ();
video_event.GrabFocus ();
// Ugly hack to ensure the video window is mapped/realized
if (!video_display_initial_shown) {
video_display_initial_shown = true;
if (video_display != null) {
video_display.Show ();
}
GLib.Idle.Add (delegate {
CheckIdle ();
return false;
});
return;
}
CheckIdle ();
}
protected override void OnHidden ()
{
base.OnHidden ();
video_display.Hide ();
}
private void CheckIdle ()
{
IVideoDisplay ivideo_display = video_display as IVideoDisplay;
if (ivideo_display != null) {
video_display.Visible = !ivideo_display.IsIdle;
}
track_info_display.Visible = false;
(substitute_audio_display ?? track_info_display).Visible = ivideo_display.IsIdle;
}
private void OnVideoDisplayIdleStateChanged (object o, EventArgs args)
{
CheckIdle ();
}
[GLib.ConnectBefore]
void OnMouseMove (object o, MotionNotifyEventArgs args)
{
if (ServiceManager.PlayerEngine.InDvdMenu) {
ServiceManager.PlayerEngine.NotifyMouseMove (args.Event.X, args.Event.Y);
}
}
[GLib.ConnectBefore]
void OnButtonPress (object o, ButtonPressEventArgs args)
{
switch (args.Event.Type) {
case Gdk.EventType.TwoButtonPress:
var iaservice = ServiceManager.Get<InterfaceActionService> ();
var action = iaservice.ViewActions["FullScreenAction"] as Gtk.ToggleAction;
if (action != null && action.Sensitive) {
action.Active = !action.Active;
}
break;
case Gdk.EventType.ButtonPress:
video_event.GrabFocus ();
if (ServiceManager.PlayerEngine.InDvdMenu) {
ServiceManager.PlayerEngine.NotifyMouseButtonPressed ((int)args.Event.Button, args.Event.X, args.Event.Y);
}
break;
}
}
[GLib.ConnectBefore]
void OnButtonRelease (object o, ButtonReleaseEventArgs args)
{
switch (args.Event.Type) {
case Gdk.EventType.ButtonRelease:
if (ServiceManager.PlayerEngine.InDvdMenu) {
ServiceManager.PlayerEngine.NotifyMouseButtonReleased ((int)args.Event.Button, args.Event.X, args.Event.Y);
}
break;
}
}
[GLib.ConnectBefore]
void OnKeyPress (object o, KeyPressEventArgs args)
{
if (!ServiceManager.PlayerEngine.InDvdMenu) {
return;
}
switch (args.Event.Key) {
case Gdk.Key.leftarrow:
case Gdk.Key.KP_Left:
case Gdk.Key.Left:
ServiceManager.PlayerEngine.NavigateToLeftMenu ();
args.RetVal = true;
break;
case Gdk.Key.rightarrow:
case Gdk.Key.KP_Right:
case Gdk.Key.Right:
ServiceManager.PlayerEngine.NavigateToRightMenu ();
args.RetVal = true;
break;
case Gdk.Key.uparrow:
case Gdk.Key.KP_Up:
case Gdk.Key.Up:
ServiceManager.PlayerEngine.NavigateToUpMenu ();
args.RetVal = true;
break;
case Gdk.Key.downarrow:
case Gdk.Key.KP_Down:
case Gdk.Key.Down:
ServiceManager.PlayerEngine.NavigateToDownMenu ();
args.RetVal = true;
break;
case Gdk.Key.Break:
case Gdk.Key.KP_Enter:
case Gdk.Key.Return:
ServiceManager.PlayerEngine.ActivateCurrentMenu ();
args.RetVal = true;
break;
}
}
}
}
| |
using FluentMigrator.Runner.Generators.DB2;
using FluentMigrator.Runner.Generators.DB2.iSeries;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.Db2
{
[TestFixture]
public class Db2TableTests : BaseTableTests
{
protected Db2Generator Generator;
[SetUp]
public void Setup()
{
Generator = new Db2Generator(new Db2ISeriesQuoter());
}
[Test]
public override void CanCreateTableWithCustomColumnTypeWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[1].Type = null;
expression.Columns[1].CustomType = "json";
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 json NOT NULL, PRIMARY KEY (TestColumn1))");
}
[Test]
public override void CanCreateTableWithCustomColumnTypeWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[1].Type = null;
expression.Columns[1].CustomType = "json";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 json NOT NULL, PRIMARY KEY (TestColumn1))");
}
[Test]
public override void CanCreateTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultValueExplicitlySetToNullWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
expression.Columns[0].DefaultValue = null;
expression.Columns[0].TableName = expression.TableName;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL DEFAULT NULL, TestColumn2 INTEGER NOT NULL DEFAULT 0)");
}
[Test]
public override void CanCreateTableWithDefaultValueExplicitlySetToNullWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
expression.Columns[0].DefaultValue = null;
expression.Columns[0].TableName = expression.TableName;
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL DEFAULT NULL, TestColumn2 INTEGER NOT NULL DEFAULT 0)");
}
[Test]
public override void CanCreateTableWithDefaultValueWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL DEFAULT 'Default', TestColumn2 INTEGER NOT NULL DEFAULT 0)");
}
[Test]
public override void CanCreateTableWithIdentityWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithAutoIncrementExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 INTEGER NOT NULL AS IDENTITY, TestColumn2 INTEGER NOT NULL)");
}
[Test]
public override void CanCreateTableWithIdentityWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithAutoIncrementExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 INTEGER NOT NULL AS IDENTITY, TestColumn2 INTEGER NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultValueWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL DEFAULT 'Default', TestColumn2 INTEGER NOT NULL DEFAULT 0)");
}
[Test]
public override void CanCreateTableWithMultiColumnPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithMultiColumnPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL, PRIMARY KEY (TestColumn1, TestColumn2))");
}
[Test]
public override void CanCreateTableWithMultiColumnPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL, PRIMARY KEY (TestColumn1, TestColumn2))");
}
[Test]
public override void CanCreateTableWithNamedMultiColumnPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedMultiColumnPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL, CONSTRAINT TestKey PRIMARY KEY (TestColumn1, TestColumn2))");
}
[Test]
public override void CanCreateTableWithNamedMultiColumnPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL, CONSTRAINT TestKey PRIMARY KEY (TestColumn1, TestColumn2))");
}
[Test]
public override void CanCreateTableWithNamedPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL, CONSTRAINT TestKey PRIMARY KEY (TestColumn1))");
}
[Test]
public override void CanCreateTableWithNamedPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL, CONSTRAINT TestKey PRIMARY KEY (TestColumn1))");
}
[Test]
public override void CanCreateTableWithNullableFieldWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNullableColumn();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200, TestColumn2 INTEGER NOT NULL)");
}
[Test]
public override void CanCreateTableWithNullableFieldWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNullableColumn();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200, TestColumn2 INTEGER NOT NULL)");
}
[Test]
public override void CanCreateTableWithPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestSchema.TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL, PRIMARY KEY (TestColumn1))");
}
[Test]
public override void CanCreateTableWithPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE TestTable1 (TestColumn1 DBCLOB(1048576) CCSID 1200 NOT NULL, TestColumn2 INTEGER NOT NULL, PRIMARY KEY (TestColumn1))");
}
[Test]
public override void CanDropTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("DROP TABLE TestSchema.TestTable1");
}
[Test]
public override void CanDropTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("DROP TABLE TestTable1");
}
[Test]
public override void CanRenameTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetRenameTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("RENAME TABLE TestSchema.TestTable1 TO TestTable2");
}
[Test]
public override void CanRenameTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetRenameTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("RENAME TABLE TestTable1 TO TestTable2");
}
}
}
| |
//
// Copyright (c) 2004-2017 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.
//
using System.Collections;
using System.Linq;
using System.Threading;
using NLog.LayoutRenderers;
using System.Xml;
using NLog.Config;
using NLog.UnitTests.LayoutRenderers;
#if !NETSTANDARD
namespace NLog.UnitTests
{
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.CSharp;
using Xunit;
using NLog.Layouts;
using System.Collections.Generic;
public class ConfigFileLocatorTests : NLogTestBase
{
private string appConfigContents = @"
<configuration>
<configSections>
<section name='nlog' type='NLog.Config.ConfigSectionHandler, NLog' requirePermission='false' />
</configSections>
<nlog>
<targets>
<target name='c' type='Console' layout='AC ${message}' />
</targets>
<rules>
<logger name='*' minLevel='Info' writeTo='c' />
</rules>
</nlog>
</configuration>
";
private string appNLogContents = @"
<nlog>
<targets>
<target name='c' type='Console' layout='AN ${message}' />
</targets>
<rules>
<logger name='*' minLevel='Info' writeTo='c' />
</rules>
</nlog>
";
private string nlogConfigContents = @"
<nlog>
<targets>
<target name='c' type='Console' layout='NLC ${message}' />
</targets>
<rules>
<logger name='*' minLevel='Info' writeTo='c' />
</rules>
</nlog>
";
private string nlogDllNLogContents = @"
<nlog>
<targets>
<target name='c' type='Console' layout='NDN ${message}' />
</targets>
<rules>
<logger name='*' minLevel='Info' writeTo='c' />
</rules>
</nlog>
";
private string appConfigOutput = "--BEGIN--|AC InfoMsg|AC WarnMsg|AC ErrorMsg|AC FatalMsg|--END--|";
private string appNLogOutput = "--BEGIN--|AN InfoMsg|AN WarnMsg|AN ErrorMsg|AN FatalMsg|--END--|";
private string nlogConfigOutput = "--BEGIN--|NLC InfoMsg|NLC WarnMsg|NLC ErrorMsg|NLC FatalMsg|--END--|";
private string nlogDllNLogOutput = "--BEGIN--|NDN InfoMsg|NDN WarnMsg|NDN ErrorMsg|NDN FatalMsg|--END--|";
private string missingConfigOutput = "--BEGIN--|--END--|";
private readonly string _tempDirectory;
public ConfigFileLocatorTests()
{
_tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_tempDirectory);
}
[Fact]
public void MissingConfigFileTest()
{
string output = RunTest();
Assert.Equal(missingConfigOutput, output);
}
[Fact]
public void NLogDotConfigTest()
{
File.WriteAllText(Path.Combine(_tempDirectory, "NLog.config"), nlogConfigContents);
string output = RunTest();
Assert.Equal(nlogConfigOutput, output);
}
[Fact]
public void NLogDotDllDotNLogTest()
{
File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents);
string output = RunTest();
Assert.Equal(nlogDllNLogOutput, output);
}
[Fact]
public void NLogDotDllDotNLogInDirectoryWithSpaces()
{
File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents);
string output = RunTest();
Assert.Equal(nlogDllNLogOutput, output);
}
[Fact]
public void AppDotConfigTest()
{
File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.config"), appConfigContents);
string output = RunTest();
Assert.Equal(appConfigOutput, output);
}
[Fact]
public void AppDotNLogTest()
{
File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.nlog"), appNLogContents);
string output = RunTest();
Assert.Equal(appNLogOutput, output);
}
[Fact]
public void PrecedenceTest()
{
var precedence = new[]
{
new
{
File = "ConfigFileLocator.exe.config",
Contents = appConfigContents,
Output = appConfigOutput
},
new
{
File = "NLog.config",
Contents = nlogConfigContents,
Output = nlogConfigOutput
},
new
{
File = "ConfigFileLocator.exe.nlog",
Contents = appNLogContents,
Output = appNLogOutput
},
new
{
File = "NLog.dll.nlog",
Contents = nlogDllNLogContents,
Output = nlogDllNLogOutput
},
};
// deploy all files
foreach (var p in precedence)
{
File.WriteAllText(Path.Combine(_tempDirectory, p.File), p.Contents);
}
string output;
// walk files in precedence order and delete config files
foreach (var p in precedence)
{
output = RunTest();
Assert.Equal(p.Output, output);
File.Delete(Path.Combine(_tempDirectory, p.File));
}
output = RunTest();
Assert.Equal(missingConfigOutput, output);
}
[Fact]
void FuncLayoutRendererRegisterTest1()
{
LayoutRenderer.Register("the-answer", (info) => "42");
Layout l = "${the-answer}";
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("42", result);
}
[Fact]
void FuncLayoutRendererRegisterTest1WithXML()
{
LayoutRenderer.Register("the-answer", (info) => "42");
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<targets>
<target name='debug' type='Debug' layout= '${the-answer}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetCurrentClassLogger();
logger.Debug("test1");
AssertDebugLastMessage("debug", "42");
}
[Fact]
void FuncLayoutRendererRegisterTest2()
{
LayoutRenderer.Register("message-length", (info) => info.Message.Length);
Layout l = "${message-length}";
var result = l.Render(LogEventInfo.Create(LogLevel.Error, "logger-adhoc", "1234567890"));
Assert.Equal("10", result);
}
[Fact]
public void GetCandidateConfigTest()
{
Assert.NotNull(XmlLoggingConfiguration.GetCandidateConfigFilePaths());
var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths();
var count = candidateConfigFilePaths.Count();
Assert.True(count > 0);
}
[Fact]
public void GetCandidateConfigTest_list_is_readonly()
{
Assert.Throws<NotSupportedException>(() =>
{
var list = new List<string> { "c:\\global\\temp.config" };
XmlLoggingConfiguration.SetCandidateConfigFilePaths(list);
var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths();
var list2 = candidateConfigFilePaths as IList;
list2.Add("test");
});
}
[Fact]
public void SetCandidateConfigTest()
{
var list = new List<string> { "c:\\global\\temp.config" };
XmlLoggingConfiguration.SetCandidateConfigFilePaths(list);
Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths());
//no side effects
list.Add("c:\\global\\temp2.config");
Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths());
}
[Fact]
public void ResetCandidateConfigTest()
{
var countBefore = XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count();
var list = new List<string> { "c:\\global\\temp.config" };
XmlLoggingConfiguration.SetCandidateConfigFilePaths(list);
Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths());
XmlLoggingConfiguration.ResetCandidateConfigFilePath();
Assert.Equal(countBefore, XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count());
}
private string RunTest()
{
string sourceCode = @"
using System;
using System.Reflection;
using NLog;
class C1
{
private static ILogger logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
Console.WriteLine(""--BEGIN--"");
logger.Trace(""TraceMsg"");
logger.Debug(""DebugMsg"");
logger.Info(""InfoMsg"");
logger.Warn(""WarnMsg"");
logger.Error(""ErrorMsg"");
logger.Fatal(""FatalMsg"");
Console.WriteLine(""--END--"");
}
}";
var provider = new CSharpCodeProvider();
var options = new CompilerParameters();
options.OutputAssembly = Path.Combine(_tempDirectory, "ConfigFileLocator.exe");
options.GenerateExecutable = true;
options.ReferencedAssemblies.Add(typeof(ILogger).Assembly.Location);
options.IncludeDebugInformation = true;
if (!File.Exists(options.OutputAssembly))
{
var results = provider.CompileAssemblyFromSource(options, sourceCode);
Assert.False(results.Errors.HasWarnings);
Assert.False(results.Errors.HasErrors);
File.Copy(typeof(ILogger).Assembly.Location, Path.Combine(_tempDirectory, "NLog.dll"));
}
return RunAndRedirectOutput(options.OutputAssembly);
}
public static string RunAndRedirectOutput(string exeFile)
{
using (var proc = new Process())
{
#if MONO
var sb = new StringBuilder();
sb.AppendFormat("\"{0}\" ", exeFile);
proc.StartInfo.Arguments = sb.ToString();
proc.StartInfo.FileName = "mono";
proc.StartInfo.StandardOutputEncoding = Encoding.UTF8;
proc.StartInfo.StandardErrorEncoding = Encoding.UTF8;
#else
proc.StartInfo.FileName = exeFile;
#endif
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
proc.StartInfo.RedirectStandardInput = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();
Assert.Equal(string.Empty, proc.StandardError.ReadToEnd());
return proc.StandardOutput.ReadToEnd().Replace("\r", "").Replace("\n", "|");
}
}
}
}
#endif
| |
using System;
using System.Collections;
/// <summary>
/// System.Math.Log(System.Double)
/// </summary>
public class MathLog
{
public static int Main(string[] args)
{
MathLog log = new MathLog();
TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Log(System.Double)...");
if (log.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the monotonicity of ln(d)...");
try
{
double var1 = 100.1 * TestLibrary.Generator.GetDouble(-55);
double var2 = 100.1 * TestLibrary.Generator.GetDouble(-55);
if (var1 < var2)
{
if (Math.Log(var1) >= Math.Log(var2))
{
TestLibrary.TestFramework.LogError("001", "The value of ln(var1)=" + Math.Log(var1).ToString() +
" should be less than ln(var2)=" + Math.Log(var2).ToString());
retVal = false;
}
}
else if (var1 > var2)
{
if (Math.Log(var1) <= Math.Log(var2))
{
TestLibrary.TestFramework.LogError("002", "The value of ln(var1)=" + Math.Log(var1).ToString() +
" should be larger than ln(var2)=" + Math.Log(var2).ToString());
retVal = false;
}
}
else
{
if (!MathTestLib.DoubleIsWithinEpsilon(Math.Log(var1) ,Math.Log(var2)))
{
TestLibrary.TestFramework.LogError("003", "The value of ln(var1)=" + Math.Log(var1).ToString() +
" should be equal to ln(var2)=" + Math.Log(var2).ToString());
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004","Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the value is negative when var is between o and 1...");
try
{
double var = 0;
while (var <= 0 && var >= 1)
{
var = TestLibrary.Generator.GetDouble(-55);
}
if (Math.Log(var) >= 0)
{
TestLibrary.TestFramework.LogError("005", "The value should be negative, is " + Math.Log(var).ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006","Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify the value of ln(1) is 0...");
try
{
double var = 1;
if (!MathTestLib.DoubleIsWithinEpsilon(Math.Log(var),0))
{
TestLibrary.TestFramework.LogError("007", "The value of ln(1) should be zero, is " + Math.Log(var).ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008","Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify the value of ln(var) is larger than zero...");
try
{
double var = TestLibrary.Generator.GetDouble(-55);
while (var <= 1)
{
var *= 10 ;
}
if (Math.Log(var) < 0)
{
TestLibrary.TestFramework.LogError("009", "The value should be larger than zero, is " + Math.Log(var).ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010","Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify the value of ln(0)...");
try
{
double var = 0;
if (!double.IsNegativeInfinity(Math.Log(var)))
{
TestLibrary.TestFramework.LogError("011", "the value of ln(0) should be negativeInfinity, is " +
Math.Log(var).ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012","Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the value of ln(var) when var is negative...");
try
{
double var = -TestLibrary.Generator.GetDouble(-55);
while (var >= 0)
{
var = TestLibrary.Generator.GetDouble(-55);
}
if (!double.IsNaN(Math.Log(var)))
{
TestLibrary.TestFramework.LogError("013", "The value should be NaN, is " + Math.Log(var).ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014","Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the value of ln(e)...");
try
{
double var = Math.E;
if (!MathTestLib.DoubleIsWithinEpsilon(Math.Log(var) ,1))
{
TestLibrary.TestFramework.LogError("015", "The value should be equal to 1, is " + Math.Log(var).ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016","Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
}
| |
// 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 TestMixOnesZerosUInt16()
{
var test = new BooleanTwoComparisonOpTest__TestMixOnesZerosUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local 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 BooleanTwoComparisonOpTest__TestMixOnesZerosUInt16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt16);
private const int Op2ElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector128<UInt16> _clsVar1;
private static Vector128<UInt16> _clsVar2;
private Vector128<UInt16> _fld1;
private Vector128<UInt16> _fld2;
private BooleanTwoComparisonOpTest__DataTable<UInt16, UInt16> _dataTable;
static BooleanTwoComparisonOpTest__TestMixOnesZerosUInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
}
public BooleanTwoComparisonOpTest__TestMixOnesZerosUInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new BooleanTwoComparisonOpTest__DataTable<UInt16, UInt16>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestMixOnesZeros(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestMixOnesZeros(
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestMixOnesZeros(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestMixOnesZeros(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var result = Sse41.TestMixOnesZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse41.TestMixOnesZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse41.TestMixOnesZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanTwoComparisonOpTest__TestMixOnesZerosUInt16();
var result = Sse41.TestMixOnesZeros(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestMixOnesZeros(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> left, Vector128<UInt16> right, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
if (((expectedResult1 == false) && (expectedResult2 == false)) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestMixOnesZeros)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System;
public class Shadow : MonoBehaviour {
public Material m;
private double size;
private double centre;
private int numPoints = 50;
private double delay = 1000/60;
public double maxVariation;
private double wiggle = 0.002d;
private double wiggleLim = 0.05d;
private int updateCount = 0;
private double exagDir;
private double exagAmnt = .01d;
private int updateLim = 120;
private double exagRange = (System.Math.PI / 10) / 2;
private List<Point> points = new List<Point>();
private int maxWiggles = 30;
public void meshInit() {
Vector2[] vertices = new Vector2[points.Count + 4];
int j = 0;
for (; j < points.Count; j++) {
Point p = points[j];
double x = centre - Math.Cos (p.getTheta()) * p.getRad();
double y = -Camera.main.orthographicSize - Camera.main.orthographicSize * 0.05d + (Math.Sin (p.getTheta()) * p.getRad());
vertices[j] = new Vector2((float)x,(float) y);
}
vertices [j++] = new Vector2 ((float)+ size,(float) -size);
vertices [j++] = new Vector2 ((float)size, (float)size);
vertices [j++] = new Vector2 ((float)- size, (float)size);
vertices [j++] = new Vector2 ((float)- size, (float)- size);
Triangulator t = new Triangulator (vertices);
int[] indices = t.Triangulate ();
Vector3[] v3 = new Vector3[vertices.Length];
for (int i = 0; i < v3.Length; i++) {
v3[i] = new Vector3(vertices[i].x, vertices[i].y, 0);
}
Mesh m = new Mesh ();
m.vertices = v3;
m.triangles = indices;
m.RecalculateNormals ();
m.RecalculateBounds ();
//Add to stuff
this.GetComponent<MeshFilter> ().mesh = m;
}
public List<Point> getPoints() {
return points;
}
void pointsInit() {
double lim = System.Math.Max (size, size) / 2;
double increment = Math.PI / (numPoints - 1);
for (int i = 0; i < numPoints; i++) {
points.Add (new Point (increment * i, lim));
}
}
public bool isInScreen(Vector2 v) {
float height = Camera.main.orthographicSize;
float width = height * Camera.main.aspect;
float x = v.x;
float y = v.y;
if (x > -width && x < width) {
if (y > - height && y < height) {
return true;
}
}
return false;
}
// Use this for initialization
void Start () {
maxVariation = 0.03d / delay;
maxVariation = maxVariation + Application.loadedLevel / 30;
GetComponent<Renderer> ().material.shader = Shader.Find ("Transparent/Diffuse");
GetComponent<Renderer> ().material = m;
GetComponent<Renderer> ().material.color = new Color (0.1f, 0.1f, 0.1f, 1f);
GetComponent<Renderer> ().sortingLayerID = GetComponent<Transform>().parent.GetComponent<Renderer>().sortingLayerID;
Camera cam = Camera.main;
float height = 2f * cam.orthographicSize;
float width = height * cam.aspect;
size = Math.Max (width, height);
centre = 0;
pointsInit ();
setExagDir ();
meshInit ();
}
void setExagDir() {
System.Random rand = new System.Random();
exagDir = rand.NextDouble () * Math.PI;
}
public float getBlackAverage(){
float totalRadius = 0;
for(int i = 0; i < points.Count; ++i){
totalRadius += (float)points[i].getRad();
}
totalRadius = totalRadius / points.Count;
float maxRad = (float)size / 1.35f;
return 100f / maxRad * totalRadius;
}
// Update is called once per frame
void Update () {
if (GameObject.Find ("Main Camera").GetComponent<SkyColouring> ().ready) {
System.Random rand = new System.Random ();
if (updateCount++ > updateLim) {
updateCount = rand.Next (updateLim - updateLim / 10);
setExagDir ();
}
for (int i = 0; i < points.Count; i++) {
Point p = points [i];
double theta = p.getTheta ();
if (theta < exagDir - exagRange || theta > exagDir + exagRange) {
p.setRad (p.getRad () - p.getRad () * rand.NextDouble () * maxVariation);
} else {
double amnt;
if (theta < exagDir) {
amnt = (theta - (exagDir - exagRange)) / exagRange;
} else {
amnt = ((exagDir + exagRange) - theta) / exagRange;
}
p.setRad (p.getRad () - p.getRad () * rand.NextDouble () * exagAmnt * amnt);
}
//Wiggles
double wiggleAmnt = wiggle * rand.NextDouble ();
if (System.Math.Abs (p.getDrawOffset ()) + p.getRad () > p.getRad () + p.getRad () * wiggleLim) {
p.setWiggleCount (0);
if (p.getDrawOffset () > 0) {
p.setDrawOffset (p.getDrawOffset () - p.getRad () * wiggleAmnt);
} else {
p.setDrawOffset (p.getDrawOffset () + p.getRad () * wiggleAmnt);
}
p.setWiggleOutwards (!p.isWiggleOutwards ());
} else {
if (p.isWiggleOutwards ()) {
p.setDrawOffset (p.getDrawOffset () + p.getRad () * wiggleAmnt);
} else {
p.setDrawOffset (p.getDrawOffset () - p.getRad () * wiggleAmnt);
}
}
p.setWiggleCount (p.getWiggleCount () + 1);
if (p.getWiggleCount () > maxWiggles) {
p.setWiggleOutwards (!p.isWiggleOutwards ());
p.setWiggleCount (rand.Next (maxWiggles - 5));
}
}
Mesh m = GetComponent<MeshFilter> ().mesh;
Vector3[] v3 = m.vertices;
//Update the mesh
Vector2[] vertices = new Vector2[v3.Length];
int j = 0;
for (; j < points.Count; j++) {
Point p = points [j];
double x = centre - Math.Cos (p.getTheta ()) * (p.getRad () + p.getDrawOffset ());
double y = -Camera.main.orthographicSize - Camera.main.orthographicSize * 0.05d + (Math.Sin (p.getTheta ()) * (p.getRad () + p.getDrawOffset ()));
vertices [j] = new Vector2 ((float)x, (float)y);
}
vertices [j++] = new Vector2 ((float)+ size, (float)-size);
vertices [j++] = new Vector2 ((float)size, (float)size);
vertices [j++] = new Vector2 ((float)- size, (float)size);
vertices [j++] = new Vector2 ((float)- size, (float)- size);
Triangulator t = new Triangulator (vertices);
int[] indices = t.Triangulate ();
for (int i = 0; i < v3.Length; i++) {
v3 [i] = new Vector3 (vertices [i].x, vertices [i].y, 0);
}
m.vertices = v3;
m.triangles = indices;
m.RecalculateNormals ();
m.RecalculateBounds ();
}
}
public void pushback(){
for (int i = 0; i < points.Count; i++) {
double newRad = points[i].getRad () + size * 0.075d;
if (newRad >= size) {
newRad = size;
}
points[i].setRad(newRad);
}
}
}
public class Point {
double theta;
double rad ;
double drawOffset ;
int wiggleCount;
bool wiggleOutwards;
public Point(double theta, double rad) {
this.theta = theta;
this.rad = rad;
this.drawOffset = 0;
System.Random rand = new System.Random ();
wiggleOutwards = rand.Next (2) == 1;
wiggleCount = 0;
}
public double getX() {
return -Math.Cos (getTheta()) * (getRad () + getDrawOffset());
}
public double getY() {
return -Camera.main.orthographicSize + (Math.Sin (getTheta()) * (getRad() + getDrawOffset()));
}
public double getTheta() {
return theta;
}
public void setTheta(double theta) {
this.theta = theta;
}
public double getRad() {
return rad;
}
public void setRad(double rad) {
this.rad = rad;
}
public bool isWiggleOutwards() {
return wiggleOutwards;
}
public void setWiggleOutwards(bool wiggleOutwards) {
this.wiggleOutwards = wiggleOutwards;
}
public int getWiggleCount() {
return wiggleCount;
}
public void setWiggleCount(int wiggleCount) {
this.wiggleCount = wiggleCount;
}
public double getDrawOffset() {
return drawOffset;
}
public void setDrawOffset(double drawOffset) {
this.drawOffset = drawOffset;
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Base for handling both client side and server side calls.
/// Handles native call lifecycle and provides convenience methods.
/// </summary>
internal abstract class AsyncCallBase<TWrite, TRead>
{
readonly Func<TWrite, byte[]> serializer;
readonly Func<byte[], TRead> deserializer;
protected readonly CompletionCallbackDelegate sendFinishedHandler;
protected readonly CompletionCallbackDelegate readFinishedHandler;
protected readonly CompletionCallbackDelegate halfclosedHandler;
protected readonly object myLock = new object();
protected GCHandle gchandle;
protected CallSafeHandle call;
protected bool disposed;
protected bool started;
protected bool errorOccured;
protected bool cancelRequested;
protected AsyncCompletionDelegate sendCompletionDelegate; // Completion of a pending send or sendclose if not null.
protected bool readPending; // True if there is a read in progress.
protected bool readingDone;
protected bool halfcloseRequested;
protected bool halfclosed;
protected bool finished; // True if close has been received from the peer.
// Streaming reads will be delivered to this observer. For a call that only does unary read it may remain null.
protected IObserver<TRead> readObserver;
public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer)
{
this.serializer = Preconditions.CheckNotNull(serializer);
this.deserializer = Preconditions.CheckNotNull(deserializer);
this.sendFinishedHandler = CreateBatchCompletionCallback(HandleSendFinished);
this.readFinishedHandler = CreateBatchCompletionCallback(HandleReadFinished);
this.halfclosedHandler = CreateBatchCompletionCallback(HandleHalfclosed);
}
/// <summary>
/// Requests cancelling the call.
/// </summary>
public void Cancel()
{
lock (myLock)
{
Preconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.Cancel();
}
}
}
/// <summary>
/// Requests cancelling the call with given status.
/// </summary>
public void CancelWithStatus(Status status)
{
lock (myLock)
{
Preconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.CancelWithStatus(status);
}
}
}
protected void InitializeInternal(CallSafeHandle call)
{
lock (myLock)
{
// Make sure this object and the delegated held by it will not be garbage collected
// before we release this handle.
gchandle = GCHandle.Alloc(this);
this.call = call;
}
}
/// <summary>
/// Initiates sending a message. Only once send operation can be active at a time.
/// completionDelegate is invoked upon completion.
/// </summary>
protected void StartSendMessageInternal(TWrite msg, AsyncCompletionDelegate completionDelegate)
{
byte[] payload = UnsafeSerialize(msg);
lock (myLock)
{
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckSendingAllowed();
call.StartSendMessage(payload, sendFinishedHandler);
sendCompletionDelegate = completionDelegate;
}
}
/// <summary>
/// Requests receiving a next message.
/// </summary>
protected void StartReceiveMessage()
{
lock (myLock)
{
Preconditions.CheckState(started);
Preconditions.CheckState(!disposed);
Preconditions.CheckState(!errorOccured);
Preconditions.CheckState(!readingDone);
Preconditions.CheckState(!readPending);
call.StartReceiveMessage(readFinishedHandler);
readPending = true;
}
}
/// <summary>
/// Default behavior just completes the read observer, but more sofisticated behavior might be required
/// by subclasses.
/// </summary>
protected virtual void CompleteReadObserver()
{
FireReadObserverOnCompleted();
}
/// <summary>
/// If there are no more pending actions and no new actions can be started, releases
/// the underlying native resources.
/// </summary>
protected bool ReleaseResourcesIfPossible()
{
if (!disposed && call != null)
{
if (halfclosed && readingDone && finished)
{
ReleaseResources();
return true;
}
}
return false;
}
private void ReleaseResources()
{
if (call != null)
{
call.Dispose();
}
gchandle.Free();
disposed = true;
}
protected void CheckSendingAllowed()
{
Preconditions.CheckState(started);
Preconditions.CheckState(!disposed);
Preconditions.CheckState(!errorOccured);
Preconditions.CheckState(!halfcloseRequested, "Already halfclosed.");
Preconditions.CheckState(sendCompletionDelegate == null, "Only one write can be pending at a time");
}
protected byte[] UnsafeSerialize(TWrite msg)
{
return serializer(msg);
}
protected bool TrySerialize(TWrite msg, out byte[] payload)
{
try
{
payload = serializer(msg);
return true;
}
catch(Exception)
{
Console.WriteLine("Exception occured while trying to serialize message");
payload = null;
return false;
}
}
protected bool TryDeserialize(byte[] payload, out TRead msg)
{
try
{
msg = deserializer(payload);
return true;
}
catch(Exception)
{
Console.WriteLine("Exception occured while trying to deserialize message");
msg = default(TRead);
return false;
}
}
protected void FireReadObserverOnNext(TRead value)
{
try
{
readObserver.OnNext(value);
}
catch(Exception e)
{
Console.WriteLine("Exception occured while invoking readObserver.OnNext: " + e);
}
}
protected void FireReadObserverOnCompleted()
{
try
{
readObserver.OnCompleted();
}
catch(Exception e)
{
Console.WriteLine("Exception occured while invoking readObserver.OnCompleted: " + e);
}
}
protected void FireReadObserverOnError(Exception error)
{
try
{
readObserver.OnError(error);
}
catch(Exception e)
{
Console.WriteLine("Exception occured while invoking readObserver.OnError: " + e);
}
}
protected void FireCompletion(AsyncCompletionDelegate completionDelegate, Exception error)
{
try
{
completionDelegate(error);
}
catch(Exception e)
{
Console.WriteLine("Exception occured while invoking completion delegate: " + e);
}
}
/// <summary>
/// Creates completion callback delegate that wraps the batch completion handler in a try catch block to
/// prevent propagating exceptions accross managed/unmanaged boundary.
/// </summary>
protected CompletionCallbackDelegate CreateBatchCompletionCallback(Action<bool, BatchContextSafeHandleNotOwned> handler)
{
return new CompletionCallbackDelegate( (error, batchContextPtr) => {
try
{
var ctx = new BatchContextSafeHandleNotOwned(batchContextPtr);
bool wasError = (error != GRPCOpError.GRPC_OP_OK);
handler(wasError, ctx);
}
catch(Exception e)
{
Console.WriteLine("Caught exception in a native handler: " + e);
}
});
}
/// <summary>
/// Handles send completion.
/// </summary>
private void HandleSendFinished(bool wasError, BatchContextSafeHandleNotOwned ctx)
{
AsyncCompletionDelegate origCompletionDelegate = null;
lock (myLock)
{
origCompletionDelegate = sendCompletionDelegate;
sendCompletionDelegate = null;
ReleaseResourcesIfPossible();
}
if (wasError)
{
FireCompletion(origCompletionDelegate, new OperationFailedException("Send failed"));
}
else
{
FireCompletion(origCompletionDelegate, null);
}
}
/// <summary>
/// Handles halfclose completion.
/// </summary>
private void HandleHalfclosed(bool wasError, BatchContextSafeHandleNotOwned ctx)
{
AsyncCompletionDelegate origCompletionDelegate = null;
lock (myLock)
{
halfclosed = true;
origCompletionDelegate = sendCompletionDelegate;
sendCompletionDelegate = null;
ReleaseResourcesIfPossible();
}
if (wasError)
{
FireCompletion(origCompletionDelegate, new OperationFailedException("Halfclose failed"));
}
else
{
FireCompletion(origCompletionDelegate, null);
}
}
/// <summary>
/// Handles streaming read completion.
/// </summary>
private void HandleReadFinished(bool wasError, BatchContextSafeHandleNotOwned ctx)
{
var payload = ctx.GetReceivedMessage();
lock (myLock)
{
readPending = false;
if (payload == null)
{
readingDone = true;
}
ReleaseResourcesIfPossible();
}
// TODO: handle the case when error occured...
if (payload != null)
{
// TODO: handle deserialization error
TRead msg;
TryDeserialize(payload, out msg);
FireReadObserverOnNext(msg);
// Start a new read. The current one has already been delivered,
// so correct ordering of reads is assured.
StartReceiveMessage();
}
else
{
CompleteReadObserver();
}
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Caching.Topologies.Local;
using Alachisoft.NCache.Caching.Topologies;
namespace Alachisoft.NCache.Caching.Enumeration
{
/// <summary>
/// A singleton Class that is responsible for all the management of snaphot pool for Enumeration.
/// This class can be used to get snaphot from snaphot pool for enumeration based on size of data that snaphot will return and is configurable in service config.
/// </summary>
///
internal class CacheSnapshotPool
{
static readonly CacheSnapshotPool instance = new CacheSnapshotPool();
/// <summary>
/// Minimum number of keys to be present in cache to go for snaphot pooling.
/// </summary>
private int _minSnaphotSizeForPooling = 100000;
/// <summary>
/// The maximum number of Snaphots available for pooling.
/// </summary>
private int _maxSnapshotsInPool = 10;
/// <summary>
/// The time after which we will genarate a new snaphot if a client requests enumerator on cache and
/// if this time is not elapsed we will return the same pool.
/// </summary>
private int _newSnapshotCreationThreshold = 120; // In secs
/// <summary>
/// Contains the mapping between cache id and pool specific to that cache.
/// </summary>
Hashtable _cachePoolMap;
static CacheSnapshotPool()
{
}
CacheSnapshotPool()
{
if (System.Configuration.ConfigurationSettings.AppSettings.Get("NCacheServer.EnableSnapshotPoolingCacheSize") != null)
_minSnaphotSizeForPooling = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings.Get("NCacheServer.MinimumSnaphotSizeForPooling"));
if (System.Configuration.ConfigurationSettings.AppSettings.Get("NCacheServer.MaxNumOfSnapshotsInPool") != null)
_maxSnapshotsInPool = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings.Get("NCacheServer.SnapshotPoolSize"));
if (System.Configuration.ConfigurationSettings.AppSettings.Get("NCacheServer.NewSnapshotCreationTimeInSec") != null)
_newSnapshotCreationThreshold = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings.Get("NCacheServer.SnapshotCreationThreshold"));
_cachePoolMap = new Hashtable();
}
public static CacheSnapshotPool Instance
{
get
{
return instance;
}
}
/// <summary>
/// Get a snaphot from the pool
/// </summary>
/// <param name="pointerID"></param>
/// <param name="cache"></param>
/// <returns></returns>
public Array GetSnaphot(string pointerID, CacheBase cache)
{
CachePool pool = null;
if (_cachePoolMap.Contains(cache.Context.CacheRoot.Name))
{
pool = _cachePoolMap[cache.Context.CacheRoot.Name] as CachePool;
return pool.GetSnaphotInPool(pointerID, cache);
}
else
{
pool = new CachePool(_minSnaphotSizeForPooling, _maxSnapshotsInPool, _newSnapshotCreationThreshold);
_cachePoolMap.Add(cache.Context.CacheRoot.Name, pool);
}
return pool.GetSnaphotInPool(pointerID, cache);
}
/// <summary>
/// Get a snaphot from the pool for a particular cache.
/// </summary>
public void DiposeSnapshot(string pointerID, CacheBase cache)
{
CachePool pool = null;
if (_cachePoolMap.Contains(cache.Context.CacheRoot.Name))
{
pool = _cachePoolMap[cache.Context.CacheRoot.Name] as CachePool;
pool.DiposeSnapshotInPool(pointerID);
}
}
/// <summary>
/// Dispose the pool created for a cache when the cache is disposed.
/// </summary>
/// <param name="cacheId"></param>
public void DisposePool(string cacheId)
{
_cachePoolMap.Remove(cacheId);
}
class CachePool
{
/// <summary>
/// Minimum number of keys to be present in cache to go for snaphot pooling.
/// </summary>
private int _minimumSnaphotSizeForPooling = 100000;
/// <summary>
/// The maximum number of Snaphots available for pooling.
/// </summary>
private int _maxNumOfSnapshotsInPool = 10;
/// <summary>
/// The time after which we will genarate a new snaphot if a client requests enumerator on cache and
/// if this time is not elapsed we will return the same pool.
/// </summary>
private int _newSnapshotCreationTimeInSec = 120;
/// <summary>
/// The time on which a new snapshot was created and added to Snaphot Pool
/// </summary>
private DateTime _lastSnaphotCreationTime = DateTime.MinValue;
/// <summary>
/// The pool containing all the available snaphots.
/// </summary>
private Dictionary<string, Array> _pool = new Dictionary<string, Array>();
/// <summary>
/// Contains the mapping between pointer and its snaphot. tells which pointer is using which snapshot in pool.
/// </summary>
private Dictionary<string, string> _enumeratorSnaphotMap = new Dictionary<string, string>();
/// <summary>
/// Contains the map for each snapshot and number of enumerators on it. Tells how many emumerators a references
/// a particluar snaphot.
/// </summary>
private Dictionary<string, int> _snapshotRefCountMap = new Dictionary<string, int>();
/// <summary>
/// holds the id of current usable snaphot of the pool
/// </summary>
private string _currentUsableSnapshot;
/// <summary>
/// Returns a unique GUID that is assigned to the new snaphot added to the pool
/// </summary>
/// <returns></returns>
private string GetNewUniqueID()
{
return Guid.NewGuid().ToString();
}
internal CachePool(int minSnaphotSizeForPooling, int maxSnapshotsInPool, int newSnapshotCreationThreshold)
{
_minimumSnaphotSizeForPooling = minSnaphotSizeForPooling;
_maxNumOfSnapshotsInPool = maxSnapshotsInPool;
_newSnapshotCreationTimeInSec = newSnapshotCreationThreshold;
}
/// <summary>
/// Return a snaphot from the snaphot pool to be used by current enumerator
/// </summary>
/// <param name="pointerID">unque id of the enumeration pointer being used by current enumerator.</param>
/// <param name="cache">underlying cache from which snapshot has to be taken.</param>
/// <returns>snaphot as an array.</returns>
public Array GetSnaphotInPool(string pointerID, CacheBase cache)
{
string uniqueID = string.Empty;
if (cache.Count < _minimumSnaphotSizeForPooling)
{
return cache.Keys;
}
else
{
if (_pool.Count == 0)
{
uniqueID = GetNewUniqueID();
_pool.Add(uniqueID, cache.Keys);
_lastSnaphotCreationTime = DateTime.Now;
_currentUsableSnapshot = uniqueID;
}
else if (_pool.Count < _maxNumOfSnapshotsInPool)
{
TimeSpan elapsedTime = DateTime.Now.Subtract(_lastSnaphotCreationTime);
if (elapsedTime.TotalSeconds >= _newSnapshotCreationTimeInSec)
{
uniqueID = GetNewUniqueID();
_pool.Add(uniqueID, cache.Keys);
_lastSnaphotCreationTime = DateTime.Now;
_currentUsableSnapshot = uniqueID;
}
}
if (!_enumeratorSnaphotMap.ContainsKey(pointerID))
{
_enumeratorSnaphotMap.Add(pointerID, uniqueID);
if (!_snapshotRefCountMap.ContainsKey(uniqueID))
{
_snapshotRefCountMap.Add(uniqueID, 1);
}
else
{
int refCount = _snapshotRefCountMap[uniqueID];
refCount++;
_snapshotRefCountMap[uniqueID] = refCount;
}
}
return _pool[_currentUsableSnapshot];
}
}
/// <summary>
/// Dispose a snaphot from the pool that is not being used by any emumerator.
/// </summary>
/// <param name="pointerID">unque id of the enumeration pointer being used by current enumerator.</param>
public void DiposeSnapshotInPool(string pointerID)
{
if (_enumeratorSnaphotMap.ContainsKey(pointerID))
{
string snapshotID = _enumeratorSnaphotMap[pointerID];
if (!string.IsNullOrEmpty(snapshotID))
{
if (_snapshotRefCountMap.ContainsKey(snapshotID))
{
int refCount = _snapshotRefCountMap[snapshotID];
refCount--;
if (refCount == 0)
_pool.Remove(snapshotID);
else
_snapshotRefCountMap[snapshotID] = refCount;
}
}
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
public class CCMotionStreak : CCNode, ICCTexture
{
// ivars
int maxPoints;
int numOfPoints;
int previousNumOfPoints;
float fadeDelta;
float minSeg;
float stroke;
float[] pointState;
CCPoint positionR;
CCPoint[] pointVertexes;
CCV3F_C4B_T2F[] vertices;
#region Properties
public CCTexture2D Texture { get; set; }
public CCBlendFunc BlendFunc { get; set; }
public bool FastMode { get; set; }
public bool StartingPositionInitialized { get; private set; }
public override CCPoint Position
{
set
{
StartingPositionInitialized = true;
positionR = value;
}
}
public override byte Opacity
{
get { return 0; }
set { }
}
public override bool IsColorModifiedByOpacity
{
get { return false; }
set { }
}
#endregion Properties
#region Constructors
public CCMotionStreak()
{
BlendFunc = CCBlendFunc.NonPremultiplied;
}
public CCMotionStreak(float fade, float minSeg, float stroke, CCColor3B color, string path)
: this(fade, minSeg, stroke, color, CCTextureCache.SharedTextureCache.AddImage(path))
{
}
public CCMotionStreak(float fade, float minSegIn, float strokeIn, CCColor3B color, CCTexture2D texture)
{
AnchorPoint = CCPoint.Zero;
IgnoreAnchorPointForPosition = true;
StartingPositionInitialized = false;
FastMode = true;
Texture = texture;
Color = color;
stroke = strokeIn;
BlendFunc = CCBlendFunc.NonPremultiplied;
minSeg = (minSegIn == -1.0f) ? stroke / 5.0f : minSegIn;
minSeg *= minSeg;
fadeDelta = 1.0f / fade;
maxPoints = (int) (fade * 60.0f) + 2;
pointState = new float[maxPoints];
pointVertexes = new CCPoint[maxPoints];
vertices = new CCV3F_C4B_T2F[(maxPoints + 1) * 2];
Schedule();
}
#endregion Constructors
#region Drawing
protected override void Draw()
{
Window.DrawManager.BlendFunc(BlendFunc);
Window.DrawManager.BindTexture(Texture);
Window.DrawManager.VertexColorEnabled = true;
Window.DrawManager.DrawPrimitives(PrimitiveType.TriangleStrip, vertices, 0, numOfPoints * 2 - 2);
}
#endregion Drawing
#region Updating
static bool VertexLineIntersect(float Ax, float Ay, float Bx, float By, float Cx,
float Cy, float Dx, float Dy, out float T)
{
float distAB, theCos, theSin, newX;
T = 0;
// FAIL: Line undefined
if ((Ax == Bx && Ay == By) || (Cx == Dx && Cy == Dy)) return false;
// Translate system to make A the origin
Bx -= Ax;
By -= Ay;
Cx -= Ax;
Cy -= Ay;
Dx -= Ax;
Dy -= Ay;
// Length of segment AB
distAB = (float) Math.Sqrt(Bx * Bx + By * By);
// Rotate the system so that point B is on the positive X axis.
theCos = Bx / distAB;
theSin = By / distAB;
newX = Cx * theCos + Cy * theSin;
Cy = Cy * theCos - Cx * theSin;
Cx = newX;
newX = Dx * theCos + Dy * theSin;
Dy = Dy * theCos - Dx * theSin;
Dx = newX;
// FAIL: Lines are parallel.
if (Cy == Dy) return false;
// Discover the relative position of the intersection in the line AB
T = (Dx + (Cx - Dx) * Dy / (Dy - Cy)) / distAB;
// Success.
return true;
}
static void VertexLineToPolygon(CCPoint[] points, float stroke, CCV3F_C4B_T2F[] vertices, int offset, int nuPoints)
{
nuPoints += offset;
if (nuPoints <= 1) return;
stroke *= 0.5f;
int idx;
int nuPointsMinus = nuPoints - 1;
float rad70 = MathHelper.ToRadians(70);
float rad170 = MathHelper.ToRadians(170);
for (int i = offset; i < nuPoints; i++)
{
idx = i * 2;
CCPoint p1 = points[i];
CCPoint perpVector;
if (i == 0)
{
perpVector = CCPoint.PerpendicularCCW(CCPoint.Normalize(p1 - points[i + 1]));
}
else if (i == nuPointsMinus)
{
perpVector = CCPoint.PerpendicularCCW(CCPoint.Normalize(points[i - 1] - p1));
}
else
{
CCPoint p2 = points[i + 1];
CCPoint p0 = points[i - 1];
CCPoint p2p1 = CCPoint.Normalize(p2 - p1);
CCPoint p0p1 = CCPoint.Normalize(p0 - p1);
// Calculate angle between vectors
var angle = (float) Math.Acos(CCPoint.Dot(p2p1, p0p1));
if (angle < rad70)
{
perpVector = CCPoint.PerpendicularCCW(CCPoint.Normalize(CCPoint.Midpoint(p2p1, p0p1)));
}
else if (angle < rad170)
{
perpVector = CCPoint.Normalize(CCPoint.Midpoint(p2p1, p0p1));
}
else
{
perpVector = CCPoint.PerpendicularCCW(CCPoint.Normalize(p2 - p0));
}
}
perpVector = perpVector * stroke;
vertices[idx].Vertices = new CCVertex3F(p1.X + perpVector.X, p1.Y + perpVector.Y, 0);
vertices[idx + 1].Vertices = new CCVertex3F(p1.X - perpVector.X, p1.Y - perpVector.Y, 0);
}
// Validate vertexes
offset = (offset == 0) ? 0 : offset - 1;
for (int i = offset; i < nuPointsMinus; i++)
{
idx = i * 2;
int idx1 = idx + 2;
CCVertex3F p1 = vertices[idx].Vertices;
CCVertex3F p2 = vertices[idx + 1].Vertices;
CCVertex3F p3 = vertices[idx1].Vertices;
CCVertex3F p4 = vertices[idx1 + 1].Vertices;
float s;
bool fixVertex = !VertexLineIntersect(p1.X, p1.Y, p4.X, p4.Y, p2.X, p2.Y, p3.X, p3.Y, out s);
if (!fixVertex)
{
if (s < 0.0f || s > 1.0f)
{
fixVertex = true;
}
}
if (fixVertex)
{
vertices[idx1].Vertices = p4;
vertices[idx1 + 1].Vertices = p3;
}
}
}
void Reset()
{
numOfPoints = 0;
}
public void TintWithColor(CCColor3B colors)
{
Color = colors;
for (int i = 0; i < numOfPoints * 2; i++)
{
vertices[i].Colors = new CCColor4B(colors.R, colors.G, colors.B, 255);
}
}
public override void Update(float delta)
{
if (!StartingPositionInitialized)
{
return;
}
delta *= fadeDelta;
int newIdx, newIdx2, i, i2;
int mov = 0;
// Update current points
for (i = 0; i < numOfPoints; i++)
{
pointState[i] -= delta;
if (pointState[i] <= 0)
{
mov++;
}
else
{
newIdx = i - mov;
if (mov > 0)
{
// Move data
pointState[newIdx] = pointState[i];
// Move point
pointVertexes[newIdx] = pointVertexes[i];
// Move vertices
i2 = i * 2;
newIdx2 = newIdx * 2;
vertices[newIdx2].Vertices = vertices[i2].Vertices;
vertices[newIdx2 + 1].Vertices = vertices[i2 + 1].Vertices;
// Move color
vertices[newIdx2].Colors = vertices[i2].Colors;
vertices[newIdx2 + 1].Colors = vertices[i2 + 1].Colors;
}
else
{
newIdx2 = newIdx * 2;
}
vertices[newIdx2].Colors.A = vertices[newIdx2 + 1].Colors.A = (byte) (pointState[newIdx] * 255.0f);
}
}
numOfPoints -= mov;
// Append new point
bool appendNewPoint = true;
if (numOfPoints >= maxPoints)
{
appendNewPoint = false;
}
else if (numOfPoints > 0)
{
bool a1 = pointVertexes[numOfPoints - 1].DistanceSquared(ref positionR) < minSeg;
bool a2 = (numOfPoints != 1) && (pointVertexes[numOfPoints - 2].DistanceSquared(ref positionR) < (minSeg * 2.0f));
if (a1 || a2)
{
appendNewPoint = false;
}
}
if (appendNewPoint)
{
pointVertexes[numOfPoints] = positionR;
pointState[numOfPoints] = 1.0f;
// Color asignation
int offset = numOfPoints * 2;
vertices[offset].Colors = vertices[offset + 1].Colors = new CCColor4B(DisplayedColor.R, DisplayedColor.G, DisplayedColor.B, 255);
// Generate polygon
if (numOfPoints > 0 && FastMode)
{
if (numOfPoints > 1)
{
VertexLineToPolygon(pointVertexes, stroke, vertices, numOfPoints, 1);
}
else
{
VertexLineToPolygon(pointVertexes, stroke, vertices, 0, 2);
}
}
numOfPoints++;
}
if (!FastMode)
{
VertexLineToPolygon(pointVertexes, stroke, vertices, 0, numOfPoints);
}
// Updated Tex Coords only if they are different than previous step
if (numOfPoints > 0 && previousNumOfPoints != numOfPoints)
{
float texDelta = 1.0f / numOfPoints;
for (i = 0; i < numOfPoints; i++)
{
vertices[i * 2].TexCoords = new CCTex2F(0, texDelta * i);
vertices[i * 2 + 1].TexCoords = new CCTex2F(1, texDelta * i);
}
previousNumOfPoints = numOfPoints;
}
}
#endregion Updating
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Routing;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
public class FormActionTagHelperTest
{
[Fact]
public async Task ProcessAsync_GeneratesExpectedOutput()
{
// Arrange
var expectedTagName = "not-button-or-submit";
var metadataProvider = new TestModelMetadataProvider();
var tagHelperContext = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList
{
{ "id", "my-id" },
},
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
expectedTagName,
attributes: new TagHelperAttributeList
{
{ "id", "my-id" },
},
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something Else"); // ignored
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
var urlHelper = new Mock<IUrlHelper>(MockBehavior.Strict);
urlHelper
.Setup(mock => mock.Action(It.IsAny<UrlActionContext>()))
.Returns<UrlActionContext>(c => $"{c.Controller}/{c.Action}/{(c.Values as RouteValueDictionary)["name"]}");
var viewContext = new ViewContext();
var urlHelperFactory = new Mock<IUrlHelperFactory>(MockBehavior.Strict);
urlHelperFactory
.Setup(f => f.GetUrlHelper(viewContext))
.Returns(urlHelper.Object);
var tagHelper = new FormActionTagHelper(urlHelperFactory.Object)
{
Action = "index",
Controller = "home",
RouteValues =
{
{ "name", "value" },
},
ViewContext = viewContext,
};
// Act
await tagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Collection(
output.Attributes,
attribute =>
{
Assert.Equal("id", attribute.Name, StringComparer.Ordinal);
Assert.Equal("my-id", attribute.Value as string, StringComparer.Ordinal);
},
attribute =>
{
Assert.Equal("formaction", attribute.Name, StringComparer.Ordinal);
Assert.Equal("home/index/value", attribute.Value as string, StringComparer.Ordinal);
});
Assert.False(output.IsContentModified);
Assert.False(output.PostContent.IsModified);
Assert.False(output.PostElement.IsModified);
Assert.False(output.PreContent.IsModified);
Assert.False(output.PreElement.IsModified);
Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode);
Assert.Equal(expectedTagName, output.TagName);
}
[Fact]
public async Task ProcessAsync_GeneratesExpectedOutput_WithRoute()
{
// Arrange
var expectedTagName = "not-button-or-submit";
var metadataProvider = new TestModelMetadataProvider();
var tagHelperContext = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList
{
{ "id", "my-id" },
},
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
expectedTagName,
attributes: new TagHelperAttributeList
{
{ "id", "my-id" },
},
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something Else"); // ignored
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
var urlHelper = new Mock<IUrlHelper>(MockBehavior.Strict);
urlHelper
.Setup(mock => mock.RouteUrl(It.IsAny<UrlRouteContext>()))
.Returns<UrlRouteContext>(c => $"{c.RouteName}/{(c.Values as RouteValueDictionary)["name"]}");
var viewContext = new ViewContext();
var urlHelperFactory = new Mock<IUrlHelperFactory>(MockBehavior.Strict);
urlHelperFactory
.Setup(f => f.GetUrlHelper(viewContext))
.Returns(urlHelper.Object);
var tagHelper = new FormActionTagHelper(urlHelperFactory.Object)
{
Route = "routine",
RouteValues =
{
{ "name", "value" },
},
ViewContext = viewContext,
};
// Act
await tagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Collection(
output.Attributes,
attribute =>
{
Assert.Equal("id", attribute.Name, StringComparer.Ordinal);
Assert.Equal("my-id", attribute.Value as string, StringComparer.Ordinal);
},
attribute =>
{
Assert.Equal("formaction", attribute.Name, StringComparer.Ordinal);
Assert.Equal("routine/value", attribute.Value as string, StringComparer.Ordinal);
});
Assert.False(output.IsContentModified);
Assert.False(output.PostContent.IsModified);
Assert.False(output.PostElement.IsModified);
Assert.False(output.PreContent.IsModified);
Assert.False(output.PreElement.IsModified);
Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode);
Assert.Equal(expectedTagName, output.TagName);
}
// RouteValues property value, expected RouteValuesDictionary content.
public static TheoryData<IDictionary<string, string>, IDictionary<string, object>> RouteValuesData
{
get
{
return new TheoryData<IDictionary<string, string>, IDictionary<string, object>>
{
{ null, null },
// FormActionTagHelper ignores an empty route values dictionary.
{ new Dictionary<string, string>(), null },
{
new Dictionary<string, string> { { "name", "value" } },
new Dictionary<string, object> { { "name", "value" } }
},
{
new SortedDictionary<string, string>(StringComparer.Ordinal)
{
{ "name1", "value1" },
{ "name2", "value2" },
},
new SortedDictionary<string, object>(StringComparer.Ordinal)
{
{ "name1", "value1" },
{ "name2", "value2" },
}
},
};
}
}
[Theory]
[MemberData(nameof(RouteValuesData))]
public async Task ProcessAsync_CallsActionWithExpectedParameters(
IDictionary<string, string> routeValues,
IDictionary<string, object> expectedRouteValues)
{
// Arrange
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"button",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
return Task.FromResult<TagHelperContent>(new DefaultTagHelperContent());
});
var urlHelper = new Mock<IUrlHelper>(MockBehavior.Strict);
urlHelper
.Setup(mock => mock.Action(It.IsAny<UrlActionContext>()))
.Callback<UrlActionContext>(param =>
{
Assert.Equal("delete", param.Action, StringComparer.Ordinal);
Assert.Equal("books", param.Controller, StringComparer.Ordinal);
Assert.Equal("test", param.Fragment, StringComparer.Ordinal);
Assert.Null(param.Host);
Assert.Null(param.Protocol);
Assert.Equal<KeyValuePair<string, object>>(expectedRouteValues, param.Values as RouteValueDictionary);
})
.Returns("home/index");
var viewContext = new ViewContext();
var urlHelperFactory = new Mock<IUrlHelperFactory>(MockBehavior.Strict);
urlHelperFactory
.Setup(f => f.GetUrlHelper(viewContext))
.Returns(urlHelper.Object);
var tagHelper = new FormActionTagHelper(urlHelperFactory.Object)
{
Action = "delete",
Controller = "books",
Fragment = "test",
RouteValues = routeValues,
ViewContext = viewContext,
};
// Act
await tagHelper.ProcessAsync(context, output);
// Assert
Assert.Equal("button", output.TagName);
var attribute = Assert.Single(output.Attributes);
Assert.Equal("formaction", attribute.Name);
Assert.Equal("home/index", attribute.Value);
Assert.Empty(output.Content.GetContent());
}
[Theory]
[MemberData(nameof(RouteValuesData))]
public async Task ProcessAsync_CallsRouteUrlWithExpectedParameters(
IDictionary<string, string> routeValues,
IDictionary<string, object> expectedRouteValues)
{
// Arrange
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"button",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
return Task.FromResult<TagHelperContent>(new DefaultTagHelperContent());
});
var urlHelper = new Mock<IUrlHelper>(MockBehavior.Strict);
urlHelper
.Setup(mock => mock.RouteUrl(It.IsAny<UrlRouteContext>()))
.Callback<UrlRouteContext>(param =>
{
Assert.Null(param.Host);
Assert.Null(param.Protocol);
Assert.Equal("test", param.Fragment, StringComparer.Ordinal);
Assert.Equal("Default", param.RouteName, StringComparer.Ordinal);
Assert.Equal<KeyValuePair<string, object>>(expectedRouteValues, param.Values as RouteValueDictionary);
})
.Returns("home/index");
var viewContext = new ViewContext();
var urlHelperFactory = new Mock<IUrlHelperFactory>(MockBehavior.Strict);
urlHelperFactory
.Setup(f => f.GetUrlHelper(viewContext))
.Returns(urlHelper.Object);
var tagHelper = new FormActionTagHelper(urlHelperFactory.Object)
{
Route = "Default",
Fragment = "test",
RouteValues = routeValues,
ViewContext = viewContext,
};
// Act
await tagHelper.ProcessAsync(context, output);
// Assert
Assert.Equal("button", output.TagName);
var attribute = Assert.Single(output.Attributes);
Assert.Equal("formaction", attribute.Name);
Assert.Equal("home/index", attribute.Value);
Assert.Empty(output.Content.GetContent());
}
// Area property value, RouteValues property value, expected "area" in final RouteValuesDictionary.
public static TheoryData<string, Dictionary<string, string>, string> AreaRouteValuesData
{
get
{
return new TheoryData<string, Dictionary<string, string>, string>
{
{ "Area", null, "Area" },
// Explicit Area overrides value in the dictionary.
{ "Area", new Dictionary<string, string> { { "area", "Home" } }, "Area" },
// Empty string is also passed through to the helper.
{ string.Empty, null, string.Empty },
{ string.Empty, new Dictionary<string, string> { { "area", "Home" } }, string.Empty },
// Fall back "area" entry in the provided route values if Area is null.
{ null, new Dictionary<string, string> { { "area", "Admin" } }, "Admin" },
};
}
}
[Theory]
[MemberData(nameof(AreaRouteValuesData))]
public async Task ProcessAsync_CallsActionWithExpectedRouteValues(
string area,
Dictionary<string, string> routeValues,
string expectedArea)
{
// Arrange
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"submit",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
return Task.FromResult<TagHelperContent>(new DefaultTagHelperContent());
});
var expectedRouteValues = new Dictionary<string, object> { { "area", expectedArea } };
var urlHelper = new Mock<IUrlHelper>(MockBehavior.Strict);
urlHelper
.Setup(mock => mock.Action(It.IsAny<UrlActionContext>()))
.Callback<UrlActionContext>(param => Assert.Equal(expectedRouteValues, param.Values as RouteValueDictionary))
.Returns("admin/dashboard/index");
var viewContext = new ViewContext();
var urlHelperFactory = new Mock<IUrlHelperFactory>(MockBehavior.Strict);
urlHelperFactory
.Setup(f => f.GetUrlHelper(viewContext))
.Returns(urlHelper.Object);
var tagHelper = new FormActionTagHelper(urlHelperFactory.Object)
{
Action = "Index",
Area = area,
Controller = "Dashboard",
RouteValues = routeValues,
ViewContext = viewContext,
};
// Act
await tagHelper.ProcessAsync(context, output);
// Assert
Assert.Equal("submit", output.TagName);
var attribute = Assert.Single(output.Attributes);
Assert.Equal("formaction", attribute.Name);
Assert.Equal("admin/dashboard/index", attribute.Value);
Assert.Empty(output.Content.GetContent());
}
[Theory]
[MemberData(nameof(AreaRouteValuesData))]
public async Task ProcessAsync_CallsRouteUrlWithExpectedRouteValues(
string area,
Dictionary<string, string> routeValues,
string expectedArea)
{
// Arrange
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"submit",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
return Task.FromResult<TagHelperContent>(new DefaultTagHelperContent());
});
var expectedRouteValues = new Dictionary<string, object> { { "area", expectedArea } };
var urlHelper = new Mock<IUrlHelper>(MockBehavior.Strict);
urlHelper
.Setup(mock => mock.RouteUrl(It.IsAny<UrlRouteContext>()))
.Callback<UrlRouteContext>(param => Assert.Equal(expectedRouteValues, param.Values as RouteValueDictionary))
.Returns("admin/dashboard/index");
var viewContext = new ViewContext();
var urlHelperFactory = new Mock<IUrlHelperFactory>(MockBehavior.Strict);
urlHelperFactory
.Setup(f => f.GetUrlHelper(viewContext))
.Returns(urlHelper.Object);
var tagHelper = new FormActionTagHelper(urlHelperFactory.Object)
{
Area = area,
Route = "routine",
RouteValues = routeValues,
ViewContext = viewContext,
};
// Act
await tagHelper.ProcessAsync(context, output);
// Assert
Assert.Equal("submit", output.TagName);
var attribute = Assert.Single(output.Attributes);
Assert.Equal("formaction", attribute.Name);
Assert.Equal("admin/dashboard/index", attribute.Value);
Assert.Empty(output.Content.GetContent());
}
[Fact]
public async Task ProcessAsync_WithPageAndArea_CallsUrlHelperWithExpectedValues()
{
// Arrange
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"submit",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
return Task.FromResult<TagHelperContent>(new DefaultTagHelperContent());
});
var urlHelper = new Mock<IUrlHelper>();
urlHelper
.Setup(mock => mock.RouteUrl(It.IsAny<UrlRouteContext>()))
.Callback<UrlRouteContext>(routeContext =>
{
var rvd = Assert.IsType<RouteValueDictionary>(routeContext.Values);
Assert.Collection(
rvd.OrderBy(item => item.Key),
item =>
{
Assert.Equal("area", item.Key);
Assert.Equal("test-area", item.Value);
},
item =>
{
Assert.Equal("page", item.Key);
Assert.Equal("/my-page", item.Value);
});
})
.Returns("admin/dashboard/index")
.Verifiable();
var viewContext = new ViewContext
{
RouteData = new RouteData(),
};
urlHelper.SetupGet(h => h.ActionContext)
.Returns(viewContext);
var urlHelperFactory = new Mock<IUrlHelperFactory>(MockBehavior.Strict);
urlHelperFactory
.Setup(f => f.GetUrlHelper(viewContext))
.Returns(urlHelper.Object);
var tagHelper = new FormActionTagHelper(urlHelperFactory.Object)
{
Area = "test-area",
Page = "/my-page",
ViewContext = viewContext,
};
// Act
await tagHelper.ProcessAsync(context, output);
// Assert
urlHelper.Verify();
}
[Theory]
[InlineData("button", "Action")]
[InlineData("button", "Controller")]
[InlineData("button", "Route")]
[InlineData("button", "asp-route-")]
[InlineData("submit", "Action")]
[InlineData("submit", "Controller")]
[InlineData("submit", "Route")]
[InlineData("submit", "asp-route-")]
public async Task ProcessAsync_ThrowsIfFormActionConflictsWithBoundAttributes(string tagName, string propertyName)
{
// Arrange
var urlHelperFactory = new Mock<IUrlHelperFactory>().Object;
var tagHelper = new FormActionTagHelper(urlHelperFactory);
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList
{
{ "formaction", "my-action" }
},
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null));
if (propertyName == "asp-route-")
{
tagHelper.RouteValues.Add("name", "value");
}
else
{
typeof(FormActionTagHelper).GetProperty(propertyName).SetValue(tagHelper, "Home");
}
var expectedErrorMessage = $"Cannot override the 'formaction' attribute for <{tagName}>. <{tagName}> " +
"elements with a specified 'formaction' must not have attributes starting with 'asp-route-' or an " +
"'asp-action', 'asp-controller', 'asp-area', 'asp-fragment', 'asp-route', 'asp-page' or 'asp-page-handler' attribute.";
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output));
Assert.Equal(expectedErrorMessage, ex.Message);
}
[Theory]
[InlineData("button", "Action")]
[InlineData("button", "Controller")]
[InlineData("submit", "Action")]
[InlineData("submit", "Controller")]
public async Task ProcessAsync_ThrowsIfRouteAndActionOrControllerProvided(string tagName, string propertyName)
{
// Arrange
var urlHelperFactory = new Mock<IUrlHelperFactory>().Object;
var tagHelper = new FormActionTagHelper(urlHelperFactory)
{
Route = "Default",
};
typeof(FormActionTagHelper).GetProperty(propertyName).SetValue(tagHelper, "Home");
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null));
var expectedErrorMessage = string.Join(
Environment.NewLine,
$"Cannot determine the 'formaction' attribute for <{tagName}>. The following attributes are mutually exclusive:",
"asp-route",
"asp-controller, asp-action",
"asp-page, asp-page-handler");
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output));
Assert.Equal(expectedErrorMessage, ex.Message);
}
[Theory]
[InlineData("button")]
[InlineData("submit")]
public async Task ProcessAsync_ThrowsIfRouteAndPageProvided(string tagName)
{
// Arrange
var urlHelperFactory = new Mock<IUrlHelperFactory>().Object;
var tagHelper = new FormActionTagHelper(urlHelperFactory)
{
Route = "Default",
Page = "Page",
};
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null));
var expectedErrorMessage = string.Join(
Environment.NewLine,
$"Cannot determine the 'formaction' attribute for <{tagName}>. The following attributes are mutually exclusive:",
"asp-route",
"asp-controller, asp-action",
"asp-page, asp-page-handler");
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output));
Assert.Equal(expectedErrorMessage, ex.Message);
}
[Theory]
[InlineData("button")]
[InlineData("submit")]
public async Task ProcessAsync_ThrowsIfRouteAndPageHandlerProvided(string tagName)
{
// Arrange
var urlHelperFactory = new Mock<IUrlHelperFactory>().Object;
var tagHelper = new FormActionTagHelper(urlHelperFactory)
{
Route = "Default",
PageHandler = "PageHandler",
};
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null));
var expectedErrorMessage = string.Join(
Environment.NewLine,
$"Cannot determine the 'formaction' attribute for <{tagName}>. The following attributes are mutually exclusive:",
"asp-route",
"asp-controller, asp-action",
"asp-page, asp-page-handler");
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output));
Assert.Equal(expectedErrorMessage, ex.Message);
}
[Theory]
[InlineData("button")]
[InlineData("submit")]
public async Task ProcessAsync_ThrowsIfActionAndPageProvided(string tagName)
{
// Arrange
var urlHelperFactory = new Mock<IUrlHelperFactory>().Object;
var tagHelper = new FormActionTagHelper(urlHelperFactory)
{
Action = "Default",
Page = "Page",
};
var output = new TagHelperOutput(
tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null));
var expectedErrorMessage = string.Join(
Environment.NewLine,
$"Cannot determine the 'formaction' attribute for <{tagName}>. The following attributes are mutually exclusive:",
"asp-route",
"asp-controller, asp-action",
"asp-page, asp-page-handler");
var context = new TagHelperContext(
tagName: "form-action",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output));
Assert.Equal(expectedErrorMessage, ex.Message);
}
}
}
| |
#if !DISABLE_PLAYFABCLIENT_API && !DISABLE_PLAYFABENTITY_API
using PlayFab.Internal;
using System.Collections.Generic;
using System.Linq;
namespace PlayFab.UUnit
{
public class EntityApiTests : UUnitTestCase
{
// Test-data constants
private const string TEST_OBJ_NAME = "testCounter";
// Test variables
private const string TEST_FILE_NAME = "testfile";
private readonly byte[] _testPayload = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
private int _testInteger;
private bool _shouldDeleteFiles;
private PlayFabClientInstanceAPI clientApi;
private PlayFabAuthenticationInstanceAPI authApi;
private PlayFabDataInstanceAPI dataApi;
public override void ClassSetUp()
{
clientApi = new PlayFabClientInstanceAPI();
authApi = new PlayFabAuthenticationInstanceAPI(clientApi.authenticationContext);
dataApi = new PlayFabDataInstanceAPI(clientApi.authenticationContext);
PlayFabSettings.staticPlayer.ForgetAllCredentials();
}
public override void SetUp(UUnitTestContext testContext)
{
// Verify all the inputs won't cause crashes in the tests
var titleInfoSet = !string.IsNullOrEmpty(PlayFabSettings.TitleId);
if (!titleInfoSet)
testContext.Skip(); // We cannot do client tests if the titleId is not given
}
public override void Tick(UUnitTestContext testContext)
{
// Do nothing, because the test finishes asynchronously
}
public override void TearDown(UUnitTestContext testContext)
{
// TearDown is not currently suited to handle async cases, though I think it's possible to handle the case
// For now, this is an example of bad test design (kicking off async work after the test stops),
// but in this case, it should only happen if the test fails anyways, so it's... more tolerable
DeleteFiles(testContext, new List<string> { TEST_FILE_NAME }, false, UUnitFinishState.FAILED, "Problem in the test: Test state was failed in TearDown, and actual test state was lost");
}
public override void ClassTearDown()
{
PlayFabSettings.staticPlayer.ForgetAllCredentials();
}
private void SharedErrorCallback(PlayFabError error)
{
// This error was not expected. Report it and fail.
((UUnitTestContext)error.CustomData).Fail(error.GenerateErrorReport());
}
/// <summary>
/// CLIENT/ENTITY API
/// Log in or create a user, track their PlayFabId
/// </summary>
[UUnitTest]
public void EntityClientLogin(UUnitTestContext testContext)
{
var loginRequest = new ClientModels.LoginWithCustomIDRequest
{
CustomId = PlayFabSettings.BuildIdentifier,
CreateAccount = true,
};
clientApi.LoginWithCustomID(loginRequest, PlayFabUUnitUtils.ApiActionWrapper<ClientModels.LoginResult>(testContext, LoginCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void LoginCallback(ClientModels.LoginResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
testContext.True(clientApi.IsClientLoggedIn(), "Client login failed");
testContext.True(dataApi.IsEntityLoggedIn(), "Entity login didn't transfer to DataApi");
testContext.EndTest(UUnitFinishState.PASSED, PlayFabSettings.TitleId + ", " + result.PlayFabId);
}
/// <summary>
/// ENTITY API
/// Verify that a client login can be converted into an entity token
/// </summary>
[UUnitTest]
public void GetEntityToken(UUnitTestContext testContext)
{
var tokenRequest = new AuthenticationModels.GetEntityTokenRequest();
authApi.GetEntityToken(tokenRequest, PlayFabUUnitUtils.ApiActionWrapper<AuthenticationModels.GetEntityTokenResponse>(testContext, GetTokenCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void GetTokenCallback(AuthenticationModels.GetEntityTokenResponse result)
{
var testContext = (UUnitTestContext)result.CustomData;
testContext.StringEquals("title_player_account", result.Entity.Type, "GetEntityToken Entity Type not expected: " + result.Entity.Type);
testContext.True(clientApi.IsClientLoggedIn(), "Client login failed");
testContext.True(dataApi.IsEntityLoggedIn(), "Entity login didn't transfer to DataApi");
testContext.EndTest(UUnitFinishState.PASSED, PlayFabSettings.TitleId + ", " + result.EntityToken.Substring(0, 25) + "...");
}
/// <summary>
/// ENTITY API
/// Test a sequence of calls that modifies entity objects,
/// and verifies that the next sequential API call contains updated information.
/// Verify that the object is correctly modified on the next call.
/// </summary>
[UUnitTest]
public void ObjectApi(UUnitTestContext testContext)
{
testContext.True(dataApi.IsEntityLoggedIn(), "Client");
var getRequest = new DataModels.GetObjectsRequest { Entity = new DataModels.EntityKey { Id = clientApi.authenticationContext.EntityId, Type = clientApi.authenticationContext.EntityType }, EscapeObject = true };
dataApi.GetObjects(getRequest, PlayFabUUnitUtils.ApiActionWrapper<DataModels.GetObjectsResponse>(testContext, GetObjectCallback1), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void GetObjectCallback1(DataModels.GetObjectsResponse result)
{
var testContext = (UUnitTestContext)result.CustomData;
_testInteger = 0; // Default if the data isn't present
foreach (var eachObjPair in result.Objects)
if (eachObjPair.Key == TEST_OBJ_NAME)
int.TryParse(eachObjPair.Value.EscapedDataObject, out _testInteger);
_testInteger = (_testInteger + 1) % 100; // This test is about the Expected value changing - but not testing more complicated issues like bounds
var updateRequest = new DataModels.SetObjectsRequest
{
Entity = new DataModels.EntityKey { Id = clientApi.authenticationContext.EntityId, Type = clientApi.authenticationContext.EntityType },
Objects = new List<DataModels.SetObject> {
new DataModels.SetObject{ ObjectName = TEST_OBJ_NAME, DataObject = _testInteger }
}
};
dataApi.SetObjects(updateRequest, PlayFabUUnitUtils.ApiActionWrapper<DataModels.SetObjectsResponse>(testContext, UpdateObjectCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void UpdateObjectCallback(DataModels.SetObjectsResponse result)
{
var testContext = (UUnitTestContext)result.CustomData;
var getRequest = new DataModels.GetObjectsRequest { Entity = new DataModels.EntityKey { Id = clientApi.authenticationContext.EntityId, Type = clientApi.authenticationContext.EntityType }, EscapeObject = true };
dataApi.GetObjects(getRequest, PlayFabUUnitUtils.ApiActionWrapper<DataModels.GetObjectsResponse>(testContext, GetObjectCallback2), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void GetObjectCallback2(DataModels.GetObjectsResponse result)
{
var testContext = (UUnitTestContext)result.CustomData;
testContext.IntEquals(result.Objects.Count, 1, "Incorrect number of entity objects: " + result.Objects.Count);
testContext.True(result.Objects.ContainsKey(TEST_OBJ_NAME), "Expected Test object not found: " + result.Objects.Keys.FirstOrDefault());
var actualInteger = int.Parse(result.Objects[TEST_OBJ_NAME].EscapedDataObject);
testContext.IntEquals(_testInteger, actualInteger, "Entity Object was not updated: " + actualInteger + "!=" + _testInteger);
testContext.EndTest(UUnitFinishState.PASSED, actualInteger.ToString());
}
#region PUT_Verb_Test
/// <summary>
/// ENTITY PUT API
/// Tests a sequence of calls that upload file to a server via PUT.
/// Verifies that the file can be downloaded with the same information it's been saved with.
/// This sequence assumes that at test start, there are no files on the entity, and it will create and delete a file.
/// </summary>
//[UUnitTest]
public void PutApi(UUnitTestContext testContext)
{
var loginRequest = new ClientModels.LoginWithCustomIDRequest
{
CustomId = PlayFabSettings.BuildIdentifier,
CreateAccount = true,
};
clientApi.LoginWithCustomID(loginRequest, PlayFabUUnitUtils.ApiActionWrapper<ClientModels.LoginResult>(testContext, LoginCallbackPutTest), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void LoginCallbackPutTest(ClientModels.LoginResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
if (result.EntityToken != null)
{
LoadFiles(testContext);
}
else
{
testContext.Fail("Entity Token is null!");
}
}
private void LoadFiles(UUnitTestContext testContext)
{
var request = new DataModels.GetFilesRequest
{
Entity = new DataModels.EntityKey { Id = clientApi.authenticationContext.EntityId, Type = clientApi.authenticationContext.EntityType },
};
dataApi.GetFiles(request, PlayFabUUnitUtils.ApiActionWrapper<DataModels.GetFilesResponse>(testContext, OnGetFilesInfo), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
void OnGetFilesInfo(DataModels.GetFilesResponse result)
{
var testContext = (UUnitTestContext)result.CustomData;
bool testFileFound = false;
DataModels.GetFileMetadata fileMetaData = new DataModels.GetFileMetadata();
foreach (var eachFilePair in result.Metadata)
{
if (eachFilePair.Key.Equals(TEST_FILE_NAME))
{
testFileFound = true;
_shouldDeleteFiles = true; // We attached a file to the player, teardown should delete the file if the test fails
fileMetaData = eachFilePair.Value;
break; // this test only support one file
}
}
if (!testFileFound)
{
UploadFile(testContext, TEST_FILE_NAME);
}
else
{
GetActualFile(testContext, fileMetaData);
}
}
void GetActualFile(UUnitTestContext testContext, DataModels.GetFileMetadata fileData)
{
PlayFabHttp.SimpleGetCall(fileData.DownloadUrl,
PlayFabUUnitUtils.SimpleApiActionWrapper<byte[]>(testContext, TestFileContent),
error =>
{
testContext.Fail(error);
});
}
void UploadFile(UUnitTestContext testContext, string fileName)
{
var request = new DataModels.InitiateFileUploadsRequest
{
Entity = new DataModels.EntityKey { Id = clientApi.authenticationContext.EntityId, Type = clientApi.authenticationContext.EntityType },
FileNames = new List<string>
{
fileName
},
};
dataApi.InitiateFileUploads(request, PlayFabUUnitUtils.ApiActionWrapper<DataModels.InitiateFileUploadsResponse>(testContext, OnInitFileUpload), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, OnInitFailed), testContext);
}
void DeleteFiles(UUnitTestContext testContext, List<string> fileName, bool shouldEndTest, UUnitFinishState finishState, string finishMessage)
{
if (!_shouldDeleteFiles) // Only delete the file if it was created
return;
var request = new DataModels.DeleteFilesRequest
{
Entity = new DataModels.EntityKey { Id = clientApi.authenticationContext.EntityId, Type = clientApi.authenticationContext.EntityType },
FileNames = fileName,
};
_shouldDeleteFiles = false; // We have successfully deleted the file, it should not try again in teardown
dataApi.DeleteFiles(request, result =>
{
if (shouldEndTest)
testContext.EndTest(finishState, finishMessage);
},
PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
void OnInitFailed(PlayFabError error)
{
var testContext = (UUnitTestContext)error.CustomData;
if (error.Error == PlayFabErrorCode.EntityFileOperationPending)
{
var request = new DataModels.AbortFileUploadsRequest
{
Entity = new DataModels.EntityKey { Id = clientApi.authenticationContext.EntityId, Type = clientApi.authenticationContext.EntityType },
FileNames = new List<string> { TEST_FILE_NAME },
};
dataApi.AbortFileUploads(request, PlayFabUUnitUtils.ApiActionWrapper<DataModels.AbortFileUploadsResponse>(testContext, OnAbortFileUpload), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
else
{
if (error.CustomData != null)
{
SharedErrorCallback(error);
}
else
{
testContext.Fail(error.ErrorMessage);
}
}
}
void OnAbortFileUpload(DataModels.AbortFileUploadsResponse result)
{
var testContext = (UUnitTestContext)result.CustomData;
UploadFile(testContext, TEST_FILE_NAME);
}
void OnInitFileUpload(DataModels.InitiateFileUploadsResponse response)
{
var testContext = (UUnitTestContext)response.CustomData;
PlayFabHttp.SimplePutCall(response.UploadDetails[0].UploadUrl,
_testPayload,
PlayFabUUnitUtils.SimpleApiActionWrapper<byte[]>(testContext, FinalizeUpload),
error =>
{
testContext.Fail(error);
}
);
}
void FinalizeUpload(UUnitTestContext testContext, byte[] payload)
{
var request = new DataModels.FinalizeFileUploadsRequest
{
Entity = new DataModels.EntityKey { Id = clientApi.authenticationContext.EntityId, Type = clientApi.authenticationContext.EntityType },
FileNames = new List<string> { TEST_FILE_NAME },
};
dataApi.FinalizeFileUploads(request, PlayFabUUnitUtils.ApiActionWrapper<DataModels.FinalizeFileUploadsResponse>(testContext, OnUploadSuccess), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
void OnUploadSuccess(DataModels.FinalizeFileUploadsResponse result)
{
_shouldDeleteFiles = true; // We attached a file to the player, teardown should delete the file if the test fails
var testContext = (UUnitTestContext)result.CustomData;
LoadFiles(testContext);
}
void TestFileContent(UUnitTestContext testContext, byte[] result)
{
var json = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
testContext.NotNull(result, "Raw file result was null");
testContext.True(result.Length > 0, "Raw file result was zero length");
testContext.StringEquals(json.SerializeObject(_testPayload), json.SerializeObject(result), json.SerializeObject(result));
DeleteFiles(testContext, new List<string> { TEST_FILE_NAME }, true, UUnitFinishState.PASSED, "File " + TEST_FILE_NAME + " was succesfully created and uploaded to server with PUT");
}
#endregion
}
}
#endif
| |
/*
* 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 log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Profile
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalUserProfilesServicesConnector")]
public class LocalUserProfilesServicesConnector : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private ThreadedClasses.RwLockedDictionary<UUID, Scene> regions = new ThreadedClasses.RwLockedDictionary<UUID, Scene>();
public IUserProfilesService ServiceModule
{
get; private set;
}
public bool Enabled
{
get; private set;
}
public string Name
{
get
{
return "LocalUserProfilesServicesConnector";
}
}
public string ConfigName
{
get; private set;
}
public Type ReplaceableInterface
{
get { return null; }
}
public LocalUserProfilesServicesConnector()
{
m_log.Debug("[LOCAL USERPROFILES SERVICE CONNECTOR]: LocalUserProfileServicesConnector no params");
}
public LocalUserProfilesServicesConnector(IConfigSource source)
{
m_log.Debug("[LOCAL USERPROFILES SERVICE CONNECTOR]: LocalUserProfileServicesConnector instantiated directly.");
InitialiseService(source);
}
public void InitialiseService(IConfigSource source)
{
ConfigName = "UserProfilesService";
// Instantiate the request handler
IHttpServer Server = MainServer.Instance;
IConfig config = source.Configs[ConfigName];
if (config == null)
{
m_log.Error("[LOCAL USERPROFILES SERVICE CONNECTOR]: UserProfilesService missing from OpenSim.ini");
return;
}
if(!config.GetBoolean("Enabled",false))
{
Enabled = false;
return;
}
Enabled = true;
string serviceDll = config.GetString("LocalServiceModule",
String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL USERPROFILES SERVICE CONNECTOR]: No LocalServiceModule named in section UserProfilesService");
return;
}
Object[] args = new Object[] { source, ConfigName };
ServiceModule =
ServerUtils.LoadPlugin<IUserProfilesService>(serviceDll,
args);
if (ServiceModule == null)
{
m_log.Error("[LOCAL USERPROFILES SERVICE CONNECTOR]: Can't load user profiles service");
return;
}
Enabled = true;
JsonRpcProfileHandlers handler = new JsonRpcProfileHandlers(ServiceModule);
Server.AddJsonRPCHandler("avatarclassifiedsrequest", handler.AvatarClassifiedsRequest);
Server.AddJsonRPCHandler("classified_update", handler.ClassifiedUpdate);
Server.AddJsonRPCHandler("classifieds_info_query", handler.ClassifiedInfoRequest);
Server.AddJsonRPCHandler("classified_delete", handler.ClassifiedDelete);
Server.AddJsonRPCHandler("avatarpicksrequest", handler.AvatarPicksRequest);
Server.AddJsonRPCHandler("pickinforequest", handler.PickInfoRequest);
Server.AddJsonRPCHandler("picks_update", handler.PicksUpdate);
Server.AddJsonRPCHandler("picks_delete", handler.PicksDelete);
Server.AddJsonRPCHandler("avatarnotesrequest", handler.AvatarNotesRequest);
Server.AddJsonRPCHandler("avatar_notes_update", handler.NotesUpdate);
Server.AddJsonRPCHandler("avatar_properties_request", handler.AvatarPropertiesRequest);
Server.AddJsonRPCHandler("avatar_properties_update", handler.AvatarPropertiesUpdate);
Server.AddJsonRPCHandler("avatar_interests_update", handler.AvatarInterestsUpdate);
Server.AddJsonRPCHandler("user_preferences_update", handler.UserPreferenecesUpdate);
Server.AddJsonRPCHandler("user_preferences_request", handler.UserPreferencesRequest);
Server.AddJsonRPCHandler("image_assets_request", handler.AvatarImageAssetsRequest);
Server.AddJsonRPCHandler("user_data_request", handler.RequestUserAppData);
Server.AddJsonRPCHandler("user_data_update", handler.UpdateUserAppData);
}
#region ISharedRegionModule implementation
void ISharedRegionModule.PostInitialise()
{
if(!Enabled)
return;
}
#endregion
#region IRegionModuleBase implementation
void IRegionModuleBase.Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("UserProfilesServices", "");
if (name == Name)
{
InitialiseService(source);
m_log.Info("[LOCAL USERPROFILES SERVICE CONNECTOR]: Local user profiles connector enabled");
}
}
}
void IRegionModuleBase.Close()
{
return;
}
void IRegionModuleBase.AddRegion(Scene scene)
{
if (!Enabled)
return;
try
{
regions.Add(scene.RegionInfo.RegionID, scene);
}
catch
{
m_log.ErrorFormat("[LOCAL USERPROFILES SERVICE CONNECTOR]: simulator seems to have more than one region with the same UUID. Please correct this!");
}
}
void IRegionModuleBase.RemoveRegion(Scene scene)
{
if (!Enabled)
return;
regions.Remove(scene.RegionInfo.RegionID);
}
void IRegionModuleBase.RegionLoaded(Scene scene)
{
if (!Enabled)
return;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
namespace System.Configuration
{
public sealed class ConfigurationProperty
{
internal static readonly ConfigurationValidatorBase s_nonEmptyStringValidator = new StringValidator(1);
private static readonly ConfigurationValidatorBase s_defaultValidatorInstance = new DefaultValidator();
internal static readonly string s_defaultCollectionPropertyName = "";
private TypeConverter _converter;
private volatile bool _isConfigurationElementType;
private volatile bool _isTypeInited;
private ConfigurationPropertyOptions _options;
public ConfigurationProperty(string name, Type type)
{
object defaultValue = null;
ConstructorInit(name, type, ConfigurationPropertyOptions.None, null, null);
if (type == typeof(string))
{
defaultValue = string.Empty;
}
else if (type.IsValueType)
{
defaultValue = TypeUtil.CreateInstance(type);
}
SetDefaultValue(defaultValue);
}
public ConfigurationProperty(string name, Type type, object defaultValue)
: this(name, type, defaultValue, ConfigurationPropertyOptions.None)
{ }
public ConfigurationProperty(string name, Type type, object defaultValue, ConfigurationPropertyOptions options)
: this(name, type, defaultValue, null, null, options)
{ }
public ConfigurationProperty(string name,
Type type,
object defaultValue,
TypeConverter typeConverter,
ConfigurationValidatorBase validator,
ConfigurationPropertyOptions options)
: this(name, type, defaultValue, typeConverter, validator, options, null)
{ }
public ConfigurationProperty(string name,
Type type,
object defaultValue,
TypeConverter typeConverter,
ConfigurationValidatorBase validator,
ConfigurationPropertyOptions options,
string description)
{
ConstructorInit(name, type, options, validator, typeConverter);
SetDefaultValue(defaultValue);
}
internal ConfigurationProperty(PropertyInfo info)
{
Debug.Assert(info != null, "info != null");
ConfigurationPropertyAttribute propertyAttribute = null;
DescriptionAttribute descriptionAttribute = null;
// For compatibility we read the component model default value attribute. It is only
// used if ConfigurationPropertyAttribute doesn't provide the default value.
DefaultValueAttribute defaultValueAttribute = null;
TypeConverter typeConverter = null;
ConfigurationValidatorBase validator = null;
// Look for relevant attributes
foreach (Attribute attribute in Attribute.GetCustomAttributes(info))
{
if (attribute is TypeConverterAttribute)
{
typeConverter = TypeUtil.CreateInstance<TypeConverter>(((TypeConverterAttribute)attribute).ConverterTypeName);
}
else if (attribute is ConfigurationPropertyAttribute)
{
propertyAttribute = (ConfigurationPropertyAttribute)attribute;
}
else if (attribute is ConfigurationValidatorAttribute)
{
if (validator != null)
{
// We only allow one validator to be specified on a property.
//
// Consider: introduce a new validator type ( CompositeValidator ) that is a
// list of validators and executes them all
throw new ConfigurationErrorsException(
string.Format(SR.Validator_multiple_validator_attributes, info.Name));
}
ConfigurationValidatorAttribute validatorAttribute = (ConfigurationValidatorAttribute)attribute;
validatorAttribute.SetDeclaringType(info.DeclaringType);
validator = validatorAttribute.ValidatorInstance;
}
else if (attribute is DescriptionAttribute)
{
descriptionAttribute = (DescriptionAttribute)attribute;
}
else if (attribute is DefaultValueAttribute)
{
defaultValueAttribute = (DefaultValueAttribute)attribute;
}
}
Type propertyType = info.PropertyType;
// If the property is a Collection we need to look for the ConfigurationCollectionAttribute for
// additional customization.
if (typeof(ConfigurationElementCollection).IsAssignableFrom(propertyType))
{
// Look for the ConfigurationCollection attribute on the property itself, fall back
// on the property type.
ConfigurationCollectionAttribute collectionAttribute =
Attribute.GetCustomAttribute(info,
typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute ??
Attribute.GetCustomAttribute(propertyType,
typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
if (collectionAttribute != null)
{
if (collectionAttribute.AddItemName.IndexOf(',') == -1) AddElementName = collectionAttribute.AddItemName;
RemoveElementName = collectionAttribute.RemoveItemName;
ClearElementName = collectionAttribute.ClearItemsName;
}
}
// This constructor shouldn't be invoked if the reflection info is not for an actual config property
Debug.Assert(propertyAttribute != null, "attribProperty != null");
ConstructorInit(propertyAttribute.Name,
info.PropertyType,
propertyAttribute.Options,
validator,
typeConverter);
// Figure out the default value
InitDefaultValueFromTypeInfo(propertyAttribute, defaultValueAttribute);
// Get the description
if (!string.IsNullOrEmpty(descriptionAttribute?.Description))
Description = descriptionAttribute.Description;
}
public string Name { get; private set; }
public string Description { get; }
internal string ProvidedName { get; private set; }
internal bool IsConfigurationElementType
{
get
{
if (_isTypeInited)
return _isConfigurationElementType;
_isConfigurationElementType = typeof(ConfigurationElement).IsAssignableFrom(Type);
_isTypeInited = true;
return _isConfigurationElementType;
}
}
public Type Type { get; private set; }
public object DefaultValue { get; private set; }
public bool IsRequired => (_options & ConfigurationPropertyOptions.IsRequired) != 0;
public bool IsKey => (_options & ConfigurationPropertyOptions.IsKey) != 0;
public bool IsDefaultCollection => (_options & ConfigurationPropertyOptions.IsDefaultCollection) != 0;
public bool IsTypeStringTransformationRequired
=> (_options & ConfigurationPropertyOptions.IsTypeStringTransformationRequired) != 0;
public bool IsAssemblyStringTransformationRequired
=> (_options & ConfigurationPropertyOptions.IsAssemblyStringTransformationRequired) != 0;
public bool IsVersionCheckRequired => (_options & ConfigurationPropertyOptions.IsVersionCheckRequired) != 0;
public TypeConverter Converter
{
get
{
CreateConverter();
return _converter;
}
}
public ConfigurationValidatorBase Validator { get; private set; }
internal string AddElementName { get; }
internal string RemoveElementName { get; }
internal string ClearElementName { get; }
private void ConstructorInit(
string name,
Type type,
ConfigurationPropertyOptions options,
ConfigurationValidatorBase validator,
TypeConverter converter)
{
if (typeof(ConfigurationSection).IsAssignableFrom(type))
{
throw new ConfigurationErrorsException(
string.Format(SR.Config_properties_may_not_be_derived_from_configuration_section, name));
}
// save the provided name so we can check for default collection names
ProvidedName = name;
if (((options & ConfigurationPropertyOptions.IsDefaultCollection) != 0) && string.IsNullOrEmpty(name))
{
name = s_defaultCollectionPropertyName;
}
else
{
ValidatePropertyName(name);
}
Name = name;
Type = type;
_options = options;
Validator = validator;
_converter = converter;
// Use the default validator if none was supplied
if (Validator == null)
{
Validator = s_defaultValidatorInstance;
}
else
{
// Make sure the supplied validator supports the type of this property
if (!Validator.CanValidate(Type))
throw new ConfigurationErrorsException(string.Format(SR.Validator_does_not_support_prop_type, Name));
}
}
private void ValidatePropertyName(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException(SR.String_null_or_empty, nameof(name));
if (BaseConfigurationRecord.IsReservedAttributeName(name))
throw new ArgumentException(string.Format(SR.Property_name_reserved, name));
}
private void SetDefaultValue(object value)
{
// Validate the default value if any. This should make errors from invalid defaults easier to catch
if (ConfigurationElement.IsNullOrNullProperty(value))
return;
if (!Type.IsInstanceOfType(value))
{
if (!Converter.CanConvertFrom(value.GetType()))
throw new ConfigurationErrorsException(string.Format(SR.Default_value_wrong_type, Name));
value = Converter.ConvertFrom(value);
}
Validate(value);
DefaultValue = value;
}
private void InitDefaultValueFromTypeInfo(
ConfigurationPropertyAttribute configurationProperty,
DefaultValueAttribute defaultValueAttribute)
{
object defaultValue = configurationProperty.DefaultValue;
// If the ConfigurationPropertyAttribute has no default try the DefaultValueAttribute
if (ConfigurationElement.IsNullOrNullProperty(defaultValue))
defaultValue = defaultValueAttribute?.Value;
// Convert the default value from string if necessary
if (defaultValue is string && (Type != typeof(string)))
{
try
{
defaultValue = Converter.ConvertFromInvariantString((string)defaultValue);
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(string.Format(SR.Default_value_conversion_error_from_string,
Name, ex.Message));
}
}
// If we still have no default, use string Empty for string or the default for value types
if (ConfigurationElement.IsNullOrNullProperty(defaultValue))
{
if (Type == typeof(string))
{
defaultValue = string.Empty;
}
else if (Type.IsValueType)
{
defaultValue = TypeUtil.CreateInstance(Type);
}
}
SetDefaultValue(defaultValue);
}
internal object ConvertFromString(string value)
{
object result;
try
{
result = Converter.ConvertFromInvariantString(value);
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(string.Format(SR.Top_level_conversion_error_from_string, Name,
ex.Message));
}
return result;
}
internal string ConvertToString(object value)
{
try
{
if (Type == typeof(bool))
{
// The boolean converter will break 1.1 compat for bool
return (bool)value ? "true" : "false";
}
else
{
return Converter.ConvertToInvariantString(value);
}
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(
string.Format(SR.Top_level_conversion_error_to_string, Name, ex.Message));
}
}
internal void Validate(object value)
{
try
{
Validator.Validate(value);
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(
string.Format(SR.Top_level_validation_error, Name, ex.Message), ex);
}
}
private void CreateConverter()
{
if (_converter != null) return;
if (Type.IsEnum)
{
// We use our custom converter for all enums
_converter = new GenericEnumConverter(Type);
}
else if (Type.IsSubclassOf(typeof(ConfigurationElement)))
{
// Type converters aren't allowed on ConfigurationElement
// derived classes.
return;
}
else
{
_converter = TypeDescriptor.GetConverter(Type);
if ((_converter == null) ||
!_converter.CanConvertFrom(typeof(string)) ||
!_converter.CanConvertTo(typeof(string)))
{
// Need to be able to convert to/from string
throw new ConfigurationErrorsException(string.Format(SR.No_converter, Name, Type.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.
/******************************************************************************
* 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;
using static System.Runtime.Intrinsics.X86.Sse;
using static System.Runtime.Intrinsics.X86.Sse2;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertSingle4()
{
var test = new InsertVector128Test__InsertSingle4();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class InsertVector128Test__InsertSingle4
{
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(InsertVector128Test__InsertSingle4 testClass)
{
var result = Sse41.Insert(_fld1, _fld2, 4);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static InsertVector128Test__InsertSingle4()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public InsertVector128Test__InsertSingle4()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Insert(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
4
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Insert(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
4
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Insert(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
4
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
(byte)4
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)4
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)4
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Insert(
_clsVar1,
_clsVar2,
4
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse41.Insert(left, right, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertVector128Test__InsertSingle4();
var result = Sse41.Insert(test._fld1, test._fld2, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Insert(_fld1, _fld2, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Insert(test._fld1, test._fld2, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (i == 2 ? BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(0.0f) : BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Single>(Vector128<Single>, Vector128<Single>.4): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualMachineImagesOperations operations.
/// </summary>
internal partial class VirtualMachineImagesOperations : IServiceOperations<ComputeManagementClient>, IVirtualMachineImagesOperations
{
/// <summary>
/// Initializes a new instance of the VirtualMachineImagesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VirtualMachineImagesOperations(ComputeManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ComputeManagementClient
/// </summary>
public ComputeManagementClient Client { get; private set; }
/// <summary>
/// Gets a virtual machine image.
/// </summary>
/// <param name='location'>
/// The name of a supported Azure region.
/// </param>
/// <param name='publisherName'>
/// A valid image publisher.
/// </param>
/// <param name='offer'>
/// A valid image publisher offer.
/// </param>
/// <param name='skus'>
/// A valid image SKU.
/// </param>
/// <param name='version'>
/// A valid image SKU version.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualMachineImage>> GetWithHttpMessagesAsync(string location, string publisherName, string offer, string skus, string version, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (publisherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publisherName");
}
if (offer == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "offer");
}
if (skus == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "skus");
}
if (version == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "version");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-30";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("publisherName", publisherName);
tracingParameters.Add("offer", offer);
tracingParameters.Add("skus", skus);
tracingParameters.Add("version", version);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions/{version}").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName));
_url = _url.Replace("{offer}", System.Uri.EscapeDataString(offer));
_url = _url.Replace("{skus}", System.Uri.EscapeDataString(skus));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualMachineImage>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualMachineImage>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of all virtual machine image versions for the specified
/// location, publisher, offer, and SKU.
/// </summary>
/// <param name='location'>
/// The name of a supported Azure region.
/// </param>
/// <param name='publisherName'>
/// A valid image publisher.
/// </param>
/// <param name='offer'>
/// A valid image publisher offer.
/// </param>
/// <param name='skus'>
/// A valid image SKU.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<VirtualMachineImageResource>>> ListWithHttpMessagesAsync(string location, string publisherName, string offer, string skus, ODataQuery<VirtualMachineImageResource> odataQuery = default(ODataQuery<VirtualMachineImageResource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (publisherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publisherName");
}
if (offer == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "offer");
}
if (skus == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "skus");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-30";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("location", location);
tracingParameters.Add("publisherName", publisherName);
tracingParameters.Add("offer", offer);
tracingParameters.Add("skus", skus);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName));
_url = _url.Replace("{offer}", System.Uri.EscapeDataString(offer));
_url = _url.Replace("{skus}", System.Uri.EscapeDataString(skus));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<VirtualMachineImageResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<VirtualMachineImageResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of virtual machine image offers for the specified location and
/// publisher.
/// </summary>
/// <param name='location'>
/// The name of a supported Azure region.
/// </param>
/// <param name='publisherName'>
/// A valid image publisher.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<VirtualMachineImageResource>>> ListOffersWithHttpMessagesAsync(string location, string publisherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (publisherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publisherName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-30";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("publisherName", publisherName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListOffers", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<VirtualMachineImageResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<VirtualMachineImageResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of virtual machine image publishers for the specified Azure
/// location.
/// </summary>
/// <param name='location'>
/// The name of a supported Azure region.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<VirtualMachineImageResource>>> ListPublishersWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-30";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListPublishers", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<VirtualMachineImageResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<VirtualMachineImageResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of virtual machine image SKUs for the specified location,
/// publisher, and offer.
/// </summary>
/// <param name='location'>
/// The name of a supported Azure region.
/// </param>
/// <param name='publisherName'>
/// A valid image publisher.
/// </param>
/// <param name='offer'>
/// A valid image publisher offer.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<VirtualMachineImageResource>>> ListSkusWithHttpMessagesAsync(string location, string publisherName, string offer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (publisherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publisherName");
}
if (offer == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "offer");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-30";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("publisherName", publisherName);
tracingParameters.Add("offer", offer);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListSkus", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName));
_url = _url.Replace("{offer}", System.Uri.EscapeDataString(offer));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<VirtualMachineImageResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<VirtualMachineImageResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for RouteTablesOperations.
/// </summary>
public static partial class RouteTablesOperationsExtensions
{
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
public static void Delete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName)
{
operations.DeleteAsync(resourceGroupName, routeTableName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static RouteTable Get(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, routeTableName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> GetAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeTableName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
public static RouteTable CreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, routeTableName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> CreateOrUpdateAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<RouteTable> List(this IRouteTablesOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAsync(this IRouteTablesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<RouteTable> ListAll(this IRouteTablesOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAllAsync(this IRouteTablesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
public static void BeginDelete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName)
{
operations.BeginDeleteAsync(resourceGroupName, routeTableName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
public static RouteTable BeginCreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeTableName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> BeginCreateOrUpdateAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteTable> ListNext(this IRouteTablesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListNextAsync(this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteTable> ListAllNext(this IRouteTablesOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAllNextAsync(this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////
// Description: Data Access class for the table 'Users'
// Generated by LLBLGen v1.21.2003.712 Final on: 14 Oktober 2005, 23:56:46
// Because the Base Class already implements IDispose, this class doesn't.
///////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace BkNet.DataAccess
{
/// <summary>
/// Purpose: Data Access class for the table 'Users'.
/// </summary>
public class Users : DBInteractionBase
{
#region Class Member Declarations
private SqlInt32 _groupId, _groupIdOld, _userId;
private SqlString _namaLengkap, _userName, _password;
#endregion
/// <summary>
/// Purpose: Class constructor.
/// </summary>
public Users()
{
// Nothing for now.
}
/// <summary>
/// Purpose: IsExist method. This method will check exsisting username in database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>UserId</LI>
/// <LI>UserName. May be SqlString.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public bool IsExist()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_IsExist]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _userId));
cmdToExecute.Parameters.Add(new SqlParameter("@UserName", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _userName));
cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString());
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_IsExist' reported the ErrorCode: " + _errorCode);
}
return IsExist==1;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::IsExist::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Insert method. This method will insert one new row into the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>UserId</LI>
/// <LI>UserName. May be SqlString.Null</LI>
/// <LI>Password. May be SqlString.Null</LI>
/// <LI>NamaLengkap. May be SqlString.Null</LI>
/// <LI>GroupId. May be SqlInt32.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Insert()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_Insert]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@UserName", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _userName));
cmdToExecute.Parameters.Add(new SqlParameter("@Password", SqlDbType.VarChar, 100, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _password));
cmdToExecute.Parameters.Add(new SqlParameter("@NamaLengkap", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _namaLengkap));
cmdToExecute.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _groupId));
cmdToExecute.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _userId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_userId = (SqlInt32)cmdToExecute.Parameters["@UserId"].Value;
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_Insert' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::Insert::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method. This method will Update one existing row in the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>UserId</LI>
/// <LI>UserName. May be SqlString.Null</LI>
/// <LI>Password. May be SqlString.Null</LI>
/// <LI>NamaLengkap. May be SqlString.Null</LI>
/// <LI>GroupId. May be SqlInt32.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Update()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_Update]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _userId));
cmdToExecute.Parameters.Add(new SqlParameter("@UserName", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _userName));
cmdToExecute.Parameters.Add(new SqlParameter("@Password", SqlDbType.VarChar, 100, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _password));
cmdToExecute.Parameters.Add(new SqlParameter("@NamaLengkap", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _namaLengkap));
cmdToExecute.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _groupId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_Update' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::Update::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>UserId</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Delete()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_Delete]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _userId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_Delete' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::Delete::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>UserId</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// <LI>UserId</LI>
/// <LI>UserName</LI>
/// <LI>Password</LI>
/// <LI>NamaLengkap</LI>
/// <LI>GroupId</LI>
/// </UL>
/// Will fill all properties corresponding with a field in the table with the value of the row selected.
/// </remarks>
public override DataTable SelectOne()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_SelectOne]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("Users");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _userId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_SelectOne' reported the ErrorCode: " + _errorCode);
}
if(toReturn.Rows.Count > 0)
{
_userId = SqlInt32.Parse(toReturn.Rows[0]["UserId"].ToString());
_userName = toReturn.Rows[0]["UserName"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["UserName"];
_password = toReturn.Rows[0]["Password"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Password"];
_namaLengkap = toReturn.Rows[0]["NamaLengkap"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["NamaLengkap"];
_groupId = toReturn.Rows[0]["GroupId"] == System.DBNull.Value ? SqlInt32.Null : SqlInt32.Parse(toReturn.Rows[0]["GroupId"].ToString());
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::SelectOne::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: SelectAll method. This method will Select all rows from the table.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override DataTable SelectAll()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_SelectAll]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("Users");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_SelectAll' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::SelectAll::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
public DataTable SelectAllByUserId()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_SelectAllByUserId]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("Users");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _userId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_SelectAllByUserId' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::SelectAllByUserId::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: Login method. This method will check validation username and password.
/// </summary>
/// <returns>Blank message if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>UserName. May be SqlString.Null</LI>
/// <LI>Password. May be SqlString.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>UserId. May be SqlInt32.Null</LI>
/// <LI>GroupId. May be SqlInt32.Null</LI>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public string Login()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_Login]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@UserName", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _userName));
cmdToExecute.Parameters.Add(new SqlParameter("@Password", SqlDbType.VarChar, 100, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _password));
cmdToExecute.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _userId));
cmdToExecute.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _groupId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorMessage", SqlDbType.VarChar, 255, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Proposed, ""));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
string errorMessage = (string)cmdToExecute.Parameters["@ErrorMessage"].Value;
_userId = (SqlInt32)cmdToExecute.Parameters["@UserId"].Value;
_groupId = (SqlInt32)cmdToExecute.Parameters["@GroupId"].Value;
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_Login' reported the ErrorCode: " + _errorCode);
}
return errorMessage;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::Login::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
public bool HasAccessToPolicy(string PolicyName)
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_HasAccessToPolicy]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _userId));
cmdToExecute.Parameters.Add(new SqlParameter("@PolicyName", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, PolicyName));
cmdToExecute.Parameters.Add(new SqlParameter("@IsAccess", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
int IsAccess = int.Parse(cmdToExecute.Parameters["@IsAccess"].Value.ToString());
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_HasAccessToPolicy' reported the ErrorCode: " + _errorCode);
}
return IsAccess==1;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::HasAccessToPolicy::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Untuk mengambil semua policy yang dimiliki oleh user
/// Created By Ekitea On 23 July 2006
/// </summary>
/// <returns></returns>
public DataTable GetAllPolicy()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[Users_GetAllPolicy]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("Users");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _userId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int) LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'Users_GetAllPolicy' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Users::GetAllPolicy::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
#region Class Property Declarations
public SqlInt32 UserId
{
get
{
return _userId;
}
set
{
SqlInt32 userIdTmp = (SqlInt32)value;
if(userIdTmp.IsNull)
{
throw new ArgumentOutOfRangeException("UserId", "UserId can't be NULL");
}
_userId = value;
}
}
public SqlString UserName
{
get
{
return _userName;
}
set
{
_userName = value;
}
}
public SqlString Password
{
get
{
return _password;
}
set
{
_password = value;
}
}
public SqlString NamaLengkap
{
get
{
return _namaLengkap;
}
set
{
_namaLengkap = value;
}
}
public SqlInt32 GroupId
{
get
{
return _groupId;
}
set
{
_groupId = value;
}
}
public SqlInt32 GroupIdOld
{
get
{
return _groupIdOld;
}
set
{
_groupIdOld = value;
}
}
#endregion
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="UIElement.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Avalonia
{
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Input;
using Avalonia.Media;
public class UIElement : Visual, IInputElement
{
public static readonly DependencyProperty FocusableProperty =
DependencyProperty.Register(
"Focusable",
typeof(bool),
typeof(UIElement));
public static readonly DependencyProperty IsKeyboardFocusedProperty =
DependencyProperty.Register(
"IsKeyboardFocused",
typeof(bool),
typeof(UIElement));
public static readonly DependencyProperty IsMouseOverProperty =
DependencyProperty.Register(
"IsMouseOver",
typeof(bool),
typeof(UIElement));
public static readonly DependencyProperty IsMouseCapturedProperty =
DependencyProperty.Register(
"IsMouseCaptured",
typeof(bool),
typeof(UIElement));
public static readonly DependencyProperty OpacityProperty =
DependencyProperty.Register(
"Opacity",
typeof(double),
typeof(UIElement),
new PropertyMetadata(1.0));
public static readonly DependencyProperty SnapsToDevicePixelsProperty =
DependencyProperty.Register(
"SnapsToDevicePixels",
typeof(bool),
typeof(UIElement));
public static readonly RoutedEvent GotKeyboardFocusEvent =
Keyboard.GotKeyboardFocusEvent.AddOwner(typeof(UIElement));
public static readonly RoutedEvent LostKeyboardFocusEvent =
Keyboard.LostKeyboardFocusEvent.AddOwner(typeof(UIElement));
public static readonly RoutedEvent KeyDownEvent =
Keyboard.KeyDownEvent.AddOwner(typeof(UIElement));
public static readonly RoutedEvent MouseEnterEvent =
Mouse.MouseEnterEvent.AddOwner(typeof(UIElement));
public static readonly RoutedEvent MouseLeaveEvent =
Mouse.MouseLeaveEvent.AddOwner(typeof(UIElement));
public static readonly RoutedEvent MouseLeftButtonDownEvent =
Mouse.MouseLeftButtonDownEvent.AddOwner(typeof(UIElement));
public static readonly RoutedEvent MouseLeftButtonUpEvent =
Mouse.MouseLeftButtonUpEvent.AddOwner(typeof(UIElement));
public static readonly RoutedEvent MouseMoveEvent =
Mouse.MouseMoveEvent.AddOwner(typeof(UIElement));
public static readonly RoutedEvent TextInputEvent =
TextCompositionManager.TextInputEvent.AddOwner(typeof(UIElement));
private bool measureCalled;
private Size previousMeasureSize;
private Dictionary<RoutedEvent, List<Delegate>> eventHandlers = new Dictionary<RoutedEvent, List<Delegate>>();
public UIElement()
{
this.IsMeasureValid = true;
this.IsArrangeValid = true;
this.AddHandler(GotKeyboardFocusEvent, (KeyboardFocusChangedEventHandler)((s, e) => this.OnGotKeyboardFocus(e)));
this.AddHandler(LostKeyboardFocusEvent, (KeyboardFocusChangedEventHandler)((s, e) => this.OnLostKeyboardFocus(e)));
this.AddHandler(MouseEnterEvent, (MouseEventHandler)((s, e) => this.OnMouseEnter(e)));
this.AddHandler(MouseLeaveEvent, (MouseEventHandler)((s, e) => this.OnMouseLeave(e)));
this.AddHandler(MouseLeftButtonDownEvent, (MouseButtonEventHandler)((s, e) => this.OnMouseLeftButtonDown(e)));
this.AddHandler(MouseLeftButtonUpEvent, (MouseButtonEventHandler)((s, e) => this.OnMouseLeftButtonUp(e)));
this.AddHandler(MouseMoveEvent, (MouseEventHandler)((s, e) => this.OnMouseMove(e)));
this.AddHandler(TextInputEvent, (TextCompositionEventHandler)((s, e) => this.OnTextInput(e)));
}
public event KeyEventHandler KeyDown
{
add { this.AddHandler(KeyDownEvent, value); }
remove { this.RemoveHandler(KeyDownEvent, value); }
}
public event MouseEventHandler MouseEnter
{
add { this.AddHandler(MouseEnterEvent, value); }
remove { this.RemoveHandler(MouseEnterEvent, value); }
}
public event MouseEventHandler MouseLeave
{
add { this.AddHandler(MouseLeaveEvent, value); }
remove { this.RemoveHandler(MouseLeaveEvent, value); }
}
public event MouseButtonEventHandler MouseLeftButtonDown
{
add { this.AddHandler(MouseLeftButtonDownEvent, value); }
remove { this.RemoveHandler(MouseLeftButtonDownEvent, value); }
}
public event MouseButtonEventHandler MouseLeftButtonUp
{
add { this.AddHandler(MouseLeftButtonUpEvent, value); }
remove { this.RemoveHandler(MouseLeftButtonUpEvent, value); }
}
public event MouseEventHandler MouseMove
{
add { this.AddHandler(MouseMoveEvent, value); }
remove { this.RemoveHandler(MouseMoveEvent, value); }
}
public Size DesiredSize { get; set; }
public bool IsMeasureValid { get; private set; }
public bool IsArrangeValid { get; private set; }
public bool IsVisible
{
get
{
// TODO: Implement visibility.
return true;
}
}
public Size RenderSize { get; private set; }
public bool Focusable
{
get { return (bool)this.GetValue(FocusableProperty); }
set { this.SetValue(FocusableProperty, value); }
}
public bool IsKeyboardFocused
{
get { return (bool)this.GetValue(IsKeyboardFocusedProperty); }
}
public bool IsMouseOver
{
get { return (bool)this.GetValue(IsMouseOverProperty); }
}
public bool IsMouseCaptured
{
get { return (bool)this.GetValue(IsMouseCapturedProperty); }
private set { this.SetValue(IsMouseCapturedProperty, value); }
}
public double Opacity
{
get { return (double)this.GetValue(OpacityProperty); }
set { this.SetValue(OpacityProperty, value); }
}
// TODO: Actually implement this.
public bool SnapsToDevicePixels
{
get { return (bool)this.GetValue(SnapsToDevicePixelsProperty); }
set { this.SetValue(SnapsToDevicePixelsProperty, value); }
}
public void CaptureMouse()
{
Mouse.Capture(this);
this.IsMouseCaptured = true;
}
public void ReleaseMouseCapture()
{
if (Mouse.Captured == this)
{
Mouse.Capture(null);
this.IsMouseCaptured = false;
}
}
public void Measure(Size availableSize)
{
this.measureCalled = true;
this.previousMeasureSize = availableSize;
this.DesiredSize = this.MeasureCore(availableSize);
this.IsMeasureValid = true;
this.IsArrangeValid = false;
}
public void Arrange(Rect finalRect)
{
if (!this.measureCalled || !this.IsMeasureValid)
{
this.Measure(this.measureCalled ? this.previousMeasureSize : finalRect.Size);
}
this.ArrangeCore(finalRect);
this.IsArrangeValid = true;
}
public void InvalidateMeasure()
{
this.IsMeasureValid = false;
LayoutManager.Instance.QueueMeasure(this);
}
public void InvalidateArrange()
{
this.IsArrangeValid = false;
LayoutManager.Instance.QueueArrange(this);
}
public void InvalidateVisual()
{
this.InvalidateArrange();
}
public void UpdateLayout()
{
Size size = this.RenderSize;
this.Measure(size);
this.Arrange(new Rect(size));
}
public IInputElement InputHitTest(Point point)
{
Rect bounds = new Rect(this.RenderSize);
if (bounds.Contains(point))
{
foreach (UIElement child in VisualTreeHelper.GetChildren(this).OfType<UIElement>())
{
Point offsetPoint = point - child.VisualOffset;
IInputElement hit = child.InputHitTest(offsetPoint);
if (hit != null)
{
return hit;
}
}
return this;
}
else
{
return null;
}
}
public void AddHandler(RoutedEvent routedEvent, Delegate handler)
{
if (routedEvent == null)
{
throw new ArgumentNullException("routedEvent");
}
if (handler == null)
{
throw new ArgumentNullException("handler");
}
List<Delegate> delegates;
if (!this.eventHandlers.TryGetValue(routedEvent, out delegates))
{
delegates = new List<Delegate>();
this.eventHandlers.Add(routedEvent, delegates);
}
delegates.Add(handler);
}
public void RemoveHandler(RoutedEvent routedEvent, Delegate handler)
{
if (routedEvent == null)
{
throw new ArgumentNullException("routedEvent");
}
if (handler == null)
{
throw new ArgumentNullException("handler");
}
List<Delegate> delegates;
if (this.eventHandlers.TryGetValue(routedEvent, out delegates))
{
delegates.Remove(handler);
}
}
public void RaiseEvent(RoutedEventArgs e)
{
if (e.RoutedEvent != null)
{
switch (e.RoutedEvent.RoutingStrategy)
{
case RoutingStrategy.Bubble:
this.BubbleEvent(e);
break;
case RoutingStrategy.Direct:
this.RaiseEventImpl(e);
break;
default:
throw new NotImplementedException();
}
}
}
internal override Rect GetHitTestBounds()
{
return new Rect((Point)this.VisualOffset, this.RenderSize);
}
protected internal virtual void OnRender(DrawingContext drawingContext)
{
}
protected virtual Size MeasureCore(Size availableSize)
{
return new Size();
}
protected virtual void ArrangeCore(Rect finalRect)
{
this.VisualOffset = (Vector)finalRect.TopLeft;
this.RenderSize = finalRect.Size;
}
protected virtual void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
}
protected virtual void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
}
protected virtual void OnMouseEnter(MouseEventArgs e)
{
}
protected virtual void OnMouseLeave(MouseEventArgs e)
{
}
protected virtual void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
}
protected virtual void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
}
protected virtual void OnMouseMove(MouseEventArgs e)
{
}
protected virtual void OnTextInput(TextCompositionEventArgs e)
{
}
private void BubbleEvent(RoutedEventArgs e)
{
UIElement target = this;
while (target != null)
{
target.RaiseEventImpl(e);
target = VisualTreeHelper.GetAncestor<UIElement>(target);
}
}
private void RaiseEventImpl(RoutedEventArgs e)
{
List<Delegate> delegates;
if (this.eventHandlers.TryGetValue(e.RoutedEvent, out delegates))
{
foreach (Delegate handler in delegates)
{
// TODO: Implement the Handled stuff.
handler.DynamicInvoke(this, e);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System.Text.Formatting;
using System.Buffers.Text;
using System.IO;
namespace System.Text.JsonLab.Tests
{
public class JsonWriterTests
{
private const int ExtraArraySize = 500;
[Fact]
public void WriteJsonUtf8()
{
var formatter = new ArrayFormatterWrapper(1024, SymbolTable.InvariantUtf8);
var json = new Utf8JsonWriter<ArrayFormatterWrapper>(formatter, prettyPrint: false);
Write(ref json);
var formatted = formatter.Formatted;
var str = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count);
Assert.Equal(expected, str.Replace(" ", ""));
formatter.Clear();
json = new Utf8JsonWriter<ArrayFormatterWrapper>(formatter, prettyPrint: true);
Write(ref json);
formatted = formatter.Formatted;
str = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count);
Assert.Equal(expected, str.Replace("\r\n", "").Replace("\n", "").Replace(" ", ""));
}
static readonly string expected = "{\"age\":30,\"first\":\"John\",\"last\":\"Smith\",\"phoneNumbers\":[\"425-000-1212\",\"425-000-1213\",null],\"address\":{\"street\":\"1MicrosoftWay\",\"city\":\"Redmond\",\"zip\":98052},\"values\":[425121,-425122,425123]}";
static void Write(ref Utf8JsonWriter<ArrayFormatterWrapper> json)
{
json.WriteObjectStart();
json.WriteAttribute("age", 30);
json.WriteAttribute("first", "John");
json.WriteAttribute("last", "Smith");
json.WriteArrayStart("phoneNumbers");
json.WriteValue("425-000-1212");
json.WriteValue("425-000-1213");
json.WriteNull();
json.WriteArrayEnd();
json.WriteObjectStart("address");
json.WriteAttribute("street", "1 Microsoft Way");
json.WriteAttribute("city", "Redmond");
json.WriteAttribute("zip", 98052);
json.WriteObjectEnd();
json.WriteArrayStart("values");
json.WriteValue(425121);
json.WriteValue(-425122);
json.WriteValue(425123);
json.WriteArrayEnd();
json.WriteObjectEnd();
json.Flush();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WriteHelloWorldJsonUtf8(bool prettyPrint)
{
string expectedStr = GetHelloWorldExpectedString(prettyPrint, isUtf8: true);
var output = new ArrayFormatterWrapper(1024, SymbolTable.InvariantUtf8);
var jsonUtf8 = new Utf8JsonWriter<ArrayFormatterWrapper>(output, prettyPrint);
jsonUtf8.WriteObjectStart();
jsonUtf8.WriteAttribute("message", "Hello, World!");
jsonUtf8.WriteObjectEnd();
jsonUtf8.Flush();
ArraySegment<byte> formatted = output.Formatted;
string actualStr = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count);
Assert.Equal(expectedStr, actualStr);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WriteBasicJsonUtf8(bool prettyPrint)
{
int[] data = GetData(ExtraArraySize, 42, -10000, 10000);
string expectedStr = GetExpectedString(prettyPrint, isUtf8: true, data);
var output = new ArrayFormatterWrapper(1024, SymbolTable.InvariantUtf8);
var jsonUtf8 = new Utf8JsonWriter<ArrayFormatterWrapper>(output, prettyPrint);
jsonUtf8.WriteObjectStart();
jsonUtf8.WriteAttribute("age", 42);
jsonUtf8.WriteAttribute("first", "John");
jsonUtf8.WriteAttribute("last", "Smith");
jsonUtf8.WriteArrayStart("phoneNumbers");
jsonUtf8.WriteValue("425-000-1212");
jsonUtf8.WriteValue("425-000-1213");
jsonUtf8.WriteArrayEnd();
jsonUtf8.WriteObjectStart("address");
jsonUtf8.WriteAttribute("street", "1 Microsoft Way");
jsonUtf8.WriteAttribute("city", "Redmond");
jsonUtf8.WriteAttribute("zip", 98052);
jsonUtf8.WriteObjectEnd();
// Add a large array of values
jsonUtf8.WriteArrayStart("ExtraArray");
for (var i = 0; i < ExtraArraySize; i++)
{
jsonUtf8.WriteValue(data[i]);
}
jsonUtf8.WriteArrayEnd();
jsonUtf8.WriteObjectEnd();
jsonUtf8.Flush();
ArraySegment<byte> formatted = output.Formatted;
string actualStr = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count);
Assert.Equal(expectedStr, actualStr);
}
private static int[] GetData(int size, int seed, int minValue, int maxValue)
{
int[] data = new int[size];
Random rand = new Random(seed);
for (int i = 0; i < ExtraArraySize; i++)
{
data[i] = rand.Next(minValue, maxValue);
}
return data;
}
private static string GetHelloWorldExpectedString(bool prettyPrint, bool isUtf8)
{
MemoryStream ms = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(ms, new UTF8Encoding(false), 1024, true);
StringBuilder sb = new StringBuilder();
StringWriter stringWriter = new StringWriter(sb);
TextWriter writer = isUtf8 ? streamWriter : (TextWriter)stringWriter;
var json = new Newtonsoft.Json.JsonTextWriter(writer)
{
Formatting = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None
};
json.WriteStartObject();
json.WritePropertyName("message");
json.WriteValue("Hello, World!");
json.WriteEnd();
json.Flush();
return isUtf8 ? Encoding.UTF8.GetString(ms.ToArray()) : sb.ToString();
}
private static string GetExpectedString(bool prettyPrint, bool isUtf8, int[] data)
{
MemoryStream ms = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(ms, new UTF8Encoding(false), 1024, true);
StringBuilder sb = new StringBuilder();
StringWriter stringWriter = new StringWriter(sb);
TextWriter writer = isUtf8 ? streamWriter : (TextWriter)stringWriter;
var json = new Newtonsoft.Json.JsonTextWriter(writer)
{
Formatting = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None
};
json.WriteStartObject();
json.WritePropertyName("age");
json.WriteValue(42);
json.WritePropertyName("first");
json.WriteValue("John");
json.WritePropertyName("last");
json.WriteValue("Smith");
json.WritePropertyName("phoneNumbers");
json.WriteStartArray();
json.WriteValue("425-000-1212");
json.WriteValue("425-000-1213");
json.WriteEnd();
json.WritePropertyName("address");
json.WriteStartObject();
json.WritePropertyName("street");
json.WriteValue("1 Microsoft Way");
json.WritePropertyName("city");
json.WriteValue("Redmond");
json.WritePropertyName("zip");
json.WriteValue(98052);
json.WriteEnd();
// Add a large array of values
json.WritePropertyName("ExtraArray");
json.WriteStartArray();
for (var i = 0; i < ExtraArraySize; i++)
{
json.WriteValue(data[i]);
}
json.WriteEnd();
json.WriteEnd();
json.Flush();
return isUtf8 ? Encoding.UTF8.GetString(ms.ToArray()) : sb.ToString();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias Scripting;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.FileSystem;
using Microsoft.CodeAnalysis.Editor.Implementation.Interactive;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver;
internal abstract class InteractiveEvaluator : IInteractiveEvaluator, ICurrentWorkingDirectoryDiscoveryService
{
// full path or null
private readonly string _responseFilePath;
private readonly InteractiveHost _interactiveHost;
private string _initialWorkingDirectory;
private string _initialScriptFileOpt;
private readonly IContentType _contentType;
private readonly InteractiveWorkspace _workspace;
private IInteractiveWindow _currentWindow;
private ImmutableHashSet<MetadataReference> _references;
private ImmutableArray<string> _rspImports;
private MetadataReferenceResolver _metadataReferenceResolver;
private SourceReferenceResolver _sourceReferenceResolver;
private ProjectId _previousSubmissionProjectId;
private ProjectId _currentSubmissionProjectId;
private readonly IViewClassifierAggregatorService _classifierAggregator;
private readonly IInteractiveWindowCommandsFactory _commandsFactory;
private readonly ImmutableArray<IInteractiveWindowCommand> _commands;
private IInteractiveWindowCommands _interactiveCommands;
private ITextView _currentTextView;
private ITextBuffer _currentSubmissionBuffer;
private readonly ISet<ValueTuple<ITextView, ITextBuffer>> _submissionBuffers = new HashSet<ValueTuple<ITextView, ITextBuffer>>();
private int _submissionCount = 0;
private readonly EventHandler<ContentTypeChangedEventArgs> _contentTypeChangedHandler;
public ImmutableArray<string> ReferenceSearchPaths { get; private set; }
public ImmutableArray<string> SourceSearchPaths { get; private set; }
public string WorkingDirectory { get; private set; }
internal InteractiveEvaluator(
IContentType contentType,
HostServices hostServices,
IViewClassifierAggregatorService classifierAggregator,
IInteractiveWindowCommandsFactory commandsFactory,
ImmutableArray<IInteractiveWindowCommand> commands,
string responseFilePath,
string initialWorkingDirectory,
string interactiveHostPath,
Type replType)
{
Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath));
_contentType = contentType;
_responseFilePath = responseFilePath;
_workspace = new InteractiveWorkspace(this, hostServices);
_contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged);
_classifierAggregator = classifierAggregator;
_initialWorkingDirectory = initialWorkingDirectory;
_commandsFactory = commandsFactory;
_commands = commands;
// The following settings will apply when the REPL starts without .rsp file.
// They are discarded once the REPL is reset.
ReferenceSearchPaths = ImmutableArray<string>.Empty;
SourceSearchPaths = ImmutableArray<string>.Empty;
WorkingDirectory = initialWorkingDirectory;
var metadataService = _workspace.CurrentSolution.Services.MetadataService;
_metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory);
_sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory);
_interactiveHost = new InteractiveHost(replType, interactiveHostPath, initialWorkingDirectory);
_interactiveHost.ProcessStarting += ProcessStarting;
}
public IContentType ContentType
{
get
{
return _contentType;
}
}
public IInteractiveWindow CurrentWindow
{
get
{
return _currentWindow;
}
set
{
if (_currentWindow != value)
{
_interactiveHost.Output = value.OutputWriter;
_interactiveHost.ErrorOutput = value.ErrorOutputWriter;
if (_currentWindow != null)
{
_currentWindow.SubmissionBufferAdded -= SubmissionBufferAdded;
}
_currentWindow = value;
}
_currentWindow.SubmissionBufferAdded += SubmissionBufferAdded;
_interactiveCommands = _commandsFactory.CreateInteractiveCommands(_currentWindow, "#", _commands);
}
}
protected IInteractiveWindowCommands InteractiveCommands
{
get
{
return _interactiveCommands;
}
}
protected abstract string LanguageName { get; }
protected abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver, ImmutableArray<string> imports);
protected abstract ParseOptions ParseOptions { get; }
protected abstract CommandLineParser CommandLineParser { get; }
#region Initialization
public string GetConfiguration()
{
return null;
}
private IInteractiveWindow GetInteractiveWindow()
{
var window = CurrentWindow;
if (window == null)
{
throw new InvalidOperationException(EditorFeaturesResources.EngineMustBeAttachedToAnInteractiveWindow);
}
return window;
}
public Task<ExecutionResult> InitializeAsync()
{
var window = GetInteractiveWindow();
_interactiveHost.Output = window.OutputWriter;
_interactiveHost.ErrorOutput = window.ErrorOutputWriter;
return ResetAsyncWorker();
}
public void Dispose()
{
_workspace.Dispose();
_interactiveHost.Dispose();
}
/// <summary>
/// Invoked by <see cref="InteractiveHost"/> when a new process is being started.
/// </summary>
private void ProcessStarting(bool initialize)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(new Action(() => ProcessStarting(initialize)));
return;
}
// Freeze all existing classifications and then clear the list of
// submission buffers we have.
FreezeClassifications();
_submissionBuffers.Clear();
// We always start out empty
_workspace.ClearSolution();
_currentSubmissionProjectId = null;
_previousSubmissionProjectId = null;
var metadataService = _workspace.CurrentSolution.Services.MetadataService;
var mscorlibRef = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly);
var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveScriptGlobals).Assembly.Location, Script.HostAssemblyReferenceProperties);
_references = ImmutableHashSet.Create<MetadataReference>(mscorlibRef, interactiveHostObjectRef);
_rspImports = ImmutableArray<string>.Empty;
_initialScriptFileOpt = null;
ReferenceSearchPaths = ImmutableArray<string>.Empty;
SourceSearchPaths = ImmutableArray<string>.Empty;
if (initialize && File.Exists(_responseFilePath))
{
// The base directory for relative paths is the directory that contains the .rsp file.
// Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
var rspDirectory = Path.GetDirectoryName(_responseFilePath);
var args = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null);
if (args.Errors.Length == 0)
{
var metadataResolver = CreateMetadataReferenceResolver(metadataService, args.ReferencePaths, rspDirectory);
var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory);
// ignore unresolved references, they will be reported in the interactive window:
var rspReferences = args.ResolveMetadataReferences(metadataResolver).Where(r => !(r is UnresolvedMetadataReference));
_initialScriptFileOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;
ReferenceSearchPaths = args.ReferencePaths;
SourceSearchPaths = args.SourcePaths;
_references = _references.Union(rspReferences);
_rspImports = CommandLineHelpers.GetImports(args);
}
}
_metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory);
_sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory);
// create the first submission project in the workspace after reset:
if (_currentSubmissionBuffer != null)
{
AddSubmission(_currentTextView, _currentSubmissionBuffer, this.LanguageName);
}
}
private Dispatcher Dispatcher
{
get { return ((FrameworkElement)GetInteractiveWindow().TextView).Dispatcher; }
}
private static MetadataReferenceResolver CreateMetadataReferenceResolver(IMetadataService metadataService, ImmutableArray<string> searchPaths, string baseDirectory)
{
return new RuntimeMetadataReferenceResolver(
new RelativePathResolver(searchPaths, baseDirectory),
null,
GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null,
(path, properties) => metadataService.GetReference(path, properties));
}
private static SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new SourceFileResolver(searchPaths, baseDirectory);
}
#endregion
#region Workspace
private void SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs args)
{
AddSubmission(_currentWindow.TextView, args.NewBuffer, this.LanguageName);
}
// The REPL window might change content type to host command content type (when a host command is typed at the beginning of the buffer).
private void LanguageBufferContentTypeChanged(object sender, ContentTypeChangedEventArgs e)
{
// It's not clear whether this situation will ever happen, but just in case.
if (e.BeforeContentType == e.AfterContentType)
{
return;
}
var buffer = e.Before.TextBuffer;
var contentTypeName = this.ContentType.TypeName;
var afterIsLanguage = e.AfterContentType.IsOfType(contentTypeName);
var afterIsInteractiveCommand = e.AfterContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
var beforeIsLanguage = e.BeforeContentType.IsOfType(contentTypeName);
var beforeIsInteractiveCommand = e.BeforeContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
Debug.Assert((afterIsLanguage && beforeIsInteractiveCommand)
|| (beforeIsLanguage && afterIsInteractiveCommand));
// We're switching between the target language and the Interactive Command "language".
// First, remove the current submission from the solution.
var oldSolution = _workspace.CurrentSolution;
var newSolution = oldSolution;
foreach (var documentId in _workspace.GetRelatedDocumentIds(buffer.AsTextContainer()))
{
Debug.Assert(documentId != null);
newSolution = newSolution.RemoveDocument(documentId);
// TODO (tomat): Is there a better way to remove mapping between buffer and document in REPL?
// Perhaps TrackingWorkspace should implement RemoveDocumentAsync?
_workspace.ClearOpenDocument(documentId);
}
// Next, remove the previous submission project and update the workspace.
newSolution = newSolution.RemoveProject(_currentSubmissionProjectId);
_workspace.SetCurrentSolution(newSolution);
// Add a new submission with the correct language for the current buffer.
var languageName = afterIsLanguage
? this.LanguageName
: InteractiveLanguageNames.InteractiveCommand;
AddSubmission(_currentTextView, buffer, languageName);
}
private void AddSubmission(ITextView textView, ITextBuffer subjectBuffer, string languageName)
{
var solution = _workspace.CurrentSolution;
Project project;
ImmutableArray<string> imports;
if (_previousSubmissionProjectId != null)
{
// only the first project needs imports
imports = ImmutableArray<string>.Empty;
}
else if (_initialScriptFileOpt != null)
{
// insert a project for initialization script listed in .rsp:
project = CreateSubmissionProject(solution, languageName, _rspImports);
var documentId = DocumentId.CreateNewId(project.Id, debugName: _initialScriptFileOpt);
solution = project.Solution.AddDocument(documentId, Path.GetFileName(_initialScriptFileOpt), new FileTextLoader(_initialScriptFileOpt, defaultEncoding: null));
_previousSubmissionProjectId = project.Id;
imports = ImmutableArray<string>.Empty;
}
else
{
imports = _rspImports;
}
// project for the new submission:
project = CreateSubmissionProject(solution, languageName, imports);
// Keep track of this buffer so we can freeze the classifications for it in the future.
var viewAndBuffer = ValueTuple.Create(textView, subjectBuffer);
if (!_submissionBuffers.Contains(viewAndBuffer))
{
_submissionBuffers.Add(ValueTuple.Create(textView, subjectBuffer));
}
SetSubmissionDocument(subjectBuffer, project);
_currentSubmissionProjectId = project.Id;
if (_currentSubmissionBuffer != null)
{
_currentSubmissionBuffer.ContentTypeChanged -= _contentTypeChangedHandler;
}
subjectBuffer.ContentTypeChanged += _contentTypeChangedHandler;
subjectBuffer.Properties[typeof(ICurrentWorkingDirectoryDiscoveryService)] = this;
_currentSubmissionBuffer = subjectBuffer;
_currentTextView = textView;
}
private Project CreateSubmissionProject(Solution solution, string languageName, ImmutableArray<string> imports)
{
var name = "Submission#" + (_submissionCount++);
// Grab a local copy so we aren't closing over the field that might change. The
// collection itself is an immutable collection.
var localReferences = _references;
var localCompilationOptions = GetSubmissionCompilationOptions(name, _metadataReferenceResolver, _sourceReferenceResolver, imports);
var localParseOptions = ParseOptions;
var projectId = ProjectId.CreateNewId(debugName: name);
solution = solution.AddProject(
ProjectInfo.Create(
projectId,
VersionStamp.Create(),
name: name,
assemblyName: name,
language: languageName,
compilationOptions: localCompilationOptions,
parseOptions: localParseOptions,
documents: null,
projectReferences: null,
metadataReferences: localReferences,
hostObjectType: typeof(InteractiveScriptGlobals),
isSubmission: true));
if (_previousSubmissionProjectId != null)
{
solution = solution.AddProjectReference(projectId, new ProjectReference(_previousSubmissionProjectId));
}
return solution.GetProject(projectId);
}
private void SetSubmissionDocument(ITextBuffer buffer, Project project)
{
var documentId = DocumentId.CreateNewId(project.Id, debugName: project.Name);
var solution = project.Solution
.AddDocument(documentId, project.Name, buffer.CurrentSnapshot.AsText());
_workspace.SetCurrentSolution(solution);
// opening document will start workspace listening to changes in this text container
_workspace.OpenDocument(documentId, buffer.AsTextContainer());
}
private void FreezeClassifications()
{
foreach (var textViewAndBuffer in _submissionBuffers)
{
var textView = textViewAndBuffer.Item1;
var textBuffer = textViewAndBuffer.Item2;
if (textBuffer != _currentSubmissionBuffer)
{
InertClassifierProvider.CaptureExistingClassificationSpans(_classifierAggregator, textView, textBuffer);
}
}
}
#endregion
#region IInteractiveEngine
public virtual bool CanExecuteCode(string text)
{
if (_interactiveCommands != null && _interactiveCommands.InCommand)
{
return true;
}
return false;
}
public Task<ExecutionResult> ResetAsync(bool initialize = true)
{
GetInteractiveWindow().AddInput(_interactiveCommands.CommandPrefix + "reset");
GetInteractiveWindow().WriteLine(InteractiveEditorFeaturesResources.ResettingExecutionEngine);
GetInteractiveWindow().FlushOutput();
return ResetAsyncWorker(initialize);
}
private async Task<ExecutionResult> ResetAsyncWorker(bool initialize = true)
{
try
{
var options = new InteractiveHostOptions(
initializationFile: initialize ? _responseFilePath : null,
culture: CultureInfo.CurrentUICulture);
var result = await _interactiveHost.ResetAsync(options).ConfigureAwait(false);
if (result.Success)
{
UpdateResolvers(result);
}
return new ExecutionResult(result.Success);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public async Task<ExecutionResult> ExecuteCodeAsync(string text)
{
try
{
if (InteractiveCommands.InCommand)
{
var cmdResult = InteractiveCommands.TryExecuteCommand();
if (cmdResult != null)
{
return await cmdResult.ConfigureAwait(false);
}
}
var result = await _interactiveHost.ExecuteAsync(text).ConfigureAwait(false);
if (result.Success)
{
// We are not executing a command (the current content type is not "Interactive Command"),
// so the source document should not have been removed.
Debug.Assert(_workspace.CurrentSolution.GetProject(_currentSubmissionProjectId).HasDocuments);
// only remember the submission if we compiled successfully, otherwise we
// ignore it's id so we don't reference it in the next submission.
_previousSubmissionProjectId = _currentSubmissionProjectId;
// Grab any directive references from it
var compilation = await _workspace.CurrentSolution.GetProject(_previousSubmissionProjectId).GetCompilationAsync().ConfigureAwait(false);
_references = _references.Union(compilation.DirectiveReferences);
// update local search paths - remote paths has already been updated
UpdateResolvers(result);
}
return new ExecutionResult(result.Success);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public void AbortExecution()
{
// TODO: abort execution
}
public string FormatClipboard()
{
// keep the clipboard content as is
return null;
}
#endregion
#region Paths, Resolvers
private void UpdateResolvers(RemoteExecutionResult result)
{
UpdateResolvers(result.ChangedReferencePaths.AsImmutableOrNull(), result.ChangedSourcePaths.AsImmutableOrNull(), result.ChangedWorkingDirectory);
}
private void UpdateResolvers(ImmutableArray<string> changedReferenceSearchPaths, ImmutableArray<string> changedSourceSearchPaths, string changedWorkingDirectory)
{
if (changedReferenceSearchPaths.IsDefault && changedSourceSearchPaths.IsDefault && changedWorkingDirectory == null)
{
return;
}
var solution = _workspace.CurrentSolution;
// Maybe called after reset, when no submissions are available.
var optionsOpt = (_currentSubmissionProjectId != null) ? solution.GetProjectState(_currentSubmissionProjectId).CompilationOptions : null;
if (changedWorkingDirectory != null)
{
WorkingDirectory = changedWorkingDirectory;
}
if (!changedReferenceSearchPaths.IsDefault)
{
ReferenceSearchPaths = changedReferenceSearchPaths;
}
if (!changedSourceSearchPaths.IsDefault)
{
SourceSearchPaths = changedSourceSearchPaths;
}
if (!changedReferenceSearchPaths.IsDefault || changedWorkingDirectory != null)
{
_metadataReferenceResolver = CreateMetadataReferenceResolver(_workspace.CurrentSolution.Services.MetadataService, ReferenceSearchPaths, WorkingDirectory);
if (optionsOpt != null)
{
optionsOpt = optionsOpt.WithMetadataReferenceResolver(_metadataReferenceResolver);
}
}
if (!changedSourceSearchPaths.IsDefault || changedWorkingDirectory != null)
{
_sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, WorkingDirectory);
if (optionsOpt != null)
{
optionsOpt = optionsOpt.WithSourceReferenceResolver(_sourceReferenceResolver);
}
}
if (optionsOpt != null)
{
_workspace.SetCurrentSolution(solution.WithProjectCompilationOptions(_currentSubmissionProjectId, optionsOpt));
}
}
public async Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory)
{
try
{
var result = await _interactiveHost.SetPathsAsync(referenceSearchPaths.ToArray(), sourceSearchPaths.ToArray(), workingDirectory).ConfigureAwait(false);
UpdateResolvers(result);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public string GetPrompt()
{
if (CurrentWindow.CurrentLanguageBuffer != null &&
CurrentWindow.CurrentLanguageBuffer.CurrentSnapshot.LineCount > 1)
{
return ". ";
}
return "> ";
}
#endregion
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Xml;
using log4net.Appender;
using log4net.Util;
using log4net.Core;
using log4net.ObjectRenderer;
namespace log4net.Repository.Hierarchy
{
/// <summary>
/// Initializes the log4net environment using an XML DOM.
/// </summary>
/// <remarks>
/// <para>
/// Configures a <see cref="Hierarchy"/> using an XML DOM.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class XmlHierarchyConfigurator
{
private enum ConfigUpdateMode
{
Merge,
Overwrite
}
#region Public Instance Constructors
/// <summary>
/// Construct the configurator for a hierarchy
/// </summary>
/// <param name="hierarchy">The hierarchy to build.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="XmlHierarchyConfigurator" /> class
/// with the specified <see cref="Hierarchy" />.
/// </para>
/// </remarks>
public XmlHierarchyConfigurator(Hierarchy hierarchy)
{
m_hierarchy = hierarchy;
m_appenderBag = new Hashtable();
}
#endregion Public Instance Constructors
#region Public Instance Methods
/// <summary>
/// Configure the hierarchy by parsing a DOM tree of XML elements.
/// </summary>
/// <param name="element">The root element to parse.</param>
/// <remarks>
/// <para>
/// Configure the hierarchy by parsing a DOM tree of XML elements.
/// </para>
/// </remarks>
public void Configure(XmlElement element)
{
if (element == null || m_hierarchy == null)
{
return;
}
string rootElementName = element.LocalName;
if (rootElementName != CONFIGURATION_TAG)
{
LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element.");
return;
}
if (!LogLog.EmitInternalMessages)
{
// Look for a emitDebug attribute to enable internal debug
string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR);
LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "].");
if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null")
{
LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true);
}
else
{
LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute.");
}
}
if (!LogLog.InternalDebugging)
{
// Look for a debug attribute to enable internal debug
string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR);
LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR+" attribute [" + debugAttribute + "].");
if (debugAttribute.Length>0 && debugAttribute != "null")
{
LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true);
}
else
{
LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute.");
}
string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR);
if (confDebug.Length>0 && confDebug != "null")
{
LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated.");
LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead.");
LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true);
}
}
// Default mode is merge
ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge;
// Look for the config update attribute
string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR);
if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0)
{
// Parse the attribute
try
{
configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute);
}
catch
{
LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]");
}
}
// IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0
LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "].");
// Only reset configuration if overwrite flag specified
if (configUpdateMode == ConfigUpdateMode.Overwrite)
{
// Reset to original unset configuration
m_hierarchy.ResetConfiguration();
LogLog.Debug(declaringType, "Configuration reset before reading config.");
}
/* Building Appender objects, placing them in a local namespace
for future reference */
/* Process all the top level elements */
foreach (XmlNode currentNode in element.ChildNodes)
{
if (currentNode.NodeType == XmlNodeType.Element)
{
XmlElement currentElement = (XmlElement)currentNode;
if (currentElement.LocalName == LOGGER_TAG)
{
ParseLogger(currentElement);
}
else if (currentElement.LocalName == CATEGORY_TAG)
{
// TODO: deprecated use of category
ParseLogger(currentElement);
}
else if (currentElement.LocalName == ROOT_TAG)
{
ParseRoot(currentElement);
}
else if (currentElement.LocalName == RENDERER_TAG)
{
ParseRenderer(currentElement);
}
else if (currentElement.LocalName == APPENDER_TAG)
{
// We ignore appenders in this pass. They will
// be found and loaded if they are referenced.
}
else
{
// Read the param tags and set properties on the hierarchy
SetParameter(currentElement, m_hierarchy);
}
}
}
// Lastly set the hierarchy threshold
string thresholdStr = element.GetAttribute(THRESHOLD_ATTR);
LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]");
if (thresholdStr.Length > 0 && thresholdStr != "null")
{
Level thresholdLevel = (Level) ConvertStringTo(typeof(Level), thresholdStr);
if (thresholdLevel != null)
{
m_hierarchy.Threshold = thresholdLevel;
}
else
{
LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)");
}
}
// Done reading config
}
#endregion Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Parse appenders by IDREF.
/// </summary>
/// <param name="appenderRef">The appender ref element.</param>
/// <returns>The instance of the appender that the ref refers to.</returns>
/// <remarks>
/// <para>
/// Parse an XML element that represents an appender and return
/// the appender.
/// </para>
/// </remarks>
protected IAppender FindAppenderByReference(XmlElement appenderRef)
{
string appenderName = appenderRef.GetAttribute(REF_ATTR);
IAppender appender = (IAppender)m_appenderBag[appenderName];
if (appender != null)
{
return appender;
}
else
{
// Find the element with that id
XmlElement element = null;
if (appenderName != null && appenderName.Length > 0)
{
foreach (XmlElement curAppenderElement in appenderRef.OwnerDocument.GetElementsByTagName(APPENDER_TAG))
{
if (curAppenderElement.GetAttribute("name") == appenderName)
{
element = curAppenderElement;
break;
}
}
}
if (element == null)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: No appender named [" + appenderName + "] could be found.");
return null;
}
else
{
appender = ParseAppender(element);
if (appender != null)
{
m_appenderBag[appenderName] = appender;
}
return appender;
}
}
}
/// <summary>
/// Parses an appender element.
/// </summary>
/// <param name="appenderElement">The appender element.</param>
/// <returns>The appender instance or <c>null</c> when parsing failed.</returns>
/// <remarks>
/// <para>
/// Parse an XML element that represents an appender and return
/// the appender instance.
/// </para>
/// </remarks>
protected IAppender ParseAppender(XmlElement appenderElement)
{
string appenderName = appenderElement.GetAttribute(NAME_ATTR);
string typeName = appenderElement.GetAttribute(TYPE_ATTR);
LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]");
try
{
IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true));
appender.Name = appenderName;
foreach (XmlNode currentNode in appenderElement.ChildNodes)
{
/* We're only interested in Elements */
if (currentNode.NodeType == XmlNodeType.Element)
{
XmlElement currentElement = (XmlElement)currentNode;
// Look for the appender ref tag
if (currentElement.LocalName == APPENDER_REF_TAG)
{
string refName = currentElement.GetAttribute(REF_ATTR);
IAppenderAttachable appenderContainer = appender as IAppenderAttachable;
if (appenderContainer != null)
{
LogLog.Debug(declaringType, "Attaching appender named [" + refName + "] to appender named [" + appender.Name + "].");
IAppender referencedAppender = FindAppenderByReference(currentElement);
if (referencedAppender != null)
{
appenderContainer.AddAppender(referencedAppender);
}
}
else
{
LogLog.Error(declaringType, "Requesting attachment of appender named ["+refName+ "] to appender named [" + appender.Name + "] which does not implement log4net.Core.IAppenderAttachable.");
}
}
else
{
// For all other tags we use standard set param method
SetParameter(currentElement, appender);
}
}
}
IOptionHandler optionHandler = appender as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
LogLog.Debug(declaringType, "Created Appender [" + appenderName + "]");
return appender;
}
catch (Exception ex)
{
// Yes, it's ugly. But all exceptions point to the same problem: we can't create an Appender
LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex);
return null;
}
}
/// <summary>
/// Parses a logger element.
/// </summary>
/// <param name="loggerElement">The logger element.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents a logger.
/// </para>
/// </remarks>
protected void ParseLogger(XmlElement loggerElement)
{
// Create a new log4net.Logger object from the <logger> element.
string loggerName = loggerElement.GetAttribute(NAME_ATTR);
LogLog.Debug(declaringType, "Retrieving an instance of log4net.Repository.Logger for logger [" + loggerName + "].");
Logger log = m_hierarchy.GetLogger(loggerName) as Logger;
// Setting up a logger needs to be an atomic operation, in order
// to protect potential log operations while logger
// configuration is in progress.
lock(log)
{
bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute(ADDITIVITY_ATTR), true);
LogLog.Debug(declaringType, "Setting [" + log.Name + "] additivity to [" + additivity + "].");
log.Additivity = additivity;
ParseChildrenOfLoggerElement(loggerElement, log, false);
}
}
/// <summary>
/// Parses the root logger element.
/// </summary>
/// <param name="rootElement">The root element.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents the root logger.
/// </para>
/// </remarks>
protected void ParseRoot(XmlElement rootElement)
{
Logger root = m_hierarchy.Root;
// logger configuration needs to be atomic
lock(root)
{
ParseChildrenOfLoggerElement(rootElement, root, true);
}
}
/// <summary>
/// Parses the children of a logger element.
/// </summary>
/// <param name="catElement">The category element.</param>
/// <param name="log">The logger instance.</param>
/// <param name="isRoot">Flag to indicate if the logger is the root logger.</param>
/// <remarks>
/// <para>
/// Parse the child elements of a <logger> element.
/// </para>
/// </remarks>
protected void ParseChildrenOfLoggerElement(XmlElement catElement, Logger log, bool isRoot)
{
// Remove all existing appenders from log. They will be
// reconstructed if need be.
log.RemoveAllAppenders();
foreach (XmlNode currentNode in catElement.ChildNodes)
{
if (currentNode.NodeType == XmlNodeType.Element)
{
XmlElement currentElement = (XmlElement) currentNode;
if (currentElement.LocalName == APPENDER_REF_TAG)
{
IAppender appender = FindAppenderByReference(currentElement);
string refName = currentElement.GetAttribute(REF_ATTR);
if (appender != null)
{
LogLog.Debug(declaringType, "Adding appender named [" + refName + "] to logger [" + log.Name + "].");
log.AddAppender(appender);
}
else
{
LogLog.Error(declaringType, "Appender named [" + refName + "] not found.");
}
}
else if (currentElement.LocalName == LEVEL_TAG || currentElement.LocalName == PRIORITY_TAG)
{
ParseLevel(currentElement, log, isRoot);
}
else
{
SetParameter(currentElement, log);
}
}
}
IOptionHandler optionHandler = log as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
}
/// <summary>
/// Parses an object renderer.
/// </summary>
/// <param name="element">The renderer element.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents a renderer.
/// </para>
/// </remarks>
protected void ParseRenderer(XmlElement element)
{
string renderingClassName = element.GetAttribute(RENDERING_TYPE_ATTR);
string renderedClassName = element.GetAttribute(RENDERED_TYPE_ATTR);
LogLog.Debug(declaringType, "Rendering class [" + renderingClassName + "], Rendered class [" + renderedClassName + "].");
IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(renderingClassName, typeof(IObjectRenderer), null);
if (renderer == null)
{
LogLog.Error(declaringType, "Could not instantiate renderer [" + renderingClassName + "].");
return;
}
else
{
try
{
m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(renderedClassName, true, true), renderer);
}
catch(Exception e)
{
LogLog.Error(declaringType, "Could not find class [" + renderedClassName + "].", e);
}
}
}
/// <summary>
/// Parses a level element.
/// </summary>
/// <param name="element">The level element.</param>
/// <param name="log">The logger object to set the level on.</param>
/// <param name="isRoot">Flag to indicate if the logger is the root logger.</param>
/// <remarks>
/// <para>
/// Parse an XML element that represents a level.
/// </para>
/// </remarks>
protected void ParseLevel(XmlElement element, Logger log, bool isRoot)
{
string loggerName = log.Name;
if (isRoot)
{
loggerName = "root";
}
string levelStr = element.GetAttribute(VALUE_ATTR);
LogLog.Debug(declaringType, "Logger [" + loggerName + "] Level string is [" + levelStr + "].");
if (INHERITED == levelStr)
{
if (isRoot)
{
LogLog.Error(declaringType, "Root level cannot be inherited. Ignoring directive.");
}
else
{
LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to inherit from parent.");
log.Level = null;
}
}
else
{
log.Level = log.Hierarchy.LevelMap[levelStr];
if (log.Level == null)
{
LogLog.Error(declaringType, "Undefined level [" + levelStr + "] on Logger [" + loggerName + "].");
}
else
{
LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to [name=\"" + log.Level.Name + "\",value=" + log.Level.Value + "].");
}
}
}
/// <summary>
/// Sets a parameter on an object.
/// </summary>
/// <param name="element">The parameter element.</param>
/// <param name="target">The object to set the parameter on.</param>
/// <remarks>
/// The parameter name must correspond to a writable property
/// on the object. The value of the parameter is a string,
/// therefore this function will attempt to set a string
/// property first. If unable to set a string property it
/// will inspect the property and its argument type. It will
/// attempt to call a static method called <c>Parse</c> on the
/// type of the property. This method will take a single
/// string argument and return a value that can be used to
/// set the property.
/// </remarks>
protected void SetParameter(XmlElement element, object target)
{
// Get the property name
string name = element.GetAttribute(NAME_ATTR);
// If the name attribute does not exist then use the name of the element
if (element.LocalName != PARAM_TAG || name == null || name.Length == 0)
{
name = element.LocalName;
}
// Look for the property on the target object
Type targetType = target.GetType();
Type propertyType = null;
PropertyInfo propInfo = null;
MethodInfo methInfo = null;
// Try to find a writable property
propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
if (propInfo != null && propInfo.CanWrite)
{
// found a property
propertyType = propInfo.PropertyType;
}
else
{
propInfo = null;
// look for a method with the signature Add<property>(type)
methInfo = FindMethodInfo(targetType, name);
if (methInfo != null)
{
propertyType = methInfo.GetParameters()[0].ParameterType;
}
}
if (propertyType == null)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]");
}
else
{
string propertyValue = null;
if (element.GetAttributeNode(VALUE_ATTR) != null)
{
propertyValue = element.GetAttribute(VALUE_ATTR);
}
else if (element.HasChildNodes)
{
// Concatenate the CDATA and Text nodes together
foreach(XmlNode childNode in element.ChildNodes)
{
if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text)
{
if (propertyValue == null)
{
propertyValue = childNode.InnerText;
}
else
{
propertyValue += childNode.InnerText;
}
}
}
}
if(propertyValue != null)
{
#if !NETCF
try
{
// Expand environment variables in the string.
propertyValue = OptionConverter.SubstituteVariables(propertyValue, Environment.GetEnvironmentVariables());
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// unrestricted environment permission. If this occurs the expansion
// will be skipped with the following warning message.
LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
}
#endif
Type parsedObjectConversionTargetType = null;
// Check if a specific subtype is specified on the element using the 'type' attribute
string subTypeString = element.GetAttribute(TYPE_ATTR);
if (subTypeString != null && subTypeString.Length > 0)
{
// Read the explicit subtype
try
{
Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true);
LogLog.Debug(declaringType, "Parameter ["+name+"] specified subtype ["+subType.FullName+"]");
if (!propertyType.IsAssignableFrom(subType))
{
// Check if there is an appropriate type converter
if (OptionConverter.CanConvertTypeTo(subType, propertyType))
{
// Must re-convert to the real property type
parsedObjectConversionTargetType = propertyType;
// Use sub type as intermediary type
propertyType = subType;
}
else
{
LogLog.Error(declaringType, "subtype ["+subType.FullName+"] set on ["+name+"] is not a subclass of property type ["+propertyType.FullName+"] and there are no acceptable type conversions.");
}
}
else
{
// The subtype specified is found and is actually a subtype of the property
// type, therefore we can switch to using this type.
propertyType = subType;
}
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to find type ["+subTypeString+"] set on ["+name+"]", ex);
}
}
// Now try to convert the string value to an acceptable type
// to pass to this property.
object convertedValue = ConvertStringTo(propertyType, propertyValue);
// Check if we need to do an additional conversion
if (convertedValue != null && parsedObjectConversionTargetType != null)
{
LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]");
convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType);
}
if (convertedValue != null)
{
if (propInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");
try
{
// Pass to the property
propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
}
}
else if (methInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");
try
{
// Pass to the property
methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {convertedValue}, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
}
}
}
else
{
LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)");
}
}
else
{
object createdObject = null;
if (propertyType == typeof(string) && !HasAttributesOrElements(element))
{
// If the property is a string and the element is empty (no attributes
// or child elements) then we special case the object value to an empty string.
// This is necessary because while the String is a class it does not have
// a default constructor that creates an empty string, which is the behavior
// we are trying to simulate and would be expected from CreateObjectFromXml
createdObject = "";
}
else
{
// No value specified
Type defaultObjectType = null;
if (IsTypeConstructible(propertyType))
{
defaultObjectType = propertyType;
}
createdObject = CreateObjectFromXml(element, defaultObjectType, propertyType);
}
if (createdObject == null)
{
LogLog.Error(declaringType, "Failed to create object to set param: "+name);
}
else
{
if (propInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Property ["+ propInfo.Name +"] to object ["+ createdObject +"]");
try
{
// Pass to the property
propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
}
}
else if (methInfo != null)
{
// Got a converted result
LogLog.Debug(declaringType, "Setting Collection Property ["+ methInfo.Name +"] to object ["+ createdObject +"]");
try
{
// Pass to the property
methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {createdObject}, CultureInfo.InvariantCulture);
}
catch(TargetInvocationException targetInvocationEx)
{
LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
}
}
}
}
}
}
/// <summary>
/// Test if an element has no attributes or child elements
/// </summary>
/// <param name="element">the element to inspect</param>
/// <returns><c>true</c> if the element has any attributes or child elements, <c>false</c> otherwise</returns>
private bool HasAttributesOrElements(XmlElement element)
{
foreach(XmlNode node in element.ChildNodes)
{
if (node.NodeType == XmlNodeType.Attribute || node.NodeType == XmlNodeType.Element)
{
return true;
}
}
return false;
}
/// <summary>
/// Test if a <see cref="Type"/> is constructible with <c>Activator.CreateInstance</c>.
/// </summary>
/// <param name="type">the type to inspect</param>
/// <returns><c>true</c> if the type is creatable using a default constructor, <c>false</c> otherwise</returns>
private static bool IsTypeConstructible(Type type)
{
if (type.IsClass && !type.IsAbstract)
{
ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]);
if (defaultConstructor != null && !defaultConstructor.IsAbstract && !defaultConstructor.IsPrivate)
{
return true;
}
}
return false;
}
/// <summary>
/// Look for a method on the <paramref name="targetType"/> that matches the <paramref name="name"/> supplied
/// </summary>
/// <param name="targetType">the type that has the method</param>
/// <param name="name">the name of the method</param>
/// <returns>the method info found</returns>
/// <remarks>
/// <para>
/// The method must be a public instance method on the <paramref name="targetType"/>.
/// The method must be named <paramref name="name"/> or "Add" followed by <paramref name="name"/>.
/// The method must take a single parameter.
/// </para>
/// </remarks>
private MethodInfo FindMethodInfo(Type targetType, string name)
{
string requiredMethodNameA = name;
string requiredMethodNameB = "Add" + name;
MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach(MethodInfo methInfo in methods)
{
if (!methInfo.IsStatic)
{
if (string.Compare(methInfo.Name, requiredMethodNameA, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ||
string.Compare(methInfo.Name, requiredMethodNameB, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
{
// Found matching method name
// Look for version with one arg only
System.Reflection.ParameterInfo[] methParams = methInfo.GetParameters();
if (methParams.Length == 1)
{
return methInfo;
}
}
}
}
return null;
}
/// <summary>
/// Converts a string value to a target type.
/// </summary>
/// <param name="type">The type of object to convert the string to.</param>
/// <param name="value">The string value to use as the value of the object.</param>
/// <returns>
/// <para>
/// An object of type <paramref name="type"/> with value <paramref name="value"/> or
/// <c>null</c> when the conversion could not be performed.
/// </para>
/// </returns>
protected object ConvertStringTo(Type type, string value)
{
// Hack to allow use of Level in property
if (typeof(Level) == type)
{
// Property wants a level
Level levelValue = m_hierarchy.LevelMap[value];
if (levelValue == null)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified ["+ value +"]");
}
return levelValue;
}
return OptionConverter.ConvertStringTo(type, value);
}
/// <summary>
/// Creates an object as specified in XML.
/// </summary>
/// <param name="element">The XML element that contains the definition of the object.</param>
/// <param name="defaultTargetType">The object type to use if not explicitly specified.</param>
/// <param name="typeConstraint">The type that the returned object must be or must inherit from.</param>
/// <returns>The object or <c>null</c></returns>
/// <remarks>
/// <para>
/// Parse an XML element and create an object instance based on the configuration
/// data.
/// </para>
/// <para>
/// The type of the instance may be specified in the XML. If not
/// specified then the <paramref name="defaultTargetType"/> is used
/// as the type. However the type is specified it must support the
/// <paramref name="typeConstraint"/> type.
/// </para>
/// </remarks>
protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
{
Type objectType = null;
// Get the object type
string objectTypeString = element.GetAttribute(TYPE_ATTR);
if (objectTypeString == null || objectTypeString.Length == 0)
{
if (defaultTargetType == null)
{
LogLog.Error(declaringType, "Object type not specified. Cannot create object of type ["+typeConstraint.FullName+"]. Missing Value or Type.");
return null;
}
else
{
// Use the default object type
objectType = defaultTargetType;
}
}
else
{
// Read the explicit object type
try
{
objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to find type ["+objectTypeString+"]", ex);
return null;
}
}
bool requiresConversion = false;
// Got the object type. Check that it meets the typeConstraint
if (typeConstraint != null)
{
if (!typeConstraint.IsAssignableFrom(objectType))
{
// Check if there is an appropriate type converter
if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint))
{
requiresConversion = true;
}
else
{
LogLog.Error(declaringType, "Object type ["+objectType.FullName+"] is not assignable to type ["+typeConstraint.FullName+"]. There are no acceptable type conversions.");
return null;
}
}
}
// Create using the default constructor
object createdObject = null;
try
{
createdObject = Activator.CreateInstance(objectType);
}
catch(Exception createInstanceEx)
{
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: "+createInstanceEx.ToString());
}
// Set any params on object
foreach (XmlNode currentNode in element.ChildNodes)
{
if (currentNode.NodeType == XmlNodeType.Element)
{
SetParameter((XmlElement)currentNode, createdObject);
}
}
// Check if we need to call ActivateOptions
IOptionHandler optionHandler = createdObject as IOptionHandler;
if (optionHandler != null)
{
optionHandler.ActivateOptions();
}
// Ok object should be initialized
if (requiresConversion)
{
// Convert the object type
return OptionConverter.ConvertTypeTo(createdObject, typeConstraint);
}
else
{
// The object is of the correct type
return createdObject;
}
}
#endregion Protected Instance Methods
#region Private Constants
// String constants used while parsing the XML data
private const string CONFIGURATION_TAG = "log4net";
private const string RENDERER_TAG = "renderer";
private const string APPENDER_TAG = "appender";
private const string APPENDER_REF_TAG = "appender-ref";
private const string PARAM_TAG = "param";
// TODO: Deprecate use of category tags
private const string CATEGORY_TAG = "category";
// TODO: Deprecate use of priority tag
private const string PRIORITY_TAG = "priority";
private const string LOGGER_TAG = "logger";
private const string NAME_ATTR = "name";
private const string TYPE_ATTR = "type";
private const string VALUE_ATTR = "value";
private const string ROOT_TAG = "root";
private const string LEVEL_TAG = "level";
private const string REF_ATTR = "ref";
private const string ADDITIVITY_ATTR = "additivity";
private const string THRESHOLD_ATTR = "threshold";
private const string CONFIG_DEBUG_ATTR = "configDebug";
private const string INTERNAL_DEBUG_ATTR = "debug";
private const string EMIT_INTERNAL_DEBUG_ATTR = "emitDebug";
private const string CONFIG_UPDATE_MODE_ATTR = "update";
private const string RENDERING_TYPE_ATTR = "renderingClass";
private const string RENDERED_TYPE_ATTR = "renderedClass";
// flag used on the level element
private const string INHERITED = "inherited";
#endregion Private Constants
#region Private Instance Fields
/// <summary>
/// key: appenderName, value: appender.
/// </summary>
private Hashtable m_appenderBag;
/// <summary>
/// The Hierarchy being configured.
/// </summary>
private readonly Hierarchy m_hierarchy;
#endregion Private Instance Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the XmlHierarchyConfigurator class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(XmlHierarchyConfigurator);
#endregion Private Static Fields
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using Internal.Metadata.NativeFormat;
using AssemblyFlags = Internal.Metadata.NativeFormat.AssemblyFlags;
using Internal.TypeSystem;
namespace Internal.TypeSystem.NativeFormat
{
/// <summary>
/// Represent an module in the CLI sense. Note, that as the NativeFormat for metadata can aggregate
/// multiple modules, this class represents a subset of a NativeFormat metadata file.
/// </summary>
public sealed class NativeFormatModule : ModuleDesc, IAssemblyDesc
{
private QualifiedScopeDefinition[] _assemblyDefinitions;
public struct QualifiedScopeDefinition
{
public QualifiedScopeDefinition(NativeFormatMetadataUnit metadataUnit, Handle handle)
{
MetadataUnit = metadataUnit;
Handle = handle.ToScopeDefinitionHandle(metadataUnit.MetadataReader);
Definition = metadataUnit.MetadataReader.GetScopeDefinition(Handle);
}
public readonly NativeFormatMetadataUnit MetadataUnit;
public readonly ScopeDefinitionHandle Handle;
public readonly ScopeDefinition Definition;
public MetadataReader MetadataReader
{
get
{
return MetadataUnit.MetadataReader;
}
}
}
public override IAssemblyDesc Assembly
{
get
{
return this;
}
}
public NativeFormatModule(TypeSystemContext context, QualifiedScopeDefinition[] assemblyDefinitions)
: base(context, null)
{
_assemblyDefinitions = assemblyDefinitions;
}
private class ReferenceKeyValuePair<TKey, TValue>
{
public ReferenceKeyValuePair(TKey key, TValue value)
{
Key = key;
Value = value;
}
public TKey Key;
public TValue Value;
}
private struct QualifiedNamespaceDefinition
{
public QualifiedNamespaceDefinition(NativeFormatMetadataUnit metadataUnit, NamespaceDefinition namespaceDefinition)
{
MetadataUnit = metadataUnit;
Definition = namespaceDefinition;
}
public readonly NativeFormatMetadataUnit MetadataUnit;
public readonly NamespaceDefinition Definition;
public MetadataReader MetadataReader
{
get
{
return MetadataUnit.MetadataReader;
}
}
}
private class NamespaceDefinitionHashtable : LockFreeReaderHashtable<string, ReferenceKeyValuePair<string, QualifiedNamespaceDefinition[]>>
{
private NativeFormatModule _module;
private QualifiedScopeDefinition[] _scopes;
public NamespaceDefinitionHashtable(NativeFormatModule module, QualifiedScopeDefinition[] scopes)
{
_module = module;
_scopes = scopes;
}
protected override int GetKeyHashCode(string key)
{
return key.GetHashCode();
}
protected override int GetValueHashCode(ReferenceKeyValuePair<string, QualifiedNamespaceDefinition[]> value)
{
return value.Key.GetHashCode();
}
protected override bool CompareKeyToValue(string key, ReferenceKeyValuePair<string, QualifiedNamespaceDefinition[]> value)
{
return key.Equals(value.Key);
}
protected override bool CompareValueToValue(ReferenceKeyValuePair<string, QualifiedNamespaceDefinition[]> value1, ReferenceKeyValuePair<string, QualifiedNamespaceDefinition[]> value2)
{
return value1.Key.Equals(value2.Key);
}
protected override ReferenceKeyValuePair<string, QualifiedNamespaceDefinition[]> CreateValueFromKey(string key)
{
ArrayBuilder<QualifiedNamespaceDefinition> namespaceDefinitions = new ArrayBuilder<QualifiedNamespaceDefinition>();
foreach (QualifiedScopeDefinition qdefinition in _scopes)
{
MetadataReader metadataReader = qdefinition.MetadataReader;
NamespaceDefinitionHandle rootNamespaceHandle = qdefinition.Definition.RootNamespaceDefinition;
NamespaceDefinition currentNamespace = metadataReader.GetNamespaceDefinition(rootNamespaceHandle);
if (key == "")
{
namespaceDefinitions.Add(new QualifiedNamespaceDefinition(qdefinition.MetadataUnit, currentNamespace));
// We're done now.
}
else
{
string[] components = key.Split('.');
bool found = false;
foreach (string namespaceComponent in components)
{
found = false;
foreach (NamespaceDefinitionHandle childNamespaceHandle in currentNamespace.NamespaceDefinitions)
{
NamespaceDefinition childNamespace = metadataReader.GetNamespaceDefinition(childNamespaceHandle);
if (childNamespace.Name.StringEquals(namespaceComponent, metadataReader))
{
found = true;
currentNamespace = childNamespace;
break;
}
}
if (!found)
{
break;
}
}
if (found)
namespaceDefinitions.Add(new QualifiedNamespaceDefinition(qdefinition.MetadataUnit, currentNamespace));
}
}
return new ReferenceKeyValuePair<System.String, QualifiedNamespaceDefinition[]>(key, namespaceDefinitions.ToArray());
}
}
private NamespaceDefinitionHashtable _namespaceLookup;
private QualifiedNamespaceDefinition[] GetNamespaceDefinitionsFromString(string nameSpace)
{
if (_namespaceLookup == null)
_namespaceLookup = new NamespaceDefinitionHashtable(this, _assemblyDefinitions);
return _namespaceLookup.GetOrCreateValue(nameSpace ?? "").Value;
}
public override MetadataType GetType(string nameSpace, string name, bool throwIfNotFound = true)
{
QualifiedNamespaceDefinition[] namespaceDefinitions = GetNamespaceDefinitionsFromString(nameSpace);
foreach (QualifiedNamespaceDefinition namespaceDefinition in namespaceDefinitions)
{
// At least the namespace was found.
MetadataReader metadataReader = namespaceDefinition.MetadataReader;
// Now scan the type definitions on this namespace
foreach (var typeDefinitionHandle in namespaceDefinition.Definition.TypeDefinitions)
{
var typeDefinition = metadataReader.GetTypeDefinition(typeDefinitionHandle);
if (typeDefinition.Name.StringEquals(name, metadataReader))
{
return (MetadataType)namespaceDefinition.MetadataUnit.GetType((Handle)typeDefinitionHandle);
}
}
}
foreach (QualifiedNamespaceDefinition namespaceDefinition in namespaceDefinitions)
{
// At least the namespace was found.
MetadataReader metadataReader = namespaceDefinition.MetadataReader;
// Now scan the type forwarders on this namespace
foreach (var typeForwarderHandle in namespaceDefinition.Definition.TypeForwarders)
{
var typeForwarder = metadataReader.GetTypeForwarder(typeForwarderHandle);
if (typeForwarder.Name.StringEquals(name, metadataReader))
{
ModuleDesc forwardTargetModule = namespaceDefinition.MetadataUnit.GetModule(typeForwarder.Scope);
return forwardTargetModule.GetType(nameSpace, name, throwIfNotFound);
}
}
}
if (throwIfNotFound)
throw CreateTypeLoadException(nameSpace + "." + name);
return null;
}
/// <summary>
/// Enumerate all type definitions in a given native module. Iterate all scopes
/// and recursively enumerate the namespace trees and all namespace and nested types there.
/// </summary>
public override IEnumerable<MetadataType> GetAllTypes()
{
foreach (QualifiedScopeDefinition scopeDefinition in _assemblyDefinitions)
{
foreach (MetadataType type in GetTypesInNamespace(
scopeDefinition.MetadataUnit,
scopeDefinition.MetadataReader,
scopeDefinition.Definition.RootNamespaceDefinition))
{
yield return type;
}
}
}
/// <summary>
/// Enumerate all type definitions within a given namespace.
/// </summary>
/// <param name="metadataUnit">Metadata unit containing the namespace</param>
/// <param name="metadataReader">Metadata reader for the scope metadata</param>
/// <param name="namespaceDefinitionHandle">Namespace to enumerate</param>
private IEnumerable<MetadataType> GetTypesInNamespace(
NativeFormatMetadataUnit metadataUnit,
MetadataReader metadataReader,
NamespaceDefinitionHandle namespaceDefinitionHandle)
{
NamespaceDefinition namespaceDefinition = metadataReader.GetNamespaceDefinition(namespaceDefinitionHandle);
// First, enumerate all types (including nested) in the current namespace
foreach (TypeDefinitionHandle namespaceTypeHandle in namespaceDefinition.TypeDefinitions)
{
yield return (MetadataType)metadataUnit.GetType(namespaceTypeHandle);
foreach (MetadataType nestedType in GetNestedTypes(metadataUnit, metadataReader, namespaceTypeHandle))
{
yield return nestedType;
}
}
// Second, recurse into nested namespaces
foreach (NamespaceDefinitionHandle nestedNamespace in namespaceDefinition.NamespaceDefinitions)
{
foreach (MetadataType type in GetTypesInNamespace(metadataUnit, metadataReader, nestedNamespace))
{
yield return type;
}
}
}
/// <summary>
/// Enumerate all nested types under a given owning type.
/// </summary>
/// <param name="metadataUnit">Metadata unit containing the type</param>
/// <param name="metadataReader">Metadata reader for the type metadata</param>
/// <param name="owningTypeHandle">Containing type to search for nested types</param>
private IEnumerable<MetadataType> GetNestedTypes(
NativeFormatMetadataUnit metadataUnit,
MetadataReader metadataReader,
TypeDefinitionHandle owningTypeHandle)
{
TypeDefinition owningType = metadataReader.GetTypeDefinition(owningTypeHandle);
foreach (TypeDefinitionHandle nestedTypeHandle in owningType.NestedTypes)
{
yield return (MetadataType)metadataUnit.GetType(nestedTypeHandle);
foreach (MetadataType nestedType in GetNestedTypes(metadataUnit, metadataReader, nestedTypeHandle))
{
yield return nestedType;
}
}
}
public Exception CreateTypeLoadException(string fullTypeName)
{
return new TypeLoadException(String.Format("Could not load type '{0}' from assembly '{1}'.", fullTypeName, this.ToString()));
}
public override MetadataType GetGlobalModuleType()
{
return null;
// TODO handle the global module type.
}
private AssemblyName _assemblyName;
// Returns cached copy of the name. Caller has to create a clone before mutating the name.
public AssemblyName GetName()
{
if (_assemblyName == null)
{
MetadataReader metadataReader = _assemblyDefinitions[0].MetadataReader;
ScopeDefinition definition = _assemblyDefinitions[0].Definition;
AssemblyName an = new AssemblyName();
an.Name = metadataReader.GetString(definition.Name);
an.Version = new Version(definition.MajorVersion, definition.MinorVersion, definition.BuildNumber, definition.RevisionNumber);
byte[] publicKeyOrToken = definition.PublicKey.ConvertByteCollectionToArray();
if ((definition.Flags & AssemblyFlags.PublicKey) != 0)
{
an.SetPublicKey(publicKeyOrToken);
}
else
{
an.SetPublicKeyToken(publicKeyOrToken);
}
// TODO: ContentType, Culture - depends on newer version of the System.Reflection contract
_assemblyName = an;
}
return _assemblyName;
}
public bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
foreach (QualifiedScopeDefinition definition in _assemblyDefinitions)
{
if (definition.MetadataReader.HasCustomAttribute(definition.Definition.CustomAttributes,
attributeNamespace, attributeName))
return true;
}
return false;
}
public override string ToString()
{
return GetName().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.
/*============================================================
**
**
**
** Purpose: Platform independent integer
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
namespace System
{
// CONTRACT with Runtime
// The UIntPtr type is one of the primitives understood by the compilers and runtime
// Data Contract: Single field of type void *
[CLSCompliant(false)]
public struct UIntPtr
{
unsafe private void* _value;
[Intrinsic]
public static readonly UIntPtr Zero;
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(uint value)
{
_value = (void*)value;
}
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if BIT64
_value = (void*)value;
#else
_value = (void*)checked((uint)value);
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(void* value)
{
_value = value;
}
[Intrinsic]
[NonVersionable]
public unsafe void* ToPointer()
{
return _value;
}
[Intrinsic]
[NonVersionable]
public unsafe uint ToUInt32()
{
#if BIT64
return checked((uint)_value);
#else
return (uint)_value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe ulong ToUInt64()
{
return (ulong)_value;
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(uint value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(ulong value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator UIntPtr(void* value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
{
return value._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator uint (UIntPtr value)
{
#if BIT64
return checked((uint)value._value);
#else
return (uint)value._value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator ulong (UIntPtr value)
{
return (ulong)value._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static bool operator ==(UIntPtr value1, UIntPtr value2)
{
return value1._value == value2._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static bool operator !=(UIntPtr value1, UIntPtr value2)
{
return value1._value != value2._value;
}
public static unsafe int Size
{
[Intrinsic]
[NonVersionable]
get
{
#if BIT64
return 8;
#else
return 4;
#endif
}
}
public unsafe override String ToString()
{
#if BIT64
return ((ulong)_value).ToString(FormatProvider.InvariantCulture);
#else
return ((uint)_value).ToString(FormatProvider.InvariantCulture);
#endif
}
public unsafe override bool Equals(Object obj)
{
if (obj is UIntPtr)
{
return (_value == ((UIntPtr)obj)._value);
}
return false;
}
public unsafe override int GetHashCode()
{
#if BIT64
ulong l = (ulong)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else
return unchecked((int)_value);
#endif
}
[NonVersionable]
public static UIntPtr Add(UIntPtr pointer, int offset)
{
return pointer + offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator +(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() + (uint)offset);
#endif
}
[NonVersionable]
public static UIntPtr Subtract(UIntPtr pointer, int offset)
{
return pointer - offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator -(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() - (uint)offset);
#endif
}
}
}
| |
// 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 gax = Google.Api.Gax;
using giav = Google.Identity.AccessContextManager.V1;
using sys = System;
namespace Google.Identity.AccessContextManager.V1
{
/// <summary>Resource name for the <c>GcpUserAccessBinding</c> resource.</summary>
public sealed partial class GcpUserAccessBindingName : gax::IResourceName, sys::IEquatable<GcpUserAccessBindingName>
{
/// <summary>The possible contents of <see cref="GcpUserAccessBindingName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>.
/// </summary>
OrganizationGcpUserAccessBinding = 1,
}
private static gax::PathTemplate s_organizationGcpUserAccessBinding = new gax::PathTemplate("organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}");
/// <summary>Creates a <see cref="GcpUserAccessBindingName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="GcpUserAccessBindingName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static GcpUserAccessBindingName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new GcpUserAccessBindingName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="GcpUserAccessBindingName"/> with the pattern
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="gcpUserAccessBindingId">
/// The <c>GcpUserAccessBinding</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="GcpUserAccessBindingName"/> constructed from the provided ids.
/// </returns>
public static GcpUserAccessBindingName FromOrganizationGcpUserAccessBinding(string organizationId, string gcpUserAccessBindingId) =>
new GcpUserAccessBindingName(ResourceNameType.OrganizationGcpUserAccessBinding, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gcpUserAccessBindingId: gax::GaxPreconditions.CheckNotNullOrEmpty(gcpUserAccessBindingId, nameof(gcpUserAccessBindingId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GcpUserAccessBindingName"/> with pattern
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="gcpUserAccessBindingId">
/// The <c>GcpUserAccessBinding</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="GcpUserAccessBindingName"/> with pattern
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>.
/// </returns>
public static string Format(string organizationId, string gcpUserAccessBindingId) =>
FormatOrganizationGcpUserAccessBinding(organizationId, gcpUserAccessBindingId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="GcpUserAccessBindingName"/> with pattern
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="gcpUserAccessBindingId">
/// The <c>GcpUserAccessBinding</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="GcpUserAccessBindingName"/> with pattern
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>.
/// </returns>
public static string FormatOrganizationGcpUserAccessBinding(string organizationId, string gcpUserAccessBindingId) =>
s_organizationGcpUserAccessBinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(gcpUserAccessBindingId, nameof(gcpUserAccessBindingId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="GcpUserAccessBindingName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gcpUserAccessBindingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="GcpUserAccessBindingName"/> if successful.</returns>
public static GcpUserAccessBindingName Parse(string gcpUserAccessBindingName) =>
Parse(gcpUserAccessBindingName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="GcpUserAccessBindingName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gcpUserAccessBindingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="GcpUserAccessBindingName"/> if successful.</returns>
public static GcpUserAccessBindingName Parse(string gcpUserAccessBindingName, bool allowUnparsed) =>
TryParse(gcpUserAccessBindingName, allowUnparsed, out GcpUserAccessBindingName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GcpUserAccessBindingName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="gcpUserAccessBindingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GcpUserAccessBindingName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gcpUserAccessBindingName, out GcpUserAccessBindingName result) =>
TryParse(gcpUserAccessBindingName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="GcpUserAccessBindingName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="gcpUserAccessBindingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="GcpUserAccessBindingName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string gcpUserAccessBindingName, bool allowUnparsed, out GcpUserAccessBindingName result)
{
gax::GaxPreconditions.CheckNotNull(gcpUserAccessBindingName, nameof(gcpUserAccessBindingName));
gax::TemplatedResourceName resourceName;
if (s_organizationGcpUserAccessBinding.TryParseName(gcpUserAccessBindingName, out resourceName))
{
result = FromOrganizationGcpUserAccessBinding(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(gcpUserAccessBindingName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private GcpUserAccessBindingName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string gcpUserAccessBindingId = null, string organizationId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
GcpUserAccessBindingId = gcpUserAccessBindingId;
OrganizationId = organizationId;
}
/// <summary>
/// Constructs a new instance of a <see cref="GcpUserAccessBindingName"/> class from the component parts of
/// pattern <c>organizations/{organization}/gcpUserAccessBindings/{gcp_user_access_binding}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="gcpUserAccessBindingId">
/// The <c>GcpUserAccessBinding</c> ID. Must not be <c>null</c> or empty.
/// </param>
public GcpUserAccessBindingName(string organizationId, string gcpUserAccessBindingId) : this(ResourceNameType.OrganizationGcpUserAccessBinding, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gcpUserAccessBindingId: gax::GaxPreconditions.CheckNotNullOrEmpty(gcpUserAccessBindingId, nameof(gcpUserAccessBindingId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>GcpUserAccessBinding</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string GcpUserAccessBindingId { get; }
/// <summary>
/// The <c>Organization</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string OrganizationId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.OrganizationGcpUserAccessBinding: return s_organizationGcpUserAccessBinding.Expand(OrganizationId, GcpUserAccessBindingId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as GcpUserAccessBindingName);
/// <inheritdoc/>
public bool Equals(GcpUserAccessBindingName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(GcpUserAccessBindingName a, GcpUserAccessBindingName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(GcpUserAccessBindingName a, GcpUserAccessBindingName b) => !(a == b);
}
public partial class GcpUserAccessBinding
{
/// <summary>
/// <see cref="giav::GcpUserAccessBindingName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public giav::GcpUserAccessBindingName GcpUserAccessBindingName
{
get => string.IsNullOrEmpty(Name) ? null : giav::GcpUserAccessBindingName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AccessLevelName"/>-typed view over the <see cref="AccessLevels"/> resource name property.
/// </summary>
public gax::ResourceNameList<AccessLevelName> AccessLevelsAsAccessLevelNames
{
get => new gax::ResourceNameList<AccessLevelName>(AccessLevels, s => string.IsNullOrEmpty(s) ? null : AccessLevelName.Parse(s, allowUnparsed: true));
}
}
}
| |
namespace android
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Manifest : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Manifest(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class permission : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal permission(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public permission() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.Manifest.permission._m0.native == global::System.IntPtr.Zero)
global::android.Manifest.permission._m0 = @__env.GetMethodIDNoThrow(global::android.Manifest.permission.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.Manifest.permission.staticClass, global::android.Manifest.permission._m0);
Init(@__env, handle);
}
public static global::java.lang.String ACCESS_CHECKIN_PROPERTIES
{
get
{
return "android.permission.ACCESS_CHECKIN_PROPERTIES";
}
}
public static global::java.lang.String ACCESS_COARSE_LOCATION
{
get
{
return "android.permission.ACCESS_COARSE_LOCATION";
}
}
public static global::java.lang.String ACCESS_FINE_LOCATION
{
get
{
return "android.permission.ACCESS_FINE_LOCATION";
}
}
public static global::java.lang.String ACCESS_LOCATION_EXTRA_COMMANDS
{
get
{
return "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS";
}
}
public static global::java.lang.String ACCESS_MOCK_LOCATION
{
get
{
return "android.permission.ACCESS_MOCK_LOCATION";
}
}
public static global::java.lang.String ACCESS_NETWORK_STATE
{
get
{
return "android.permission.ACCESS_NETWORK_STATE";
}
}
public static global::java.lang.String ACCESS_SURFACE_FLINGER
{
get
{
return "android.permission.ACCESS_SURFACE_FLINGER";
}
}
public static global::java.lang.String ACCESS_WIFI_STATE
{
get
{
return "android.permission.ACCESS_WIFI_STATE";
}
}
public static global::java.lang.String ACCOUNT_MANAGER
{
get
{
return "android.permission.ACCOUNT_MANAGER";
}
}
public static global::java.lang.String AUTHENTICATE_ACCOUNTS
{
get
{
return "android.permission.AUTHENTICATE_ACCOUNTS";
}
}
public static global::java.lang.String BATTERY_STATS
{
get
{
return "android.permission.BATTERY_STATS";
}
}
public static global::java.lang.String BIND_APPWIDGET
{
get
{
return "android.permission.BIND_APPWIDGET";
}
}
public static global::java.lang.String BIND_DEVICE_ADMIN
{
get
{
return "android.permission.BIND_DEVICE_ADMIN";
}
}
public static global::java.lang.String BIND_INPUT_METHOD
{
get
{
return "android.permission.BIND_INPUT_METHOD";
}
}
public static global::java.lang.String BIND_WALLPAPER
{
get
{
return "android.permission.BIND_WALLPAPER";
}
}
public static global::java.lang.String BLUETOOTH
{
get
{
return "android.permission.BLUETOOTH";
}
}
public static global::java.lang.String BLUETOOTH_ADMIN
{
get
{
return "android.permission.BLUETOOTH_ADMIN";
}
}
public static global::java.lang.String BRICK
{
get
{
return "android.permission.BRICK";
}
}
public static global::java.lang.String BROADCAST_PACKAGE_REMOVED
{
get
{
return "android.permission.BROADCAST_PACKAGE_REMOVED";
}
}
public static global::java.lang.String BROADCAST_SMS
{
get
{
return "android.permission.BROADCAST_SMS";
}
}
public static global::java.lang.String BROADCAST_STICKY
{
get
{
return "android.permission.BROADCAST_STICKY";
}
}
public static global::java.lang.String BROADCAST_WAP_PUSH
{
get
{
return "android.permission.BROADCAST_WAP_PUSH";
}
}
public static global::java.lang.String CALL_PHONE
{
get
{
return "android.permission.CALL_PHONE";
}
}
public static global::java.lang.String CALL_PRIVILEGED
{
get
{
return "android.permission.CALL_PRIVILEGED";
}
}
public static global::java.lang.String CAMERA
{
get
{
return "android.permission.CAMERA";
}
}
public static global::java.lang.String CHANGE_COMPONENT_ENABLED_STATE
{
get
{
return "android.permission.CHANGE_COMPONENT_ENABLED_STATE";
}
}
public static global::java.lang.String CHANGE_CONFIGURATION
{
get
{
return "android.permission.CHANGE_CONFIGURATION";
}
}
public static global::java.lang.String CHANGE_NETWORK_STATE
{
get
{
return "android.permission.CHANGE_NETWORK_STATE";
}
}
public static global::java.lang.String CHANGE_WIFI_MULTICAST_STATE
{
get
{
return "android.permission.CHANGE_WIFI_MULTICAST_STATE";
}
}
public static global::java.lang.String CHANGE_WIFI_STATE
{
get
{
return "android.permission.CHANGE_WIFI_STATE";
}
}
public static global::java.lang.String CLEAR_APP_CACHE
{
get
{
return "android.permission.CLEAR_APP_CACHE";
}
}
public static global::java.lang.String CLEAR_APP_USER_DATA
{
get
{
return "android.permission.CLEAR_APP_USER_DATA";
}
}
public static global::java.lang.String CONTROL_LOCATION_UPDATES
{
get
{
return "android.permission.CONTROL_LOCATION_UPDATES";
}
}
public static global::java.lang.String DELETE_CACHE_FILES
{
get
{
return "android.permission.DELETE_CACHE_FILES";
}
}
public static global::java.lang.String DELETE_PACKAGES
{
get
{
return "android.permission.DELETE_PACKAGES";
}
}
public static global::java.lang.String DEVICE_POWER
{
get
{
return "android.permission.DEVICE_POWER";
}
}
public static global::java.lang.String DIAGNOSTIC
{
get
{
return "android.permission.DIAGNOSTIC";
}
}
public static global::java.lang.String DISABLE_KEYGUARD
{
get
{
return "android.permission.DISABLE_KEYGUARD";
}
}
public static global::java.lang.String DUMP
{
get
{
return "android.permission.DUMP";
}
}
public static global::java.lang.String EXPAND_STATUS_BAR
{
get
{
return "android.permission.EXPAND_STATUS_BAR";
}
}
public static global::java.lang.String FACTORY_TEST
{
get
{
return "android.permission.FACTORY_TEST";
}
}
public static global::java.lang.String FLASHLIGHT
{
get
{
return "android.permission.FLASHLIGHT";
}
}
public static global::java.lang.String FORCE_BACK
{
get
{
return "android.permission.FORCE_BACK";
}
}
public static global::java.lang.String GET_ACCOUNTS
{
get
{
return "android.permission.GET_ACCOUNTS";
}
}
public static global::java.lang.String GET_PACKAGE_SIZE
{
get
{
return "android.permission.GET_PACKAGE_SIZE";
}
}
public static global::java.lang.String GET_TASKS
{
get
{
return "android.permission.GET_TASKS";
}
}
public static global::java.lang.String GLOBAL_SEARCH
{
get
{
return "android.permission.GLOBAL_SEARCH";
}
}
public static global::java.lang.String HARDWARE_TEST
{
get
{
return "android.permission.HARDWARE_TEST";
}
}
public static global::java.lang.String INJECT_EVENTS
{
get
{
return "android.permission.INJECT_EVENTS";
}
}
public static global::java.lang.String INSTALL_LOCATION_PROVIDER
{
get
{
return "android.permission.INSTALL_LOCATION_PROVIDER";
}
}
public static global::java.lang.String INSTALL_PACKAGES
{
get
{
return "android.permission.INSTALL_PACKAGES";
}
}
public static global::java.lang.String INTERNAL_SYSTEM_WINDOW
{
get
{
return "android.permission.INTERNAL_SYSTEM_WINDOW";
}
}
public static global::java.lang.String INTERNET
{
get
{
return "android.permission.INTERNET";
}
}
public static global::java.lang.String KILL_BACKGROUND_PROCESSES
{
get
{
return "android.permission.KILL_BACKGROUND_PROCESSES";
}
}
public static global::java.lang.String MANAGE_ACCOUNTS
{
get
{
return "android.permission.MANAGE_ACCOUNTS";
}
}
public static global::java.lang.String MANAGE_APP_TOKENS
{
get
{
return "android.permission.MANAGE_APP_TOKENS";
}
}
public static global::java.lang.String MASTER_CLEAR
{
get
{
return "android.permission.MASTER_CLEAR";
}
}
public static global::java.lang.String MODIFY_AUDIO_SETTINGS
{
get
{
return "android.permission.MODIFY_AUDIO_SETTINGS";
}
}
public static global::java.lang.String MODIFY_PHONE_STATE
{
get
{
return "android.permission.MODIFY_PHONE_STATE";
}
}
public static global::java.lang.String MOUNT_FORMAT_FILESYSTEMS
{
get
{
return "android.permission.MOUNT_FORMAT_FILESYSTEMS";
}
}
public static global::java.lang.String MOUNT_UNMOUNT_FILESYSTEMS
{
get
{
return "android.permission.MOUNT_UNMOUNT_FILESYSTEMS";
}
}
public static global::java.lang.String PERSISTENT_ACTIVITY
{
get
{
return "android.permission.PERSISTENT_ACTIVITY";
}
}
public static global::java.lang.String PROCESS_OUTGOING_CALLS
{
get
{
return "android.permission.PROCESS_OUTGOING_CALLS";
}
}
public static global::java.lang.String READ_CALENDAR
{
get
{
return "android.permission.READ_CALENDAR";
}
}
public static global::java.lang.String READ_CONTACTS
{
get
{
return "android.permission.READ_CONTACTS";
}
}
public static global::java.lang.String READ_FRAME_BUFFER
{
get
{
return "android.permission.READ_FRAME_BUFFER";
}
}
public static global::java.lang.String READ_HISTORY_BOOKMARKS
{
get
{
return "com.android.browser.permission.READ_HISTORY_BOOKMARKS";
}
}
public static global::java.lang.String READ_INPUT_STATE
{
get
{
return "android.permission.READ_INPUT_STATE";
}
}
public static global::java.lang.String READ_LOGS
{
get
{
return "android.permission.READ_LOGS";
}
}
public static global::java.lang.String READ_OWNER_DATA
{
get
{
return "android.permission.READ_OWNER_DATA";
}
}
public static global::java.lang.String READ_PHONE_STATE
{
get
{
return "android.permission.READ_PHONE_STATE";
}
}
public static global::java.lang.String READ_SMS
{
get
{
return "android.permission.READ_SMS";
}
}
public static global::java.lang.String READ_SYNC_SETTINGS
{
get
{
return "android.permission.READ_SYNC_SETTINGS";
}
}
public static global::java.lang.String READ_SYNC_STATS
{
get
{
return "android.permission.READ_SYNC_STATS";
}
}
public static global::java.lang.String REBOOT
{
get
{
return "android.permission.REBOOT";
}
}
public static global::java.lang.String RECEIVE_BOOT_COMPLETED
{
get
{
return "android.permission.RECEIVE_BOOT_COMPLETED";
}
}
public static global::java.lang.String RECEIVE_MMS
{
get
{
return "android.permission.RECEIVE_MMS";
}
}
public static global::java.lang.String RECEIVE_SMS
{
get
{
return "android.permission.RECEIVE_SMS";
}
}
public static global::java.lang.String RECEIVE_WAP_PUSH
{
get
{
return "android.permission.RECEIVE_WAP_PUSH";
}
}
public static global::java.lang.String RECORD_AUDIO
{
get
{
return "android.permission.RECORD_AUDIO";
}
}
public static global::java.lang.String REORDER_TASKS
{
get
{
return "android.permission.REORDER_TASKS";
}
}
public static global::java.lang.String RESTART_PACKAGES
{
get
{
return "android.permission.RESTART_PACKAGES";
}
}
public static global::java.lang.String SEND_SMS
{
get
{
return "android.permission.SEND_SMS";
}
}
public static global::java.lang.String SET_ACTIVITY_WATCHER
{
get
{
return "android.permission.SET_ACTIVITY_WATCHER";
}
}
public static global::java.lang.String SET_ALWAYS_FINISH
{
get
{
return "android.permission.SET_ALWAYS_FINISH";
}
}
public static global::java.lang.String SET_ANIMATION_SCALE
{
get
{
return "android.permission.SET_ANIMATION_SCALE";
}
}
public static global::java.lang.String SET_DEBUG_APP
{
get
{
return "android.permission.SET_DEBUG_APP";
}
}
public static global::java.lang.String SET_ORIENTATION
{
get
{
return "android.permission.SET_ORIENTATION";
}
}
public static global::java.lang.String SET_PREFERRED_APPLICATIONS
{
get
{
return "android.permission.SET_PREFERRED_APPLICATIONS";
}
}
public static global::java.lang.String SET_PROCESS_LIMIT
{
get
{
return "android.permission.SET_PROCESS_LIMIT";
}
}
public static global::java.lang.String SET_TIME
{
get
{
return "android.permission.SET_TIME";
}
}
public static global::java.lang.String SET_TIME_ZONE
{
get
{
return "android.permission.SET_TIME_ZONE";
}
}
public static global::java.lang.String SET_WALLPAPER
{
get
{
return "android.permission.SET_WALLPAPER";
}
}
public static global::java.lang.String SET_WALLPAPER_HINTS
{
get
{
return "android.permission.SET_WALLPAPER_HINTS";
}
}
public static global::java.lang.String SIGNAL_PERSISTENT_PROCESSES
{
get
{
return "android.permission.SIGNAL_PERSISTENT_PROCESSES";
}
}
public static global::java.lang.String STATUS_BAR
{
get
{
return "android.permission.STATUS_BAR";
}
}
public static global::java.lang.String SUBSCRIBED_FEEDS_READ
{
get
{
return "android.permission.SUBSCRIBED_FEEDS_READ";
}
}
public static global::java.lang.String SUBSCRIBED_FEEDS_WRITE
{
get
{
return "android.permission.SUBSCRIBED_FEEDS_WRITE";
}
}
public static global::java.lang.String SYSTEM_ALERT_WINDOW
{
get
{
return "android.permission.SYSTEM_ALERT_WINDOW";
}
}
public static global::java.lang.String UPDATE_DEVICE_STATS
{
get
{
return "android.permission.UPDATE_DEVICE_STATS";
}
}
public static global::java.lang.String USE_CREDENTIALS
{
get
{
return "android.permission.USE_CREDENTIALS";
}
}
public static global::java.lang.String VIBRATE
{
get
{
return "android.permission.VIBRATE";
}
}
public static global::java.lang.String WAKE_LOCK
{
get
{
return "android.permission.WAKE_LOCK";
}
}
public static global::java.lang.String WRITE_APN_SETTINGS
{
get
{
return "android.permission.WRITE_APN_SETTINGS";
}
}
public static global::java.lang.String WRITE_CALENDAR
{
get
{
return "android.permission.WRITE_CALENDAR";
}
}
public static global::java.lang.String WRITE_CONTACTS
{
get
{
return "android.permission.WRITE_CONTACTS";
}
}
public static global::java.lang.String WRITE_EXTERNAL_STORAGE
{
get
{
return "android.permission.WRITE_EXTERNAL_STORAGE";
}
}
public static global::java.lang.String WRITE_GSERVICES
{
get
{
return "android.permission.WRITE_GSERVICES";
}
}
public static global::java.lang.String WRITE_HISTORY_BOOKMARKS
{
get
{
return "com.android.browser.permission.WRITE_HISTORY_BOOKMARKS";
}
}
public static global::java.lang.String WRITE_OWNER_DATA
{
get
{
return "android.permission.WRITE_OWNER_DATA";
}
}
public static global::java.lang.String WRITE_SECURE_SETTINGS
{
get
{
return "android.permission.WRITE_SECURE_SETTINGS";
}
}
public static global::java.lang.String WRITE_SETTINGS
{
get
{
return "android.permission.WRITE_SETTINGS";
}
}
public static global::java.lang.String WRITE_SMS
{
get
{
return "android.permission.WRITE_SMS";
}
}
public static global::java.lang.String WRITE_SYNC_SETTINGS
{
get
{
return "android.permission.WRITE_SYNC_SETTINGS";
}
}
static permission()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.Manifest.permission.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/Manifest$permission"));
}
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class permission_group : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal permission_group(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public permission_group() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.Manifest.permission_group._m0.native == global::System.IntPtr.Zero)
global::android.Manifest.permission_group._m0 = @__env.GetMethodIDNoThrow(global::android.Manifest.permission_group.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.Manifest.permission_group.staticClass, global::android.Manifest.permission_group._m0);
Init(@__env, handle);
}
public static global::java.lang.String ACCOUNTS
{
get
{
return "android.permission-group.ACCOUNTS";
}
}
public static global::java.lang.String COST_MONEY
{
get
{
return "android.permission-group.COST_MONEY";
}
}
public static global::java.lang.String DEVELOPMENT_TOOLS
{
get
{
return "android.permission-group.DEVELOPMENT_TOOLS";
}
}
public static global::java.lang.String HARDWARE_CONTROLS
{
get
{
return "android.permission-group.HARDWARE_CONTROLS";
}
}
public static global::java.lang.String LOCATION
{
get
{
return "android.permission-group.LOCATION";
}
}
public static global::java.lang.String MESSAGES
{
get
{
return "android.permission-group.MESSAGES";
}
}
public static global::java.lang.String NETWORK
{
get
{
return "android.permission-group.NETWORK";
}
}
public static global::java.lang.String PERSONAL_INFO
{
get
{
return "android.permission-group.PERSONAL_INFO";
}
}
public static global::java.lang.String PHONE_CALLS
{
get
{
return "android.permission-group.PHONE_CALLS";
}
}
public static global::java.lang.String STORAGE
{
get
{
return "android.permission-group.STORAGE";
}
}
public static global::java.lang.String SYSTEM_TOOLS
{
get
{
return "android.permission-group.SYSTEM_TOOLS";
}
}
static permission_group()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.Manifest.permission_group.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/Manifest$permission_group"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
public Manifest() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.Manifest._m0.native == global::System.IntPtr.Zero)
global::android.Manifest._m0 = @__env.GetMethodIDNoThrow(global::android.Manifest.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.Manifest.staticClass, global::android.Manifest._m0);
Init(@__env, handle);
}
static Manifest()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.Manifest.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/Manifest"));
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// Radio
/// </summary>
[DataContract]
public partial class Radio : IEquatable<Radio>, IValidatableObject
{
public Radio()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="Radio" /> class.
/// </summary>
/// <param name="AnchorCaseSensitive">When set to **true**, the anchor string does not consider case when matching strings in the document. The default value is **true**..</param>
/// <param name="AnchorHorizontalAlignment">Specifies the alignment of anchor tabs with anchor strings. Possible values are **left** or **right**. The default value is **left**..</param>
/// <param name="AnchorIgnoreIfNotPresent">When set to **true**, this tab is ignored if anchorString is not found in the document..</param>
/// <param name="AnchorMatchWholeWord">When set to **true**, the anchor string in this tab matches whole words only (strings embedded in other strings are ignored.) The default value is **true**..</param>
/// <param name="AnchorString">Anchor text information for a radio button..</param>
/// <param name="AnchorUnits">Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches..</param>
/// <param name="AnchorXOffset">Specifies the X axis location of the tab, in achorUnits, relative to the anchorString..</param>
/// <param name="AnchorYOffset">Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString..</param>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="Locked">When set to **true**, the signer cannot change the data of the custom tab..</param>
/// <param name="PageNumber">Specifies the page number on which the tab is located..</param>
/// <param name="Required">When set to **true**, the signer is required to fill out this tab.</param>
/// <param name="Selected">When set to **true**, the radio button is selected..</param>
/// <param name="TabId">The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call]. .</param>
/// <param name="TabOrder">.</param>
/// <param name="Value">Specifies the value of the tab. .</param>
/// <param name="XPosition">This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position..</param>
/// <param name="YPosition">This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position..</param>
public Radio(string AnchorCaseSensitive = default(string), string AnchorHorizontalAlignment = default(string), string AnchorIgnoreIfNotPresent = default(string), string AnchorMatchWholeWord = default(string), string AnchorString = default(string), string AnchorUnits = default(string), string AnchorXOffset = default(string), string AnchorYOffset = default(string), ErrorDetails ErrorDetails = default(ErrorDetails), string Locked = default(string), string PageNumber = default(string), string Required = default(string), string Selected = default(string), string TabId = default(string), string TabOrder = default(string), string Value = default(string), string XPosition = default(string), string YPosition = default(string))
{
this.AnchorCaseSensitive = AnchorCaseSensitive;
this.AnchorHorizontalAlignment = AnchorHorizontalAlignment;
this.AnchorIgnoreIfNotPresent = AnchorIgnoreIfNotPresent;
this.AnchorMatchWholeWord = AnchorMatchWholeWord;
this.AnchorString = AnchorString;
this.AnchorUnits = AnchorUnits;
this.AnchorXOffset = AnchorXOffset;
this.AnchorYOffset = AnchorYOffset;
this.ErrorDetails = ErrorDetails;
this.Locked = Locked;
this.PageNumber = PageNumber;
this.Required = Required;
this.Selected = Selected;
this.TabId = TabId;
this.TabOrder = TabOrder;
this.Value = Value;
this.XPosition = XPosition;
this.YPosition = YPosition;
}
/// <summary>
/// When set to **true**, the anchor string does not consider case when matching strings in the document. The default value is **true**.
/// </summary>
/// <value>When set to **true**, the anchor string does not consider case when matching strings in the document. The default value is **true**.</value>
[DataMember(Name="anchorCaseSensitive", EmitDefaultValue=false)]
public string AnchorCaseSensitive { get; set; }
/// <summary>
/// Specifies the alignment of anchor tabs with anchor strings. Possible values are **left** or **right**. The default value is **left**.
/// </summary>
/// <value>Specifies the alignment of anchor tabs with anchor strings. Possible values are **left** or **right**. The default value is **left**.</value>
[DataMember(Name="anchorHorizontalAlignment", EmitDefaultValue=false)]
public string AnchorHorizontalAlignment { get; set; }
/// <summary>
/// When set to **true**, this tab is ignored if anchorString is not found in the document.
/// </summary>
/// <value>When set to **true**, this tab is ignored if anchorString is not found in the document.</value>
[DataMember(Name="anchorIgnoreIfNotPresent", EmitDefaultValue=false)]
public string AnchorIgnoreIfNotPresent { get; set; }
/// <summary>
/// When set to **true**, the anchor string in this tab matches whole words only (strings embedded in other strings are ignored.) The default value is **true**.
/// </summary>
/// <value>When set to **true**, the anchor string in this tab matches whole words only (strings embedded in other strings are ignored.) The default value is **true**.</value>
[DataMember(Name="anchorMatchWholeWord", EmitDefaultValue=false)]
public string AnchorMatchWholeWord { get; set; }
/// <summary>
/// Anchor text information for a radio button.
/// </summary>
/// <value>Anchor text information for a radio button.</value>
[DataMember(Name="anchorString", EmitDefaultValue=false)]
public string AnchorString { get; set; }
/// <summary>
/// Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.
/// </summary>
/// <value>Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.</value>
[DataMember(Name="anchorUnits", EmitDefaultValue=false)]
public string AnchorUnits { get; set; }
/// <summary>
/// Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorXOffset", EmitDefaultValue=false)]
public string AnchorXOffset { get; set; }
/// <summary>
/// Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorYOffset", EmitDefaultValue=false)]
public string AnchorYOffset { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// When set to **true**, the signer cannot change the data of the custom tab.
/// </summary>
/// <value>When set to **true**, the signer cannot change the data of the custom tab.</value>
[DataMember(Name="locked", EmitDefaultValue=false)]
public string Locked { get; set; }
/// <summary>
/// Specifies the page number on which the tab is located.
/// </summary>
/// <value>Specifies the page number on which the tab is located.</value>
[DataMember(Name="pageNumber", EmitDefaultValue=false)]
public string PageNumber { get; set; }
/// <summary>
/// When set to **true**, the signer is required to fill out this tab
/// </summary>
/// <value>When set to **true**, the signer is required to fill out this tab</value>
[DataMember(Name="required", EmitDefaultValue=false)]
public string Required { get; set; }
/// <summary>
/// When set to **true**, the radio button is selected.
/// </summary>
/// <value>When set to **true**, the radio button is selected.</value>
[DataMember(Name="selected", EmitDefaultValue=false)]
public string Selected { get; set; }
/// <summary>
/// The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].
/// </summary>
/// <value>The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call]. </value>
[DataMember(Name="tabId", EmitDefaultValue=false)]
public string TabId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="tabOrder", EmitDefaultValue=false)]
public string TabOrder { get; set; }
/// <summary>
/// Specifies the value of the tab.
/// </summary>
/// <value>Specifies the value of the tab. </value>
[DataMember(Name="value", EmitDefaultValue=false)]
public string Value { get; set; }
/// <summary>
/// This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="xPosition", EmitDefaultValue=false)]
public string XPosition { get; set; }
/// <summary>
/// This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="yPosition", EmitDefaultValue=false)]
public string YPosition { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Radio {\n");
sb.Append(" AnchorCaseSensitive: ").Append(AnchorCaseSensitive).Append("\n");
sb.Append(" AnchorHorizontalAlignment: ").Append(AnchorHorizontalAlignment).Append("\n");
sb.Append(" AnchorIgnoreIfNotPresent: ").Append(AnchorIgnoreIfNotPresent).Append("\n");
sb.Append(" AnchorMatchWholeWord: ").Append(AnchorMatchWholeWord).Append("\n");
sb.Append(" AnchorString: ").Append(AnchorString).Append("\n");
sb.Append(" AnchorUnits: ").Append(AnchorUnits).Append("\n");
sb.Append(" AnchorXOffset: ").Append(AnchorXOffset).Append("\n");
sb.Append(" AnchorYOffset: ").Append(AnchorYOffset).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" Locked: ").Append(Locked).Append("\n");
sb.Append(" PageNumber: ").Append(PageNumber).Append("\n");
sb.Append(" Required: ").Append(Required).Append("\n");
sb.Append(" Selected: ").Append(Selected).Append("\n");
sb.Append(" TabId: ").Append(TabId).Append("\n");
sb.Append(" TabOrder: ").Append(TabOrder).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append(" XPosition: ").Append(XPosition).Append("\n");
sb.Append(" YPosition: ").Append(YPosition).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Radio);
}
/// <summary>
/// Returns true if Radio instances are equal
/// </summary>
/// <param name="other">Instance of Radio to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Radio other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AnchorCaseSensitive == other.AnchorCaseSensitive ||
this.AnchorCaseSensitive != null &&
this.AnchorCaseSensitive.Equals(other.AnchorCaseSensitive)
) &&
(
this.AnchorHorizontalAlignment == other.AnchorHorizontalAlignment ||
this.AnchorHorizontalAlignment != null &&
this.AnchorHorizontalAlignment.Equals(other.AnchorHorizontalAlignment)
) &&
(
this.AnchorIgnoreIfNotPresent == other.AnchorIgnoreIfNotPresent ||
this.AnchorIgnoreIfNotPresent != null &&
this.AnchorIgnoreIfNotPresent.Equals(other.AnchorIgnoreIfNotPresent)
) &&
(
this.AnchorMatchWholeWord == other.AnchorMatchWholeWord ||
this.AnchorMatchWholeWord != null &&
this.AnchorMatchWholeWord.Equals(other.AnchorMatchWholeWord)
) &&
(
this.AnchorString == other.AnchorString ||
this.AnchorString != null &&
this.AnchorString.Equals(other.AnchorString)
) &&
(
this.AnchorUnits == other.AnchorUnits ||
this.AnchorUnits != null &&
this.AnchorUnits.Equals(other.AnchorUnits)
) &&
(
this.AnchorXOffset == other.AnchorXOffset ||
this.AnchorXOffset != null &&
this.AnchorXOffset.Equals(other.AnchorXOffset)
) &&
(
this.AnchorYOffset == other.AnchorYOffset ||
this.AnchorYOffset != null &&
this.AnchorYOffset.Equals(other.AnchorYOffset)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.Locked == other.Locked ||
this.Locked != null &&
this.Locked.Equals(other.Locked)
) &&
(
this.PageNumber == other.PageNumber ||
this.PageNumber != null &&
this.PageNumber.Equals(other.PageNumber)
) &&
(
this.Required == other.Required ||
this.Required != null &&
this.Required.Equals(other.Required)
) &&
(
this.Selected == other.Selected ||
this.Selected != null &&
this.Selected.Equals(other.Selected)
) &&
(
this.TabId == other.TabId ||
this.TabId != null &&
this.TabId.Equals(other.TabId)
) &&
(
this.TabOrder == other.TabOrder ||
this.TabOrder != null &&
this.TabOrder.Equals(other.TabOrder)
) &&
(
this.Value == other.Value ||
this.Value != null &&
this.Value.Equals(other.Value)
) &&
(
this.XPosition == other.XPosition ||
this.XPosition != null &&
this.XPosition.Equals(other.XPosition)
) &&
(
this.YPosition == other.YPosition ||
this.YPosition != null &&
this.YPosition.Equals(other.YPosition)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.AnchorCaseSensitive != null)
hash = hash * 59 + this.AnchorCaseSensitive.GetHashCode();
if (this.AnchorHorizontalAlignment != null)
hash = hash * 59 + this.AnchorHorizontalAlignment.GetHashCode();
if (this.AnchorIgnoreIfNotPresent != null)
hash = hash * 59 + this.AnchorIgnoreIfNotPresent.GetHashCode();
if (this.AnchorMatchWholeWord != null)
hash = hash * 59 + this.AnchorMatchWholeWord.GetHashCode();
if (this.AnchorString != null)
hash = hash * 59 + this.AnchorString.GetHashCode();
if (this.AnchorUnits != null)
hash = hash * 59 + this.AnchorUnits.GetHashCode();
if (this.AnchorXOffset != null)
hash = hash * 59 + this.AnchorXOffset.GetHashCode();
if (this.AnchorYOffset != null)
hash = hash * 59 + this.AnchorYOffset.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.Locked != null)
hash = hash * 59 + this.Locked.GetHashCode();
if (this.PageNumber != null)
hash = hash * 59 + this.PageNumber.GetHashCode();
if (this.Required != null)
hash = hash * 59 + this.Required.GetHashCode();
if (this.Selected != null)
hash = hash * 59 + this.Selected.GetHashCode();
if (this.TabId != null)
hash = hash * 59 + this.TabId.GetHashCode();
if (this.TabOrder != null)
hash = hash * 59 + this.TabOrder.GetHashCode();
if (this.Value != null)
hash = hash * 59 + this.Value.GetHashCode();
if (this.XPosition != null)
hash = hash * 59 + this.XPosition.GetHashCode();
if (this.YPosition != null)
hash = hash * 59 + this.YPosition.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The implementation of the "Test-Connection" cmdlet.
/// </summary>
[Cmdlet(VerbsDiagnostic.Test, "Connection", DefaultParameterSetName = ParameterSetPingCount, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135266")]
[OutputType(typeof(PingReport), ParameterSetName = new string[] { ParameterSetPingCount })]
[OutputType(typeof(PingReply), ParameterSetName = new string[] { ParameterSetPingContinues, ParameterSetDetectionOfMTUSize })]
[OutputType(typeof(bool), ParameterSetName = new string[] { ParameterSetPingCount, ParameterSetPingContinues, ParameterSetConnectionByTCPPort })]
[OutputType(typeof(Int32), ParameterSetName = new string[] { ParameterSetDetectionOfMTUSize })]
[OutputType(typeof(TraceRouteReply), ParameterSetName = new string[] { ParameterSetTraceRoute })]
public class TestConnectionCommand : PSCmdlet
{
private const string ParameterSetPingCount = "PingCount";
private const string ParameterSetPingContinues = "PingContinues";
private const string ParameterSetTraceRoute = "TraceRoute";
private const string ParameterSetConnectionByTCPPort = "ConnectionByTCPPort";
private const string ParameterSetDetectionOfMTUSize = "DetectionOfMTUSize";
#region Parameters
/// <summary>
/// Do ping test.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[Parameter(ParameterSetName = ParameterSetPingContinues)]
public SwitchParameter Ping { get; set; } = true;
/// <summary>
/// Force using IPv4 protocol.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[Parameter(ParameterSetName = ParameterSetPingContinues)]
[Parameter(ParameterSetName = ParameterSetTraceRoute)]
[Parameter(ParameterSetName = ParameterSetDetectionOfMTUSize)]
[Parameter(ParameterSetName = ParameterSetConnectionByTCPPort)]
public SwitchParameter IPv4 { get; set; }
/// <summary>
/// Force using IPv6 protocol.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[Parameter(ParameterSetName = ParameterSetPingContinues)]
[Parameter(ParameterSetName = ParameterSetTraceRoute)]
[Parameter(ParameterSetName = ParameterSetDetectionOfMTUSize)]
[Parameter(ParameterSetName = ParameterSetConnectionByTCPPort)]
public SwitchParameter IPv6 { get; set; }
/// <summary>
/// Do reverse DNS lookup to get names for IP addresses.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[Parameter(ParameterSetName = ParameterSetPingContinues)]
[Parameter(ParameterSetName = ParameterSetTraceRoute)]
[Parameter(ParameterSetName = ParameterSetDetectionOfMTUSize)]
[Parameter(ParameterSetName = ParameterSetConnectionByTCPPort)]
public SwitchParameter ResolveDestination { get; set; }
/// <summary>
/// Source from which to do a test (ping, trace route, ...).
/// The default is Local Host.
/// Remoting is not yet implemented internally in the cmdlet.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[Parameter(ParameterSetName = ParameterSetPingContinues)]
[Parameter(ParameterSetName = ParameterSetTraceRoute)]
[Parameter(ParameterSetName = ParameterSetConnectionByTCPPort)]
public string Source { get; } = Dns.GetHostName();
/// <summary>
/// The number of times the Ping data packets can be forwarded by routers.
/// As gateways and routers transmit packets through a network,
/// they decrement the Time-to-Live (TTL) value found in the packet header.
/// The default (from Windows) is 128 hops.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[Parameter(ParameterSetName = ParameterSetPingContinues)]
[Parameter(ParameterSetName = ParameterSetTraceRoute)]
[ValidateRange(0, sMaxHops)]
[Alias("Ttl", "TimeToLive", "Hops")]
public int MaxHops { get; set; } = sMaxHops;
private const int sMaxHops = 128;
/// <summary>
/// Count of attempts.
/// The default (from Windows) is 4 times.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[ValidateRange(ValidateRangeKind.Positive)]
public int Count { get; set; } = 4;
/// <summary>
/// Delay between attempts.
/// The default (from Windows) is 1 second.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[Parameter(ParameterSetName = ParameterSetPingContinues)]
[ValidateRange(ValidateRangeKind.Positive)]
public int Delay { get; set; } = 1;
/// <summary>
/// Buffer size to send.
/// The default (from Windows) is 32 bites.
/// Max value is 65500 (limit from Windows API).
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[Parameter(ParameterSetName = ParameterSetPingContinues)]
[Alias("Size", "Bytes", "BS")]
[ValidateRange(0, 65500)]
public int BufferSize { get; set; } = DefaultSendBufferSize;
/// <summary>
/// Don't fragment ICMP packages.
/// Currently CoreFX not supports this on Unix.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingCount)]
[Parameter(ParameterSetName = ParameterSetPingContinues)]
public SwitchParameter DontFragment { get; set; }
/// <summary>
/// Continue ping until user press Ctrl-C
/// or Int.MaxValue threshold reached.
/// </summary>
[Parameter(ParameterSetName = ParameterSetPingContinues)]
public SwitchParameter Continues { get; set; }
/// <summary>
/// Set short output kind ('bool' for Ping, 'int' for MTU size ...).
/// Default is to return typed result object(s).
/// </summary>
[Parameter()]
public SwitchParameter Quiet;
/// <summary>
/// Time-out value in seconds.
/// If a response is not received in this time, no response is assumed.
/// It is not the cmdlet timeout! It is a timeout for waiting one ping response.
/// The default (from Windows) is 5 second.
/// </summary>
[Parameter()]
[ValidateRange(ValidateRangeKind.Positive)]
public int TimeoutSeconds { get; set; } = 5;
/// <summary>
/// Destination - computer name or IP address.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[Alias("ComputerName")]
public string[] TargetName { get; set; }
/// <summary>
/// Detect MTU size.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = ParameterSetDetectionOfMTUSize)]
public SwitchParameter MTUSizeDetect { get; set; }
/// <summary>
/// Do traceroute test.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = ParameterSetTraceRoute)]
public SwitchParameter Traceroute { get; set; }
/// <summary>
/// Do tcp connection test.
/// </summary>
[ValidateRange(0, 65535)]
[Parameter(Mandatory = true, ParameterSetName = ParameterSetConnectionByTCPPort)]
public int TCPPort { get; set; }
#endregion Parameters
/// <summary>
/// Init the cmdlet.
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
switch (ParameterSetName)
{
case ParameterSetPingContinues:
Count = int.MaxValue;
break;
}
}
/// <summary>
/// Process a connection test.
/// </summary>
protected override void ProcessRecord()
{
foreach (var targetName in TargetName)
{
switch (ParameterSetName)
{
case ParameterSetPingCount:
case ParameterSetPingContinues:
ProcessPing(targetName);
break;
case ParameterSetDetectionOfMTUSize:
ProcessMTUSize(targetName);
break;
case ParameterSetTraceRoute:
ProcessTraceroute(targetName);
break;
case ParameterSetConnectionByTCPPort:
ProcessConnectionByTCPPort(targetName);
break;
}
}
}
#region ConnectionTest
private void ProcessConnectionByTCPPort(String targetNameOrAddress)
{
string resolvedTargetName = null;
IPAddress targetAddress = null;
if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress))
{
return;
}
WriteConnectionTestHeader(resolvedTargetName, targetAddress.ToString());
TcpClient client = new TcpClient();
try
{
Task connectionTask = client.ConnectAsync(targetAddress, TCPPort);
string targetString = targetAddress.ToString();
for (var i = 1; i <= TimeoutSeconds; i++)
{
WriteConnectionTestProgress(targetNameOrAddress, targetString, i);
Task timeoutTask = Task.Delay(millisecondsDelay: 1000);
Task.WhenAny(connectionTask, timeoutTask).Result.Wait();
if (timeoutTask.Status == TaskStatus.Faulted || timeoutTask.Status == TaskStatus.Canceled)
{
// Waiting is interrupted by Ctrl-C.
WriteObject(false);
return;
}
if (connectionTask.Status == TaskStatus.RanToCompletion)
{
WriteObject(true);
return;
}
}
}
catch
{
// Silently ignore connection errors.
}
finally
{
client.Close();
WriteConnectionTestFooter();
}
WriteObject(false);
}
private void WriteConnectionTestHeader(string resolvedTargetName, string targetAddress)
{
_testConnectionProgressBarActivity = StringUtil.Format(TestConnectionResources.ConnectionTestStart, resolvedTargetName, targetAddress);
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, ProgressRecordSpace);
WriteProgress(record);
}
private void WriteConnectionTestProgress(string targetNameOrAddress, string targetAddress, int timeout)
{
var msg = StringUtil.Format(TestConnectionResources.ConnectionTestDescription,
targetNameOrAddress,
targetAddress,
timeout);
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, msg);
WriteProgress(record);
}
private void WriteConnectionTestFooter()
{
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, ProgressRecordSpace);
record.RecordType = ProgressRecordType.Completed;
WriteProgress(record);
}
#endregion ConnectionTest
#region TracerouteTest
private void ProcessTraceroute(String targetNameOrAddress)
{
string resolvedTargetName = null;
IPAddress targetAddress = null;
byte[] buffer = GetSendBuffer(BufferSize);
if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress))
{
return;
}
WriteConsoleTraceRouteHeader(resolvedTargetName, targetAddress.ToString());
TraceRouteResult traceRouteResult = new TraceRouteResult(Source, targetAddress, resolvedTargetName);
Int32 currentHop = 1;
Ping sender = new Ping();
PingOptions pingOptions = new PingOptions(currentHop, DontFragment.IsPresent);
PingReply reply = null;
Int32 timeout = TimeoutSeconds * 1000;
do
{
TraceRouteReply traceRouteReply = new TraceRouteReply();
pingOptions.Ttl = traceRouteReply.Hop = currentHop;
currentHop++;
// In the specific case we don't use 'Count' property.
// If we change 'DefaultTraceRoutePingCount' we should change 'ConsoleTraceRouteReply' resource string.
for (int i = 1; i <= DefaultTraceRoutePingCount; i++)
{
try
{
reply = sender.Send(targetAddress, timeout, buffer, pingOptions);
traceRouteReply.PingReplies.Add(reply);
}
catch (PingException ex)
{
string message = StringUtil.Format(TestConnectionResources.NoPingResult,
resolvedTargetName,
ex.Message);
Exception pingException = new System.Net.NetworkInformation.PingException(message, ex.InnerException);
ErrorRecord errorRecord = new ErrorRecord(pingException,
TestConnectionExceptionId,
ErrorCategory.ResourceUnavailable,
resolvedTargetName);
WriteError(errorRecord);
continue;
}
catch
{
// Ignore host resolve exceptions.
}
// We use short delay because it is impossible DoS with trace route.
Thread.Sleep(200);
}
if (ResolveDestination && reply.Status == IPStatus.Success)
{
traceRouteReply.ReplyRouterName = Dns.GetHostEntry(reply.Address).HostName;
}
traceRouteReply.ReplyRouterAddress = reply.Address;
WriteTraceRouteProgress(traceRouteReply);
traceRouteResult.Replies.Add(traceRouteReply);
} while (reply != null && currentHop <= sMaxHops && (reply.Status == IPStatus.TtlExpired || reply.Status == IPStatus.TimedOut));
WriteTraceRouteFooter();
if (Quiet.IsPresent)
{
WriteObject(currentHop <= sMaxHops);
}
else
{
WriteObject(traceRouteResult);
}
}
private void WriteConsoleTraceRouteHeader(string resolvedTargetName, string targetAddress)
{
_testConnectionProgressBarActivity = StringUtil.Format(TestConnectionResources.TraceRouteStart, resolvedTargetName, targetAddress, MaxHops);
WriteInformation(_testConnectionProgressBarActivity, s_PSHostTag);
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, ProgressRecordSpace);
WriteProgress(record);
}
private string _testConnectionProgressBarActivity;
private static string[] s_PSHostTag = new string[] { "PSHOST" };
private void WriteTraceRouteProgress(TraceRouteReply traceRouteReply)
{
string msg = string.Empty;
if (traceRouteReply.PingReplies[2].Status == IPStatus.TtlExpired || traceRouteReply.PingReplies[2].Status == IPStatus.Success)
{
var routerAddress = traceRouteReply.ReplyRouterAddress.ToString();
var routerName = traceRouteReply.ReplyRouterName ?? routerAddress;
var roundtripTime0 = traceRouteReply.PingReplies[0].Status == IPStatus.TimedOut ? "*" : traceRouteReply.PingReplies[0].RoundtripTime.ToString();
var roundtripTime1 = traceRouteReply.PingReplies[1].Status == IPStatus.TimedOut ? "*" : traceRouteReply.PingReplies[1].RoundtripTime.ToString();
msg = StringUtil.Format(TestConnectionResources.TraceRouteReply,
traceRouteReply.Hop, roundtripTime0, roundtripTime1, traceRouteReply.PingReplies[2].RoundtripTime.ToString(),
routerName, routerAddress);
}
else
{
msg = StringUtil.Format(TestConnectionResources.TraceRouteTimeOut, traceRouteReply.Hop);
}
WriteInformation(msg, s_PSHostTag);
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, msg);
WriteProgress(record);
}
private void WriteTraceRouteFooter()
{
WriteInformation(TestConnectionResources.TraceRouteComplete, s_PSHostTag);
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, ProgressRecordSpace);
record.RecordType = ProgressRecordType.Completed;
WriteProgress(record);
}
/// <summary>
/// The class contains an information about a trace route attempt.
/// </summary>
public class TraceRouteReply
{
internal TraceRouteReply()
{
PingReplies = new List<PingReply>(DefaultTraceRoutePingCount);
}
/// <summary>
/// Number of current hop (router).
/// </summary>
public int Hop;
/// <summary>
/// List of ping replies for current hop (router).
/// </summary>
public List<PingReply> PingReplies;
/// <summary>
/// Router IP address.
/// </summary>
public IPAddress ReplyRouterAddress;
/// <summary>
/// Resolved router name.
/// </summary>
public string ReplyRouterName;
}
/// <summary>
/// The class contains an information about the source, the destination and trace route results.
/// </summary>
public class TraceRouteResult
{
internal TraceRouteResult(string source, IPAddress destinationAddress, string destinationHost)
{
Source = source;
DestinationAddress = destinationAddress;
DestinationHost = destinationHost;
Replies = new List<TraceRouteReply>();
}
/// <summary>
/// Source from which to trace route.
/// </summary>
public string Source { get; }
/// <summary>
/// Destination to which to trace route.
/// </summary>
public IPAddress DestinationAddress { get; }
/// <summary>
/// Destination to which to trace route.
/// </summary>
public string DestinationHost { get; }
/// <summary>
/// </summary>
public List<TraceRouteReply> Replies { get; }
}
#endregion TracerouteTest
#region MTUSizeTest
private void ProcessMTUSize(String targetNameOrAddress)
{
PingReply reply, replyResult = null;
string resolvedTargetName = null;
IPAddress targetAddress = null;
if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress))
{
return;
}
WriteMTUSizeHeader(resolvedTargetName, targetAddress.ToString());
// Cautious! Algorithm is sensitive to changing boundary values.
int HighMTUSize = 10000;
int CurrentMTUSize = 1473;
int LowMTUSize = targetAddress.AddressFamily == AddressFamily.InterNetworkV6 ? 1280 : 68;
Int32 timeout = TimeoutSeconds * 1000;
try
{
Ping sender = new Ping();
PingOptions pingOptions = new PingOptions(MaxHops, true);
int retry = 1;
while (LowMTUSize < (HighMTUSize - 1))
{
byte[] buffer = GetSendBuffer(CurrentMTUSize);
WriteMTUSizeProgress(CurrentMTUSize, retry);
WriteDebug(StringUtil.Format("LowMTUSize: {0}, CurrentMTUSize: {1}, HighMTUSize: {2}", LowMTUSize, CurrentMTUSize, HighMTUSize));
reply = sender.Send(targetAddress, timeout, buffer, pingOptions);
// Cautious! Algorithm is sensitive to changing boundary values.
if (reply.Status == IPStatus.PacketTooBig)
{
HighMTUSize = CurrentMTUSize;
retry = 1;
}
else if (reply.Status == IPStatus.Success)
{
LowMTUSize = CurrentMTUSize;
replyResult = reply;
retry = 1;
}
else
{
// Target host don't reply - try again up to 'Count'.
if (retry >= Count)
{
string message = StringUtil.Format(TestConnectionResources.NoPingResult,
targetAddress,
reply.Status.ToString());
Exception pingException = new System.Net.NetworkInformation.PingException(message);
ErrorRecord errorRecord = new ErrorRecord(pingException,
TestConnectionExceptionId,
ErrorCategory.ResourceUnavailable,
targetAddress);
WriteError(errorRecord);
return;
}
else
{
retry++;
continue;
}
}
CurrentMTUSize = (LowMTUSize + HighMTUSize) / 2;
// Prevent DoS attack.
Thread.Sleep(100);
}
}
catch (PingException ex)
{
string message = StringUtil.Format(TestConnectionResources.NoPingResult, targetAddress, ex.Message);
Exception pingException = new System.Net.NetworkInformation.PingException(message, ex.InnerException);
ErrorRecord errorRecord = new ErrorRecord(pingException,
TestConnectionExceptionId,
ErrorCategory.ResourceUnavailable,
targetAddress);
WriteError(errorRecord);
return;
}
WriteMTUSizeFooter();
if (Quiet.IsPresent)
{
WriteObject(CurrentMTUSize);
}
else
{
var res = PSObject.AsPSObject(replyResult);
PSMemberInfo sourceProperty = new PSNoteProperty("Source", Source);
res.Members.Add(sourceProperty);
PSMemberInfo destinationProperty = new PSNoteProperty("Destination", targetNameOrAddress);
res.Members.Add(destinationProperty);
PSMemberInfo mtuSizeProperty = new PSNoteProperty("MTUSize", CurrentMTUSize);
res.Members.Add(mtuSizeProperty);
res.TypeNames.Insert(0, "PingReply#MTUSize");
WriteObject(res);
}
}
private void WriteMTUSizeHeader(string resolvedTargetName, string targetAddress)
{
_testConnectionProgressBarActivity = StringUtil.Format(TestConnectionResources.MTUSizeDetectStart,
resolvedTargetName,
targetAddress,
BufferSize);
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, ProgressRecordSpace);
WriteProgress(record);
}
private void WriteMTUSizeProgress(int currentMTUSize, int retry)
{
var msg = StringUtil.Format(TestConnectionResources.MTUSizeDetectDescription, currentMTUSize, retry);
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, msg);
WriteProgress(record);
}
private void WriteMTUSizeFooter()
{
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, ProgressRecordSpace);
record.RecordType = ProgressRecordType.Completed;
WriteProgress(record);
}
#endregion MTUSizeTest
#region PingTest
private void ProcessPing(String targetNameOrAddress)
{
string resolvedTargetName = null;
IPAddress targetAddress = null;
if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress))
{
return;
}
if (!Continues.IsPresent)
{
WritePingHeader(resolvedTargetName, targetAddress.ToString());
}
bool quietResult = true;
byte[] buffer = GetSendBuffer(BufferSize);
Ping sender = new Ping();
PingOptions pingOptions = new PingOptions(MaxHops, DontFragment.IsPresent);
PingReply reply = null;
PingReport pingReport = new PingReport(Source, resolvedTargetName);
Int32 timeout = TimeoutSeconds * 1000;
Int32 delay = Delay * 1000;
for (int i = 1; i <= Count; i++)
{
try
{
reply = sender.Send(targetAddress, timeout, buffer, pingOptions);
}
catch (PingException ex)
{
string message = StringUtil.Format(TestConnectionResources.NoPingResult, resolvedTargetName, ex.Message);
Exception pingException = new System.Net.NetworkInformation.PingException(message, ex.InnerException);
ErrorRecord errorRecord = new ErrorRecord(pingException,
TestConnectionExceptionId,
ErrorCategory.ResourceUnavailable,
resolvedTargetName);
WriteError(errorRecord);
quietResult = false;
continue;
}
if (Continues.IsPresent)
{
WriteObject(reply);
}
else
{
if (Quiet.IsPresent)
{
// Return 'true' only if all pings have completed successfully.
quietResult &= reply.Status == IPStatus.Success;
}
else
{
pingReport.Replies.Add(reply);
}
WritePingProgress(reply);
}
// Delay between ping but not after last ping.
if (i < Count && Delay > 0)
{
Thread.Sleep(delay);
}
}
if (!Continues.IsPresent)
{
WritePingFooter();
}
if (Quiet.IsPresent)
{
WriteObject(quietResult);
}
else
{
WriteObject(pingReport);
}
}
private void WritePingHeader(string resolvedTargetName, string targetAddress)
{
_testConnectionProgressBarActivity = StringUtil.Format(TestConnectionResources.MTUSizeDetectStart,
resolvedTargetName,
targetAddress,
BufferSize);
WriteInformation(_testConnectionProgressBarActivity, s_PSHostTag);
ProgressRecord record = new ProgressRecord(s_ProgressId,
_testConnectionProgressBarActivity,
ProgressRecordSpace);
WriteProgress(record);
}
private void WritePingProgress(PingReply reply)
{
string msg = string.Empty;
if (reply.Status != IPStatus.Success)
{
msg = TestConnectionResources.PingTimeOut;
}
else
{
msg = StringUtil.Format(TestConnectionResources.PingReply,
reply.Address.ToString(),
reply.Buffer.Length,
reply.RoundtripTime,
reply.Options?.Ttl);
}
WriteInformation(msg, s_PSHostTag);
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, msg);
WriteProgress(record);
}
private void WritePingFooter()
{
WriteInformation(TestConnectionResources.PingComplete, s_PSHostTag);
ProgressRecord record = new ProgressRecord(s_ProgressId, _testConnectionProgressBarActivity, ProgressRecordSpace);
record.RecordType = ProgressRecordType.Completed;
WriteProgress(record);
}
/// <summary>
/// The class contains an information about the source, the destination and ping results.
/// </summary>
public class PingReport
{
internal PingReport(string source, string destination)
{
Source = source;
Destination = destination;
Replies = new List<PingReply>();
}
/// <summary>
/// Source from which to ping.
/// </summary>
public string Source { get; }
/// <summary>
/// Destination to which to ping.
/// </summary>
public string Destination { get; }
/// <summary>
/// Ping results for every ping attempt.
/// </summary>
public List<PingReply> Replies { get; }
}
#endregion PingTest
private bool InitProcessPing(String targetNameOrAddress, out string resolvedTargetName, out IPAddress targetAddress)
{
IPHostEntry hostEntry = null;
resolvedTargetName = targetNameOrAddress;
if (IPAddress.TryParse(targetNameOrAddress, out targetAddress))
{
if (ResolveDestination)
{
hostEntry = Dns.GetHostEntry(targetNameOrAddress);
resolvedTargetName = hostEntry.HostName;
}
}
else
{
try
{
hostEntry = Dns.GetHostEntry(targetNameOrAddress);
if (ResolveDestination)
{
resolvedTargetName = hostEntry.HostName;
hostEntry = Dns.GetHostEntry(hostEntry.HostName);
}
}
catch (Exception ex)
{
string message = StringUtil.Format(TestConnectionResources.NoPingResult,
resolvedTargetName,
TestConnectionResources.CannotResolveTargetName);
Exception pingException = new System.Net.NetworkInformation.PingException(message, ex);
ErrorRecord errorRecord = new ErrorRecord(pingException,
TestConnectionExceptionId,
ErrorCategory.ResourceUnavailable,
resolvedTargetName);
WriteError(errorRecord);
return false;
}
if (IPv6 || IPv4)
{
AddressFamily addressFamily = IPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
foreach (var address in hostEntry.AddressList)
{
if (address.AddressFamily == addressFamily)
{
targetAddress = address;
break;
}
}
if (targetAddress == null)
{
string message = StringUtil.Format(TestConnectionResources.NoPingResult,
resolvedTargetName,
TestConnectionResources.TargetAddressAbsent);
Exception pingException = new System.Net.NetworkInformation.PingException(message, null);
ErrorRecord errorRecord = new ErrorRecord(pingException,
TestConnectionExceptionId,
ErrorCategory.ResourceUnavailable,
resolvedTargetName);
WriteError(errorRecord);
return false;
}
}
else
{
targetAddress = hostEntry.AddressList[0];
}
}
return true;
}
// Users most often use the default buffer size so we cache the buffer.
// Creates and filles a send buffer. This follows the ping.exe and CoreFX model.
private byte[] GetSendBuffer(int bufferSize)
{
if (bufferSize == DefaultSendBufferSize && s_DefaultSendBuffer != null)
{
return s_DefaultSendBuffer;
}
byte[] sendBuffer = new byte[bufferSize];
for (int i = 0; i < bufferSize; i++)
{
sendBuffer[i] = (byte)((int)'a' + i % 23);
}
if (bufferSize == DefaultSendBufferSize && s_DefaultSendBuffer == null)
{
s_DefaultSendBuffer = sendBuffer;
}
return sendBuffer;
}
// Count of pings sent per each trace route hop.
// Default = 3 (from Windows).
// If we change 'DefaultTraceRoutePingCount' we should change 'ConsoleTraceRouteReply' resource string.
private const int DefaultTraceRoutePingCount = 3;
/// Create the default send buffer once and cache it.
private const int DefaultSendBufferSize = 32;
private static byte[] s_DefaultSendBuffer = null;
// Random value for WriteProgress Activity Id.
private static readonly int s_ProgressId = 174593053;
// Empty message string for Progress Bar.
private const string ProgressRecordSpace = " ";
private const string TestConnectionExceptionId = "TestConnectionException";
}
}
| |
/*
* 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 java = biz.ritter.javapi;
using System.IO;
using System.Collections;
using System.Text;
namespace Kajabity.Tools.Java
{
/// <summary>
/// Use this class for writing a set of key value pair strings to an
/// output stream using the Java properties format.
/// </summary>
internal class JavaPropertyWriter
{
private static char[] HEX = new char[] { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
private java.util.Properties hashtable;
/// <summary>
/// Construct an instance of this class.
/// </summary>
/// <param name="hashtable">The Hashtable (or JavaProperties) instance
/// whose values are to be written.</param>
public JavaPropertyWriter( java.util.Properties hashtable )
{
this.hashtable = hashtable;
}
/// <summary>
/// Write the properties to the output stream.
/// </summary>
/// <param name="stream">The output stream where the properties are written.</param>
/// <param name="comments">Optional comments that are placed at the beginning of the output.</param>
public void Write(java.io.Writer stream, String comments )
{
// Create a writer to output to an ISO-8859-1 encoding (code page 28592).
//StreamWriter writer = new StreamWriter( stream, System.Text.Encoding.GetEncoding( 28592 ) );
java.io.BufferedWriter writer = new java.io.BufferedWriter(stream);
if( comments != null)
{
comments = "# " + comments;
}
writer.write(comments);
writer.newLine();
writer.write( "# " + DateTime.Now.ToString() );
writer.newLine();
writer.flush();
for( IEnumerator e = hashtable.Keys.GetEnumerator(); e.MoveNext(); )
{
String key = e.Current.ToString();
String val = hashtable[ key ].ToString();
writer.write( escapeKey( key ) + "=" + escapeValue( val ) );
writer.newLine();
writer.flush();
}
}
/// <summary>
/// Escape the string as a Key with character set ISO-8859-1 -
/// the characters 0-127 are US-ASCII and we will escape any others. The passed string is Unicode which extends
/// ISO-8859-1 - so all is well.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private string escapeKey( string s )
{
StringBuilder buf = new StringBuilder();
bool first = true;
foreach( char c in s )
{
// Avoid confusing with a comment: '!' (33), '#' (35).
if( first )
{
first = false;
if( c == '!' || c == '#' )
{
buf.Append( '\\' );
}
}
switch( c )
{
case '\t': // =09 U+0009 HORIZONTAL TABULATION \t
buf.Append( '\\' ).Append( 't' );
break;
case '\n': // =0A U+000A LINE FEED \n
buf.Append( '\\' ).Append( 'n' );
break;
case '\f': // =0C U+000C FORM FEED \f
buf.Append( '\\' ).Append( 'f' );
break;
case '\r': // =0D U+000D CARRIAGE RETURN \r
buf.Append( '\\' ).Append( 'r' );
break;
case ' ': // 32: ' '
case ':': // 58: ':'
case '=': // 61: '='
case '\\': // 92: '\'
buf.Append( '\\' ).Append( c );
break;
default:
if( c > 31 && c < 127 )
{
buf.Append( c );
}
else
{
buf.Append( '\\' ).Append( 'u' );
buf.Append( HEX[ (c >> 12) & 0xF ] );
buf.Append( HEX[ (c >> 8) & 0xF ] );
buf.Append( HEX[ (c >> 4) & 0xF ] );
buf.Append( HEX[ c & 0xF ] );
}
break;
}
}
return buf.ToString();
}
private string escapeValue( string s )
{
StringBuilder buf = new StringBuilder();
bool first = true;
foreach( char c in s )
{
// Handle value starting with whitespace.
if( first )
{
first = false;
if( c == ' ' )
{
buf.Append( '\\' ).Append( ' ' );
continue;
}
else if( c == '\t' ) // =09 U+0009 HORIZONTAL TABULATION \t
{
buf.Append( '\\' ).Append( 't' );
continue;
}
}
switch( c )
{
case '\t': // =09 U+0009 HORIZONTAL TABULATION \t
buf.Append( '\t' ); //OK after first position.
break;
case '\n': // =0A U+000A LINE FEED \n
buf.Append( '\\' ).Append( 'n' );
break;
case '\f': // =0C U+000C FORM FEED \f
buf.Append( '\\' ).Append( 'f' );
break;
case '\r': // =0D U+000D CARRIAGE RETURN \r
buf.Append( '\\' ).Append( 'r' );
break;
case '\\': // 92: '\'
buf.Append( '\\' ).Append( c );
break;
default:
if( c > 31 && c < 127 )
{
buf.Append( c );
}
else
{
buf.Append( '\\' ).Append( 'u' );
buf.Append( HEX[ (c >> 12) & 0xF ] );
buf.Append( HEX[ (c >> 8) & 0xF ] );
buf.Append( HEX[ (c >> 4) & 0xF ] );
buf.Append( HEX[ c & 0xF ] );
}
break;
}
}
return buf.ToString();
}
}
}
| |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Matty.Server.Migrations;
public partial class Init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
UserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
Email = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(type: "bit", nullable: false),
PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: true),
SecurityStamp = table.Column<string>(type: "nvarchar(max)", nullable: true),
ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true),
PhoneNumber = table.Column<string>(type: "nvarchar(max)", nullable: true),
PhoneNumberConfirmed = table.Column<bool>(type: "bit", nullable: false),
TwoFactorEnabled = table.Column<bool>(type: "bit", nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
LockoutEnabled = table.Column<bool>(type: "bit", nullable: false),
AccessFailedCount = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "OpenIddictApplications",
columns: table => new
{
Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClientId = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true),
ClientSecret = table.Column<string>(type: "nvarchar(max)", nullable: true),
ConcurrencyToken = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
ConsentType = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
DisplayName = table.Column<string>(type: "nvarchar(max)", nullable: true),
DisplayNames = table.Column<string>(type: "nvarchar(max)", nullable: true),
Permissions = table.Column<string>(type: "nvarchar(max)", nullable: true),
PostLogoutRedirectUris = table.Column<string>(type: "nvarchar(max)", nullable: true),
Properties = table.Column<string>(type: "nvarchar(max)", nullable: true),
RedirectUris = table.Column<string>(type: "nvarchar(max)", nullable: true),
Requirements = table.Column<string>(type: "nvarchar(max)", nullable: true),
Type = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_OpenIddictApplications", x => x.Id);
});
migrationBuilder.CreateTable(
name: "OpenIddictScopes",
columns: table => new
{
Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
ConcurrencyToken = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
Descriptions = table.Column<string>(type: "nvarchar(max)", nullable: true),
DisplayName = table.Column<string>(type: "nvarchar(max)", nullable: true),
DisplayNames = table.Column<string>(type: "nvarchar(max)", nullable: true),
Name = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
Properties = table.Column<string>(type: "nvarchar(max)", nullable: true),
Resources = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_OpenIddictScopes", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClaimType = table.Column<string>(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false),
ProviderKey = table.Column<string>(type: "nvarchar(450)", nullable: false),
ProviderDisplayName = table.Column<string>(type: "nvarchar(max)", nullable: true),
UserId = table.Column<string>(type: "nvarchar(450)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(type: "nvarchar(450)", nullable: false),
RoleId = table.Column<string>(type: "nvarchar(450)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(type: "nvarchar(450)", nullable: false),
LoginProvider = table.Column<string>(type: "nvarchar(450)", nullable: false),
Name = table.Column<string>(type: "nvarchar(450)", nullable: false),
Value = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "OpenIddictAuthorizations",
columns: table => new
{
Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
ApplicationId = table.Column<string>(type: "nvarchar(450)", nullable: true),
ConcurrencyToken = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
CreationDate = table.Column<DateTime>(type: "datetime2", nullable: true),
Properties = table.Column<string>(type: "nvarchar(max)", nullable: true),
Scopes = table.Column<string>(type: "nvarchar(max)", nullable: true),
Status = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
Subject = table.Column<string>(type: "nvarchar(400)", maxLength: 400, nullable: true),
Type = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_OpenIddictAuthorizations", x => x.Id);
table.ForeignKey(
name: "FK_OpenIddictAuthorizations_OpenIddictApplications_ApplicationId",
column: x => x.ApplicationId,
principalTable: "OpenIddictApplications",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "OpenIddictTokens",
columns: table => new
{
Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
ApplicationId = table.Column<string>(type: "nvarchar(450)", nullable: true),
AuthorizationId = table.Column<string>(type: "nvarchar(450)", nullable: true),
ConcurrencyToken = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
CreationDate = table.Column<DateTime>(type: "datetime2", nullable: true),
ExpirationDate = table.Column<DateTime>(type: "datetime2", nullable: true),
Payload = table.Column<string>(type: "nvarchar(max)", nullable: true),
Properties = table.Column<string>(type: "nvarchar(max)", nullable: true),
RedemptionDate = table.Column<DateTime>(type: "datetime2", nullable: true),
ReferenceId = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true),
Status = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
Subject = table.Column<string>(type: "nvarchar(400)", maxLength: 400, nullable: true),
Type = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_OpenIddictTokens", x => x.Id);
table.ForeignKey(
name: "FK_OpenIddictTokens_OpenIddictApplications_ApplicationId",
column: x => x.ApplicationId,
principalTable: "OpenIddictApplications",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_OpenIddictTokens_OpenIddictAuthorizations_AuthorizationId",
column: x => x.AuthorizationId,
principalTable: "OpenIddictAuthorizations",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_OpenIddictApplications_ClientId",
table: "OpenIddictApplications",
column: "ClientId",
unique: true,
filter: "[ClientId] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_OpenIddictAuthorizations_ApplicationId_Status_Subject_Type",
table: "OpenIddictAuthorizations",
columns: new[] { "ApplicationId", "Status", "Subject", "Type" });
migrationBuilder.CreateIndex(
name: "IX_OpenIddictScopes_Name",
table: "OpenIddictScopes",
column: "Name",
unique: true,
filter: "[Name] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_OpenIddictTokens_ApplicationId_Status_Subject_Type",
table: "OpenIddictTokens",
columns: new[] { "ApplicationId", "Status", "Subject", "Type" });
migrationBuilder.CreateIndex(
name: "IX_OpenIddictTokens_AuthorizationId",
table: "OpenIddictTokens",
column: "AuthorizationId");
migrationBuilder.CreateIndex(
name: "IX_OpenIddictTokens_ReferenceId",
table: "OpenIddictTokens",
column: "ReferenceId",
unique: true,
filter: "[ReferenceId] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "OpenIddictScopes");
migrationBuilder.DropTable(
name: "OpenIddictTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
migrationBuilder.DropTable(
name: "OpenIddictAuthorizations");
migrationBuilder.DropTable(
name: "OpenIddictApplications");
}
}
| |
namespace XenAdmin.Dialogs
{
partial class RoleElevationDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RoleElevationDialog));
this.labelBlurb = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelCurrentRoleValue = new System.Windows.Forms.Label();
this.labelCurrentRole = new System.Windows.Forms.Label();
this.labelCurrentUserValue = new System.Windows.Forms.Label();
this.labelCurrentUser = new System.Windows.Forms.Label();
this.labelRequiredRole = new System.Windows.Forms.Label();
this.labelRequiredRoleValue = new System.Windows.Forms.Label();
this.TextBoxUsername = new System.Windows.Forms.TextBox();
this.labelPassword = new System.Windows.Forms.Label();
this.labelUserName = new System.Windows.Forms.Label();
this.buttonAuthorize = new System.Windows.Forms.Button();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.labelCurrentAction = new System.Windows.Forms.Label();
this.labelCurrentActionValue = new System.Windows.Forms.Label();
this.labelServer = new System.Windows.Forms.Label();
this.labelServerValue = new System.Windows.Forms.Label();
this.divider = new System.Windows.Forms.GroupBox();
this.labelBlurb2 = new System.Windows.Forms.Label();
this.TextBoxPassword = new System.Windows.Forms.TextBox();
this.panel1 = new System.Windows.Forms.Panel();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// labelBlurb
//
resources.ApplyResources(this.labelBlurb, "labelBlurb");
this.tableLayoutPanel1.SetColumnSpan(this.labelBlurb, 2);
this.labelBlurb.MaximumSize = new System.Drawing.Size(380, 0);
this.labelBlurb.Name = "labelBlurb";
//
// buttonCancel
//
resources.ApplyResources(this.buttonCancel, "buttonCancel");
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// labelCurrentRoleValue
//
resources.ApplyResources(this.labelCurrentRoleValue, "labelCurrentRoleValue");
this.labelCurrentRoleValue.MaximumSize = new System.Drawing.Size(250, 0);
this.labelCurrentRoleValue.Name = "labelCurrentRoleValue";
//
// labelCurrentRole
//
resources.ApplyResources(this.labelCurrentRole, "labelCurrentRole");
this.labelCurrentRole.Name = "labelCurrentRole";
//
// labelCurrentUserValue
//
resources.ApplyResources(this.labelCurrentUserValue, "labelCurrentUserValue");
this.labelCurrentUserValue.Name = "labelCurrentUserValue";
//
// labelCurrentUser
//
resources.ApplyResources(this.labelCurrentUser, "labelCurrentUser");
this.labelCurrentUser.Name = "labelCurrentUser";
//
// labelRequiredRole
//
resources.ApplyResources(this.labelRequiredRole, "labelRequiredRole");
this.labelRequiredRole.Name = "labelRequiredRole";
//
// labelRequiredRoleValue
//
resources.ApplyResources(this.labelRequiredRoleValue, "labelRequiredRoleValue");
this.labelRequiredRoleValue.MaximumSize = new System.Drawing.Size(250, 0);
this.labelRequiredRoleValue.Name = "labelRequiredRoleValue";
//
// TextBoxUsername
//
resources.ApplyResources(this.TextBoxUsername, "TextBoxUsername");
this.TextBoxUsername.Name = "TextBoxUsername";
this.TextBoxUsername.TextChanged += new System.EventHandler(this.TextBoxUsername_TextChanged);
//
// labelPassword
//
resources.ApplyResources(this.labelPassword, "labelPassword");
this.labelPassword.Name = "labelPassword";
//
// labelUserName
//
resources.ApplyResources(this.labelUserName, "labelUserName");
this.labelUserName.Name = "labelUserName";
//
// buttonAuthorize
//
resources.ApplyResources(this.buttonAuthorize, "buttonAuthorize");
this.buttonAuthorize.Name = "buttonAuthorize";
this.buttonAuthorize.UseVisualStyleBackColor = true;
this.buttonAuthorize.Click += new System.EventHandler(this.buttonAuthorize_Click);
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.pictureBox1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.labelBlurb, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentAction, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentActionValue, 2, 1);
this.tableLayoutPanel1.Controls.Add(this.labelServer, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.labelServerValue, 2, 2);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentUser, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentUserValue, 2, 3);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentRole, 1, 4);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentRoleValue, 2, 4);
this.tableLayoutPanel1.Controls.Add(this.divider, 1, 5);
this.tableLayoutPanel1.Controls.Add(this.labelBlurb2, 1, 6);
this.tableLayoutPanel1.Controls.Add(this.labelRequiredRole, 1, 7);
this.tableLayoutPanel1.Controls.Add(this.labelRequiredRoleValue, 3, 7);
this.tableLayoutPanel1.Controls.Add(this.labelUserName, 1, 8);
this.tableLayoutPanel1.Controls.Add(this.TextBoxUsername, 2, 8);
this.tableLayoutPanel1.Controls.Add(this.labelPassword, 1, 9);
this.tableLayoutPanel1.Controls.Add(this.TextBoxPassword, 2, 9);
this.tableLayoutPanel1.Controls.Add(this.panel1, 2, 10);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// pictureBox1
//
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Name = "pictureBox1";
this.tableLayoutPanel1.SetRowSpan(this.pictureBox1, 2);
this.pictureBox1.TabStop = false;
//
// labelCurrentAction
//
resources.ApplyResources(this.labelCurrentAction, "labelCurrentAction");
this.labelCurrentAction.Name = "labelCurrentAction";
//
// labelCurrentActionValue
//
resources.ApplyResources(this.labelCurrentActionValue, "labelCurrentActionValue");
this.labelCurrentActionValue.Name = "labelCurrentActionValue";
//
// labelServer
//
resources.ApplyResources(this.labelServer, "labelServer");
this.labelServer.Name = "labelServer";
//
// labelServerValue
//
resources.ApplyResources(this.labelServerValue, "labelServerValue");
this.labelServerValue.Name = "labelServerValue";
//
// divider
//
this.tableLayoutPanel1.SetColumnSpan(this.divider, 2);
resources.ApplyResources(this.divider, "divider");
this.divider.Name = "divider";
this.divider.TabStop = false;
//
// labelBlurb2
//
resources.ApplyResources(this.labelBlurb2, "labelBlurb2");
this.tableLayoutPanel1.SetColumnSpan(this.labelBlurb2, 2);
this.labelBlurb2.MaximumSize = new System.Drawing.Size(380, 0);
this.labelBlurb2.Name = "labelBlurb2";
//
// TextBoxPassword
//
resources.ApplyResources(this.TextBoxPassword, "TextBoxPassword");
this.TextBoxPassword.Name = "TextBoxPassword";
this.TextBoxPassword.UseSystemPasswordChar = true;
this.TextBoxPassword.TextChanged += new System.EventHandler(this.TextBoxPassword_TextChanged);
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Controls.Add(this.buttonCancel);
this.panel1.Controls.Add(this.buttonAuthorize);
this.panel1.Name = "panel1";
//
// RoleElevationDialog
//
this.AcceptButton = this.buttonAuthorize;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.buttonCancel;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "RoleElevationDialog";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label labelBlurb;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label labelCurrentRoleValue;
private System.Windows.Forms.Label labelCurrentRole;
private System.Windows.Forms.Label labelCurrentUserValue;
private System.Windows.Forms.Label labelCurrentUser;
private System.Windows.Forms.Label labelRequiredRole;
private System.Windows.Forms.Label labelRequiredRoleValue;
internal System.Windows.Forms.TextBox TextBoxUsername;
private System.Windows.Forms.Label labelPassword;
private System.Windows.Forms.Label labelUserName;
private System.Windows.Forms.Button buttonAuthorize;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
internal System.Windows.Forms.TextBox TextBoxPassword;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label labelBlurb2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.GroupBox divider;
private System.Windows.Forms.Label labelCurrentActionValue;
private System.Windows.Forms.Label labelCurrentAction;
private System.Windows.Forms.Label labelServer;
private System.Windows.Forms.Label labelServerValue;
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.DataControlField.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
abstract public partial class DataControlField : System.Web.UI.IStateManager, System.Web.UI.IDataSourceViewSchemaAccessor
{
#region Methods and constructors
protected internal System.Web.UI.WebControls.DataControlField CloneField ()
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.DataControlField>() != null);
return default(System.Web.UI.WebControls.DataControlField);
}
protected virtual new void CopyProperties (System.Web.UI.WebControls.DataControlField newField)
{
Contract.Requires (newField != null);
}
protected abstract System.Web.UI.WebControls.DataControlField CreateField ();
protected DataControlField ()
{
}
public virtual new void ExtractValuesFromCell (System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
{
}
public virtual new bool Initialize (bool sortingEnabled, System.Web.UI.Control control)
{
return default(bool);
}
public virtual new void InitializeCell (DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
{
Contract.Requires (cell != null);
}
protected virtual new void LoadViewState (Object savedState)
{
}
protected virtual new void OnFieldChanged ()
{
}
protected virtual new Object SaveViewState ()
{
return default(Object);
}
void System.Web.UI.IStateManager.LoadViewState (Object state)
{
}
Object System.Web.UI.IStateManager.SaveViewState ()
{
return default(Object);
}
void System.Web.UI.IStateManager.TrackViewState ()
{
}
protected virtual new void TrackViewState ()
{
}
public virtual new void ValidateSupportsCallback ()
{
}
#endregion
#region Properties and indexers
public virtual new string AccessibleHeaderText
{
get
{
return default(string);
}
set
{
}
}
protected System.Web.UI.Control Control
{
get
{
return default(System.Web.UI.Control);
}
}
public Style ControlStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.Style>() != null);
return default(Style);
}
}
protected bool DesignMode
{
get
{
return default(bool);
}
}
public TableItemStyle FooterStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public virtual new string FooterText
{
get
{
return default(string);
}
set
{
}
}
public virtual new string HeaderImageUrl
{
get
{
return default(string);
}
set
{
}
}
public TableItemStyle HeaderStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public virtual new string HeaderText
{
get
{
return default(string);
}
set
{
}
}
public virtual new bool InsertVisible
{
get
{
return default(bool);
}
set
{
}
}
protected bool IsTrackingViewState
{
get
{
return default(bool);
}
}
public TableItemStyle ItemStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public virtual new bool ShowHeader
{
get
{
return default(bool);
}
set
{
}
}
public virtual new string SortExpression
{
get
{
return default(string);
}
set
{
}
}
Object System.Web.UI.IDataSourceViewSchemaAccessor.DataSourceViewSchema
{
get
{
return default(Object);
}
set
{
}
}
bool System.Web.UI.IStateManager.IsTrackingViewState
{
get
{
return default(bool);
}
}
protected System.Web.UI.StateBag ViewState
{
get
{
Contract.Ensures(Contract.Result<StateBag>() != null);
return default(System.Web.UI.StateBag);
}
}
public bool Visible
{
get
{
return default(bool);
}
set
{
}
}
#endregion
}
}
| |
using System;
using System.Threading.Tasks;
using Xamarin.Forms.Platform;
namespace Xamarin.Forms
{
[ContentProperty("Content")]
[RenderWith(typeof(_ScrollViewRenderer))]
public class ScrollView : Layout, IScrollViewController, IElementConfiguration<ScrollView>
{
public static readonly BindableProperty OrientationProperty = BindableProperty.Create("Orientation", typeof(ScrollOrientation), typeof(ScrollView), ScrollOrientation.Vertical);
static readonly BindablePropertyKey ScrollXPropertyKey = BindableProperty.CreateReadOnly("ScrollX", typeof(double), typeof(ScrollView), 0d);
public static readonly BindableProperty ScrollXProperty = ScrollXPropertyKey.BindableProperty;
static readonly BindablePropertyKey ScrollYPropertyKey = BindableProperty.CreateReadOnly("ScrollY", typeof(double), typeof(ScrollView), 0d);
public static readonly BindableProperty ScrollYProperty = ScrollYPropertyKey.BindableProperty;
static readonly BindablePropertyKey ContentSizePropertyKey = BindableProperty.CreateReadOnly("ContentSize", typeof(Size), typeof(ScrollView), default(Size));
public static readonly BindableProperty ContentSizeProperty = ContentSizePropertyKey.BindableProperty;
readonly Lazy<PlatformConfigurationRegistry<ScrollView>> _platformConfigurationRegistry;
View _content;
TaskCompletionSource<bool> _scrollCompletionSource;
public View Content
{
get { return _content; }
set
{
if (_content == value)
return;
OnPropertyChanging();
if (_content != null)
InternalChildren.Remove(_content);
_content = value;
if (_content != null)
InternalChildren.Add(_content);
OnPropertyChanged();
}
}
public Size ContentSize
{
get { return (Size)GetValue(ContentSizeProperty); }
private set { SetValue(ContentSizePropertyKey, value); }
}
public ScrollOrientation Orientation
{
get { return (ScrollOrientation)GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
public double ScrollX
{
get { return (double)GetValue(ScrollXProperty); }
private set { SetValue(ScrollXPropertyKey, value); }
}
public double ScrollY
{
get { return (double)GetValue(ScrollYProperty); }
private set { SetValue(ScrollYPropertyKey, value); }
}
public ScrollView()
{
_platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<ScrollView>>(() => new PlatformConfigurationRegistry<ScrollView>(this));
}
Point IScrollViewController.GetScrollPositionForElement(VisualElement item, ScrollToPosition pos)
{
ScrollToPosition position = pos;
double y = GetCoordinate(item, "Y", 0);
double x = GetCoordinate(item, "X", 0);
if (position == ScrollToPosition.MakeVisible)
{
bool isItemVisible = ScrollX < y && ScrollY + Height > y;
if (isItemVisible)
return new Point(ScrollX, ScrollY);
switch (Orientation)
{
case ScrollOrientation.Vertical:
position = y > ScrollY ? ScrollToPosition.End : ScrollToPosition.Start;
break;
case ScrollOrientation.Horizontal:
position = x > ScrollX ? ScrollToPosition.End : ScrollToPosition.Start;
break;
case ScrollOrientation.Both:
position = x > ScrollX || y > ScrollY ? ScrollToPosition.End : ScrollToPosition.Start;
break;
}
}
switch (position)
{
case ScrollToPosition.Center:
y = y - Height / 2 + item.Height / 2;
x = x - Width / 2 + item.Width / 2;
break;
case ScrollToPosition.End:
y = y - Height + item.Height;
x = x - Width + item.Width;
break;
}
return new Point(x, y);
}
event EventHandler<ScrollToRequestedEventArgs> IScrollViewController.ScrollToRequested
{
add { ScrollToRequested += value; }
remove { ScrollToRequested -= value; }
}
void IScrollViewController.SendScrollFinished()
{
if (_scrollCompletionSource != null)
_scrollCompletionSource.TrySetResult(true);
}
void IScrollViewController.SetScrolledPosition(double x, double y)
{
if (ScrollX == x && ScrollY == y)
return;
ScrollX = x;
ScrollY = y;
EventHandler<ScrolledEventArgs> handler = Scrolled;
if (handler != null)
handler(this, new ScrolledEventArgs(x, y));
}
public event EventHandler<ScrolledEventArgs> Scrolled;
public IPlatformElementConfiguration<T, ScrollView> On<T>() where T : IConfigPlatform
{
return _platformConfigurationRegistry.Value.On<T>();
}
public Task ScrollToAsync(double x, double y, bool animated)
{
var args = new ScrollToRequestedEventArgs(x, y, animated);
OnScrollToRequested(args);
return _scrollCompletionSource.Task;
}
public Task ScrollToAsync(Element element, ScrollToPosition position, bool animated)
{
if (!Enum.IsDefined(typeof(ScrollToPosition), position))
throw new ArgumentException("position is not a valid ScrollToPosition", "position");
if (element == null)
throw new ArgumentNullException("element");
if (!CheckElementBelongsToScrollViewer(element))
throw new ArgumentException("element does not belong to this ScrollVIew", "element");
var args = new ScrollToRequestedEventArgs(element, position, animated);
OnScrollToRequested(args);
return _scrollCompletionSource.Task;
}
protected override void LayoutChildren(double x, double y, double width, double height)
{
if (_content != null)
{
SizeRequest size;
switch (Orientation)
{
case ScrollOrientation.Horizontal:
size = _content.Measure(double.PositiveInfinity, height, MeasureFlags.IncludeMargins);
LayoutChildIntoBoundingRegion(_content, new Rectangle(x, y, GetMaxWidth(width, size), height));
ContentSize = new Size(GetMaxWidth(width), height);
break;
case ScrollOrientation.Vertical:
size = _content.Measure(width, double.PositiveInfinity, MeasureFlags.IncludeMargins);
LayoutChildIntoBoundingRegion(_content, new Rectangle(x, y, width, GetMaxHeight(height, size)));
ContentSize = new Size(width, GetMaxHeight(height));
break;
case ScrollOrientation.Both:
size = _content.Measure(double.PositiveInfinity, double.PositiveInfinity, MeasureFlags.IncludeMargins);
LayoutChildIntoBoundingRegion(_content, new Rectangle(x, y, GetMaxWidth(width, size), GetMaxHeight(height, size)));
ContentSize = new Size(GetMaxWidth(width), GetMaxHeight(height));
break;
}
}
}
[Obsolete("Use OnMeasure")]
protected override SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint)
{
if (Content == null)
return new SizeRequest();
switch (Orientation)
{
case ScrollOrientation.Horizontal:
widthConstraint = double.PositiveInfinity;
break;
case ScrollOrientation.Vertical:
heightConstraint = double.PositiveInfinity;
break;
case ScrollOrientation.Both:
widthConstraint = double.PositiveInfinity;
heightConstraint = double.PositiveInfinity;
break;
}
SizeRequest contentRequest = Content.Measure(widthConstraint, heightConstraint, MeasureFlags.IncludeMargins);
contentRequest.Minimum = new Size(Math.Min(40, contentRequest.Minimum.Width), Math.Min(40, contentRequest.Minimum.Height));
return contentRequest;
}
internal override void ComputeConstraintForView(View view)
{
switch (Orientation)
{
case ScrollOrientation.Horizontal:
LayoutOptions vOptions = view.VerticalOptions;
if (vOptions.Alignment == LayoutAlignment.Fill && (Constraint & LayoutConstraint.VerticallyFixed) != 0)
{
view.ComputedConstraint = LayoutConstraint.VerticallyFixed;
}
break;
case ScrollOrientation.Vertical:
LayoutOptions hOptions = view.HorizontalOptions;
if (hOptions.Alignment == LayoutAlignment.Fill && (Constraint & LayoutConstraint.HorizontallyFixed) != 0)
{
view.ComputedConstraint = LayoutConstraint.HorizontallyFixed;
}
break;
case ScrollOrientation.Both:
view.ComputedConstraint = LayoutConstraint.None;
break;
}
}
bool CheckElementBelongsToScrollViewer(Element element)
{
return Equals(element, this) || element.RealParent != null && CheckElementBelongsToScrollViewer(element.RealParent);
}
void CheckTaskCompletionSource()
{
if (_scrollCompletionSource != null && _scrollCompletionSource.Task.Status == TaskStatus.Running)
{
_scrollCompletionSource.TrySetCanceled();
}
_scrollCompletionSource = new TaskCompletionSource<bool>();
}
double GetCoordinate(Element item, string coordinateName, double coordinate)
{
if (item == this)
return coordinate;
coordinate += (double)typeof(VisualElement).GetProperty(coordinateName).GetValue(item, null);
var visualParentElement = item.RealParent as VisualElement;
return visualParentElement != null ? GetCoordinate(visualParentElement, coordinateName, coordinate) : coordinate;
}
double GetMaxHeight(double height)
{
return Math.Max(height, _content.Bounds.Top + Padding.Top + _content.Bounds.Bottom + Padding.Bottom);
}
static double GetMaxHeight(double height, SizeRequest size)
{
return Math.Max(size.Request.Height, height);
}
double GetMaxWidth(double width)
{
return Math.Max(width, _content.Bounds.Left + Padding.Left + _content.Bounds.Right + Padding.Right);
}
static double GetMaxWidth(double width, SizeRequest size)
{
return Math.Max(size.Request.Width, width);
}
void OnScrollToRequested(ScrollToRequestedEventArgs e)
{
CheckTaskCompletionSource();
EventHandler<ScrollToRequestedEventArgs> handler = ScrollToRequested;
if (handler != null)
handler(this, e);
}
event EventHandler<ScrollToRequestedEventArgs> ScrollToRequested;
}
}
| |
namespace Bermuda.QL.Language {
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
public class Token {
public int kind; // token kind
public int pos; // token position in the source text (starting at 0)
public int col; // token column (starting at 1)
public int line; // token line (starting at 1)
public string val; // token value
public Token next; // ML 2005-03-11 Tokens are kept in linked list
}
//-----------------------------------------------------------------------------------
// Buffer
//-----------------------------------------------------------------------------------
public class Buffer {
// This Buffer supports the following cases:
// 1) seekable stream (file)
// a) whole stream in buffer
// b) part of stream in buffer
// 2) non seekable stream (network, console)
public const int EOF = char.MaxValue + 1;
const int MIN_BUFFER_LENGTH = 1024; // 1KB
const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB
byte[] buf; // input buffer
int bufStart; // position of first byte in buffer relative to input stream
int bufLen; // length of buffer
int fileLen; // length of input stream (may change if the stream is no file)
int bufPos; // current position in buffer
Stream stream; // input stream (seekable)
bool isUserStream; // was the stream opened by the user?
public Buffer (Stream s, bool isUserStream) {
stream = s; this.isUserStream = isUserStream;
if (stream.CanSeek) {
fileLen = (int) stream.Length;
bufLen = Math.Min(fileLen, MAX_BUFFER_LENGTH);
bufStart = Int32.MaxValue; // nothing in the buffer so far
} else {
fileLen = bufLen = bufStart = 0;
}
buf = new byte[(bufLen>0) ? bufLen : MIN_BUFFER_LENGTH];
if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start)
else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid
if (bufLen == fileLen && stream.CanSeek) Close();
}
protected Buffer(Buffer b) { // called in UTF8Buffer constructor
buf = b.buf;
bufStart = b.bufStart;
bufLen = b.bufLen;
fileLen = b.fileLen;
bufPos = b.bufPos;
stream = b.stream;
// keep destructor from closing the stream
b.stream = null;
isUserStream = b.isUserStream;
}
~Buffer() { Close(); }
protected void Close() {
if (!isUserStream && stream != null) {
stream.Close();
stream = null;
}
}
public virtual int Read () {
if (bufPos < bufLen) {
return buf[bufPos++];
} else if (Pos < fileLen) {
Pos = Pos; // shift buffer start to Pos
return buf[bufPos++];
} else if (stream != null && !stream.CanSeek && ReadNextStreamChunk() > 0) {
return buf[bufPos++];
} else {
return EOF;
}
}
public int Peek () {
int curPos = Pos;
int ch = Read();
Pos = curPos;
return ch;
}
public string GetString (int beg, int end) {
int len = 0;
char[] buf = new char[end - beg];
int oldPos = Pos;
Pos = beg;
while (Pos < end) buf[len++] = (char) Read();
Pos = oldPos;
return new String(buf, 0, len);
}
public int Pos {
get { return bufPos + bufStart; }
set {
if (value >= fileLen && stream != null && !stream.CanSeek) {
// Wanted position is after buffer and the stream
// is not seek-able e.g. network or console,
// thus we have to read the stream manually till
// the wanted position is in sight.
while (value >= fileLen && ReadNextStreamChunk() > 0);
}
if (value < 0 || value > fileLen) {
throw new FatalError("buffer out of bounds access, position: " + value);
}
if (value >= bufStart && value < bufStart + bufLen) { // already in buffer
bufPos = value - bufStart;
} else if (stream != null) { // must be swapped in
stream.Seek(value, SeekOrigin.Begin);
bufLen = stream.Read(buf, 0, buf.Length);
bufStart = value; bufPos = 0;
} else {
// set the position to the end of the file, Pos will return fileLen.
bufPos = fileLen - bufStart;
}
}
}
// Read the next chunk of bytes from the stream, increases the buffer
// if needed and updates the fields fileLen and bufLen.
// Returns the number of bytes read.
private int ReadNextStreamChunk() {
int free = buf.Length - bufLen;
if (free == 0) {
// in the case of a growing input stream
// we can neither seek in the stream, nor can we
// foresee the maximum length, thus we must adapt
// the buffer size on demand.
byte[] newBuf = new byte[bufLen * 2];
Array.Copy(buf, newBuf, bufLen);
buf = newBuf;
free = bufLen;
}
int read = stream.Read(buf, bufLen, free);
if (read > 0) {
fileLen = bufLen = (bufLen + read);
return read;
}
// end of stream reached
return 0;
}
}
//-----------------------------------------------------------------------------------
// UTF8Buffer
//-----------------------------------------------------------------------------------
public class UTF8Buffer: Buffer {
public UTF8Buffer(Buffer b): base(b) {}
public override int Read() {
int ch;
do {
ch = base.Read();
// until we find a utf8 start (0xxxxxxx or 11xxxxxx)
} while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EOF));
if (ch < 128 || ch == EOF) {
// nothing to do, first 127 chars are the same in ascii and utf8
// 0xxxxxxx or end of file character
} else if ((ch & 0xF0) == 0xF0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x07; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F; ch = base.Read();
int c4 = ch & 0x3F;
ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4;
} else if ((ch & 0xE0) == 0xE0) {
// 1110xxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x0F; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F;
ch = (((c1 << 6) | c2) << 6) | c3;
} else if ((ch & 0xC0) == 0xC0) {
// 110xxxxx 10xxxxxx
int c1 = ch & 0x1F; ch = base.Read();
int c2 = ch & 0x3F;
ch = (c1 << 6) | c2;
}
return ch;
}
}
//-----------------------------------------------------------------------------------
// Scanner
//-----------------------------------------------------------------------------------
public class Scanner {
const char EOL = '\n';
const int eofSym = 0; /* pdt */
const int maxT = 29;
const int noSym = 29;
char valCh; // current input character (for token.val)
public Buffer buffer; // scanner buffer
Token t; // current token
int ch; // current input character
int pos; // byte position of current character
int col; // column number of current character
int line; // line number of current character
int oldEols; // EOLs that appeared in a comment;
static readonly Dictionary<object, object> start; // maps first token character to start state
Token tokens; // list of tokens already peeked (first token is a dummy)
Token pt; // current peek token
char[] tval = new char[128]; // text of current token
int tlen; // length of current token
static Scanner() {
start = new Dictionary<object,object>(128);
for (int i = 48; i <= 57; ++i) start[i] = 17;
for (int i = 35; i <= 35; ++i) start[i] = 18;
for (int i = 97; i <= 122; ++i) start[i] = 18;
for (int i = 34; i <= 34; ++i) start[i] = 19;
for (int i = 64; i <= 64; ++i) start[i] = 1;
start[45] = 20;
start[40] = 13;
start[41] = 14;
start[58] = 15;
start[44] = 16;
start[60] = 23;
start[62] = 24;
start[Buffer.EOF] = -1;
}
public Scanner (string fileName) {
try {
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new Buffer(stream, false);
Init();
} catch (IOException) {
throw new FatalError("Cannot open file " + fileName);
}
}
public Scanner (Stream s) {
buffer = new Buffer(s, true);
Init();
}
void Init() {
pos = -1; line = 1; col = 0;
oldEols = 0;
NextCh();
if (ch == 0xEF) { // check optional byte order mark for UTF-8
NextCh(); int ch1 = ch;
NextCh(); int ch2 = ch;
if (ch1 != 0xBB || ch2 != 0xBF) {
throw new FatalError(String.Format("illegal byte order mark: EF {0,2:X} {1,2:X}", ch1, ch2));
}
buffer = new UTF8Buffer(buffer); col = 0;
NextCh();
}
pt = tokens = new Token(); // first token is a dummy
}
void NextCh() {
if (oldEols > 0) { ch = EOL; oldEols--; }
else {
pos = buffer.Pos;
ch = buffer.Read(); col++;
// replace isolated '\r' by '\n' in order to make
// eol handling uniform across Windows, Unix and Mac
if (ch == '\r' && buffer.Peek() != '\n') ch = EOL;
if (ch == EOL) { line++; col = 0; }
}
if (ch != Buffer.EOF) {
valCh = (char) ch;
ch = char.ToLower((char) ch);
}
}
void AddCh() {
if (tlen >= tval.Length) {
char[] newBuf = new char[2 * tval.Length];
Array.Copy(tval, 0, newBuf, 0, tval.Length);
tval = newBuf;
}
if (ch != Buffer.EOF) {
tval[tlen++] = valCh;
NextCh();
}
}
void CheckLiteral() {
switch (t.val.ToLower()) {
case "not": t.kind = 6; break;
case "to": t.kind = 9; break;
case "and": t.kind = 10; break;
case "or": t.kind = 11; break;
case "get": t.kind = 12; break;
case "set": t.kind = 13; break;
case "chart": t.kind = 14; break;
case "where": t.kind = 15; break;
case "ordered": t.kind = 18; break;
case "interval": t.kind = 19; break;
case "by": t.kind = 20; break;
case "desc": t.kind = 21; break;
case "limit": t.kind = 22; break;
case "over": t.kind = 23; break;
case "top": t.kind = 24; break;
case "bottom": t.kind = 25; break;
case "via": t.kind = 26; break;
default: break;
}
}
Token NextToken() {
while (ch == ' ' ||
ch == 10 || ch == 13
) NextCh();
int recKind = noSym;
int recEnd = pos;
t = new Token();
t.pos = pos; t.col = col; t.line = line;
int state;
if (start.ContainsKey(ch)) { state = (int) start[ch]; }
else { state = 0; }
tlen = 0; AddCh();
switch (state) {
case -1: { t.kind = eofSym; break; } // NextCh already done
case 0: {
if (recKind != noSym) {
tlen = recEnd - t.pos;
SetScannerBehindT();
}
t.kind = recKind; break;
} // NextCh already done
case 1:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 2;}
else {goto case 0;}
case 2:
recEnd = pos; recKind = 4;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 2;}
else {t.kind = 4; break;}
case 3:
if (ch == '.') {AddCh(); goto case 4;}
else {goto case 0;}
case 4:
if (ch == '"') {AddCh(); goto case 5;}
else if (ch == '#' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 6;}
else if (ch >= '0' && ch <= '9') {AddCh(); goto case 8;}
else if (ch == '-') {AddCh(); goto case 7;}
else {goto case 0;}
case 5:
if (ch == '"') {AddCh(); goto case 12;}
else if (ch >= ' ' && ch <= '!' || ch >= '#' && ch <= '+' || ch >= '-' && ch <= ':' || ch == '@' || ch >= '[' && ch <= '_' || ch >= 'a' && ch <= '{' || ch == '}') {AddCh(); goto case 5;}
else {goto case 0;}
case 6:
recEnd = pos; recKind = 5;
if (ch == '#' || ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 6;}
else {t.kind = 5; break;}
case 7:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 8;}
else {goto case 0;}
case 8:
recEnd = pos; recKind = 5;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 8;}
else if (ch == '.') {AddCh(); goto case 9;}
else {t.kind = 5; break;}
case 9:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 10;}
else {goto case 0;}
case 10:
recEnd = pos; recKind = 5;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 10;}
else {t.kind = 5; break;}
case 11:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 11;}
else if (ch == '.') {AddCh(); goto case 3;}
else {goto case 0;}
case 12:
{t.kind = 5; break;}
case 13:
{t.kind = 7; break;}
case 14:
{t.kind = 8; break;}
case 15:
{t.kind = 16; break;}
case 16:
{t.kind = 17; break;}
case 17:
recEnd = pos; recKind = 1;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 17;}
else if (ch == '.') {AddCh(); goto case 21;}
else {t.kind = 1; break;}
case 18:
recEnd = pos; recKind = 2;
if (ch == '#' || ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 18;}
else if (ch == '.') {AddCh(); goto case 3;}
else {t.kind = 2; t.val = new String(tval, 0, tlen); CheckLiteral(); return t;}
case 19:
if (ch == '"') {AddCh(); goto case 22;}
else if (ch >= ' ' && ch <= '!' || ch >= '#' && ch <= '+' || ch >= '-' && ch <= ':' || ch == '@' || ch >= '[' && ch <= '_' || ch >= 'a' && ch <= '{' || ch == '}') {AddCh(); goto case 19;}
else {goto case 0;}
case 20:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 17;}
else {goto case 0;}
case 21:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 11;}
else if (ch == '.') {AddCh(); goto case 4;}
else {goto case 0;}
case 22:
recEnd = pos; recKind = 3;
if (ch == '.') {AddCh(); goto case 3;}
else {t.kind = 3; break;}
case 23:
{t.kind = 27; break;}
case 24:
{t.kind = 28; break;}
}
t.val = new String(tval, 0, tlen);
return t;
}
private void SetScannerBehindT() {
buffer.Pos = t.pos;
NextCh();
line = t.line; col = t.col;
for (int i = 0; i < tlen; i++) NextCh();
}
// get the next token (possibly a token already seen during peeking)
public Token Scan () {
if (tokens.next == null) {
return NextToken();
} else {
pt = tokens = tokens.next;
return tokens;
}
}
// peek for the next token, ignore pragmas
public Token Peek () {
do {
if (pt.next == null) {
pt.next = NextToken();
}
pt = pt.next;
} while (pt.kind > maxT); // skip pragmas
return pt;
}
// make sure that peeking starts at the current scan position
public void ResetPeek () { pt = tokens; }
} // end Scanner
}
namespace Bermuda.QL.Language {
using System;
public class Parser {
public const int _EOF = 0;
public const int _Number = 1;
public const int _Word = 2;
public const int _Phrase = 3;
public const int _Id = 4;
public const int _Range = 5;
public const int _Not = 6;
public const int _OpenGroup = 7;
public const int _CloseGroup = 8;
public const int _RangeSeparator = 9;
public const int _And = 10;
public const int _Or = 11;
public const int _Get = 12;
public const int _Set = 13;
public const int _Chart = 14;
public const int _Where = 15;
public const int _Colon = 16;
public const int _Comma = 17;
public const int _Order = 18;
public const int _Interval = 19;
public const int _By = 20;
public const int _Desc = 21;
public const int _Limit = 22;
public const int _Over = 23;
public const int _Top = 24;
public const int _Bottom = 25;
public const int _Via = 26;
public const int maxT = 29;
const bool T = true;
const bool x = false;
const int minErrDist = 2;
public Scanner scanner;
public Errors errors;
public Token t; // last recognized token
public Token la; // lookahead token
int errDist = minErrDist;
public RootExpression RootTree { get; private set; }
bool FollowedByColon()
{
Token x = la;
//while (x.kind == _Word || x.kind == _Phrase)
x = scanner.Peek();
return x.val == ":" || x.val == "<" || x.val == ">";
}
private void MultiAdd(ExpressionTreeBase parent, ExpressionTreeBase child)
{
if (parent is MultiNodeTree)
{
((MultiNodeTree)parent).AddChild(child);
}
else if (parent is ConditionalExpression && child is ConditionalExpression)
{
((ConditionalExpression)parent).AddCondition((ConditionalExpression)child);
}
else if (parent is SingleNodeTree)
{
((SingleNodeTree)parent).SetChild(child);
}
}
private GetTypes GetGetType(string value)
{
GetTypes type;
switch(value.ToLower())
{
case "mention": type = GetTypes.Mention; break;
default: type = GetTypes.Unknown; break;
}
return type;
}
private SetterTypes GetSetterType(string value)
{
SetterTypes type;
switch(value.ToUpper())
{
case "TAG": type = SetterTypes.Tag; break;
case "SENTIMENT": type = SetterTypes.Sentiment; break;
case "DELETE": type = SetterTypes.Delete; break;
case "INFLUENCE": type = SetterTypes.Influence; break;
default: type = SetterTypes.Unknown; break;
}
return type;
}
private SelectorTypes GetSelectorType(string value)
{
SelectorTypes type;
switch(value.ToUpper())
{
case "TYPE": type = SelectorTypes.Type; break;
case "NAME": type = SelectorTypes.Name; break;
case "FROMDATE": type = SelectorTypes.FromDate; break;
case "TODATE": type = SelectorTypes.ToDate; break;
case "DATE": type = SelectorTypes.Date; break;
case "FROM": type = SelectorTypes.From; break;
case "TO": type = SelectorTypes.To; break;
case "ANYDIRECTION": type = SelectorTypes.AnyDirection; break;
case "INVOLVES": type = SelectorTypes.AnyDirection; break;
case "TAG": type = SelectorTypes.Tag; break;
case "FOR": type = SelectorTypes.For; break;
case "SENTIMENT": type = SelectorTypes.Sentiment; break;
case "SOURCE": type = SelectorTypes.Source; break;
case "AUTHOR": type = SelectorTypes.Author; break;
case "KEYWORD": type = SelectorTypes.Keyword; break;
case "INITIATOR": type = SelectorTypes.Initiator; break;
case "TARGET": type = SelectorTypes.Target; break;
case "REPLYTO": type = SelectorTypes.ReplyTo; break;
case "TAGCOUNT": type = SelectorTypes.TagCount; break;
case "COMMENTCOUNT": type = SelectorTypes.ChildCount; break;
case "DATASOURCE": type = SelectorTypes.DataSource; break;
case "DESCRIPTION": type = SelectorTypes.Description; break;
case "PARENT": type = SelectorTypes.Parent; break;
case "THEME": type = SelectorTypes.Theme; break;
case "HOUR": type = SelectorTypes.Hour; break;
case "MINUTE": type = SelectorTypes.Minute; break;
case "MONTH": type = SelectorTypes.Month; break;
case "YEAR": type = SelectorTypes.Year; break;
case "DAY": type = SelectorTypes.Day; break;
case "DATASET": type = SelectorTypes.Dataset; break;
case "IMPORTANCE": type = SelectorTypes.Importance; break;
case "CREATED": type = SelectorTypes.Created; break;
case "ISCOMMENT": type = SelectorTypes.IsComment; break;
case "INFLUENCE": type = SelectorTypes.Influence; break;
case "FOLLOWERS": type = SelectorTypes.Followers; break;
case "KLOUTSCORE": type = SelectorTypes.KloutScore; break;
case "INSTANCETYPE": type = SelectorTypes.InstanceType; break;
case "IGNOREDESCRIPTION": type = SelectorTypes.IgnoreDescription; break;
case "ID": type = SelectorTypes.Id; break;
case "DOMAIN": type = SelectorTypes.Domain; break;
case "ANYFIELD":
default: type = SelectorTypes.AnyField; break;
}
return type;
}
public Parser(Scanner scanner) {
this.scanner = scanner;
errors = new Errors();
}
void SynErr (int n) {
if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n);
errDist = 0;
}
public void SemErr (string msg) {
if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg);
errDist = 0;
}
void Get () {
for (;;) {
t = la;
la = scanner.Scan();
if (la.kind <= maxT) { ++errDist; break; }
la = t;
}
}
void Expect (int n) {
if (la.kind==n) Get(); else { SynErr(n); }
}
bool StartOf (int s) {
return set[s, la.kind];
}
void ExpectWeak (int n, int follow) {
if (la.kind == n) Get();
else {
SynErr(n);
while (!StartOf(follow)) Get();
}
}
bool WeakSeparator(int n, int syFol, int repFol) {
int kind = la.kind;
if (kind == n) {Get(); return true;}
else if (StartOf(repFol)) {return false;}
else {
SynErr(n);
while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) {
Get();
kind = la.kind;
}
return StartOf(syFol);
}
}
void EvoQL() {
if (la.kind == 12) {
GetExpression expression = new GetExpression(); RootTree = expression;
Get();
Expect(2);
expression.AddType(GetGetType(t.val));
while (la.kind == 17) {
Get();
Expect(2);
expression.AddType(GetGetType(t.val));
}
if (la.kind == 18) {
Get();
Expect(20);
Expect(3);
expression.Ordering = t.val.Substring(1, t.val.Length - 2);
if (la.kind == 21) {
Get();
expression.OrderDescending = true;
}
if (la.kind == 22) {
Get();
Expect(1);
expression.Take = Int32.Parse(t.val);
if (la.kind == 17) {
Get();
Expect(1);
expression.Skip = expression.Take; expression.Take = Int32.Parse(t.val);
}
}
}
if (StartOf(1)) {
if (la.kind == 15) {
Get();
}
ConditionGroup conditions = new ConditionGroup(); RootTree.SetChild(conditions);
Conditional(conditions);
while (StartOf(2)) {
Conditional(conditions);
}
}
} else if (la.kind == 14) {
GetExpression expression = new GetExpression(); RootTree = expression; expression.IsChart=true;
Get();
if (la.kind == 2) {
Get();
expression.Select = t.val;
if (la.kind == 20) {
Get();
if (la.kind == 24 || la.kind == 25) {
if (la.kind == 24) {
Get();
expression.GroupByDescending = true;
} else {
Get();
expression.GroupByDescending = false;
}
Expect(1);
expression.GroupByTake = Int32.Parse(t.val);
}
Expect(2);
expression.GroupBy = t.val;
if (la.kind == 26) {
Get();
Expect(2);
expression.GroupByOrderBy = t.val;
}
if (la.kind == 19) {
Get();
if (la.kind == 2) {
Get();
expression.GroupByInterval = t.val;
} else if (la.kind == 1) {
Get();
expression.GroupByInterval = t.val;
} else SynErr(30);
}
}
if (la.kind == 23) {
Get();
if (la.kind == 24 || la.kind == 25) {
if (la.kind == 24) {
Get();
expression.GroupOverDescending = true;
} else {
Get();
expression.GroupOverDescending = false;
}
Expect(1);
expression.GroupOverTake = Int32.Parse(t.val);
}
Expect(2);
expression.GroupOver = t.val;
if (la.kind == 26) {
Get();
Expect(2);
expression.GroupOverOrderBy = t.val;
}
if (la.kind == 19) {
Get();
if (la.kind == 2) {
Get();
expression.GroupOverInterval = t.val;
} else if (la.kind == 1) {
Get();
expression.GroupOverInterval = t.val;
} else SynErr(31);
}
}
}
if (StartOf(1)) {
if (la.kind == 15) {
Get();
}
ConditionGroup conditions = new ConditionGroup(); RootTree.SetChild(conditions);
Conditional(conditions);
while (StartOf(2)) {
Conditional(conditions);
}
}
} else if (StartOf(3)) {
GetExpression expression = new GetExpression(); RootTree = expression; ConditionGroup conditions = new ConditionGroup(); RootTree.SetChild(conditions);
Conditional(conditions);
while (StartOf(2)) {
Conditional(conditions);
}
} else if (la.kind == 13) {
SetExpression expression = new SetExpression(); RootTree = expression;
Get();
SetAction(expression);
while (la.kind == 2) {
SetAction(expression);
}
} else SynErr(32);
}
void Conditional(MultiNodeTree parent) {
ExpressionTreeBase addTo = parent; SingleNodeTree condition = null; ConditionalExpression lastOperation = null;
while (StartOf(2)) {
lastOperation = lastOperation ?? new AndCondition();
MultiAdd(addTo, lastOperation);
addTo = lastOperation;
if (la.kind == 6) {
Get();
NotCondition not = new NotCondition(); lastOperation.SetChild(not); lastOperation = not;
}
if (StartOf(4)) {
Condition(lastOperation);
} else if (la.kind == 7) {
ConditionGroup(lastOperation);
} else SynErr(33);
if (la.kind == 10 || la.kind == 11) {
Operation(out lastOperation);
}
else { lastOperation = null; }
}
if (lastOperation != null && lastOperation.Child == null) SemErr("Invalid Condition");
}
void SetAction(SetExpression parent) {
SetterTypes setterType;
Setter(out setterType);
SetterExpression setter = new SetterExpression(setterType);
parent.AddSetter(setter);
Literal(setter);
}
void Condition(SingleNodeTree parent) {
SelectorTypes selectorType; ModifierTypes modifierType;
if (FollowedByColon()) {
Selector(out selectorType,
out modifierType);
SelectorExpression selector = new SelectorExpression(selectorType, modifierType);
if (la.kind == 7) {
ComplexCondition(parent, selector);
} else if (StartOf(4)) {
parent.SetChild(selector);
Literal(selector);
} else SynErr(34);
} else if (StartOf(4)) {
SelectorExpression nestedSelector = new SelectorExpression(SelectorTypes.Unspecified, ModifierTypes.Equals); parent.SetChild(nestedSelector);
Literal(nestedSelector);
} else SynErr(35);
}
void ConditionGroup(SingleNodeTree parent) {
ConditionGroup group = new ConditionGroup(); parent.SetChild(group); ExpressionTreeBase addTo = group; SingleNodeTree condition = null; ConditionalExpression lastOperation = null;
Expect(7);
while (StartOf(2)) {
lastOperation = lastOperation ?? new AndCondition();
MultiAdd(addTo, lastOperation);
addTo = lastOperation;
if (la.kind == 6) {
Get();
NotCondition not = new NotCondition(); lastOperation.SetChild(not); lastOperation = not;
}
if (StartOf(4)) {
Condition(lastOperation);
} else if (la.kind == 7) {
ConditionGroup(lastOperation);
} else SynErr(36);
if (la.kind == 10 || la.kind == 11) {
Operation(out lastOperation);
}
else { lastOperation = null; }
}
if (lastOperation != null && lastOperation.Child == null) SemErr("Invalid Condition");
Expect(8);
}
void Operation(out ConditionalExpression expression) {
expression = null;
if (la.kind == 10) {
Get();
expression = new AndCondition();
} else if (la.kind == 11) {
Get();
expression = new OrCondition();
} else SynErr(37);
}
void Setter(out SetterTypes setterType) {
SetterTypes type;
Expect(2);
setterType = GetSetterType(t.val);
Expect(16);
}
void Literal(SingleNodeTree parent) {
if (la.kind == 5) {
Get();
parent.SetChild(new RangeExpression(t.val));
} else if (la.kind == 2) {
Get();
parent.SetChild(new LiteralExpression(t.val));
} else if (la.kind == 3) {
Get();
parent.SetChild(new LiteralExpression(t.val.Substring(1, t.val.Length - 2), true));
} else if (la.kind == 4) {
Get();
parent.SetChild(new ValueExpression(Int32.Parse(t.val.Substring(1))));
} else if (la.kind == 1) {
Get();
parent.SetChild(new LiteralExpression(t.val));
} else SynErr(38);
}
void Selector(out SelectorTypes selectorType,
out ModifierTypes modifierType) {
SelectorTypes type; ModifierTypes modifierResult;
Expect(2);
selectorType = GetSelectorType(t.val);
Modifier(out modifierResult);
modifierType = modifierResult;
}
void ComplexCondition(SingleNodeTree parent, SelectorExpression selector) {
ConditionGroup group = new ConditionGroup(); parent.SetChild(group); ExpressionTreeBase addTo = group; SingleNodeTree condition = null; ConditionalExpression lastOperation = null;
Expect(7);
while (StartOf(2)) {
lastOperation = lastOperation ?? new AndCondition();
MultiAdd(addTo, lastOperation);
addTo = lastOperation;
selector = new SelectorExpression(selector.Field, ModifierTypes.Equals);
if (la.kind == 6) {
Get();
Expect(16);
NotCondition not = new NotCondition(); lastOperation.SetChild(not); lastOperation = not;
}
if (la.kind == 7) {
ComplexCondition(lastOperation, selector);
} else if (StartOf(4)) {
SelectorExpression nestedSelector = new SelectorExpression(selector.Field, ModifierTypes.Equals); MultiAdd(lastOperation, nestedSelector);
Literal(nestedSelector);
} else SynErr(39);
if (la.kind == 10 || la.kind == 11) {
Operation(out lastOperation);
}
else { lastOperation = null; }
}
Expect(8);
}
void Modifier(out ModifierTypes type) {
type = ModifierTypes.Equals;
if (la.kind == 16) {
Get();
type = ModifierTypes.Equals;
} else if (la.kind == 27) {
Get();
type = ModifierTypes.LessThan;
} else if (la.kind == 28) {
Get();
type = ModifierTypes.GreaterThan;
} else SynErr(40);
}
public void Parse() {
la = new Token();
la.val = "";
Get();
EvoQL();
Expect(0);
Expect(0);
}
static readonly bool[,] set = {
{T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x},
{x,T,T,T, T,T,T,T, x,x,x,x, x,x,x,T, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x},
{x,T,T,T, T,T,T,T, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x},
{T,T,T,T, T,T,T,T, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x},
{x,T,T,T, T,T,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x}
};
} // end Parser
public class Errors {
public int count = 0; // number of errors detected
public System.IO.TextWriter errorStream = Console.Out; // error messages go to this stream
public string errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text
public void SynErr (int line, int col, int n) {
string s;
switch (n) {
case 0: s = "EOF expected"; break;
case 1: s = "Number expected"; break;
case 2: s = "Word expected"; break;
case 3: s = "Phrase expected"; break;
case 4: s = "Id expected"; break;
case 5: s = "Range expected"; break;
case 6: s = "Not expected"; break;
case 7: s = "OpenGroup expected"; break;
case 8: s = "CloseGroup expected"; break;
case 9: s = "RangeSeparator expected"; break;
case 10: s = "And expected"; break;
case 11: s = "Or expected"; break;
case 12: s = "Get expected"; break;
case 13: s = "Set expected"; break;
case 14: s = "Chart expected"; break;
case 15: s = "Where expected"; break;
case 16: s = "Colon expected"; break;
case 17: s = "Comma expected"; break;
case 18: s = "Order expected"; break;
case 19: s = "Interval expected"; break;
case 20: s = "By expected"; break;
case 21: s = "Desc expected"; break;
case 22: s = "Limit expected"; break;
case 23: s = "Over expected"; break;
case 24: s = "Top expected"; break;
case 25: s = "Bottom expected"; break;
case 26: s = "Via expected"; break;
case 27: s = "\"<\" expected"; break;
case 28: s = "\">\" expected"; break;
case 29: s = "??? expected"; break;
case 30: s = "invalid EvoQL"; break;
case 31: s = "invalid EvoQL"; break;
case 32: s = "invalid EvoQL"; break;
case 33: s = "invalid Conditional"; break;
case 34: s = "invalid Condition"; break;
case 35: s = "invalid Condition"; break;
case 36: s = "invalid ConditionGroup"; break;
case 37: s = "invalid Operation"; break;
case 38: s = "invalid Literal"; break;
case 39: s = "invalid ComplexCondition"; break;
case 40: s = "invalid Modifier"; break;
default: s = "error " + n; break;
}
errorStream.WriteLine(errMsgFormat, line, col, s);
count++;
}
public void SemErr (int line, int col, string s) {
errorStream.WriteLine(errMsgFormat, line, col, s);
count++;
}
public void SemErr (string s) {
errorStream.WriteLine(s);
count++;
}
public void Warning (int line, int col, string s) {
errorStream.WriteLine(errMsgFormat, line, col, s);
}
public void Warning(string s) {
errorStream.WriteLine(s);
}
} // Errors
public class FatalError: Exception {
public FatalError(string m): base(m) {}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.