context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//
// Copyright (c) 2012-2014 Piotr Fusik <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
#if DOTNET35
using NUnit.Framework;
using Sooda.UnitTests.BaseObjects;
using Sooda.UnitTests.Objects;
using System;
using System.Linq;
namespace Sooda.UnitTests.TestCases.Linq
{
[TestFixture]
public class ScalarTest
{
[Test]
public void All()
{
using (new SoodaTransaction())
{
bool result = Contact.Linq().All(c => c.Active);
Assert.IsTrue(result);
result = Contact.Linq().All(c => c.Name == "Mary Manager");
Assert.IsFalse(result);
}
}
[Test]
public void Any()
{
using (new SoodaTransaction())
{
bool result = Contact.Linq().Any();
Assert.IsTrue(result);
result = Contact.Linq().Where(c => c.Name == "Mary Manager").Any();
Assert.IsTrue(result);
result = Contact.Linq().Where(c => c.Name == "Barbra Streisland").Any();
Assert.IsFalse(result);
}
}
[Test]
public void AnyFiltered()
{
using (new SoodaTransaction())
{
bool result = Contact.Linq().Any(c => c.Name == "Mary Manager");
Assert.IsTrue(result);
result = Contact.Linq().Any(c => c.Name == "Barbra Streisland");
Assert.IsFalse(result);
}
}
[Test]
public void AnyFilteredBool()
{
using (new SoodaTransaction())
{
bool result = Contact.Linq().Any(c => false);
Assert.IsFalse(result);
}
}
[Test]
public void Contains()
{
using (new SoodaTransaction())
{
bool result = Contact.Linq().Contains(Contact.Mary);
Assert.IsTrue(result);
result = Contact.Linq().Where(c => c.ContactId > 1).Contains(Contact.Mary);
Assert.IsFalse(result);
result = Contact.Linq().Contains(null);
Assert.IsFalse(result);
}
}
[Test]
public void SelectContainsString()
{
using (new SoodaTransaction())
{
bool result = Contact.Linq().Select(c => c.Name).Contains("Mary Manager");
Assert.IsTrue(result);
result = Contact.Linq().Select(c => c.Name).Contains("Jarek Kowalski");
Assert.IsFalse(result);
}
}
[Test]
public void SelectContainsSoodaObject()
{
using (new SoodaTransaction())
{
bool result = Contact.Linq().Select(c => c.Manager).Contains(Contact.Mary);
Assert.IsTrue(result);
result = Contact.Linq().Select(c => c.Manager).Contains(Contact.Ed);
Assert.IsFalse(result);
result = Contact.Linq().Select(c => c.Manager).Contains(null);
Assert.IsTrue(result);
}
}
[Test]
public void Count()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Count();
Assert.AreEqual(7, result);
result = Contact.Linq().Where(c => c.Name == "Mary Manager").Count();
Assert.AreEqual(1, result);
result = Contact.Linq().Where(c => c.Name == "Barbra Streisland").Count();
Assert.AreEqual(0, result);
}
}
[Test]
public void CountFiltered()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Count(c => c.Name == "Mary Manager");
Assert.AreEqual(1, result);
result = Contact.Linq().Count(c => c.Name == "Barbra Streisland");
Assert.AreEqual(0, result);
}
}
[Test]
public void CountFilteredBool()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Count(c => true);
Assert.AreEqual(7, result);
}
}
[Test]
public void AverageInt()
{
using (new SoodaTransaction())
{
double result = Contact.Linq().Where(c => c.ContactId <= 3).Average(c => c.ContactId);
Assert.AreEqual(2.0, result);
}
}
[Test]
public void AverageIntFractional()
{
using (new SoodaTransaction())
{
double result = Contact.Linq().Where(c => c.ContactId <= 2).Average(c => c.ContactId);
Assert.AreEqual(1.5, result);
}
}
[Test]
public void AverageDecimal()
{
using (new SoodaTransaction())
{
decimal result = Contact.Linq().Where(c => new int[] { 2, 3 }.Contains(c.ContactId)).Average(c => c.LastSalary.Value);
Assert.AreEqual(289.5M, result);
}
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void AverageEmpty()
{
using (new SoodaTransaction())
{
Contact.Linq().Where(c => c.ContactId > 1000).Average(c => c.ContactId);
}
}
[Test]
public void MinInt()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Min(c => c.ContactId);
Assert.AreEqual(1, result);
}
}
[Test]
public void SelectMinInt()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Select(c => c.ContactId).Min();
Assert.AreEqual(1, result);
}
}
[Test]
public void MinDecimal()
{
using (new SoodaTransaction())
{
decimal result = Contact.Linq().Min(c => c.LastSalary.Value);
Assert.AreEqual(-1M, result);
}
}
[Test]
public void SelectMinDecimal()
{
using (new SoodaTransaction())
{
decimal result = Contact.Linq().Select(c => c.LastSalary.Value).Min();
Assert.AreEqual(-1M, result);
}
}
[Test]
public void MinTimeSpan()
{
using (new SoodaTransaction())
{
TimeSpan result = EightFields.Linq().Where(e => e.Id == 1).Min(e => e.TimeSpan);
Assert.AreEqual(TimeSpan.FromHours(1), result);
}
}
[Test]
public void SelectMinTimeSpan()
{
using (new SoodaTransaction())
{
TimeSpan result = EightFields.Linq().Where(e => e.Id == 1).Select(e => e.TimeSpan).Min();
Assert.AreEqual(TimeSpan.FromHours(1), result);
}
}
[Test]
public void MinNullableTimeSpan()
{
using (new SoodaTransaction())
{
TimeSpan? result = EightFields.Linq().Where(e => e.Id == 1).Min(e => (TimeSpan?) e.TimeSpan);
Assert.AreEqual(TimeSpan.FromHours(1), result);
}
}
[Test]
public void SelectMinNullableTimeSpan()
{
using (new SoodaTransaction())
{
TimeSpan? result = EightFields.Linq().Where(e => e.Id == 1).Select(e => (TimeSpan?) e.TimeSpan).Min();
Assert.AreEqual(TimeSpan.FromHours(1), result);
}
}
[Test]
public void MinDateTime()
{
using (new SoodaTransaction())
{
DateTime result = PKDateTime.Linq().Min(d => d.Id);
Assert.AreEqual(new DateTime(2000, 1, 1), result);
}
}
[Test]
public void SelectMinDateTime()
{
using (new SoodaTransaction())
{
DateTime result = PKDateTime.Linq().Select(d => d.Id).Min();
Assert.AreEqual(new DateTime(2000, 1, 1), result);
}
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void MinEmpty()
{
using (new SoodaTransaction())
{
Contact.Linq().Where(c => c.ContactId > 1000).Min(c => c.ContactId);
}
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void SelectMinEmpty()
{
using (new SoodaTransaction())
{
Contact.Linq().Where(c => c.ContactId > 1000).Select(c => c.ContactId).Min();
}
}
[Test]
public void MaxInt()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Max(c => c.ContactId);
Assert.AreEqual(53, result);
}
}
[Test]
public void SelectMaxInt()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Select(c => c.ContactId).Max();
Assert.AreEqual(53, result);
}
}
[Test]
public void MaxDecimal()
{
using (new SoodaTransaction())
{
decimal result = Contact.Linq().Max(c => c.LastSalary.Value);
Assert.AreEqual(345M, result);
}
}
[Test]
public void SelectMaxDecimal()
{
using (new SoodaTransaction())
{
decimal result = Contact.Linq().Select(c => c.LastSalary.Value).Max();
Assert.AreEqual(345M, result);
}
}
[Test]
public void MaxDateTime()
{
using (new SoodaTransaction())
{
DateTime result = PKDateTime.Linq().Max(d => d.Id);
Assert.AreEqual(new DateTime(2000, 1, 1, 2, 0, 0), result);
}
}
[Test]
public void SelectMaxDateTime()
{
using (new SoodaTransaction())
{
DateTime result = PKDateTime.Linq().Select(d => d.Id).Max();
Assert.AreEqual(new DateTime(2000, 1, 1, 2, 0, 0), result);
}
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void MaxEmpty()
{
using (new SoodaTransaction())
{
Contact.Linq().Where(c => c.ContactId > 1000).Max(c => c.ContactId);
}
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void SelectMaxEmpty()
{
using (new SoodaTransaction())
{
Contact.Linq().Where(c => c.ContactId > 1000).Select(c => c.ContactId).Max();
}
}
[Test]
public void SumInt()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Sum(c => c.ContactId);
Assert.AreEqual(212, result);
}
}
[Test]
public void SelectSumInt()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Select(c => c.ContactId).Sum();
Assert.AreEqual(212, result);
}
}
[Test]
public void SumDecimal()
{
using (new SoodaTransaction())
{
decimal result = Contact.Linq().Sum(c => c.LastSalary.Value);
Assert.AreEqual(926.388046789M, result);
}
}
[Test]
public void SelectSumDecimal()
{
using (new SoodaTransaction())
{
decimal result = Contact.Linq().Select(c => c.LastSalary.Value).Sum();
Assert.AreEqual(926.388046789M, result);
}
}
[Test]
public void SumIntEmpty()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Where(c => c.ContactId > 1000).Sum(c => c.ContactId);
Assert.AreEqual(0, result);
}
}
[Test]
public void SelectSumIntEmpty()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Where(c => c.ContactId > 1000).Select(c => c.ContactId).Sum();
Assert.AreEqual(0, result);
}
}
[Test]
public void SumDecimalEmpty()
{
using (new SoodaTransaction())
{
decimal result = Contact.Linq().Where(c => c.ContactId > 1000).Sum(c => c.LastSalary.Value);
Assert.AreEqual(0M, result);
}
}
[Test]
public void SelectSumDecimalEmpty()
{
using (new SoodaTransaction())
{
decimal result = Contact.Linq().Where(c => c.ContactId > 1000).Select(c => c.LastSalary.Value).Sum();
Assert.AreEqual(0M, result);
}
}
[Test]
public void DistinctCount()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Select(c => c.ContactId / 10).Distinct().Count();
Assert.AreEqual(2, result);
}
}
[Test]
public void DistinctMax()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Select(c => c.ContactId / 10).Distinct().Max();
Assert.AreEqual(5, result);
}
}
[Test]
public void DistinctSum()
{
using (new SoodaTransaction())
{
int result = Contact.Linq().Select(c => c.ContactId / 10 + 1).Distinct().Sum();
Assert.AreEqual(7, result);
}
}
// TODO: Average/Min/Max/Sum long/double/Nullable
}
}
#endif
| |
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
// See full license at the bottom of this file.
namespace ClauseLibrary.Common
{
/// <summary>
/// A list of constants used in the messaging.
/// </summary>
public static class SpApiConstants
{
/// <summary>
/// Request headers.
/// </summary>
public static class RequestHeaders
{
/// <summary>
/// The json content
/// </summary>
public const string JSON_CONTENT = "application/json;odata=verbose";
/// <summary>
/// The authorization
/// </summary>
public const string AUTHORIZATION = "Bearer ";
/// <summary>
/// The authorization template
/// </summary>
public const string AUTHORIZATIONTEMPLATE = AUTHORIZATION + "{0}";
/// <summary>
/// The XHTTP method
/// </summary>
public const string X_HTTP_METHOD = "X-HTTP-Method";
/// <summary>
/// The merge
/// </summary>
public const string MERGE = "MERGE";
/// <summary>
/// The delete
/// </summary>
public const string DELETE = "DELETE";
}
/// <summary>
/// Webs
/// </summary>
public static class Webs
{
/// <summary>
/// The base
/// </summary>
private const string BASE = "{0}/_api/web/webs/";
/// <summary>
/// The single site
/// </summary>
private const string SINGLE_SITE = "{0}/_api/web/";
/// <summary>
/// The permission query
/// </summary>
private const string PERMISSION_QUERY = "?$select=title,id,serverrelativeurl,url";
/// <summary>
/// The create
/// </summary>
public const string CREATE = "{0}/_api/web/webs/add";
/// <summary>
/// The get
/// </summary>
public const string GET = BASE + "?$select=title,url";
/// <summary>
/// The get all properties
/// </summary>
public const string GET_ALLPROPERTIES = SINGLE_SITE + "allproperties";
/// <summary>
/// The get permission trimmed
/// </summary>
public const string GET_PERMISSION_TRIMMED = BASE + PERMISSION_QUERY;
/// <summary>
/// The get single permission trimmed
/// </summary>
public const string GET_SINGLE_PERMISSION_TRIMMED = SINGLE_SITE + PERMISSION_QUERY;
/// <summary>
/// The get subsites
/// </summary>
public const string GET_SUBSITES = "{0}/{1}/_api/web/webinfos?$select=title,id,serverrelativeurl,url";
/// <summary>
/// The search sites
/// </summary>
public const string SEARCH_SITES =
@"{0}/_api/search/query?querytext='contentclass:STS_Web'&trimduplicates=false&rowlimit=500";
}
/// <summary>
/// Lists
/// </summary>
public static class Lists
{
/// <summary>
/// The base
/// </summary>
private const string BASE = "{0}/_api/web/lists/";
/// <summary>
/// The post
/// </summary>
public const string POST = BASE;
/// <summary>
/// The get by title
/// </summary>
public const string GET_BY_TITLE = BASE + "GetByTitle('{1}')";
/// <summary>
/// The create field
/// </summary>
public const string CREATE_FIELD = GET_BY_TITLE + "/Fields";
/// <summary>
/// The list titles
/// </summary>
public const string LIST_TITLES = BASE + "?$top=10000&$select=Title&orderBy=Title";
/// <summary>
/// The clause expand
/// </summary>
public const string CLAUSE_EXPAND = "Author,Designees,Owner,Editor";
/// <summary>
/// The group expand
/// </summary>
public const string GROUP_EXPAND = "Author,Designees,Owner";
}
/// <summary>
/// List items
/// </summary>
public static class ListItems
{
/// <summary>
/// The base
/// </summary>
private const string BASE = "{0}/_api/lists/getbytitle('{1}')/items";
/// <summary>
/// The expand
/// </summary>
public const string EXPAND = "$expand={0}";
/// <summary>
/// The get all
/// </summary>
public const string GET_ALL = BASE + "?$top=10000&$select={2}&orderBy=Title";
/// <summary>
/// The get
/// </summary>
public const string GET = BASE + "({2})?$select={3}";
/// <summary>
/// The get expanded
/// </summary>
public const string GET_EXPANDED = GET + "&$expand={4}";
/// <summary>
/// The post
/// </summary>
public const string POST = BASE;
/// <summary>
/// The merge
/// </summary>
public const string MERGE = BASE + "({2})";
/// <summary>
/// The delete
/// </summary>
public const string DELETE = BASE + "({2})";
/// <summary>
/// The count
/// </summary>
public const string COUNT = "{0}/_api/lists/getbytitle('{1}')/itemcount";
}
/// <summary>
/// Users
/// </summary>
public static class Users
{
/// <summary>
/// The base
/// </summary>
private const string BASE = "{0}/_api/web/siteusers";
/// <summary>
/// The select fields
/// </summary>
private const string SELECT_FIELDS = "$select=Id,Title";
/// <summary>
/// The get all
/// </summary>
public const string GET_ALL = BASE + "?" + SELECT_FIELDS;
/// <summary>
/// The get by identifier
/// </summary>
public const string GET_BY_ID = BASE + "/getbyid({1})?" + SELECT_FIELDS;
/// <summary>
/// The get by accountname
/// </summary>
public const string GET_BY_ACCOUNTNAME = BASE + "(@v)?@v='{1}'&" + SELECT_FIELDS;
/// <summary>
/// The get current
/// </summary>
public const string GET_CURRENT = "{0}/_api/web/CurrentUser?" + SELECT_FIELDS;
}
}
}
#region License
// ClauseLibrary, https://github.com/OfficeDev/clauselibrary
//
// Copyright 2015(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.
#endregion
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// Describes the SDN controller that is to connect with the pool
/// First published in .
/// </summary>
public partial class SDN_controller : XenObject<SDN_controller>
{
public SDN_controller()
{
}
public SDN_controller(string uuid,
sdn_controller_protocol protocol,
string address,
long port)
{
this.uuid = uuid;
this.protocol = protocol;
this.address = address;
this.port = port;
}
/// <summary>
/// Creates a new SDN_controller from a Proxy_SDN_controller.
/// </summary>
/// <param name="proxy"></param>
public SDN_controller(Proxy_SDN_controller proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(SDN_controller update)
{
uuid = update.uuid;
protocol = update.protocol;
address = update.address;
port = update.port;
}
internal void UpdateFromProxy(Proxy_SDN_controller proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
protocol = proxy.protocol == null ? (sdn_controller_protocol) 0 : (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), (string)proxy.protocol);
address = proxy.address == null ? null : (string)proxy.address;
port = proxy.port == null ? 0 : long.Parse((string)proxy.port);
}
public Proxy_SDN_controller ToProxy()
{
Proxy_SDN_controller result_ = new Proxy_SDN_controller();
result_.uuid = (uuid != null) ? uuid : "";
result_.protocol = sdn_controller_protocol_helper.ToString(protocol);
result_.address = (address != null) ? address : "";
result_.port = port.ToString();
return result_;
}
/// <summary>
/// Creates a new SDN_controller from a Hashtable.
/// </summary>
/// <param name="table"></param>
public SDN_controller(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
protocol = (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), Marshalling.ParseString(table, "protocol"));
address = Marshalling.ParseString(table, "address");
port = Marshalling.ParseLong(table, "port");
}
public bool DeepEquals(SDN_controller other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._protocol, other._protocol) &&
Helper.AreEqual2(this._address, other._address) &&
Helper.AreEqual2(this._port, other._port);
}
public override string SaveChanges(Session session, string opaqueRef, SDN_controller server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given SDN_controller.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static SDN_controller get_record(Session session, string _sdn_controller)
{
return new SDN_controller((Proxy_SDN_controller)session.proxy.sdn_controller_get_record(session.uuid, (_sdn_controller != null) ? _sdn_controller : "").parse());
}
/// <summary>
/// Get a reference to the SDN_controller instance with the specified UUID.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<SDN_controller> get_by_uuid(Session session, string _uuid)
{
return XenRef<SDN_controller>.Create(session.proxy.sdn_controller_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get the uuid field of the given SDN_controller.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static string get_uuid(Session session, string _sdn_controller)
{
return (string)session.proxy.sdn_controller_get_uuid(session.uuid, (_sdn_controller != null) ? _sdn_controller : "").parse();
}
/// <summary>
/// Get the protocol field of the given SDN_controller.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static sdn_controller_protocol get_protocol(Session session, string _sdn_controller)
{
return (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), (string)session.proxy.sdn_controller_get_protocol(session.uuid, (_sdn_controller != null) ? _sdn_controller : "").parse());
}
/// <summary>
/// Get the address field of the given SDN_controller.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static string get_address(Session session, string _sdn_controller)
{
return (string)session.proxy.sdn_controller_get_address(session.uuid, (_sdn_controller != null) ? _sdn_controller : "").parse();
}
/// <summary>
/// Get the port field of the given SDN_controller.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static long get_port(Session session, string _sdn_controller)
{
return long.Parse((string)session.proxy.sdn_controller_get_port(session.uuid, (_sdn_controller != null) ? _sdn_controller : "").parse());
}
/// <summary>
/// Introduce an SDN controller to the pool.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_protocol">Protocol to connect with the controller.</param>
/// <param name="_address">IP address of the controller.</param>
/// <param name="_port">TCP port of the controller.</param>
public static XenRef<SDN_controller> introduce(Session session, sdn_controller_protocol _protocol, string _address, long _port)
{
return XenRef<SDN_controller>.Create(session.proxy.sdn_controller_introduce(session.uuid, sdn_controller_protocol_helper.ToString(_protocol), (_address != null) ? _address : "", _port.ToString()).parse());
}
/// <summary>
/// Introduce an SDN controller to the pool.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_protocol">Protocol to connect with the controller.</param>
/// <param name="_address">IP address of the controller.</param>
/// <param name="_port">TCP port of the controller.</param>
public static XenRef<Task> async_introduce(Session session, sdn_controller_protocol _protocol, string _address, long _port)
{
return XenRef<Task>.Create(session.proxy.async_sdn_controller_introduce(session.uuid, sdn_controller_protocol_helper.ToString(_protocol), (_address != null) ? _address : "", _port.ToString()).parse());
}
/// <summary>
/// Remove the OVS manager of the pool and destroy the db record.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static void forget(Session session, string _sdn_controller)
{
session.proxy.sdn_controller_forget(session.uuid, (_sdn_controller != null) ? _sdn_controller : "").parse();
}
/// <summary>
/// Remove the OVS manager of the pool and destroy the db record.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static XenRef<Task> async_forget(Session session, string _sdn_controller)
{
return XenRef<Task>.Create(session.proxy.async_sdn_controller_forget(session.uuid, (_sdn_controller != null) ? _sdn_controller : "").parse());
}
/// <summary>
/// Return a list of all the SDN_controllers known to the system.
/// First published in .
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<SDN_controller>> get_all(Session session)
{
return XenRef<SDN_controller>.Create(session.proxy.sdn_controller_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the SDN_controller Records at once, in a single XML RPC call
/// First published in .
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<SDN_controller>, SDN_controller> get_all_records(Session session)
{
return XenRef<SDN_controller>.Create<Proxy_SDN_controller>(session.proxy.sdn_controller_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// Protocol to connect with SDN controller
/// </summary>
public virtual sdn_controller_protocol protocol
{
get { return _protocol; }
set
{
if (!Helper.AreEqual(value, _protocol))
{
_protocol = value;
Changed = true;
NotifyPropertyChanged("protocol");
}
}
}
private sdn_controller_protocol _protocol;
/// <summary>
/// IP address of the controller
/// </summary>
public virtual string address
{
get { return _address; }
set
{
if (!Helper.AreEqual(value, _address))
{
_address = value;
Changed = true;
NotifyPropertyChanged("address");
}
}
}
private string _address;
/// <summary>
/// TCP port of the controller
/// </summary>
public virtual long port
{
get { return _port; }
set
{
if (!Helper.AreEqual(value, _port))
{
_port = value;
Changed = true;
NotifyPropertyChanged("port");
}
}
}
private long _port;
}
}
| |
// 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;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Extensions.CommandLineUtils
{
internal class CommandLineApplication
{
// Indicates whether the parser should throw an exception when it runs into an unexpected argument. If this is
// set to true (the default), the parser will throw on the first unexpected argument. Otherwise, all unexpected
// arguments (including the first) are added to RemainingArguments.
private readonly bool _throwOnUnexpectedArg;
// Indicates whether the parser should check remaining arguments for command or option matches after
// encountering an unexpected argument. Ignored if _throwOnUnexpectedArg is true (the default). If
// _throwOnUnexpectedArg and this are both false, the first unexpected argument and all remaining arguments are
// added to RemainingArguments. If _throwOnUnexpectedArg is false and this is true, only unexpected arguments
// are added to RemainingArguments -- allowing a mix of expected and unexpected arguments, commands and
// options.
private readonly bool _continueAfterUnexpectedArg;
private readonly bool _treatUnmatchedOptionsAsArguments;
public CommandLineApplication(bool throwOnUnexpectedArg = true, bool continueAfterUnexpectedArg = false, bool treatUnmatchedOptionsAsArguments = false)
{
_throwOnUnexpectedArg = throwOnUnexpectedArg;
_continueAfterUnexpectedArg = continueAfterUnexpectedArg;
_treatUnmatchedOptionsAsArguments = treatUnmatchedOptionsAsArguments;
Options = new List<CommandOption>();
Arguments = new List<CommandArgument>();
Commands = new List<CommandLineApplication>();
RemainingArguments = new List<string>();
Invoke = () => 0;
}
public CommandLineApplication Parent { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public string Syntax { get; set; }
public string Description { get; set; }
public bool ShowInHelpText { get; set; } = true;
public string ExtendedHelpText { get; set; }
public readonly List<CommandOption> Options;
public CommandOption OptionHelp { get; private set; }
public CommandOption OptionVersion { get; private set; }
public readonly List<CommandArgument> Arguments;
public readonly List<string> RemainingArguments;
public bool IsShowingInformation { get; protected set; } // Is showing help or version?
public Func<int> Invoke { get; set; }
public Func<string> LongVersionGetter { get; set; }
public Func<string> ShortVersionGetter { get; set; }
public readonly List<CommandLineApplication> Commands;
public bool AllowArgumentSeparator { get; set; }
public TextWriter Out { get; set; } = Console.Out;
public TextWriter Error { get; set; } = Console.Error;
public IEnumerable<CommandOption> GetOptions()
{
var expr = Options.AsEnumerable();
var rootNode = this;
while (rootNode.Parent != null)
{
rootNode = rootNode.Parent;
expr = expr.Concat(rootNode.Options.Where(o => o.Inherited));
}
return expr;
}
public CommandLineApplication Command(string name, Action<CommandLineApplication> configuration,
bool throwOnUnexpectedArg = true)
{
var command = new CommandLineApplication(throwOnUnexpectedArg) { Name = name, Parent = this };
Commands.Add(command);
configuration(command);
return command;
}
public CommandOption Option(string template, string description, CommandOptionType optionType)
=> Option(template, description, optionType, _ => { }, inherited: false);
public CommandOption Option(string template, string description, CommandOptionType optionType, bool inherited)
=> Option(template, description, optionType, _ => { }, inherited);
public CommandOption Option(string template, string description, CommandOptionType optionType, Action<CommandOption> configuration)
=> Option(template, description, optionType, configuration, inherited: false);
public CommandOption Option(string template, string description, CommandOptionType optionType, Action<CommandOption> configuration, bool inherited)
{
var option = new CommandOption(template, optionType)
{
Description = description,
Inherited = inherited
};
Options.Add(option);
configuration(option);
return option;
}
public CommandArgument Argument(string name, string description, bool multipleValues = false)
{
return Argument(name, description, _ => { }, multipleValues);
}
public CommandArgument Argument(string name, string description, Action<CommandArgument> configuration, bool multipleValues = false)
{
var lastArg = Arguments.LastOrDefault();
if (lastArg != null && lastArg.MultipleValues)
{
var message = string.Format(
CultureInfo.CurrentCulture,
"The last argument '{0}' accepts multiple values. No more argument can be added.",
lastArg.Name);
throw new InvalidOperationException(message);
}
var argument = new CommandArgument { Name = name, Description = description, MultipleValues = multipleValues };
Arguments.Add(argument);
configuration(argument);
return argument;
}
public void OnExecute(Func<int> invoke)
{
Invoke = invoke;
}
public void OnExecute(Func<Task<int>> invoke)
{
Invoke = () => invoke().Result;
}
public int Execute(params string[] args)
{
CommandLineApplication command = this;
CommandOption option = null;
IEnumerator<CommandArgument> arguments = null;
var argumentsAssigned = false;
for (var index = 0; index < args.Length; index++)
{
var arg = args[index];
var processed = false;
if (!processed && option == null)
{
string[] longOption = null;
string[] shortOption = null;
if (arg.StartsWith("--", StringComparison.Ordinal))
{
longOption = arg.Substring(2).Split(new[] { ':', '=' }, 2);
}
else if (arg.StartsWith("-", StringComparison.Ordinal))
{
shortOption = arg.Substring(1).Split(new[] { ':', '=' }, 2);
}
if (longOption != null)
{
processed = true;
var longOptionName = longOption[0];
option = command.GetOptions().SingleOrDefault(opt => string.Equals(opt.LongName, longOptionName, StringComparison.Ordinal));
if (option == null && _treatUnmatchedOptionsAsArguments)
{
if (arguments == null)
{
arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator());
}
if (arguments.MoveNext())
{
processed = true;
arguments.Current.Values.Add(arg);
argumentsAssigned = true;
continue;
}
//else
//{
// argumentsAssigned = false;
//}
}
if (option == null)
{
var ignoreContinueAfterUnexpectedArg = false;
if (string.IsNullOrEmpty(longOptionName) &&
!command._throwOnUnexpectedArg &&
AllowArgumentSeparator)
{
// Skip over the '--' argument separator then consume all remaining arguments. All
// remaining arguments are unconditionally stored for further use.
index++;
ignoreContinueAfterUnexpectedArg = true;
}
if (HandleUnexpectedArg(
command,
args,
index,
argTypeName: "option",
ignoreContinueAfterUnexpectedArg))
{
continue;
}
break;
}
// If we find a help/version option, show information and stop parsing
if (command.OptionHelp == option)
{
command.ShowHelp();
return 0;
}
else if (command.OptionVersion == option)
{
command.ShowVersion();
return 0;
}
if (longOption.Length == 2)
{
if (!option.TryParse(longOption[1]))
{
command.ShowHint();
throw new CommandParsingException(command, $"Unexpected value '{longOption[1]}' for option '{option.LongName}'");
}
option = null;
}
else if (option.OptionType == CommandOptionType.NoValue)
{
// No value is needed for this option
option.TryParse(null);
option = null;
}
}
if (shortOption != null)
{
processed = true;
option = command.GetOptions().SingleOrDefault(opt => string.Equals(opt.ShortName, shortOption[0], StringComparison.Ordinal));
if (option == null && _treatUnmatchedOptionsAsArguments)
{
if (arguments == null)
{
arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator());
}
if (arguments.MoveNext())
{
processed = true;
arguments.Current.Values.Add(arg);
argumentsAssigned = true;
continue;
}
//else
//{
// argumentsAssigned = false;
//}
}
// If not a short option, try symbol option
if (option == null)
{
option = command.GetOptions().SingleOrDefault(opt => string.Equals(opt.SymbolName, shortOption[0], StringComparison.Ordinal));
}
if (option == null)
{
if (HandleUnexpectedArg(command, args, index, argTypeName: "option"))
{
continue;
}
break;
}
// If we find a help/version option, show information and stop parsing
if (command.OptionHelp == option)
{
command.ShowHelp();
return 0;
}
else if (command.OptionVersion == option)
{
command.ShowVersion();
return 0;
}
if (shortOption.Length == 2)
{
if (!option.TryParse(shortOption[1]))
{
command.ShowHint();
throw new CommandParsingException(command, $"Unexpected value '{shortOption[1]}' for option '{option.LongName}'");
}
option = null;
}
else if (option.OptionType == CommandOptionType.NoValue)
{
// No value is needed for this option
option.TryParse(null);
option = null;
}
}
}
if (!processed && option != null)
{
processed = true;
if (!option.TryParse(arg))
{
command.ShowHint();
throw new CommandParsingException(command, $"Unexpected value '{arg}' for option '{option.LongName}'");
}
option = null;
}
if (!processed && !argumentsAssigned)
{
var currentCommand = command;
foreach (var subcommand in command.Commands)
{
if (string.Equals(subcommand.Name, arg, StringComparison.OrdinalIgnoreCase))
{
processed = true;
command = subcommand;
break;
}
}
// If we detect a subcommand
if (command != currentCommand)
{
processed = true;
}
}
if (!processed)
{
if (arguments == null)
{
arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator());
}
if (arguments.MoveNext())
{
processed = true;
arguments.Current.Values.Add(arg);
}
}
if (!processed)
{
if (HandleUnexpectedArg(command, args, index, argTypeName: "command or argument"))
{
continue;
}
break;
}
}
if (option != null)
{
command.ShowHint();
throw new CommandParsingException(command, $"Missing value for option '{option.LongName}'");
}
return command.Invoke();
}
// Helper method that adds a help option
public CommandOption HelpOption(string template)
{
// Help option is special because we stop parsing once we see it
// So we store it separately for further use
OptionHelp = Option(template, "Show help information", CommandOptionType.NoValue);
return OptionHelp;
}
public CommandOption VersionOption(string template,
string shortFormVersion,
string longFormVersion = null)
{
if (longFormVersion == null)
{
return VersionOption(template, () => shortFormVersion);
}
else
{
return VersionOption(template, () => shortFormVersion, () => longFormVersion);
}
}
// Helper method that adds a version option
public CommandOption VersionOption(string template,
Func<string> shortFormVersionGetter,
Func<string> longFormVersionGetter = null)
{
// Version option is special because we stop parsing once we see it
// So we store it separately for further use
OptionVersion = Option(template, "Show version information", CommandOptionType.NoValue);
ShortVersionGetter = shortFormVersionGetter;
LongVersionGetter = longFormVersionGetter ?? shortFormVersionGetter;
return OptionVersion;
}
// Show short hint that reminds users to use help option
public void ShowHint()
{
if (OptionHelp != null)
{
Out.WriteLine(string.Format(CultureInfo.CurrentCulture, "Specify --{0} for a list of available options and commands.", OptionHelp.LongName));
}
}
// Show full help
public void ShowHelp(string commandName = null)
{
for (var cmd = this; cmd != null; cmd = cmd.Parent)
{
cmd.IsShowingInformation = true;
}
Out.WriteLine(GetHelpText(commandName));
}
public virtual string GetHelpText(string commandName = null)
{
var headerBuilder = new StringBuilder("Usage:");
for (var cmd = this; cmd != null; cmd = cmd.Parent)
{
headerBuilder.Insert(6, string.Format(CultureInfo.InvariantCulture, " {0}", cmd.Name));
}
CommandLineApplication target;
if (commandName == null || string.Equals(Name, commandName, StringComparison.OrdinalIgnoreCase))
{
target = this;
}
else
{
target = Commands.SingleOrDefault(cmd => string.Equals(cmd.Name, commandName, StringComparison.OrdinalIgnoreCase));
if (target != null)
{
headerBuilder.AppendFormat(CultureInfo.InvariantCulture, " {0}", commandName);
}
else
{
// The command name is invalid so don't try to show help for something that doesn't exist
target = this;
}
}
var optionsBuilder = new StringBuilder();
var commandsBuilder = new StringBuilder();
var argumentsBuilder = new StringBuilder();
var arguments = target.Arguments.Where(a => a.ShowInHelpText).ToList();
if (arguments.Any())
{
headerBuilder.Append(" [arguments]");
argumentsBuilder.AppendLine();
argumentsBuilder.AppendLine("Arguments:");
var maxArgLen = arguments.Max(a => a.Name.Length);
var outputFormat = string.Format(CultureInfo.InvariantCulture, " {{0, -{0}}}{{1}}", maxArgLen + 2);
foreach (var arg in arguments)
{
argumentsBuilder.AppendFormat(CultureInfo.InvariantCulture, outputFormat, arg.Name, arg.Description);
argumentsBuilder.AppendLine();
}
}
var options = target.GetOptions().Where(o => o.ShowInHelpText).ToList();
if (options.Any())
{
headerBuilder.Append(" [options]");
optionsBuilder.AppendLine();
optionsBuilder.AppendLine("Options:");
var maxOptLen = options.Max(o => o.Template.Length);
var outputFormat = string.Format(CultureInfo.InvariantCulture, " {{0, -{0}}}{{1}}", maxOptLen + 2);
foreach (var opt in options)
{
optionsBuilder.AppendFormat(CultureInfo.InvariantCulture, outputFormat, opt.Template, opt.Description);
optionsBuilder.AppendLine();
}
}
var commands = target.Commands.Where(c => c.ShowInHelpText).ToList();
if (commands.Any())
{
headerBuilder.Append(" [command]");
commandsBuilder.AppendLine();
commandsBuilder.AppendLine("Commands:");
var maxCmdLen = commands.Max(c => c.Name.Length);
var outputFormat = string.Format(CultureInfo.InvariantCulture, " {{0, -{0}}}{{1}}", maxCmdLen + 2);
foreach (var cmd in commands.OrderBy(c => c.Name))
{
commandsBuilder.AppendFormat(CultureInfo.InvariantCulture, outputFormat, cmd.Name, cmd.Description);
commandsBuilder.AppendLine();
}
if (OptionHelp != null)
{
commandsBuilder.AppendLine();
commandsBuilder.Append(FormattableString.Invariant($"Use \"{target.Name} [command] --{OptionHelp.LongName}\" for more information about a command."));
commandsBuilder.AppendLine();
}
}
if (target.AllowArgumentSeparator)
{
headerBuilder.Append(" [[--] <arg>...]");
}
headerBuilder.AppendLine();
var nameAndVersion = new StringBuilder();
nameAndVersion.AppendLine(GetFullNameAndVersion());
nameAndVersion.AppendLine();
return nameAndVersion.ToString()
+ headerBuilder.ToString()
+ argumentsBuilder.ToString()
+ optionsBuilder.ToString()
+ commandsBuilder.ToString()
+ target.ExtendedHelpText;
}
public void ShowVersion()
{
for (var cmd = this; cmd != null; cmd = cmd.Parent)
{
cmd.IsShowingInformation = true;
}
Out.WriteLine(FullName);
Out.WriteLine(LongVersionGetter());
}
public string GetFullNameAndVersion()
{
return ShortVersionGetter == null ? FullName : string.Format(CultureInfo.InvariantCulture, "{0} {1}", FullName, ShortVersionGetter());
}
public void ShowRootCommandFullNameAndVersion()
{
var rootCmd = this;
while (rootCmd.Parent != null)
{
rootCmd = rootCmd.Parent;
}
Out.WriteLine(rootCmd.GetFullNameAndVersion());
Out.WriteLine();
}
private bool HandleUnexpectedArg(
CommandLineApplication command,
string[] args,
int index,
string argTypeName,
bool ignoreContinueAfterUnexpectedArg = false)
{
if (command._throwOnUnexpectedArg)
{
command.ShowHint();
throw new CommandParsingException(command, $"Unrecognized {argTypeName} '{args[index]}'");
}
else if (_continueAfterUnexpectedArg && !ignoreContinueAfterUnexpectedArg)
{
// Store argument for further use.
command.RemainingArguments.Add(args[index]);
return true;
}
else
{
// Store all remaining arguments for later use.
command.RemainingArguments.AddRange(new ArraySegment<string>(args, index, args.Length - index));
return false;
}
}
private class CommandArgumentEnumerator : IEnumerator<CommandArgument>
{
private readonly IEnumerator<CommandArgument> _enumerator;
public CommandArgumentEnumerator(IEnumerator<CommandArgument> enumerator)
{
_enumerator = enumerator;
}
public CommandArgument Current
{
get
{
return _enumerator.Current;
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public void Dispose()
{
_enumerator.Dispose();
}
public bool MoveNext()
{
if (Current == null || !Current.MultipleValues)
{
return _enumerator.MoveNext();
}
// If current argument allows multiple values, we don't move forward and
// all later values will be added to current CommandArgument.Values
return true;
}
public void Reset()
{
_enumerator.Reset();
}
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <[email protected]>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI41;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI41
{
/// <summary>
/// Helper methods for LowLevelAPI tests.
/// </summary>
public static class Helpers
{
/// <summary>
/// Finds slot containing the token that matches criteria specified in Settings class
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <returns>Slot containing the token that matches criteria</returns>
public static uint GetUsableSlot(Pkcs11 pkcs11)
{
CKR rv = CKR.CKR_OK;
// Get list of available slots with token present
uint slotCount = 0;
rv = pkcs11.C_GetSlotList(true, null, ref slotCount);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(slotCount > 0);
uint[] slotList = new uint[slotCount];
rv = pkcs11.C_GetSlotList(true, slotList, ref slotCount);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Return first slot with token present when both TokenSerial and TokenLabel are null...
if (Settings.TokenSerial == null && Settings.TokenLabel == null)
return slotList[0];
// First slot with token present is OK...
uint? matchingSlot = slotList[0];
// ...unless there are matching criteria specified in Settings class
if (Settings.TokenSerial != null || Settings.TokenLabel != null)
{
matchingSlot = null;
foreach (uint slot in slotList)
{
CK_TOKEN_INFO tokenInfo = new CK_TOKEN_INFO();
rv = pkcs11.C_GetTokenInfo(slot, ref tokenInfo);
if (rv != CKR.CKR_OK)
{
if (rv == CKR.CKR_TOKEN_NOT_RECOGNIZED || rv == CKR.CKR_TOKEN_NOT_PRESENT)
continue;
else
Assert.Fail(rv.ToString());
}
if (!string.IsNullOrEmpty(Settings.TokenSerial))
if (0 != string.Compare(Settings.TokenSerial, ConvertUtils.BytesToUtf8String(tokenInfo.SerialNumber, true), StringComparison.Ordinal))
continue;
if (!string.IsNullOrEmpty(Settings.TokenLabel))
if (0 != string.Compare(Settings.TokenLabel, ConvertUtils.BytesToUtf8String(tokenInfo.Label, true), StringComparison.Ordinal))
continue;
matchingSlot = slot;
break;
}
}
Assert.IsTrue(matchingSlot != null, "Token matching criteria specified in Settings class is not present");
return matchingSlot.Value;
}
/// <summary>
/// Creates the data object.
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <param name='session'>Read-write session with user logged in</param>
/// <param name='objectId'>Output parameter for data object handle</param>
/// <returns>Return value of C_CreateObject</returns>
public static CKR CreateDataObject(Pkcs11 pkcs11, uint session, ref uint objectId)
{
CKR rv = CKR.CKR_OK;
// Prepare attribute template of new data object
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[5];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_APPLICATION, Settings.ApplicationName);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
template[4] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, "Data object content");
// Create object
rv = pkcs11.C_CreateObject(session, template, Convert.ToUInt32(template.Length), ref objectId);
// In LowLevelAPI caller has to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
return rv;
}
/// <summary>
/// Generates symetric key.
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <param name='session'>Read-write session with user logged in</param>
/// <param name='keyId'>Output parameter for key object handle</param>
/// <returns>Return value of C_GenerateKey</returns>
public static CKR GenerateKey(Pkcs11 pkcs11, uint session, ref uint keyId)
{
CKR rv = CKR.CKR_OK;
// Prepare attribute template of new key
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[6];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
template[4] = CkaUtils.CreateAttribute(CKA.CKA_DERIVE, true);
template[5] = CkaUtils.CreateAttribute(CKA.CKA_EXTRACTABLE, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_KEY_GEN);
// Generate key
rv = pkcs11.C_GenerateKey(session, ref mechanism, template, Convert.ToUInt32(template.Length), ref keyId);
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
return rv;
}
/// <summary>
/// Generates asymetric key pair.
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <param name='session'>Read-write session with user logged in</param>
/// <param name='pubKeyId'>Output parameter for public key object handle</param>
/// <param name='privKeyId'>Output parameter for private key object handle</param>
/// <returns>Return value of C_GenerateKeyPair</returns>
public static CKR GenerateKeyPair(Pkcs11 pkcs11, uint session, ref uint pubKeyId, ref uint privKeyId)
{
CKR rv = CKR.CKR_OK;
// The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
byte[] ckaId = new byte[20];
rv = pkcs11.C_GenerateRandom(session, ckaId, Convert.ToUInt32(ckaId.Length));
if (rv != CKR.CKR_OK)
return rv;
// Prepare attribute template of new public key
CK_ATTRIBUTE[] pubKeyTemplate = new CK_ATTRIBUTE[10];
pubKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
pubKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false);
pubKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
pubKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
pubKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
pubKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY, true);
pubKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY_RECOVER, true);
pubKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_WRAP, true);
pubKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_MODULUS_BITS, 1024);
pubKeyTemplate[9] = CkaUtils.CreateAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 });
// Prepare attribute template of new private key
CK_ATTRIBUTE[] privKeyTemplate = new CK_ATTRIBUTE[9];
privKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
privKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
privKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
privKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
privKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, true);
privKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
privKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_SIGN, true);
privKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SIGN_RECOVER, true);
privKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_UNWRAP, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);
// Generate key pair
rv = pkcs11.C_GenerateKeyPair(session, ref mechanism, pubKeyTemplate, Convert.ToUInt32(pubKeyTemplate.Length), privKeyTemplate, Convert.ToUInt32(privKeyTemplate.Length), ref pubKeyId, ref privKeyId);
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < privKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref privKeyTemplate[i].value);
privKeyTemplate[i].valueLen = 0;
}
for (int i = 0; i < pubKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref pubKeyTemplate[i].value);
pubKeyTemplate[i].valueLen = 0;
}
return rv;
}
}
}
| |
// 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 AlignRightSByte5()
{
var test = new ImmBinaryOpTest__AlignRightSByte5();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local 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 ImmBinaryOpTest__AlignRightSByte5
{
private struct TestStruct
{
public Vector256<SByte> _fld1;
public Vector256<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__AlignRightSByte5 testClass)
{
var result = Avx2.AlignRight(_fld1, _fld2, 5);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector256<SByte> _clsVar1;
private static Vector256<SByte> _clsVar2;
private Vector256<SByte> _fld1;
private Vector256<SByte> _fld2;
private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable;
static ImmBinaryOpTest__AlignRightSByte5()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
}
public ImmBinaryOpTest__AlignRightSByte5()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.AlignRight(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr),
5
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.AlignRight(
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)),
5
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.AlignRight(
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)),
5
);
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(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr),
(byte)5
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)),
(byte)5
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)),
(byte)5
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.AlignRight(
_clsVar1,
_clsVar2,
5
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr);
var result = Avx2.AlignRight(left, right, 5);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.AlignRight(left, right, 5);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.AlignRight(left, right, 5);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__AlignRightSByte5();
var result = Avx2.AlignRight(test._fld1, test._fld2, 5);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.AlignRight(_fld1, _fld2, 5);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.AlignRight(test._fld1, test._fld2, 5);
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(Vector256<SByte> left, Vector256<SByte> right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != right[5])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((result[i] != ((i < 16) ? ((i < 11) ? right[i + 5] : left[i - 11]) : ((i < 27) ? right[i + 5] : left[i - 11]))))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AlignRight)}<SByte>(Vector256<SByte>.5, Vector256<SByte>): {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;
}
}
}
}
| |
//
// ListBrowserSourceContents.cs
//
// Authors:
// Aaron Bockover <[email protected]>
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2007-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 System.Reflection;
using System.Collections.Generic;
using Gtk;
using Mono.Unix;
using Hyena.Data;
using Hyena.Data.Gui;
using Hyena.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Configuration;
using Banshee.Gui;
using Banshee.Collection.Gui;
using ScrolledWindow=Gtk.ScrolledWindow;
namespace Banshee.Sources.Gui
{
public abstract class FilteredListSourceContents : VBox, ISourceContents
{
private string name;
private object main_view;
private Gtk.ScrolledWindow main_scrolled_window;
private List<object> filter_views = new List<object> ();
private List<ScrolledWindow> filter_scrolled_windows = new List<ScrolledWindow> ();
private Dictionary<object, double> model_positions = new Dictionary<object, double> ();
private Paned container;
private Widget browser_container;
private InterfaceActionService action_service;
private ActionGroup browser_view_actions;
private static string menu_xml = @"
<ui>
<menubar name=""MainMenu"">
<menu name=""ViewMenu"" action=""ViewMenuAction"">
<placeholder name=""BrowserViews"">
<menuitem name=""BrowserVisible"" action=""BrowserVisibleAction"" />
<separator />
<menuitem name=""BrowserTop"" action=""BrowserTopAction"" />
<menuitem name=""BrowserLeft"" action=""BrowserLeftAction"" />
<separator />
</placeholder>
</menu>
</menubar>
</ui>
";
public FilteredListSourceContents (string name)
{
this.name = name;
InitializeViews ();
string position = ForcePosition == null ? BrowserPosition.Get () : ForcePosition;
if (position == "top") {
LayoutTop ();
} else {
LayoutLeft ();
}
if (ForcePosition != null) {
return;
}
if (ServiceManager.Contains ("InterfaceActionService")) {
action_service = ServiceManager.Get<InterfaceActionService> ();
if (action_service.FindActionGroup ("BrowserView") == null) {
browser_view_actions = new ActionGroup ("BrowserView");
browser_view_actions.Add (new RadioActionEntry [] {
new RadioActionEntry ("BrowserLeftAction", null,
Catalog.GetString ("Browser on Left"), null,
Catalog.GetString ("Show the artist/album browser to the left of the track list"), 0),
new RadioActionEntry ("BrowserTopAction", null,
Catalog.GetString ("Browser on Top"), null,
Catalog.GetString ("Show the artist/album browser above the track list"), 1),
}, position == "top" ? 1 : 0, null);
browser_view_actions.Add (new ToggleActionEntry [] {
new ToggleActionEntry ("BrowserVisibleAction", null,
Catalog.GetString ("Show Browser"), "<control>B",
Catalog.GetString ("Show or hide the artist/album browser"),
null, BrowserVisible.Get ())
});
action_service.AddActionGroup (browser_view_actions);
//action_merge_id = action_service.UIManager.NewMergeId ();
action_service.UIManager.AddUiFromString (menu_xml);
}
(action_service.FindAction("BrowserView.BrowserLeftAction") as RadioAction).Changed += OnViewModeChanged;
(action_service.FindAction("BrowserView.BrowserTopAction") as RadioAction).Changed += OnViewModeChanged;
action_service.FindAction("BrowserView.BrowserVisibleAction").Activated += OnToggleBrowser;
}
ServiceManager.SourceManager.ActiveSourceChanged += delegate {
Banshee.Base.ThreadAssist.ProxyToMain (delegate {
browser_container.Visible = ActiveSourceCanHasBrowser ? BrowserVisible.Get () : false;
});
};
NoShowAll = true;
}
protected abstract void InitializeViews ();
protected void SetupMainView<T> (ListView<T> main_view)
{
this.main_view = main_view;
main_scrolled_window = SetupView (main_view);
}
protected void SetupFilterView<T> (ListView<T> filter_view)
{
ScrolledWindow window = SetupView (filter_view);
filter_scrolled_windows.Add (window);
filter_view.HeaderVisible = false;
filter_view.SelectionProxy.Changed += OnBrowserViewSelectionChanged;
}
private ScrolledWindow SetupView (Widget view)
{
ScrolledWindow window = null;
//if (!Banshee.Base.ApplicationContext.CommandLine.Contains ("no-smooth-scroll")) {
if (Banshee.Base.ApplicationContext.CommandLine.Contains ("smooth-scroll")) {
window = new SmoothScrolledWindow ();
} else {
window = new ScrolledWindow ();
}
window.Add (view);
window.HscrollbarPolicy = PolicyType.Automatic;
window.VscrollbarPolicy = PolicyType.Automatic;
return window;
}
private void Reset ()
{
// Unparent the views' scrolled window parents so they can be re-packed in
// a new layout. The main container gets destroyed since it will be recreated.
foreach (ScrolledWindow window in filter_scrolled_windows) {
Paned filter_container = window.Parent as Paned;
if (filter_container != null) {
filter_container.Remove (window);
}
}
if (container != null && main_scrolled_window != null) {
container.Remove (main_scrolled_window);
}
if (container != null) {
Remove (container);
}
}
private void LayoutLeft ()
{
Layout (false);
}
private void LayoutTop ()
{
Layout (true);
}
private void Layout (bool top)
{
//Hyena.Log.Information ("ListBrowser LayoutLeft");
Reset ();
container = GetPane (!top);
Paned filter_box = GetPane (top);
filter_box.PositionSet = true;
Paned current_pane = filter_box;
for (int i = 0; i < filter_scrolled_windows.Count; i++) {
ScrolledWindow window = filter_scrolled_windows[i];
bool last_even_filter = (i == filter_scrolled_windows.Count - 1 && filter_scrolled_windows.Count % 2 == 0);
if (i > 0 && !last_even_filter) {
Paned new_pane = GetPane (top);
current_pane.Pack2 (new_pane, true, false);
current_pane.Position = 350;
PersistentPaneController.Control (current_pane, ControllerName (top, i));
current_pane = new_pane;
}
if (last_even_filter) {
current_pane.Pack2 (window, true, false);
current_pane.Position = 350;
PersistentPaneController.Control (current_pane, ControllerName (top, i));
} else {
current_pane.Pack1 (window, false, false);
}
}
container.Pack1 (filter_box, false, false);
container.Pack2 (main_scrolled_window, true, false);
browser_container = filter_box;
container.Position = top ? 175 : 275;
PersistentPaneController.Control (container, ControllerName (top, -1));
ShowPack ();
}
private string ControllerName (bool top, int filter)
{
if (filter == -1)
return String.Format ("{0}.browser.{1}", name, top ? "top" : "left");
else
return String.Format ("{0}.browser.{1}.{2}", name, top ? "top" : "left", filter);
}
private Paned GetPane (bool hpane)
{
if (hpane)
return new HPaned ();
else
return new VPaned ();
}
private void ShowPack ()
{
PackStart (container, true, true, 0);
NoShowAll = false;
ShowAll ();
NoShowAll = true;
browser_container.Visible = ForcePosition != null || BrowserVisible.Get ();
}
private void OnViewModeChanged (object o, ChangedArgs args)
{
//Hyena.Log.InformationFormat ("ListBrowser mode toggled, val = {0}", args.Current.Value);
if (args.Current.Value == 0) {
LayoutLeft ();
BrowserPosition.Set ("left");
} else {
LayoutTop ();
BrowserPosition.Set ("top");
}
}
private void OnToggleBrowser (object o, EventArgs args)
{
ToggleAction action = (ToggleAction)o;
browser_container.Visible = action.Active && ActiveSourceCanHasBrowser;
BrowserVisible.Set (action.Active);
if (!browser_container.Visible) {
ClearFilterSelections ();
}
}
protected abstract void ClearFilterSelections ();
protected virtual void OnBrowserViewSelectionChanged (object o, EventArgs args)
{
// If the All item is now selected, scroll to the top
Hyena.Collections.Selection selection = (Hyena.Collections.Selection) o;
if (selection.AllSelected) {
// Find the view associated with this selection; a bit yuck; pass view in args?
foreach (IListView view in filter_views) {
if (view.Selection == selection) {
view.ScrollTo (0);
break;
}
}
}
}
protected void SetModel<T> (IListModel<T> model)
{
ListView<T> view = FindListView <T> ();
if (view != null) {
SetModel (view, model);
} else {
Hyena.Log.DebugFormat ("Unable to find view for model {0}", model);
}
}
protected void SetModel<T> (ListView<T> view, IListModel<T> model)
{
if (view.Model != null) {
model_positions[view.Model] = view.Vadjustment.Value;
}
if (model == null) {
view.SetModel (null);
return;
}
if (!model_positions.ContainsKey (model)) {
model_positions[model] = 0.0;
}
view.SetModel (model, model_positions[model]);
}
private ListView<T> FindListView<T> ()
{
if (main_view is ListView<T>)
return (ListView<T>) main_view;
foreach (object view in filter_views)
if (view is ListView<T>)
return (ListView<T>) view;
return null;
}
protected virtual string ForcePosition {
get { return null; }
}
protected abstract bool ActiveSourceCanHasBrowser { get; }
#region Implement ISourceContents
protected ISource source;
public abstract bool SetSource (ISource source);
public abstract void ResetSource ();
public ISource Source {
get { return source; }
}
public Widget Widget {
get { return this; }
}
#endregion
public static readonly SchemaEntry<bool> BrowserVisible = new SchemaEntry<bool> (
"browser", "visible",
true,
"Artist/Album Browser Visibility",
"Whether or not to show the Artist/Album browser"
);
public static readonly SchemaEntry<string> BrowserPosition = new SchemaEntry<string> (
"browser", "position",
"left",
"Artist/Album Browser Position",
"The position of the Artist/Album browser; either 'top' or 'left'"
);
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace MyDynamicDisplayApp
{
partial class MainForm
{
/// <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)
{
//Ensures that any ESRI libraries that have been used are unloaded in the correct order.
//Failure to do this may result in random crashes on exit due to the operating system unloading
//the libraries in the incorrect order.
ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown();
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(MainForm));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.menuFile = new System.Windows.Forms.ToolStripMenuItem();
this.menuNewDoc = new System.Windows.Forms.ToolStripMenuItem();
this.menuOpenDoc = new System.Windows.Forms.ToolStripMenuItem();
this.menuSaveDoc = new System.Windows.Forms.ToolStripMenuItem();
this.menuSaveAs = new System.Windows.Forms.ToolStripMenuItem();
this.menuSeparator = new System.Windows.Forms.ToolStripSeparator();
this.menuExitApp = new System.Windows.Forms.ToolStripMenuItem();
this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl();
this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl();
this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl();
this.splitter1 = new System.Windows.Forms.Splitter();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.statusBarXY = new System.Windows.Forms.ToolStripStatusLabel();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuFile});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(859, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// menuFile
//
this.menuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuNewDoc,
this.menuOpenDoc,
this.menuSaveDoc,
this.menuSaveAs,
this.menuSeparator,
this.menuExitApp});
this.menuFile.Name = "menuFile";
this.menuFile.Size = new System.Drawing.Size(37, 20);
this.menuFile.Text = "File";
//
// menuNewDoc
//
this.menuNewDoc.Image = ((System.Drawing.Image)(resources.GetObject("menuNewDoc.Image")));
this.menuNewDoc.ImageTransparentColor = System.Drawing.Color.White;
this.menuNewDoc.Name = "menuNewDoc";
this.menuNewDoc.Size = new System.Drawing.Size(171, 22);
this.menuNewDoc.Text = "New Document";
this.menuNewDoc.Click += new System.EventHandler(this.menuNewDoc_Click);
//
// menuOpenDoc
//
this.menuOpenDoc.Image = ((System.Drawing.Image)(resources.GetObject("menuOpenDoc.Image")));
this.menuOpenDoc.ImageTransparentColor = System.Drawing.Color.White;
this.menuOpenDoc.Name = "menuOpenDoc";
this.menuOpenDoc.Size = new System.Drawing.Size(171, 22);
this.menuOpenDoc.Text = "Open Document...";
this.menuOpenDoc.Click += new System.EventHandler(this.menuOpenDoc_Click);
//
// menuSaveDoc
//
this.menuSaveDoc.Image = ((System.Drawing.Image)(resources.GetObject("menuSaveDoc.Image")));
this.menuSaveDoc.ImageTransparentColor = System.Drawing.Color.White;
this.menuSaveDoc.Name = "menuSaveDoc";
this.menuSaveDoc.Size = new System.Drawing.Size(171, 22);
this.menuSaveDoc.Text = "SaveDocument";
this.menuSaveDoc.Click += new System.EventHandler(this.menuSaveDoc_Click);
//
// menuSaveAs
//
this.menuSaveAs.Name = "menuSaveAs";
this.menuSaveAs.Size = new System.Drawing.Size(171, 22);
this.menuSaveAs.Text = "Save As...";
this.menuSaveAs.Click += new System.EventHandler(this.menuSaveAs_Click);
//
// menuSeparator
//
this.menuSeparator.Name = "menuSeparator";
this.menuSeparator.Size = new System.Drawing.Size(168, 6);
//
// menuExitApp
//
this.menuExitApp.Name = "menuExitApp";
this.menuExitApp.Size = new System.Drawing.Size(171, 22);
this.menuExitApp.Text = "Exit";
this.menuExitApp.Click += new System.EventHandler(this.menuExitApp_Click);
//
// axMapControl1
//
this.axMapControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axMapControl1.Location = new System.Drawing.Point(238, 52);
this.axMapControl1.Name = "axMapControl1";
this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState")));
this.axMapControl1.Size = new System.Drawing.Size(621, 512);
this.axMapControl1.TabIndex = 2;
this.axMapControl1.OnMapReplaced += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMapReplacedEventHandler(this.axMapControl1_OnMapReplaced);
this.axMapControl1.OnMouseMove += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMouseMoveEventHandler(this.axMapControl1_OnMouseMove);
//
// axToolbarControl1
//
this.axToolbarControl1.Dock = System.Windows.Forms.DockStyle.Top;
this.axToolbarControl1.Location = new System.Drawing.Point(0, 24);
this.axToolbarControl1.Name = "axToolbarControl1";
this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState")));
this.axToolbarControl1.Size = new System.Drawing.Size(859, 28);
this.axToolbarControl1.TabIndex = 3;
//
// axTOCControl1
//
this.axTOCControl1.Dock = System.Windows.Forms.DockStyle.Left;
this.axTOCControl1.Location = new System.Drawing.Point(3, 52);
this.axTOCControl1.Name = "axTOCControl1";
this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState")));
this.axTOCControl1.Size = new System.Drawing.Size(235, 512);
this.axTOCControl1.TabIndex = 4;
//
// axLicenseControl1
//
this.axLicenseControl1.Enabled = true;
this.axLicenseControl1.Location = new System.Drawing.Point(466, 278);
this.axLicenseControl1.Name = "axLicenseControl1";
this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState")));
this.axLicenseControl1.Size = new System.Drawing.Size(32, 32);
this.axLicenseControl1.TabIndex = 5;
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(0, 52);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(3, 534);
this.splitter1.TabIndex = 6;
this.splitter1.TabStop = false;
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusBarXY});
this.statusStrip1.Location = new System.Drawing.Point(3, 564);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(856, 22);
this.statusStrip1.Stretch = false;
this.statusStrip1.TabIndex = 7;
this.statusStrip1.Text = "statusBar1";
//
// statusBarXY
//
this.statusBarXY.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter;
this.statusBarXY.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.statusBarXY.Name = "statusBarXY";
this.statusBarXY.Size = new System.Drawing.Size(50, 17);
this.statusBarXY.Text = "Test 123";
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(859, 586);
this.Controls.Add(this.axLicenseControl1);
this.Controls.Add(this.axMapControl1);
this.Controls.Add(this.axTOCControl1);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.axToolbarControl1);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Name = "MainForm";
this.Text = "ArcEngine Controls Application";
this.Load += new System.EventHandler(this.MainForm_Load);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem menuFile;
private System.Windows.Forms.ToolStripMenuItem menuNewDoc;
private System.Windows.Forms.ToolStripMenuItem menuOpenDoc;
private System.Windows.Forms.ToolStripMenuItem menuSaveDoc;
private System.Windows.Forms.ToolStripMenuItem menuSaveAs;
private System.Windows.Forms.ToolStripMenuItem menuExitApp;
private System.Windows.Forms.ToolStripSeparator menuSeparator;
private ESRI.ArcGIS.Controls.AxMapControl axMapControl1;
private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1;
private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1;
private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel statusBarXY;
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from http://geoframework.codeplex.com/ version 2.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0
// | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace DotSpatial.Positioning
{
/// <summary>
/// Represents a measurement of an object's rate of travel in a particular direction.
/// </summary>
/// <remarks>Instances of this class are guaranteed to be thread-safe because the class is
/// immutable (its properties can only be changed via constructors).</remarks>
public struct Velocity : IFormattable, IEquatable<Velocity>, ICloneable<Velocity>, IXmlSerializable
{
/// <summary>
///
/// </summary>
private Speed _speed;
/// <summary>
///
/// </summary>
private Azimuth _bearing;
#region Fields
/// <summary>
/// Represents a velocity with no speed or direction.
/// </summary>
public static readonly Velocity Empty = new Velocity(Speed.Empty, Azimuth.Empty);
/// <summary>
/// Represents a velocity with an invalid or unspecified speed and direction.
/// </summary>
public static readonly Velocity Invalid = new Velocity(Speed.Invalid, Azimuth.Invalid);
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Velocity"/> struct.
/// </summary>
/// <param name="speed">The speed.</param>
/// <param name="bearing">The bearing.</param>
public Velocity(Speed speed, Azimuth bearing)
{
_speed = speed;
_bearing = bearing;
}
/// <summary>
/// Initializes a new instance of the <see cref="Velocity"/> struct.
/// </summary>
/// <param name="speed">The speed.</param>
/// <param name="bearingDegrees">The bearing degrees.</param>
public Velocity(Speed speed, double bearingDegrees)
{
_speed = speed;
_bearing = new Azimuth(bearingDegrees);
}
/// <summary>
/// Initializes a new instance of the <see cref="Velocity"/> struct.
/// </summary>
/// <param name="speed">The speed.</param>
/// <param name="speedUnits">The speed units.</param>
/// <param name="bearing">The bearing.</param>
public Velocity(double speed, SpeedUnit speedUnits, Azimuth bearing)
{
_speed = new Speed(speed, speedUnits);
_bearing = bearing;
}
/// <summary>
/// Initializes a new instance of the <see cref="Velocity"/> struct.
/// </summary>
/// <param name="speed">The speed.</param>
/// <param name="speedUnits">The speed units.</param>
/// <param name="bearingDegrees">The bearing degrees.</param>
public Velocity(double speed, SpeedUnit speedUnits, double bearingDegrees)
{
_speed = new Speed(speed, speedUnits);
_bearing = new Azimuth(bearingDegrees);
}
/// <summary>
/// Creates a new instance by parsing speed and bearing from the specified strings.
/// </summary>
/// <param name="speed">The speed.</param>
/// <param name="bearing">The bearing.</param>
public Velocity(string speed, string bearing)
: this(speed, bearing, CultureInfo.CurrentCulture)
{ }
/// <summary>
/// Creates a new instance by converting the specified strings using the specific culture.
/// </summary>
/// <param name="speed">The speed.</param>
/// <param name="bearing">The bearing.</param>
/// <param name="culture">The culture.</param>
public Velocity(string speed, string bearing, CultureInfo culture)
{
_speed = new Speed(speed, culture);
_bearing = new Azimuth(bearing, culture);
}
/// <summary>
/// Initializes a new instance of the <see cref="Velocity"/> struct.
/// </summary>
/// <param name="reader">The reader.</param>
public Velocity(XmlReader reader)
{
// Initialize all fields
_speed = Speed.Invalid;
_bearing = Azimuth.Invalid;
// Deserialize the object from XML
ReadXml(reader);
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Gets the objects rate of travel.
/// </summary>
public Speed Speed
{
get { return _speed; }
}
/// <summary>
/// Gets the objects direction of travel.
/// </summary>
public Azimuth Bearing
{
get { return _bearing; }
}
/// <summary>
/// Indicates whether the speed and bearing are both zero.
/// </summary>
public bool IsEmpty
{
get
{
return _speed.IsEmpty && _bearing.IsEmpty;
}
}
/// <summary>
/// Indicates whether the speed or bearing is invalid or unspecified.
/// </summary>
public bool IsInvalid
{
get
{
return _speed.IsInvalid || _bearing.IsInvalid;
}
}
#endregion Public Properties
#region Operators
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(Velocity left, Velocity right)
{
return left.Equals(right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(Velocity left, Velocity right)
{
return !left.Equals(right);
}
#endregion Operators
#region Overrides
/// <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 _speed.GetHashCode() ^ _bearing.GetHashCode();
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">Another object to compare to.</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)
{
if (obj is Velocity)
return Equals((Velocity)obj);
return false;
}
/// <summary>
/// Outputs the current instance as a string using the default format.
/// </summary>
/// <returns>A <strong>String</strong> representing the current instance.</returns>
public override string ToString()
{
return ToString("g", CultureInfo.CurrentCulture);
}
#endregion Overrides
#region IEquatable<Velocity>
/// <summary>
/// Compares the current instance to the specified velocity.
/// </summary>
/// <param name="other">A <strong>Velocity</strong> object to compare with.</param>
/// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns>
public bool Equals(Velocity other)
{
return _speed.Equals(other.Speed)
&& _bearing.Equals(other.Bearing);
}
/// <summary>
/// Compares the current instance to the specified velocity using the specified numeric precision.
/// </summary>
/// <param name="other">A <strong>Velocity</strong> object to compare with.</param>
/// <param name="decimals">An <strong>Integer</strong> specifying the number of fractional digits to compare.</param>
/// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns>
public bool Equals(Velocity other, int decimals)
{
return _speed.Equals(other.Speed, decimals)
&& _bearing.Equals(other.Bearing, decimals);
}
#endregion IEquatable<Velocity>
#region IFormattable Members
/// <summary>
/// Outputs the current instance as a string using the specified format and culture information.
/// </summary>
/// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param>
/// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
CultureInfo culture = (CultureInfo)formatProvider ?? CultureInfo.CurrentCulture;
if (string.IsNullOrEmpty(format)) format = "G";
// Output as speed and bearing
return _speed.ToString(format, culture)
+ " "
+ _bearing.ToString(format, culture);
}
#endregion IFormattable Members
#region IXmlSerializable Members
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.</returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("Speed");
_speed.WriteXml(writer);
writer.WriteEndElement();
writer.WriteStartElement("Bearing");
_bearing.WriteXml(writer);
writer.WriteEndElement();
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
public void ReadXml(XmlReader reader)
{
// Move to the <Speed> element
if (!reader.IsStartElement("Speed"))
reader.ReadToDescendant("Speed");
_speed.ReadXml(reader);
_bearing.ReadXml(reader);
reader.Read();
}
#endregion IXmlSerializable Members
#region ICloneable<Velocity> Members
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public Velocity Clone()
{
return new Velocity(_speed, _bearing);
}
#endregion ICloneable<Velocity> Members
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export(typeof(MiscellaneousFilesWorkspace))]
internal sealed partial class MiscellaneousFilesWorkspace : Workspace, IVsRunningDocTableEvents2, IVisualStudioHostProjectContainer
{
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
private readonly IMetadataAsSourceFileService _fileTrackingMetadataAsSourceService;
private readonly IVsRunningDocumentTable4 _runningDocumentTable;
private readonly IVsTextManager _textManager;
private readonly RoslynDocumentProvider _documentProvider;
private readonly Dictionary<Guid, LanguageInformation> _languageInformationByLanguageGuid = new Dictionary<Guid, LanguageInformation>();
/// <summary>
/// <see cref="WorkspaceRegistration"/> instances for all open buffers being tracked by by this object
/// for possible inclusion into this workspace.
/// </summary>
private IBidirectionalMap<uint, WorkspaceRegistration> _docCookieToWorkspaceRegistration = BidirectionalMap<uint, WorkspaceRegistration>.Empty;
private readonly Dictionary<ProjectId, HostProject> _hostProjects = new Dictionary<ProjectId, HostProject>();
private readonly Dictionary<uint, HostProject> _docCookiesToHostProject = new Dictionary<uint, HostProject>();
private readonly ImmutableArray<MetadataReference> _metadataReferences;
private uint _runningDocumentTableEventsCookie;
[ImportingConstructor]
public MiscellaneousFilesWorkspace(
IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
IMetadataAsSourceFileService fileTrackingMetadataAsSourceService,
SaveEventsService saveEventsService,
VisualStudioWorkspace visualStudioWorkspace,
SVsServiceProvider serviceProvider) :
base(visualStudioWorkspace.Services.HostServices, WorkspaceKind.MiscellaneousFiles)
{
_editorAdaptersFactoryService = editorAdaptersFactoryService;
_fileTrackingMetadataAsSourceService = fileTrackingMetadataAsSourceService;
_runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
_textManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));
((IVsRunningDocumentTable)_runningDocumentTable).AdviseRunningDocTableEvents(this, out _runningDocumentTableEventsCookie);
_metadataReferences = ImmutableArray.CreateRange(CreateMetadataReferences());
_documentProvider = new RoslynDocumentProvider(this, serviceProvider);
saveEventsService.StartSendingSaveEvents();
}
public void RegisterLanguage(Guid languageGuid, string languageName, string scriptExtension, ParseOptions parseOptions)
{
_languageInformationByLanguageGuid.Add(languageGuid, new LanguageInformation(languageName, scriptExtension, parseOptions));
}
internal void StartSolutionCrawler()
{
DiagnosticProvider.Enable(this, DiagnosticProvider.Options.Syntax);
}
internal void StopSolutionCrawler()
{
DiagnosticProvider.Disable(this);
}
private LanguageInformation TryGetLanguageInformation(string filename)
{
Guid fileLanguageGuid;
LanguageInformation languageInformation = null;
if (ErrorHandler.Succeeded(_textManager.MapFilenameToLanguageSID(filename, out fileLanguageGuid)))
{
_languageInformationByLanguageGuid.TryGetValue(fileLanguageGuid, out languageInformation);
}
return languageInformation;
}
private IEnumerable<MetadataReference> CreateMetadataReferences()
{
var manager = this.Services.GetService<VisualStudioMetadataReferenceManager>();
var searchPaths = ReferencePathUtilities.GetReferencePaths();
return from fileName in new[] { "mscorlib.dll", "System.dll", "System.Core.dll" }
let fullPath = FileUtilities.ResolveRelativePath(fileName, basePath: null, baseDirectory: null, searchPaths: searchPaths, fileExists: File.Exists)
where fullPath != null
select manager.CreateMetadataReferenceSnapshot(fullPath, MetadataReferenceProperties.Assembly);
}
public int OnAfterAttributeChange(uint docCookie, uint grfAttribs)
{
return VSConstants.S_OK;
}
public int OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
// Did we rename?
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_MkDocument) != 0)
{
// We want to consider this file to be added in one of two situations:
//
// 1) the old file already was a misc file, at which point we might just be doing a rename from
// one name to another with the same extension
// 2) the old file was a different extension that we weren't tracking, which may have now changed
if (TryUntrackClosingDocument(docCookie, pszMkDocumentOld) || TryGetLanguageInformation(pszMkDocumentOld) == null)
{
// Add the new one, if appropriate.
TrackOpenedDocument(docCookie, pszMkDocumentNew);
}
}
// When starting a diff, the RDT doesn't call OnBeforeDocumentWindowShow, but it does call
// OnAfterAttributeChangeEx for the temporary buffer. The native IDE used this even to
// add misc files, so we'll do the same.
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) != 0)
{
var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
if (moniker != null && TryGetLanguageInformation(moniker) != null && !_docCookiesToHostProject.ContainsKey(docCookie))
{
TrackOpenedDocument(docCookie, moniker);
}
}
if ((grfAttribs & (uint)__VSRDTATTRIB3.RDTA_DocumentInitialized) != 0)
{
// The document is now initialized, we should try tracking it
TrackOpenedDocument(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
}
return VSConstants.S_OK;
}
public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterSave(uint docCookie)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
if (dwReadLocksRemaining + dwEditLocksRemaining == 0)
{
TryUntrackClosingDocument(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
}
return VSConstants.S_OK;
}
private void TrackOpenedDocument(uint docCookie, string moniker)
{
var languageInformation = TryGetLanguageInformation(moniker);
if (languageInformation == null)
{
// We can never put this document in a workspace, so just bail
return;
}
// We don't want to realize the document here unless it's already initialized. Document initialization is watched in
// OnAfterAttributeChangeEx and will retrigger this if it wasn't already done.
if (_runningDocumentTable.IsDocumentInitialized(docCookie) && !_docCookieToWorkspaceRegistration.ContainsKey(docCookie))
{
var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);
// As long as the buffer is initialized, then we should see if we should attach
if (textBuffer != null)
{
var registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer());
registration.WorkspaceChanged += Registration_WorkspaceChanged;
_docCookieToWorkspaceRegistration = _docCookieToWorkspaceRegistration.Add(docCookie, registration);
if (!IsClaimedByAnotherWorkspace(registration))
{
AttachToDocument(docCookie, moniker);
}
}
}
}
private void Registration_WorkspaceChanged(object sender, EventArgs e)
{
var workspaceRegistration = (WorkspaceRegistration)sender;
uint docCookie;
// external workspace that listens to events from IVSRunningDocumentTable4 (just like MiscellaneousFilesWorkspace does) and registers the text buffer for opened document prior to Miscellaneous workspace getting notified of the docCookie - the prior contract assumes that MiscellaneousFilesWorkspace is always the first one to get notified
if (!_docCookieToWorkspaceRegistration.TryGetKey(workspaceRegistration, out docCookie))
{
// We haven't even started tracking the document corresponding to this registration - likely because some external workspace registered the document's buffer prior to MiscellaneousWorkspace getting notified of it.
// Just bail out for now, we will eventually receive the opened document notification and track its docCookie registration.
return;
}
var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
if (workspaceRegistration.Workspace == null)
{
HostProject hostProject;
if (_docCookiesToHostProject.TryGetValue(docCookie, out hostProject))
{
// The workspace was taken from us and released and we have only asynchronously found out now.
var document = hostProject.Document;
if (document.IsOpen)
{
RegisterText(document.GetOpenTextContainer());
}
}
else
{
// We should now claim this
AttachToDocument(docCookie, moniker);
}
}
else if (IsClaimedByAnotherWorkspace(workspaceRegistration))
{
// It's now claimed by another workspace, so we should unclaim it
if (_docCookiesToHostProject.ContainsKey(docCookie))
{
DetachFromDocument(docCookie, moniker);
}
}
}
/// <summary>
/// Stops tracking a document in the RDT for whether we should attach to it.
/// </summary>
/// <returns>true if we were previously tracking it.</returns>
private bool TryUntrackClosingDocument(uint docCookie, string moniker)
{
bool unregisteredRegistration = false;
// Remove our registration changing handler before we call DetachFromDocument. Otherwise, calling DetachFromDocument
// causes us to set the workspace to null, which we then respond to as an indication that we should
// attach again.
WorkspaceRegistration registration;
if (_docCookieToWorkspaceRegistration.TryGetValue(docCookie, out registration))
{
registration.WorkspaceChanged -= Registration_WorkspaceChanged;
_docCookieToWorkspaceRegistration = _docCookieToWorkspaceRegistration.RemoveKey(docCookie);
unregisteredRegistration = true;
}
DetachFromDocument(docCookie, moniker);
return unregisteredRegistration;
}
private bool IsClaimedByAnotherWorkspace(WorkspaceRegistration registration)
{
// Currently, we are also responsible for pushing documents to the metadata as source workspace,
// so we count that here as well
return registration.Workspace != null && registration.Workspace.Kind != WorkspaceKind.MetadataAsSource && registration.Workspace.Kind != WorkspaceKind.MiscellaneousFiles;
}
private void AttachToDocument(uint docCookie, string moniker)
{
var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);
if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
{
// We already added it, so we will keep it excluded from the misc files workspace
return;
}
// This should always succeed since we only got here if we already confirmed the moniker is acceptable
var languageInformation = TryGetLanguageInformation(moniker);
Contract.ThrowIfNull(languageInformation);
var parseOptions = languageInformation.ParseOptions;
if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
{
parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
}
// First, create the project
var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);
// Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
var document = _documentProvider.TryGetDocumentForFile(
hostProject,
ImmutableArray<string>.Empty,
moniker,
parseOptions.Kind,
canUseTextBuffer: _ => true);
// If the buffer has not yet been initialized, we won't get a document.
if (document == null)
{
return;
}
// Since we have a document, we can do the rest of the project setup.
_hostProjects.Add(hostProject.Id, hostProject);
OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());
OnDocumentAdded(document.GetInitialState());
hostProject.Document = document;
// Notify the document provider, so it knows the document is now open and a part of
// the project
_documentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document);
Contract.ThrowIfFalse(document.IsOpen);
var buffer = document.GetOpenTextBuffer();
OnDocumentOpened(document.Id, document.GetOpenTextContainer());
_docCookiesToHostProject.Add(docCookie, hostProject);
}
private void DetachFromDocument(uint docCookie, string moniker)
{
HostProject hostProject;
if (_fileTrackingMetadataAsSourceService.TryRemoveDocumentFromWorkspace(moniker))
{
return;
}
if (_docCookiesToHostProject.TryGetValue(docCookie, out hostProject))
{
var document = hostProject.Document;
OnDocumentClosed(document.Id, document.Loader);
OnDocumentRemoved(document.Id);
OnProjectRemoved(hostProject.Id);
_hostProjects.Remove(hostProject.Id);
_docCookiesToHostProject.Remove(docCookie);
document.Dispose();
return;
}
}
protected override void Dispose(bool finalize)
{
StopSolutionCrawler();
var runningDocumentTableForEvents = (IVsRunningDocumentTable)_runningDocumentTable;
runningDocumentTableForEvents.UnadviseRunningDocTableEvents(_runningDocumentTableEventsCookie);
_runningDocumentTableEventsCookie = 0;
base.Dispose(finalize);
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.ChangeDocument:
return true;
default:
return false;
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
var hostDocument = this.GetDocument(documentId);
hostDocument.UpdateText(newText);
}
private HostProject GetHostProject(ProjectId id)
{
HostProject project;
_hostProjects.TryGetValue(id, out project);
return project;
}
internal IVisualStudioHostDocument GetDocument(DocumentId id)
{
var project = GetHostProject(id.ProjectId);
if (project != null && project.Document.Id == id)
{
return project.Document;
}
return null;
}
IReadOnlyList<IVisualStudioHostProject> IVisualStudioHostProjectContainer.GetProjects()
{
return _hostProjects.Values.ToImmutableReadOnlyListOrEmpty<IVisualStudioHostProject>();
}
void IVisualStudioHostProjectContainer.NotifyNonDocumentOpenedForProject(IVisualStudioHostProject project)
{
// Since the MiscellaneousFilesWorkspace doesn't do anything lazily, this is a no-op
}
private class LanguageInformation
{
public LanguageInformation(string languageName, string scriptExtension, ParseOptions parseOptions)
{
this.LanguageName = languageName;
this.ScriptExtension = scriptExtension;
this.ParseOptions = parseOptions;
}
public string LanguageName { get; }
public string ScriptExtension { get; }
public ParseOptions ParseOptions { get; }
}
}
}
| |
#pragma warning disable 0168
using nHydrate.Generator.Common.Util;
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace nHydrate.DataImport.SqlClient
{
public class SchemaModelHelper
{
#region Public Methods
public bool IsValidConnectionString(string connectionString)
{
var valid = false;
var conn = new System.Data.SqlClient.SqlConnection();
try
{
conn.ConnectionString = connectionString;
conn.Open();
valid = true;
}
catch (Exception ex)
{
valid = false;
}
finally
{
conn.Close();
}
return valid;
}
#endregion
internal static string GetSqlDatabaseTables()
{
var sb = new StringBuilder();
sb.AppendLine("DECLARE @bar varchar(150)");
sb.AppendLine("DECLARE @val varchar(150)");
sb.AppendLine("DECLARE @tab table");
sb.AppendLine("(");
sb.AppendLine("xName varchar(150) NOT NULL,");
sb.AppendLine("xValue varchar(150) NULL,");
sb.AppendLine("xSchema varchar(150) NOT NULL");
sb.AppendLine(")");
sb.AppendLine("INSERT INTO @tab SELECT so.name, null, sc.name [schema] FROM sys.tables so INNER JOIN sys.schemas sc ON so.schema_id = sc.schema_id WHERE so.name <> 'dtproperties' AND (so.name <> 'sysdiagrams') AND (so.name <> '__nhydrateschema')AND (so.name <> '__nhydrateobjects') AND NOT (so.name like '__AUDIT__%')");
sb.AppendLine("select xName as name, xSchema as [schema], xValue selectionCriteria from @tab WHERE xName <> 'dtproperties' ORDER BY xName");
return sb.ToString();
}
internal static string GetSqlColumnsForTable()
{
return GetSqlColumnsForTable(null);
}
internal static string GetSqlForUniqueConstraints()
{
var sb = new StringBuilder();
sb.AppendLine("select o.name as TableName, col.name as ColumnName");
sb.AppendLine("from sys.indexes i inner join sys.objects o on i.object_id = o.object_id ");
sb.AppendLine(" inner join sys.index_columns ic on i.index_id = ic.index_id and ic.object_id = o.object_id");
sb.AppendLine(" INNER JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id");
sb.AppendLine("where i.is_unique = 1 and is_primary_key = 0 and is_unique_constraint = 1");
return sb.ToString();
}
internal static string GetSqlForIndexes()
{
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine("SELECT ");
sb.AppendLine(" ind.name as indexname");
sb.AppendLine(" ,ind.is_primary_key");
sb.AppendLine(" --,ind.index_id ");
sb.AppendLine(" --,ic.index_column_id ");
sb.AppendLine(" ,t.name as tablename");
sb.AppendLine(" ,col.name as columnname");
sb.AppendLine(" ,ic.is_descending_key");
sb.AppendLine(" ,ic.key_ordinal");
sb.AppendLine(" ,ind.type_desc");
sb.AppendLine(" ,ind.is_unique_constraint");
sb.AppendLine(" ,ind.is_primary_key");
sb.AppendLine(" --,ic.* ");
sb.AppendLine(" --,col.* ");
sb.AppendLine(" --,ind.* ");
sb.AppendLine("FROM sys.indexes ind ");
sb.AppendLine("INNER JOIN sys.index_columns ic ");
sb.AppendLine(" ON ind.object_id = ic.object_id and ind.index_id = ic.index_id ");
sb.AppendLine("INNER JOIN sys.columns col ");
sb.AppendLine(" ON ic.object_id = col.object_id and ic.column_id = col.column_id ");
sb.AppendLine("INNER JOIN sys.tables t ");
sb.AppendLine(" ON ind.object_id = t.object_id ");
sb.AppendLine("WHERE (1=1) ");
//sb.AppendLine(" AND ind.is_primary_key = 0 ");
//sb.AppendLine(" AND ind.is_unique = 0 ");
//sb.AppendLine(" AND ind.is_unique_constraint = 0 ");
sb.AppendLine(" AND t.is_ms_shipped = 0 ");
sb.AppendLine(" AND ic.key_ordinal <> 0");
sb.AppendLine("ORDER BY ");
sb.AppendLine(" ind.name, ic.key_ordinal");
return sb.ToString();
}
internal static string GetSqlColumnsForComputed()
{
var sb = new StringBuilder();
sb.AppendLine("select o.name as tablename, c.name as columnname, c.definition");
sb.AppendLine("from sys.computed_columns c inner join sys.objects o on c.object_id = o.object_id");
return sb.ToString();
}
internal static string GetSqlColumnsForTable(string tableName)
{
var sb = new StringBuilder();
sb.AppendLine("SELECT");
sb.AppendLine(" c.ORDINAL_POSITION as colorder,");
sb.AppendLine(" c.TABLE_NAME as tablename,");
sb.AppendLine(" c.COLUMN_NAME as columnname,");
sb.AppendLine("(");
sb.AppendLine("select top 1 c1.name");
sb.AppendLine("from sys.indexes i");
sb.AppendLine("join sys.objects o ON i.object_id = o.object_id");
sb.AppendLine("join sys.objects pk ON i.name = pk.name");
sb.AppendLine("AND pk.parent_object_id = i.object_id");
sb.AppendLine("AND pk.type = 'PK'");
sb.AppendLine("join sys.index_columns ik on i.object_id = ik.object_id");
sb.AppendLine("and i.index_id = ik.index_id");
sb.AppendLine("join sys.columns c1 ON ik.object_id = c1.object_id");
sb.AppendLine("AND ik.column_id = c1.column_id");
sb.AppendLine("AND c1.name = c.COLUMN_NAME");
sb.AppendLine("where o.name = c.TABLE_NAME");
sb.AppendLine(") as [isPrimaryKey],");
sb.AppendLine(" case WHEN");
sb.AppendLine(" (");
sb.AppendLine(" SELECT ");
sb.AppendLine(" count(*) ");
sb.AppendLine(" FROM ");
sb.AppendLine(" INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE foreignkeyccu");
sb.AppendLine(" INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS foreignkeytc on foreignkeyccu.CONSTRAINT_NAME = foreignkeytc.CONSTRAINT_NAME AND");
sb.AppendLine(" foreignkeyccu.CONSTRAINT_SCHEMA = foreignkeytc.CONSTRAINT_SCHEMA AND");
sb.AppendLine(" foreignkeytc.CONSTRAINT_TYPE = 'FOREIGN KEY'");
sb.AppendLine(" WHERE");
sb.AppendLine(" foreignkeyccu.TABLE_SCHEMA = c.TABLE_SCHEMA AND");
sb.AppendLine(" foreignkeyccu.TABLE_NAME = c.TABLE_NAME AND");
sb.AppendLine(" foreignkeyccu.COLUMN_NAME = c.COLUMN_NAME ");
sb.AppendLine(" ) > 0 THEN 'true' ELSE 'false' END as isForeignKey,");
sb.AppendLine(" c.DATA_TYPE as datatype,");
sb.AppendLine(" s.system_type_id,");
sb.AppendLine(" c.numeric_precision AS [precision], c.numeric_scale AS [scale],");
sb.AppendLine(" case when c.CHARACTER_MAXIMUM_LENGTH is null or c.CHARACTER_MAXIMUM_LENGTH > 8000 then s.max_length else c.CHARACTER_MAXIMUM_LENGTH end as max_length,");
sb.AppendLine(" case when c.IS_NULLABLE = 'No' then 0 else 1 end as allow_null, ");
sb.AppendLine(" case when c.COLUMN_DEFAULT is null then '' else c.COLUMN_DEFAULT end as default_value,");
sb.AppendLine(" case when COLUMNPROPERTY(OBJECT_ID(c.TABLE_SCHEMA+'.'+c.TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 then 1 else 0 end as is_identity,");
sb.AppendLine(" c.COLLATION_NAME AS collation");
sb.AppendLine(" FROM ");
sb.AppendLine(" INFORMATION_SCHEMA.COLUMNS c ");
sb.AppendLine(" INNER JOIN sys.types s on s.name = c.DATA_TYPE");
if (!tableName.IsEmpty())
sb.AppendLine($" WHERE c.TABLE_NAME = '{tableName}'");
sb.AppendLine(" ORDER BY");
sb.AppendLine(" c.TABLE_NAME,");
sb.AppendLine(" c.ORDINAL_POSITION");
return sb.ToString();
}
internal static string GetSqlForRelationships()
{
var sb = new StringBuilder();
sb.AppendLine("SELECT ");
sb.AppendLine(" KCU1.CONSTRAINT_NAME AS 'FK_CONSTRAINT_NAME'");
sb.AppendLine(" , KCU1.TABLE_NAME AS 'FK_TABLE_NAME'");
sb.AppendLine(" , KCU1.COLUMN_NAME AS 'FK_COLUMN_NAME' ");
sb.AppendLine(" , KCU2.TABLE_NAME AS 'UQ_TABLE_NAME'");
sb.AppendLine(" , KCU2.COLUMN_NAME AS 'UQ_COLUMN_NAME'");
sb.AppendLine(" , so.object_id");
sb.AppendLine("FROM ");
sb.AppendLine(" INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC");
sb.AppendLine(" JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1");
sb.AppendLine(" ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG ");
sb.AppendLine(" AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA");
sb.AppendLine(" AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME");
sb.AppendLine("JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2");
sb.AppendLine(" ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG ");
sb.AppendLine(" AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA");
sb.AppendLine(" AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME");
sb.AppendLine(" AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION");
sb.AppendLine("JOIN sys.objects so");
sb.AppendLine(" ON KCU1.CONSTRAINT_NAME = so.name");
sb.AppendLine("WHERE");
sb.AppendLine(" so.type = 'F'");
sb.AppendLine("ORDER BY");
sb.AppendLine(" KCU1.CONSTRAINT_NAME,");
sb.AppendLine(" KCU1.ORDINAL_POSITION");
return sb.ToString();
}
internal static string GetSqlIndexesForTable()
{
var sb = new StringBuilder();
sb.AppendLine("select t.name as tablename, i.name as indexname, c.name as columnname, i.is_primary_key");
sb.AppendLine("from sys.tables t");
sb.AppendLine("inner join sys.indexes i on i.object_id = t.object_id");
sb.AppendLine("inner join sys.index_columns ic on ic.object_id = t.object_id");
sb.AppendLine("inner join sys.columns c on c.object_id = t.object_id and");
sb.AppendLine("ic.column_id = c.column_id");
//sb.AppendLine("select o.name as tablename, i.name as indexname, i.is_primary_key from sys.objects o inner join sys.indexes i on o.object_id = i.object_id where o.[type] = 'U'");
return sb.ToString();
}
internal static string GetSqlForViews()
{
var sb = new StringBuilder();
sb.AppendLine("select s.name as schemaname, v.name, m.definition from sys.views v inner join sys.sql_modules m on v.object_id = m.object_id inner join sys.schemas s on s.schema_id= v.schema_id");
return sb.ToString();
}
internal static string GetViewBody(string sql)
{
var regEx = new Regex(@"CREATE VIEW[\r\n\s]*[a-zA-Z0-9\[\]_\.]*[\r\n\s]*AS[\r\n\s]*([\s\S\r\n]*)", RegexOptions.IgnoreCase);
var match = regEx.Match(sql);
if (match != null && match.Groups != null && match.Groups.Count == 2)
sql = match.Groups[1].Value;
else
{
var sb = new StringBuilder();
var inBody = false;
foreach (var lineText in sql.BreakLines())
{
//This is FAR from perfect. It assumes the creation line ends with the "AS" keyword for a stored proc
if (inBody)
{
sb.AppendLine(lineText);
}
else if (!inBody && (lineText.ToLower().Trim().EndsWith(" as") || lineText.ToLower().Trim() == "as"))
{
inBody = true;
}
}
sql = sb.ToString();
}
return sql.Trim();
}
internal static string GetSqlForViewsColumns()
{
var sb = new StringBuilder();
sb.AppendLine("select v.name as viewname, c.name as columnname, c.system_type_id, c.max_length, c.precision, c.scale, c.is_nullable from sys.views v inner join sys.columns c on v.object_id = c.object_id order by v.name, c.name");
return sb.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Lambda.TestUtilities;
using Amazon.Lambda.APIGatewayEvents;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Newtonsoft.Json;
using Xunit;
using Othello;
using OthelloAdapters;
namespace OthelloAWSServerless.Tests
{
public class FunctionTest : IDisposable
{
string TableName { get; }
IAmazonDynamoDB DDBClient { get; }
public FunctionTest()
{
this.TableName = "OthelloAWSServerless-OthelloGame-" + DateTime.Now.Ticks;
this.DDBClient = new AmazonDynamoDBClient(RegionEndpoint.APNortheast1);
SetupTableAsync().Wait();
}
[Fact]
public async Task GameListTestAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
var myGame = CreateNewOthelloHumanVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// List the games
request = new APIGatewayProxyRequest
{
};
context = new TestLambdaContext();
response = await functions.GetGamesAsync(request, context).ConfigureAwait(false);
Assert.Equal(200, response.StatusCode);
OthelloGameRepresentation[] gamePosts = JsonConvert.DeserializeObject<OthelloGameRepresentation[]>(response.Body);
Assert.Single(gamePosts);
Assert.Equal(game.Id, gamePosts[0].Id);
Assert.Equal(myGame.OthelloGameStrRepresentation, gamePosts[0].OthelloGameStrRepresentation);
}
[Fact]
public async Task GameAddHumanVsHumanAndGetGameTestAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Test adding a new game using player parameters
var myGame = CreateNewOthelloHumanVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// Test getting the game back out
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } }
};
context = new TestLambdaContext();
response = await functions.GetGameAsync(request, context).ConfigureAwait(false);
Assert.Equal(200, response.StatusCode);
OthelloGameRepresentation readGame = JsonConvert.DeserializeObject<OthelloGameRepresentation>(response.Body);
Assert.Equal(game.Id, readGame.Id);
Assert.Equal(myGame.OthelloGameStrRepresentation, readGame.OthelloGameStrRepresentation);
}
[Fact]
public async Task GameTestDeleteAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Test adding a new game using player parameters
var myGame = CreateNewOthelloHumanVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// Delete the game
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } }
};
context = new TestLambdaContext();
response = await functions.RemoveGameAsync(request, context).ConfigureAwait(false);
Assert.Equal(200, response.StatusCode);
// Make sure the game was deleted.
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } }
};
context = new TestLambdaContext();
response = await functions.GetGameAsync(request, context).ConfigureAwait(false);
Assert.Equal((int)HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task GameTestGetCurrentPlayerAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Add a new game using player parameters
var myGame = CreateNewOthelloHumanVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
//Test we can get the game's current player
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } }
};
context = new TestLambdaContext();
response = await functions.GetGameCurrentPlayerAsync(request, context).ConfigureAwait(false);
Assert.Equal(200, response.StatusCode);
OthelloServerlessCurrentPlayer getcurrentPlayer = JsonConvert.DeserializeObject<OthelloServerlessCurrentPlayer>(response.Body);
Assert.Equal(currentPlayer.ToString(), getcurrentPlayer.CurrentPlayer);
}
[Fact]
public async Task GameTestMakeValidMoveValidPlayerAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Add a new game using player parameters
var myGame = CreateNewOthelloHumanVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// Test we can get an valid move response
OthelloServerlessMakeMove myMoves = new OthelloServerlessMakeMove();
myMoves.GameX = 3;
myMoves.GameY = 2;
myMoves.CurrentPlayer = new OthelloGamePlayer(OthelloPlayerKind.White, "default-name-white");
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } },
Body = JsonConvert.SerializeObject(myMoves)
};
context = new TestLambdaContext();
response = await functions.MakeGameMoveAsync(request, context).ConfigureAwait(false);
var makemoveresponse = JsonConvert.DeserializeObject<OthelloServerlessMakeMoveFliplist>(response?.Body);
Assert.Equal(200, response.StatusCode);
Assert.True(makemoveresponse.IsValid);
Assert.Equal(0,makemoveresponse.Reason);
}
[Fact]
public async Task GameTestMakeInvalidMoveValidPlayerAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Add a new game using player parameters
var myGame = CreateNewOthelloHumanVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// Test we can get an valid move response
OthelloServerlessMakeMove myMoves = new OthelloServerlessMakeMove();
myMoves.GameX = 4;
myMoves.GameY = 2;
myMoves.CurrentPlayer = new OthelloGamePlayer(OthelloPlayerKind.White, "");
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } },
Body = JsonConvert.SerializeObject(myMoves)
};
context = new TestLambdaContext();
response = await functions.MakeGameMoveAsync(request, context).ConfigureAwait(false);
var makemoveresponse = JsonConvert.DeserializeObject<OthelloServerlessMakeMoveFliplist>(response?.Body);
Assert.Equal(200, response.StatusCode);
Assert.False(makemoveresponse.IsValid);
Assert.Equal(0x2, makemoveresponse.Reason);
}
[Fact]
public async Task GameTestMakeValidMoveInvalidPlayerAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Add a new game using player parameters
var myGame = CreateNewOthelloHumanVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// Test we can get an valid move response
OthelloServerlessMakeMove myMoves = new OthelloServerlessMakeMove();
myMoves.GameX = 3;
myMoves.GameY = 2;
myMoves.CurrentPlayer = new OthelloGamePlayer(OthelloPlayerKind.Black, "default-name-black");
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } },
Body = JsonConvert.SerializeObject(myMoves)
};
context = new TestLambdaContext();
response = await functions.MakeGameMoveAsync(request, context).ConfigureAwait(false);
var makemoveresponse = JsonConvert.DeserializeObject<OthelloServerlessMakeMoveFliplist>(response?.Body);
Assert.Equal(200, response.StatusCode);
Assert.False(makemoveresponse.IsValid);
Assert.Equal(0x1, makemoveresponse.Reason);
}
[Fact]
public async Task GameTestMakeInvalidMoveInvalidPlayerAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Add a new game using player parameters
var myGame = CreateNewOthelloHumanVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// Test we can get an valid move response
OthelloServerlessMakeMove myMoves = new OthelloServerlessMakeMove();
myMoves.GameX = 5;
myMoves.GameY = 2;
myMoves.CurrentPlayer = new OthelloGamePlayer(OthelloPlayerKind.Black, "default-name-black");
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } },
Body = JsonConvert.SerializeObject(myMoves)
};
context = new TestLambdaContext();
response = await functions.MakeGameMoveAsync(request, context).ConfigureAwait(false);
var makemoveresponse = JsonConvert.DeserializeObject<OthelloServerlessMakeMoveFliplist>(response?.Body);
Assert.Equal(200, response.StatusCode);
Assert.False(makemoveresponse.IsValid);
Assert.Equal(0x3, makemoveresponse.Reason);
}
[Fact]
public async Task GameAddAIVsHumanAndGetGameAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Test adding a new game using player parameters
var myGame = CreateNewOthelloAIVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// Test getting the game back out
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } }
};
context = new TestLambdaContext();
response = await functions.GetGameAsync(request, context).ConfigureAwait(false);
Assert.Equal(200, response.StatusCode);
OthelloGameRepresentation readGame = JsonConvert.DeserializeObject<OthelloGameRepresentation>(response.Body);
Assert.Equal(game.Id, readGame.Id);
Assert.Equal(myGame.OthelloGameStrRepresentation, readGame.OthelloGameStrRepresentation);
OthelloAdapter adapter = new OthelloAdapter();
adapter.GetGameFromJSON(readGame.OthelloGameStrRepresentation);
var actualcurrentplayer = adapter.GameUpdatePlayer();
Assert.Equal(currentPlayer.PlayerKind, actualcurrentplayer.PlayerKind);
}
[Fact]
public async Task GameAddAIVsHumanAndMoveAIAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Test adding a new game using player parameters
var myGame = CreateNewOthelloAIVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// Test getting the game back out
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } }
};
context = new TestLambdaContext();
response = await functions.GetGameAsync(request, context).ConfigureAwait(false);
Assert.Equal(200, response.StatusCode);
OthelloGameRepresentation readGame = JsonConvert.DeserializeObject<OthelloGameRepresentation>(response.Body);
Assert.Equal(game.Id, readGame.Id);
Assert.Equal(myGame.OthelloGameStrRepresentation, readGame.OthelloGameStrRepresentation);
// Test AI Move
// Test we can get an valid move response
OthelloServerlessMakeMove myMoves = new OthelloServerlessMakeMove();
myMoves.CurrentPlayer = new OthelloGamePlayer(OthelloPlayerKind.White, "default-name-white");
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> {{Functions.IdQueryStringName, game.Id}},
Body = JsonConvert.SerializeObject(myMoves)
};
context = new TestLambdaContext();
response = await functions.MakeGameAIMoveAsync(request, context).ConfigureAwait(false);
var makemoveresponse = JsonConvert.DeserializeObject<OthelloServerlessMakeMoveFliplist>(response?.Body);
Assert.Equal(200, response.StatusCode);
Assert.True(makemoveresponse.IsValid);
Assert.Equal(0, makemoveresponse.Reason);
}
[Fact]
public async Task GameAddAIVsHumanAndMoveAIGetBoardAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Test adding a new game using player parameters
var myGame = CreateNewOthelloAIVSHumanGame(out var myPlayers, out var currentPlayer);
var game = await AddOthelloGameRepresentation(myPlayers, functions).ConfigureAwait(false);
// Test getting the game back out
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } }
};
context = new TestLambdaContext();
response = await functions.GetGameAsync(request, context).ConfigureAwait(false);
Assert.Equal(200, response.StatusCode);
OthelloGameRepresentation readGame = JsonConvert.DeserializeObject<OthelloGameRepresentation>(response.Body);
Assert.Equal(game.Id, readGame.Id);
Assert.Equal(myGame.OthelloGameStrRepresentation, readGame.OthelloGameStrRepresentation);
OthelloAdapter adapter = new OthelloAdapter();
adapter.GetGameFromJSON(readGame.OthelloGameStrRepresentation);
var initialboard = adapter.GameDebugGetBoardInString();
// Test AI Move
// Test we can get an valid move response
OthelloServerlessMakeMove myMoves = new OthelloServerlessMakeMove();
myMoves.CurrentPlayer = new OthelloGamePlayer(OthelloPlayerKind.White, "default-name-white");
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } },
Body = JsonConvert.SerializeObject(myMoves)
};
context = new TestLambdaContext();
response = await functions.MakeGameAIMoveAsync(request, context).ConfigureAwait(false);
var makemoveresponse = JsonConvert.DeserializeObject<OthelloServerlessMakeMoveFliplist>(response?.Body);
Assert.Equal(200, response.StatusCode);
Assert.True(makemoveresponse.IsValid);
Assert.Equal(0, makemoveresponse.Reason);
//Get Board Data
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.IdQueryStringName, game.Id } },
QueryStringParameters = new Dictionary<string, string> { { Functions.DebugStringName, "true" } }
};
context = new TestLambdaContext();
response = await functions.GetGameBoardDataAsync(request, context).ConfigureAwait(false);
var board = JsonConvert.DeserializeObject<string>(response?.Body);
Assert.Equal(200, response.StatusCode);
Assert.NotEqual(initialboard, board);
}
private static async Task<OthelloGameRepresentation> AddOthelloGameRepresentation(OthelloServerlessPlayers myPlayers,
Functions functions)
{
APIGatewayProxyRequest request;
TestLambdaContext context;
APIGatewayProxyResponse response;
request = new APIGatewayProxyRequest
{
Body = JsonConvert.SerializeObject(myPlayers)
};
context = new TestLambdaContext();
response = await functions.AddGameAsync(request, context).ConfigureAwait(false);
Assert.Equal(200, response.StatusCode);
var game = JsonConvert.DeserializeObject<OthelloGameRepresentation>(response.Body);
return game;
}
private static OthelloGameRepresentation CreateNewOthelloHumanVSHumanGame(out OthelloServerlessPlayers myPlayers,
out OthelloGamePlayer currentPlayer)
{
OthelloGameRepresentation myGame = new OthelloGameRepresentation();
myPlayers = new OthelloServerlessPlayers();
myPlayers.PlayerNameWhite = "PlayerA";
myPlayers.PlayerNameBlack = "PlayerB";
myPlayers.FirstPlayerKind = OthelloPlayerKind.White;
OthelloAdapterBase OthelloGameAdapter = new OthelloAdapters.OthelloAdapter();
OthelloGameAdapter.GameCreateNewHumanVSHuman(myPlayers.PlayerNameWhite, myPlayers.PlayerNameBlack, myPlayers.FirstPlayerKind,
false);
currentPlayer = OthelloGameAdapter.GameUpdatePlayer();
myGame.CreatedTimestamp = DateTime.Now;
myGame.OthelloGameStrRepresentation = OthelloGameAdapter.GetGameJSON();
return myGame;
}
private static OthelloGameRepresentation CreateNewOthelloAIVSHumanGame(out OthelloServerlessPlayers myPlayers,
out OthelloGamePlayer currentPlayer)
{
OthelloGameRepresentation myGame = new OthelloGameRepresentation();
myPlayers = new OthelloServerlessPlayers();
myPlayers.PlayerNameWhite = "PlayerA";
myPlayers.PlayerNameBlack = "PlayerB";
myPlayers.FirstPlayerKind = OthelloPlayerKind.White;
myPlayers.UseAI = true;
myPlayers.IsHumanWhite = false;
myPlayers.Difficulty = GameDifficultyMode.Default;
OthelloAdapterBase OthelloGameAdapter = new OthelloAdapters.OthelloAdapter();
OthelloGameAdapter.GameCreateNewHumanVSAI(myPlayers.PlayerNameWhite, myPlayers.PlayerNameBlack,
false, false, myPlayers.Difficulty);
currentPlayer = OthelloGameAdapter.GameUpdatePlayer();
myGame.CreatedTimestamp = DateTime.Now;
myGame.OthelloGameStrRepresentation = OthelloGameAdapter.GetGameJSON();
return myGame;
}
/// <summary>
/// Create the DynamoDB table for testing. This table is deleted as part of the object dispose method.
/// </summary>
/// <returns></returns>
private async Task SetupTableAsync()
{
CreateTableRequest request = new CreateTableRequest
{
TableName = this.TableName,
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 2,
WriteCapacityUnits = 2
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
KeyType = KeyType.HASH,
AttributeName = Functions.IdQueryStringName
}
},
AttributeDefinitions = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = Functions.IdQueryStringName,
AttributeType = ScalarAttributeType.S
}
}
};
await this.DDBClient.CreateTableAsync(request).ConfigureAwait(false);
var describeRequest = new DescribeTableRequest { TableName = this.TableName };
DescribeTableResponse response = null;
do
{
Thread.Sleep(1000);
response = await this.DDBClient.DescribeTableAsync(describeRequest).ConfigureAwait(false);
} while (response.Table.TableStatus != TableStatus.ACTIVE);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.DDBClient.DeleteTableAsync(this.TableName).Wait();
this.DDBClient.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
// https://docs.microsoft.com/ja-jp/visualstudio/code-quality/ca1816-call-gc-suppressfinalize-correctly?view=vs-2015
GC.SuppressFinalize(this);
}
#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.Text;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
namespace System.DirectoryServices.ActiveDirectory
{
public class ActiveDirectorySchemaClass : IDisposable
{
// private variables
private DirectoryEntry _classEntry = null;
private DirectoryEntry _schemaEntry = null;
private DirectoryEntry _abstractClassEntry = null;
private NativeComInterfaces.IAdsClass _iadsClass = null;
private DirectoryContext _context = null;
internal bool isBound = false;
private bool _disposed = false;
private ActiveDirectorySchema _schema = null;
private bool _propertiesFromSchemaContainerInitialized = false;
private bool _isDefunctOnServer = false;
private Hashtable _propertyValuesFromServer = null;
// private variables for all the properties of this class
private string _ldapDisplayName = null;
private string _commonName = null;
private string _oid = null;
private string _description = null;
private bool _descriptionInitialized = false;
private bool _isDefunct = false;
private ActiveDirectorySchemaClassCollection _possibleSuperiors = null;
private ActiveDirectorySchemaClassCollection _auxiliaryClasses = null;
private ReadOnlyActiveDirectorySchemaClassCollection _possibleInferiors = null;
private ActiveDirectorySchemaPropertyCollection _mandatoryProperties = null;
private ActiveDirectorySchemaPropertyCollection _optionalProperties = null;
private ActiveDirectorySchemaClass _subClassOf = null;
private SchemaClassType _type = SchemaClassType.Structural;
private bool _typeInitialized = false;
private byte[] _schemaGuidBinaryForm = null;
private string _defaultSDSddlForm = null;
private bool _defaultSDSddlFormInitialized = false;
#region constructors
public ActiveDirectorySchemaClass(DirectoryContext context, string ldapDisplayName)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if ((context.Name == null) && (!context.isRootDomain()))
{
throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context));
}
if (context.Name != null)
{
// the target should be a valid forest name or a server
if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer())))
{
throw new ArgumentException(SR.NotADOrADAM, nameof(context));
}
}
if (ldapDisplayName == null)
{
throw new ArgumentNullException(nameof(ldapDisplayName));
}
if (ldapDisplayName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(ldapDisplayName));
}
_context = new DirectoryContext(context);
// validate the context
_schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.SchemaNamingContext);
_schemaEntry.Bind(true);
_ldapDisplayName = ldapDisplayName;
// the common name will default to the ldap display name
_commonName = ldapDisplayName;
// set the bind flag
this.isBound = false;
}
// Internal constructor
internal ActiveDirectorySchemaClass(DirectoryContext context, string ldapDisplayName, DirectoryEntry classEntry, DirectoryEntry schemaEntry)
{
_context = context;
_ldapDisplayName = ldapDisplayName;
_classEntry = classEntry;
_schemaEntry = schemaEntry;
// this constructor is only called for non-defunct classes
_isDefunctOnServer = false;
_isDefunct = _isDefunctOnServer;
// initialize the directory entry for the abstract schema class
try
{
_abstractClassEntry = DirectoryEntryManager.GetDirectoryEntryInternal(context, "LDAP://" + context.GetServerName() + "/schema/" + ldapDisplayName);
_iadsClass = (NativeComInterfaces.IAdsClass)_abstractClassEntry.NativeObject;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80005000))
{
throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySchemaClass), ldapDisplayName);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
catch (InvalidCastException)
{
// this means that we found an object but it is not a schema class
throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySchemaClass), ldapDisplayName);
}
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
// set the bind flag
this.isBound = true;
}
internal ActiveDirectorySchemaClass(DirectoryContext context, string commonName, Hashtable propertyValuesFromServer, DirectoryEntry schemaEntry)
{
_context = context;
_schemaEntry = schemaEntry;
// all relevant properties have already been retrieved from the server
_propertyValuesFromServer = propertyValuesFromServer;
Debug.Assert(_propertyValuesFromServer != null);
_propertiesFromSchemaContainerInitialized = true;
_classEntry = GetSchemaClassDirectoryEntry();
// names
_commonName = commonName;
_ldapDisplayName = (string)GetValueFromCache(PropertyManager.LdapDisplayName, true);
// this constructor is only called for defunct classes
_isDefunctOnServer = true;
_isDefunct = _isDefunctOnServer;
// set the bind flag
this.isBound = true;
}
internal ActiveDirectorySchemaClass(DirectoryContext context, string commonName, string ldapDisplayName, DirectoryEntry classEntry, DirectoryEntry schemaEntry)
{
_context = context;
_schemaEntry = schemaEntry;
_classEntry = classEntry;
// names
_commonName = commonName;
_ldapDisplayName = ldapDisplayName;
// this constructor is only called for defunct classes
_isDefunctOnServer = true;
_isDefunct = _isDefunctOnServer;
// set the bind flag
this.isBound = true;
}
#endregion constructors
#region IDisposable
public void Dispose()
{
Dispose(true);
}
// private Dispose method
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
// check if this is an explicit Dispose
// only then clean up the directory entries
if (disposing)
{
// dispose schema entry
if (_schemaEntry != null)
{
_schemaEntry.Dispose();
_schemaEntry = null;
}
// dispose class entry
if (_classEntry != null)
{
_classEntry.Dispose();
_classEntry = null;
}
// dispose abstract class entry
if (_abstractClassEntry != null)
{
_abstractClassEntry.Dispose();
_abstractClassEntry = null;
}
// dispose the schema object
if (_schema != null)
{
_schema.Dispose();
}
}
_disposed = true;
}
}
#endregion IDisposable
#region public methods
public static ActiveDirectorySchemaClass FindByName(DirectoryContext context, string ldapDisplayName)
{
ActiveDirectorySchemaClass schemaClass = null;
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if ((context.Name == null) && (!context.isRootDomain()))
{
throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context));
}
if (context.Name != null)
{
if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet()))
{
throw new ArgumentException(SR.NotADOrADAM, nameof(context));
}
}
if (ldapDisplayName == null)
{
throw new ArgumentNullException(nameof(ldapDisplayName));
}
if (ldapDisplayName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(ldapDisplayName));
}
// work with copy of the context
context = new DirectoryContext(context);
// create a schema class
schemaClass = new ActiveDirectorySchemaClass(context, ldapDisplayName, (DirectoryEntry)null, null);
return schemaClass;
}
public ReadOnlyActiveDirectorySchemaPropertyCollection GetAllProperties()
{
CheckIfDisposed();
ArrayList properties = new ArrayList();
// get the mandatory properties
properties.AddRange(MandatoryProperties);
// get the optional properties
properties.AddRange(OptionalProperties);
return new ReadOnlyActiveDirectorySchemaPropertyCollection(properties);
}
public void Save()
{
CheckIfDisposed();
if (!isBound)
{
try
{
// create a new directory entry for this class
if (_schemaEntry == null)
{
_schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
}
// this will create the class and set the CN value
string rdn = "CN=" + _commonName;
rdn = Utils.GetEscapedPath(rdn);
_classEntry = _schemaEntry.Children.Add(rdn, "classSchema");
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , _context.Name));
}
// set the ldap display name property
SetProperty(PropertyManager.LdapDisplayName, _ldapDisplayName);
// set the oid value
SetProperty(PropertyManager.GovernsID, _oid);
// set the description
SetProperty(PropertyManager.Description, _description);
// set the possibleSuperiors property
if (_possibleSuperiors != null)
{
_classEntry.Properties[PropertyManager.PossibleSuperiors].AddRange(_possibleSuperiors.GetMultiValuedProperty());
}
// set the mandatoryProperties property
if (_mandatoryProperties != null)
{
_classEntry.Properties[PropertyManager.MustContain].AddRange(_mandatoryProperties.GetMultiValuedProperty());
}
// set the optionalProperties property
if (_optionalProperties != null)
{
_classEntry.Properties[PropertyManager.MayContain].AddRange(_optionalProperties.GetMultiValuedProperty());
}
// set the subClassOf property
if (_subClassOf != null)
{
SetProperty(PropertyManager.SubClassOf, _subClassOf.Name);
}
else
{
// if no super class is specified, set it to "top"
SetProperty(PropertyManager.SubClassOf, "top");
}
// set the objectClassCategory property
SetProperty(PropertyManager.ObjectClassCategory, _type);
// set the schemaIDGuid property
if (_schemaGuidBinaryForm != null)
{
SetProperty(PropertyManager.SchemaIDGuid, _schemaGuidBinaryForm);
}
// set the default security descriptor
if (_defaultSDSddlForm != null)
{
SetProperty(PropertyManager.DefaultSecurityDescriptor, _defaultSDSddlForm);
}
}
try
{
// commit the classEntry to server
_classEntry.CommitChanges();
// Refresh the schema cache on the schema role owner
if (_schema == null)
{
ActiveDirectorySchema schemaObject = ActiveDirectorySchema.GetSchema(_context);
bool alreadyUsingSchemaRoleOwnerContext = false;
DirectoryServer schemaRoleOwner = null;
try
{
//
// if we are not already talking to the schema role owner, change the context
//
schemaRoleOwner = schemaObject.SchemaRoleOwner;
if (Utils.Compare(schemaRoleOwner.Name, _context.GetServerName()) != 0)
{
DirectoryContext schemaRoleOwnerContext = Utils.GetNewDirectoryContext(schemaRoleOwner.Name, DirectoryContextType.DirectoryServer, _context);
_schema = ActiveDirectorySchema.GetSchema(schemaRoleOwnerContext);
}
else
{
alreadyUsingSchemaRoleOwnerContext = true;
_schema = schemaObject;
}
}
finally
{
if (schemaRoleOwner != null)
{
schemaRoleOwner.Dispose();
}
if (!alreadyUsingSchemaRoleOwnerContext)
{
schemaObject.Dispose();
}
}
}
_schema.RefreshSchema();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
// now that the changes are committed to the server
// update the defunct/non-defunct status of the class on the server
_isDefunctOnServer = _isDefunct;
// invalidate all properties
_commonName = null;
_oid = null;
_description = null;
_descriptionInitialized = false;
_possibleSuperiors = null;
_auxiliaryClasses = null;
_possibleInferiors = null;
_mandatoryProperties = null;
_optionalProperties = null;
_subClassOf = null;
_typeInitialized = false;
_schemaGuidBinaryForm = null;
_defaultSDSddlForm = null;
_defaultSDSddlFormInitialized = false;
_propertiesFromSchemaContainerInitialized = false;
// set bind flag
isBound = true;
}
public override string ToString()
{
return Name;
}
public DirectoryEntry GetDirectoryEntry()
{
CheckIfDisposed();
if (!isBound)
{
throw new InvalidOperationException(SR.CannotGetObject);
}
GetSchemaClassDirectoryEntry();
Debug.Assert(_classEntry != null);
return DirectoryEntryManager.GetDirectoryEntryInternal(_context, _classEntry.Path);
}
#endregion public methods
#region public properties
public string Name
{
get
{
CheckIfDisposed();
return _ldapDisplayName;
}
}
public string CommonName
{
get
{
CheckIfDisposed();
if (isBound)
{
if (_commonName == null)
{
// get the property from the server
_commonName = (string)GetValueFromCache(PropertyManager.Cn, true);
}
}
return _commonName;
}
set
{
CheckIfDisposed();
if (isBound)
{
// set the value on the directory entry
SetProperty(PropertyManager.Cn, value);
}
_commonName = value;
}
}
public string Oid
{
get
{
CheckIfDisposed();
if (isBound)
{
if (_oid == null)
{
// get the property from the abstract schema/ schema container
// (for non-defunt classes this property is available in the abstract schema)
if (!_isDefunctOnServer)
{
try
{
_oid = _iadsClass.OID;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
else
{
_oid = (string)GetValueFromCache(PropertyManager.GovernsID, true);
}
}
}
return _oid;
}
set
{
CheckIfDisposed();
if (isBound)
{
// set the value on the directory entry
SetProperty(PropertyManager.GovernsID, value);
}
_oid = value;
}
}
public string Description
{
get
{
CheckIfDisposed();
if (isBound)
{
if (!_descriptionInitialized)
{
// get the property from the server
_description = (string)GetValueFromCache(PropertyManager.Description, false);
_descriptionInitialized = true;
}
}
return _description;
}
set
{
CheckIfDisposed();
if (isBound)
{
// set the value on the directory entry
SetProperty(PropertyManager.Description, value);
}
_description = value;
}
}
public bool IsDefunct
{
get
{
CheckIfDisposed();
// this is initialized for bound classes in the constructor
return _isDefunct;
}
set
{
CheckIfDisposed();
if (isBound)
{
// set the value on the directory entry
SetProperty(PropertyManager.IsDefunct, value);
}
_isDefunct = value;
}
}
public ActiveDirectorySchemaClassCollection PossibleSuperiors
{
get
{
CheckIfDisposed();
if (_possibleSuperiors == null)
{
if (isBound)
{
// get the property from the abstract schema/ schema container
// (for non-defunt classes this property is available in the abstract schema)
if (!_isDefunctOnServer)
{
ArrayList possibleSuperiorsList = new ArrayList();
bool listEmpty = false;
//
// IADsClass.PossibleSuperiors can return either a collection or a string
// (if there is only one value)
//
object value = null;
try
{
value = _iadsClass.PossibleSuperiors;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8000500D))
{
listEmpty = true;
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
if (!listEmpty)
{
if (value is ICollection)
{
possibleSuperiorsList.AddRange((ICollection)value);
}
else
{
// single value
possibleSuperiorsList.Add((string)value);
}
_possibleSuperiors = new ActiveDirectorySchemaClassCollection(_context, this, true /* isBound */, PropertyManager.PossibleSuperiors, possibleSuperiorsList, true /* onlyNames */);
}
else
{
// there are no superiors, return an emtpy collection
_possibleSuperiors = new ActiveDirectorySchemaClassCollection(_context, this, true /* is Bound */, PropertyManager.PossibleSuperiors, new ArrayList());
}
}
else
{
ArrayList possibleSuperiorsList = new ArrayList();
possibleSuperiorsList.AddRange(GetValuesFromCache(PropertyManager.PossibleSuperiors));
possibleSuperiorsList.AddRange(GetValuesFromCache(PropertyManager.SystemPossibleSuperiors));
_possibleSuperiors = new ActiveDirectorySchemaClassCollection(_context, this, true /* isBound */, PropertyManager.PossibleSuperiors, GetClasses(possibleSuperiorsList));
}
}
else
{
_possibleSuperiors = new ActiveDirectorySchemaClassCollection(_context, this, false /* is Bound */, PropertyManager.PossibleSuperiors, new ArrayList());
}
}
return _possibleSuperiors;
}
}
public ReadOnlyActiveDirectorySchemaClassCollection PossibleInferiors
{
get
{
CheckIfDisposed();
if (_possibleInferiors == null)
{
if (isBound)
{
// get the value from the server
_possibleInferiors = new ReadOnlyActiveDirectorySchemaClassCollection(GetClasses(GetValuesFromCache(PropertyManager.PossibleInferiors)));
}
else
{
_possibleInferiors = new ReadOnlyActiveDirectorySchemaClassCollection(new ArrayList());
}
}
return _possibleInferiors;
}
}
public ActiveDirectorySchemaPropertyCollection MandatoryProperties
{
get
{
CheckIfDisposed();
if (_mandatoryProperties == null)
{
if (isBound)
{
// get the property from the abstract schema/ schema container
// (for non-defunt classes this property is available in the abstract schema)
if (!_isDefunctOnServer)
{
ArrayList mandatoryPropertiesList = new ArrayList();
bool listEmpty = false;
//
// IADsClass.MandatoryProperties can return either a collection or a string
// (if there is only one value)
//
object value = null;
try
{
value = _iadsClass.MandatoryProperties;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8000500D))
{
listEmpty = true;
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
if (!listEmpty)
{
if (value is ICollection)
{
mandatoryPropertiesList.AddRange((ICollection)value);
}
else
{
// single value
mandatoryPropertiesList.Add((string)value);
}
_mandatoryProperties = new ActiveDirectorySchemaPropertyCollection(_context, this, true /* isBound */, PropertyManager.MustContain, mandatoryPropertiesList, true /* onlyNames */);
}
else
{
// there are no mandatory properties, return an emtpy collection
_mandatoryProperties = new ActiveDirectorySchemaPropertyCollection(_context, this, true /* isBound */, PropertyManager.MustContain, new ArrayList());
}
}
else
{
string[] propertyNames = new string[2];
propertyNames[0] = PropertyManager.SystemMustContain;
propertyNames[1] = PropertyManager.MustContain;
_mandatoryProperties = new ActiveDirectorySchemaPropertyCollection(_context, this, true /* isBound */, PropertyManager.MustContain, GetProperties(GetPropertyValuesRecursively(propertyNames)));
}
}
else
{
_mandatoryProperties = new ActiveDirectorySchemaPropertyCollection(_context, this, false /* isBound */, PropertyManager.MustContain, new ArrayList());
}
}
return _mandatoryProperties;
}
}
public ActiveDirectorySchemaPropertyCollection OptionalProperties
{
get
{
CheckIfDisposed();
if (_optionalProperties == null)
{
if (isBound)
{
// get the property from the abstract schema/ schema container
// (for non-defunt classes this property is available in the abstract schema)
if (!_isDefunctOnServer)
{
ArrayList optionalPropertiesList = new ArrayList();
bool listEmpty = false;
//
// IADsClass.OptionalProperties can return either a collection or a string
// (if there is only one value)
//
object value = null;
try
{
value = _iadsClass.OptionalProperties;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8000500D))
{
listEmpty = true;
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
if (!listEmpty)
{
if (value is ICollection)
{
optionalPropertiesList.AddRange((ICollection)value);
}
else
{
// single value
optionalPropertiesList.Add((string)value);
}
_optionalProperties = new ActiveDirectorySchemaPropertyCollection(_context, this, true /* isBound */, PropertyManager.MayContain, optionalPropertiesList, true /* onlyNames */);
}
else
{
// there are no optional properties, return an emtpy collection
_optionalProperties = new ActiveDirectorySchemaPropertyCollection(_context, this, true /* isBound */, PropertyManager.MayContain, new ArrayList());
}
}
else
{
string[] propertyNames = new string[2];
propertyNames[0] = PropertyManager.SystemMayContain;
propertyNames[1] = PropertyManager.MayContain;
ArrayList optionalPropertyList = new ArrayList();
foreach (string propertyName in GetPropertyValuesRecursively(propertyNames))
{
if (!MandatoryProperties.Contains(propertyName))
{
optionalPropertyList.Add(propertyName);
}
}
_optionalProperties = new ActiveDirectorySchemaPropertyCollection(_context, this, true /* isBound */, PropertyManager.MayContain, GetProperties(optionalPropertyList));
}
}
else
{
_optionalProperties = new ActiveDirectorySchemaPropertyCollection(_context, this, false /* isBound */, PropertyManager.MayContain, new ArrayList());
}
}
return _optionalProperties;
}
}
public ActiveDirectorySchemaClassCollection AuxiliaryClasses
{
get
{
CheckIfDisposed();
if (_auxiliaryClasses == null)
{
if (isBound)
{
// get the property from the abstract schema/ schema container
// (for non-defunt classes this property is available in the abstract schema)
if (!_isDefunctOnServer)
{
ArrayList auxiliaryClassesList = new ArrayList();
bool listEmpty = false;
//
// IADsClass.AuxDerivedFrom can return either a collection or a string
// (if there is only one value)
//
object value = null;
try
{
value = _iadsClass.AuxDerivedFrom;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8000500D))
{
listEmpty = true;
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
if (!listEmpty)
{
if (value is ICollection)
{
auxiliaryClassesList.AddRange((ICollection)value);
}
else
{
// single value
auxiliaryClassesList.Add((string)value);
}
_auxiliaryClasses = new ActiveDirectorySchemaClassCollection(_context, this, true /* isBound */, PropertyManager.AuxiliaryClass, auxiliaryClassesList, true /* onlyNames */);
}
else
{
// there are no auxiliary classes, return an emtpy collection
_auxiliaryClasses = new ActiveDirectorySchemaClassCollection(_context, this, true /* is Bound */, PropertyManager.AuxiliaryClass, new ArrayList());
}
}
else
{
string[] propertyNames = new string[2];
propertyNames[0] = PropertyManager.AuxiliaryClass;
propertyNames[1] = PropertyManager.SystemAuxiliaryClass;
_auxiliaryClasses = new ActiveDirectorySchemaClassCollection(_context, this, true /* isBound */, PropertyManager.AuxiliaryClass, GetClasses(GetPropertyValuesRecursively(propertyNames)));
}
}
else
{
_auxiliaryClasses = new ActiveDirectorySchemaClassCollection(_context, this, false /* isBound */, PropertyManager.AuxiliaryClass, new ArrayList());
}
}
return _auxiliaryClasses;
}
}
public ActiveDirectorySchemaClass SubClassOf
{
get
{
CheckIfDisposed();
if (isBound)
{
if (_subClassOf == null)
{
// get the property from the server
_subClassOf = new ActiveDirectorySchemaClass(_context, (string)GetValueFromCache(PropertyManager.SubClassOf, true), (DirectoryEntry)null, _schemaEntry);
}
}
return _subClassOf;
}
set
{
CheckIfDisposed();
if (isBound)
{
// set the value on the directory entry
SetProperty(PropertyManager.SubClassOf, value);
}
_subClassOf = value;
}
}
public SchemaClassType Type
{
get
{
CheckIfDisposed();
if (isBound)
{
if (!_typeInitialized)
{
// get the property from the server
_type = (SchemaClassType)((int)GetValueFromCache(PropertyManager.ObjectClassCategory, true));
_typeInitialized = true;
}
}
return _type;
}
set
{
CheckIfDisposed();
// validate the value that is being set
if (value < SchemaClassType.Type88 || value > SchemaClassType.Auxiliary)
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SchemaClassType));
}
if (isBound)
{
// set the value on the directory entry
SetProperty(PropertyManager.ObjectClassCategory, value);
}
_type = value;
}
}
public Guid SchemaGuid
{
get
{
CheckIfDisposed();
Guid schemaGuid = Guid.Empty;
if (isBound)
{
if (_schemaGuidBinaryForm == null)
{
// get the property from the server
_schemaGuidBinaryForm = (byte[])GetValueFromCache(PropertyManager.SchemaIDGuid, true);
}
}
// we cache the byte array and create a new guid each time
return new Guid(_schemaGuidBinaryForm);
}
set
{
CheckIfDisposed();
if (isBound)
{
// set the value on the directory entry
SetProperty(PropertyManager.SchemaIDGuid, (value.Equals(Guid.Empty)) ? null : value.ToByteArray());
}
_schemaGuidBinaryForm = (value.Equals(Guid.Empty)) ? null : value.ToByteArray();
}
}
public ActiveDirectorySecurity DefaultObjectSecurityDescriptor
{
get
{
CheckIfDisposed();
ActiveDirectorySecurity defaultObjectSecurityDescriptor = null;
if (isBound)
{
if (!_defaultSDSddlFormInitialized)
{
// get the property from the server
_defaultSDSddlForm = (string)GetValueFromCache(PropertyManager.DefaultSecurityDescriptor, false);
_defaultSDSddlFormInitialized = true;
}
}
// we cache the sddl form and create a ActiveDirectorySecurity object each time
if (_defaultSDSddlForm != null)
{
defaultObjectSecurityDescriptor = new ActiveDirectorySecurity();
defaultObjectSecurityDescriptor.SetSecurityDescriptorSddlForm(_defaultSDSddlForm);
}
return defaultObjectSecurityDescriptor;
}
set
{
CheckIfDisposed();
if (isBound)
{
// set the value on the directory entry
SetProperty(PropertyManager.DefaultSecurityDescriptor, (value == null) ? null : value.GetSecurityDescriptorSddlForm(AccessControlSections.All));
}
_defaultSDSddlForm = (value == null) ? null : value.GetSecurityDescriptorSddlForm(AccessControlSections.All);
}
}
#endregion public properties
#region private methods
private void CheckIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
//
// This method retrieves the value of a property (single valued) from the values
// that were retrieved from the server. The "mustExist" parameter controls whether or
// not an exception should be thrown if a value does not exist. If mustExist is true, this
// will throw an exception is value does not exist.
//
private object GetValueFromCache(string propertyName, bool mustExist)
{
object value = null;
// retrieve the properties from the server if necessary
InitializePropertiesFromSchemaContainer();
Debug.Assert(_propertyValuesFromServer != null);
ArrayList values = (ArrayList)_propertyValuesFromServer[propertyName.ToLower(CultureInfo.InvariantCulture)];
Debug.Assert(values != null);
if (values.Count < 1 && mustExist)
{
throw new ActiveDirectoryOperationException(SR.Format(SR.PropertyNotFound , propertyName));
}
else if (values.Count > 0)
{
value = values[0];
}
return value;
}
//
// This method retrieves all the values of a property (single valued) from the values
// that were retrieved from the server.
//
private ICollection GetValuesFromCache(string propertyName)
{
// retrieve the properties from the server if necessary
InitializePropertiesFromSchemaContainer();
Debug.Assert(_propertyValuesFromServer != null);
ArrayList values = (ArrayList)_propertyValuesFromServer[propertyName.ToLower(CultureInfo.InvariantCulture)];
Debug.Assert(values != null);
return values;
}
//
// Just calls the static method GetPropertiesFromSchemaContainer with the correct context
//
private void InitializePropertiesFromSchemaContainer()
{
if (!_propertiesFromSchemaContainerInitialized)
{
if (_schemaEntry == null)
{
_schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
}
_propertyValuesFromServer = GetPropertiesFromSchemaContainer(_context, _schemaEntry, (_isDefunctOnServer) ? _commonName : _ldapDisplayName, _isDefunctOnServer);
_propertiesFromSchemaContainerInitialized = true;
}
}
//
// This method retrieves properties for this schema class from the schema container
// on the server. For non-defunct classes only properties that are not available in the abstract
// schema are retrieved. For defunct classes, all the properties are retrieved.
// The retrieved values are stored in a class variable "propertyValuesFromServer" which is a
// hashtable indexed on the property name.
//
internal static Hashtable GetPropertiesFromSchemaContainer(DirectoryContext context, DirectoryEntry schemaEntry, string name, bool isDefunctOnServer)
{
Hashtable propertyValuesFromServer = null;
//
// The properties that are loaded from the schemaContainer for non-defunct classes:
// DistinguishedName
// CommonName
// Description
// PossibleInferiors
// SubClassOf
// Type
// SchemaGuid
// DefaultObjectSecurityDescriptor
// AuxiliaryClasses
//
//
// For defunct class we also load the remaining properties
// LdapDisplayName
// Oid
// PossibleSuperiors
// MandatoryProperties
// OptionalProperties
// AuxiliaryClasses
//
// build the filter
StringBuilder str = new StringBuilder(15);
str.Append("(&(");
str.Append(PropertyManager.ObjectCategory);
str.Append("=classSchema)");
str.Append("(");
if (!isDefunctOnServer)
{
str.Append(PropertyManager.LdapDisplayName);
}
else
{
str.Append(PropertyManager.Cn);
}
str.Append("=");
str.Append(Utils.GetEscapedFilterValue(name));
str.Append(")");
if (!isDefunctOnServer)
{
str.Append("(!(");
}
else
{
str.Append("(");
}
str.Append(PropertyManager.IsDefunct);
if (!isDefunctOnServer)
{
str.Append("=TRUE)))");
}
else
{
str.Append("=TRUE))");
}
//
// Get all the values using range retrieval
//
ArrayList propertyNamesWithRangeRetrieval = new ArrayList();
ArrayList propertyNamesWithoutRangeRetrieval = new ArrayList();
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.DistinguishedName);
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.Cn);
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.Description);
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.PossibleInferiors);
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.SubClassOf);
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.ObjectClassCategory);
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.SchemaIDGuid);
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.DefaultSecurityDescriptor);
propertyNamesWithRangeRetrieval.Add(PropertyManager.AuxiliaryClass);
propertyNamesWithRangeRetrieval.Add(PropertyManager.SystemAuxiliaryClass);
propertyNamesWithRangeRetrieval.Add(PropertyManager.MustContain);
propertyNamesWithRangeRetrieval.Add(PropertyManager.SystemMustContain);
propertyNamesWithRangeRetrieval.Add(PropertyManager.MayContain);
propertyNamesWithRangeRetrieval.Add(PropertyManager.SystemMayContain);
// if defunct, we need to retrieve all the properties from the server
if (isDefunctOnServer)
{
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.LdapDisplayName);
propertyNamesWithoutRangeRetrieval.Add(PropertyManager.GovernsID);
propertyNamesWithRangeRetrieval.Add(PropertyManager.SystemPossibleSuperiors);
propertyNamesWithRangeRetrieval.Add(PropertyManager.PossibleSuperiors);
}
try
{
propertyValuesFromServer = Utils.GetValuesWithRangeRetrieval(schemaEntry, str.ToString(), propertyNamesWithRangeRetrieval, propertyNamesWithoutRangeRetrieval, SearchScope.OneLevel);
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// object is not found since we cannot even find the container in which to search
throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySchemaClass), name);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
return propertyValuesFromServer;
}
internal DirectoryEntry GetSchemaClassDirectoryEntry()
{
if (_classEntry == null)
{
InitializePropertiesFromSchemaContainer();
_classEntry = DirectoryEntryManager.GetDirectoryEntry(_context, (string)GetValueFromCache(PropertyManager.DistinguishedName, true));
}
return _classEntry;
}
private void SetProperty(string propertyName, object value)
{
// get the distinguished name to construct the directory entry
GetSchemaClassDirectoryEntry();
Debug.Assert(_classEntry != null);
try
{
if ((value == null))
{
if (_classEntry.Properties.Contains(propertyName))
{
_classEntry.Properties[propertyName].Clear();
}
}
else
{
_classEntry.Properties[propertyName].Value = value;
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
//
// This method searches in the schema container for all non-defunct classes of the
// specified name (ldapDisplayName).
//
private ArrayList GetClasses(ICollection ldapDisplayNames)
{
ArrayList classes = new ArrayList();
SearchResultCollection resCol = null;
try
{
if (ldapDisplayNames.Count < 1)
{
return classes;
}
if (_schemaEntry == null)
{
_schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
}
// constructing the filter
StringBuilder str = new StringBuilder(100);
if (ldapDisplayNames.Count > 1)
{
str.Append("(|");
}
foreach (string ldapDisplayName in ldapDisplayNames)
{
str.Append("(");
str.Append(PropertyManager.LdapDisplayName);
str.Append("=");
str.Append(Utils.GetEscapedFilterValue(ldapDisplayName));
str.Append(")");
}
if (ldapDisplayNames.Count > 1)
{
str.Append(")");
}
string filter = "(&(" + PropertyManager.ObjectCategory + "=classSchema)" + str.ToString() + "(!(" + PropertyManager.IsDefunct + "=TRUE)))";
string[] propertiesToLoad = new string[1];
propertiesToLoad[0] = PropertyManager.LdapDisplayName;
ADSearcher searcher = new ADSearcher(_schemaEntry, filter, propertiesToLoad, SearchScope.OneLevel);
resCol = searcher.FindAll();
foreach (SearchResult res in resCol)
{
string ldapDisplayName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.LdapDisplayName);
DirectoryEntry de = res.GetDirectoryEntry();
de.AuthenticationType = Utils.DefaultAuthType;
de.Username = _context.UserName;
de.Password = _context.Password;
ActiveDirectorySchemaClass schemaClass = new ActiveDirectorySchemaClass(_context, ldapDisplayName, de, _schemaEntry);
classes.Add(schemaClass);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
finally
{
if (resCol != null)
{
resCol.Dispose();
}
}
return classes;
}
//
// This method searches in the schema container for all non-defunct properties of the
// specified name (ldapDisplayName).
//
private ArrayList GetProperties(ICollection ldapDisplayNames)
{
ArrayList properties = new ArrayList();
SearchResultCollection resCol = null;
try
{
if (ldapDisplayNames.Count < 1)
{
return properties;
}
if (_schemaEntry == null)
{
_schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext);
}
// constructing the filter
StringBuilder str = new StringBuilder(100);
if (ldapDisplayNames.Count > 1)
{
str.Append("(|");
}
foreach (string ldapDisplayName in ldapDisplayNames)
{
str.Append("(");
str.Append(PropertyManager.LdapDisplayName);
str.Append("=");
str.Append(Utils.GetEscapedFilterValue(ldapDisplayName));
str.Append(")");
}
if (ldapDisplayNames.Count > 1)
{
str.Append(")");
}
string filter = "(&(" + PropertyManager.ObjectCategory + "=attributeSchema)" + str.ToString() + "(!(" + PropertyManager.IsDefunct + "=TRUE)))";
string[] propertiesToLoad = new string[1];
propertiesToLoad[0] = PropertyManager.LdapDisplayName;
ADSearcher searcher = new ADSearcher(_schemaEntry, filter, propertiesToLoad, SearchScope.OneLevel);
resCol = searcher.FindAll();
foreach (SearchResult res in resCol)
{
string ldapDisplayName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.LdapDisplayName);
DirectoryEntry de = res.GetDirectoryEntry();
de.AuthenticationType = Utils.DefaultAuthType;
de.Username = _context.UserName;
de.Password = _context.Password;
ActiveDirectorySchemaProperty schemaProperty = new ActiveDirectorySchemaProperty(_context, ldapDisplayName, de, _schemaEntry);
properties.Add(schemaProperty);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
finally
{
if (resCol != null)
{
resCol.Dispose();
}
}
return properties;
}
private ArrayList GetPropertyValuesRecursively(string[] propertyNames)
{
ArrayList values = new ArrayList();
// get the properties of the super class
try
{
if (Utils.Compare(SubClassOf.Name, Name) != 0)
{
foreach (string value in SubClassOf.GetPropertyValuesRecursively(propertyNames))
{
if (!values.Contains(value))
{
values.Add(value);
}
}
}
// get the properties of the auxiliary classes
foreach (string auxSchemaClassName in GetValuesFromCache(PropertyManager.AuxiliaryClass))
{
ActiveDirectorySchemaClass auxSchemaClass = new ActiveDirectorySchemaClass(_context, auxSchemaClassName, (DirectoryEntry)null, null);
foreach (string property in auxSchemaClass.GetPropertyValuesRecursively(propertyNames))
{
if (!values.Contains(property))
{
values.Add(property);
}
}
}
foreach (string auxSchemaClassName in GetValuesFromCache(PropertyManager.SystemAuxiliaryClass))
{
ActiveDirectorySchemaClass auxSchemaClass = new ActiveDirectorySchemaClass(_context, auxSchemaClassName, (DirectoryEntry)null, null);
foreach (string property in auxSchemaClass.GetPropertyValuesRecursively(propertyNames))
{
if (!values.Contains(property))
{
values.Add(property);
}
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
foreach (string propertyName in propertyNames)
{
foreach (string value in GetValuesFromCache(propertyName))
{
if (!values.Contains(value))
{
values.Add(value);
}
}
}
return values;
}
#endregion private methods
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Insights;
using Microsoft.Azure.Management.Insights.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Insights
{
/// <summary>
/// Operations for managing agent diagnostic settings.
/// </summary>
internal partial class AgentDiagnosticSettingsOperations : IServiceOperations<InsightsManagementClient>, IAgentDiagnosticSettingsOperations
{
/// <summary>
/// Initializes a new instance of the AgentDiagnosticSettingsOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AgentDiagnosticSettingsOperations(InsightsManagementClient client)
{
this._client = client;
}
private InsightsManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Insights.InsightsManagementClient.
/// </summary>
public InsightsManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets the diagnostic settings.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource uri.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AgentDiagnosticSettingsGetResponse> GetAsync(string resourceUri, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/diagnosticSettings/agent";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AgentDiagnosticSettingsGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AgentDiagnosticSettingsGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
result.Location = locationInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
AgentDiagnosticSettings propertiesInstance = new AgentDiagnosticSettings();
result.Properties = propertiesInstance;
JToken nameValue2 = propertiesValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
propertiesInstance.Name = nameInstance2;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken publicConfigurationValue = propertiesValue["publicConfiguration"];
if (publicConfigurationValue != null && publicConfigurationValue.Type != JTokenType.Null)
{
string typeName = ((string)publicConfigurationValue["odata.type"]);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Puts the new diagnostic settings.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource uri.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Generic empty response. We only pass it to ensure json error
/// handling
/// </returns>
public async Task<EmptyResponse> PutAsync(string resourceUri, AgentDiagnosticSettgingsPutParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PutAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/diagnosticSettings/agent";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject agentDiagnosticSettgingsPutParametersValue = new JObject();
requestDoc = agentDiagnosticSettgingsPutParametersValue;
if (parameters.Properties != null)
{
JObject propertiesValue = new JObject();
agentDiagnosticSettgingsPutParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Name != null)
{
propertiesValue["name"] = parameters.Properties.Name;
}
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
if (parameters.Properties.PublicConfiguration != null)
{
JObject publicConfigurationValue = new JObject();
propertiesValue["publicConfiguration"] = publicConfigurationValue;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EmptyResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EmptyResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
//
// Mono.WebServer.XSPApplicationHost
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
// Lluis Sanchez Gual ([email protected])
//
// (C) Copyright 2004-2007 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Web;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Mono.Security.Protocol.Tls;
using SecurityProtocolType = Mono.Security.Protocol.Tls.SecurityProtocolType;
using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate;
namespace Mono.WebServer
{
//
// XSPWorker: The worker that do the initial processing of XSP
// requests.
//
class XSPWorker: Worker
{
ApplicationServer server;
LingeringNetworkStream netStream;
Stream stream;
IPEndPoint remoteEP;
IPEndPoint localEP;
Socket sock;
SslInformation ssl;
InitialWorkerRequest initial;
int requestId = -1;
XSPRequestBroker broker = null;
int reuses;
public XSPWorker (Socket client, EndPoint localEP, ApplicationServer server,
bool secureConnection,
Mono.Security.Protocol.Tls.SecurityProtocolType SecurityProtocol,
X509Certificate cert,
PrivateKeySelectionCallback keyCB,
bool allowClientCert,
bool requireClientCert)
{
if (secureConnection) {
ssl = new SslInformation ();
ssl.AllowClientCertificate = allowClientCert;
ssl.RequireClientCertificate = requireClientCert;
ssl.RawServerCertificate = cert.GetRawCertData ();
netStream = new LingeringNetworkStream (client, true);
SslServerStream s = new SslServerStream (netStream, cert, requireClientCert, false);
s.PrivateKeyCertSelectionDelegate += keyCB;
s.ClientCertValidationDelegate += new CertificateValidationCallback (ClientCertificateValidation);
stream = s;
} else {
netStream = new LingeringNetworkStream (client, false);
stream = netStream;
}
sock = client;
this.server = server;
this.remoteEP = (IPEndPoint) client.RemoteEndPoint;
this.localEP = (IPEndPoint) localEP;
}
public override bool IsAsync {
get { return true; }
}
public override void SetReuseCount (int nreuses)
{
reuses = nreuses;
}
public override int GetRemainingReuses ()
{
return 100 - reuses;
}
public override void Run (object state)
{
initial = new InitialWorkerRequest (stream);
byte [] buffer = InitialWorkerRequest.AllocateBuffer ();
stream.BeginRead (buffer, 0, buffer.Length, new AsyncCallback (ReadCB), buffer);
}
void ReadCB (IAsyncResult ares)
{
byte [] buffer = (byte []) ares.AsyncState;
try {
int nread = stream.EndRead (ares);
// See if we got at least 1 line
initial.SetBuffer (buffer, nread);
initial.ReadRequestData ();
ThreadPool.QueueUserWorkItem (new WaitCallback (RunInternal));
} catch (Exception e) {
InitialWorkerRequest.FreeBuffer (buffer);
HandleInitialException (e);
}
}
void HandleInitialException (Exception e)
{
//bool ignore = ((e is RequestLineException) || (e is IOException));
//if (!ignore)
// Console.WriteLine (e);
try {
if (initial != null && initial.GotSomeInput && sock.Connected) {
byte [] error = HttpErrors.ServerError ();
Write (error, 0, error.Length);
}
} catch {}
try {
Close ();
} catch {}
if (broker != null && requestId != -1)
broker.UnregisterRequest (requestId);
}
void RunInternal (object state)
{
RequestData rdata = initial.RequestData;
initial.FreeBuffer ();
string vhost = null; // TODO: read the headers in InitialWorkerRequest
int port = ((IPEndPoint) localEP).Port;
VPathToHost vapp;
try {
vapp = server.GetApplicationForPath (vhost, port, rdata.Path, true);
} catch (Exception e){
//
// This happens if the assembly is not in the GAC, so we report this
// error here.
//
Console.Error.WriteLine (e);
return;
}
XSPApplicationHost host = null;
if (vapp != null)
host = (XSPApplicationHost) vapp.AppHost;
if (host == null) {
byte [] nf = HttpErrors.NotFound (rdata.Path);
Write (nf, 0, nf.Length);
Close ();
return;
}
broker = (XSPRequestBroker) vapp.RequestBroker;
requestId = broker.RegisterRequest (this);
if (ssl != null) {
SslServerStream s = (stream as SslServerStream);
ssl.KeySize = s.CipherStrength;
ssl.SecretKeySize = s.KeyExchangeStrength;
}
try {
string redirect;
vapp.Redirect (rdata.Path, out redirect);
host.ProcessRequest (requestId, localEP,
remoteEP, rdata.Verb,
rdata.Path, rdata.QueryString,
rdata.Protocol, rdata.InputBuffer, redirect, sock.Handle, ssl);
} catch (FileNotFoundException fnf) {
// We print this one, as it might be a sign of a bad deployment
// once we require the .exe and Mono.WebServer in bin or the GAC.
Console.Error.WriteLine (fnf);
} catch (IOException) {
// This is ok (including EndOfStreamException)
} catch (Exception e) {
Console.Error.WriteLine (e);
}
}
public override int Read (byte[] buffer, int position, int size)
{
int n = stream.Read (buffer, position, size);
return (n >= 0) ? n : -1;
}
public override void Write (byte[] buffer, int position, int size)
{
try {
stream.Write (buffer, position, size);
} catch (Exception ex) {
Console.WriteLine ("Peer unexpectedly closed the connection on write. Closing our end.\n{0}", ex);
Close ();
}
}
public override void Close ()
{
Close (false);
}
public void Close (bool keepAlive)
{
if (!keepAlive || !IsConnected ()) {
stream.Close ();
if (stream != netStream) {
netStream.Close ();
} else if (false == netStream.OwnsSocket) {
try {
if (sock.Connected && !(sock.Poll (0, SelectMode.SelectRead) && sock.Available == 0))
sock.Shutdown (SocketShutdown.Both);
} catch {
// ignore
}
try {
sock.Close ();
} catch {
// ignore
}
}
return;
}
netStream.EnableLingering = false;
stream.Close ();
if (stream != netStream)
netStream.Close ();
server.ReuseSocket (sock, reuses + 1);
}
public override bool IsConnected ()
{
return netStream.Connected;
}
public override void Flush ()
{
if (stream != netStream)
stream.Flush ();
}
bool ClientCertificateValidation (X509Certificate certificate, int [] certificateErrors)
{
if (certificate != null)
ssl.RawClientCertificate = certificate.GetRawCertData (); // to avoid serialization
// right now we're accepting any client certificate - i.e. it's up to the
// web application to check if the certificate is valid (HttpClientCertificate.IsValid)
ssl.ClientCertificateValid = (certificateErrors.Length == 0);
return ssl.RequireClientCertificate ? (certificate != null) : true;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Storage.Internal;
namespace Orleans.Storage
{
/// <summary>
/// This is a simple in-memory grain implementation of a storage provider.
/// </summary>
/// <remarks>
/// This storage provider is ONLY intended for simple in-memory Development / Unit Test scenarios.
/// This class should NOT be used in Production environment,
/// because [by-design] it does not provide any resilience
/// or long-term persistence capabilities.
/// </remarks>
/// <example>
/// Example configuration for this storage provider in OrleansConfiguration.xml file:
/// <code>
/// <OrleansConfiguration xmlns="urn:orleans">
/// <Globals>
/// <StorageProviders>
/// <Provider Type="Orleans.Storage.MemoryStorage" Name="MemoryStore" />
/// </StorageProviders>
/// </code>
/// </example>
[DebuggerDisplay("MemoryStore:{Name}")]
public class MemoryGrainStorage : IGrainStorage, IDisposable
{
private MemoryGrainStorageOptions options;
private const string STATE_STORE_NAME = "MemoryStorage";
private Lazy<IMemoryStorageGrain>[] storageGrains;
private ILogger logger;
private IGrainFactory grainFactory;
/// <summary> Name of this storage provider instance. </summary>
private readonly string name;
/// <summary> Default constructor. </summary>
public MemoryGrainStorage(string name, MemoryGrainStorageOptions options, ILoggerFactory loggerFactory, IGrainFactory grainFactory)
{
this.options = options;
this.name = name;
this.logger = loggerFactory.CreateLogger($"{this.GetType().FullName}.{name}");
this.grainFactory = grainFactory;
//Init
logger.Info("Init: Name={0} NumStorageGrains={1}", name, this.options.NumStorageGrains);
storageGrains = new Lazy<IMemoryStorageGrain>[this.options.NumStorageGrains];
for (int i = 0; i < this.options.NumStorageGrains; i++)
{
int idx = i; // Capture variable to avoid modified closure error
storageGrains[idx] = new Lazy<IMemoryStorageGrain>(() => this.grainFactory.GetGrain<IMemoryStorageGrain>(idx));
}
}
/// <summary> Read state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ReadStateAsync"/>
public virtual async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Read Keys={0}", StorageProviderUtils.PrintKeys(keys));
string id = HierarchicalKeyStore.MakeStoreKey(keys);
IMemoryStorageGrain storageGrain = GetStorageGrain(id);
var state = await storageGrain.ReadStateAsync(STATE_STORE_NAME, id);
if (state != null)
{
grainState.ETag = state.ETag;
grainState.State = state.State;
}
}
/// <summary> Write state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.WriteStateAsync"/>
public virtual async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
string key = HierarchicalKeyStore.MakeStoreKey(keys);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Write {0} ", StorageProviderUtils.PrintOneWrite(keys, grainState.State, grainState.ETag));
IMemoryStorageGrain storageGrain = GetStorageGrain(key);
try
{
grainState.ETag = await storageGrain.WriteStateAsync(STATE_STORE_NAME, key, grainState);
}
catch (MemoryStorageEtagMismatchException e)
{
throw e.AsInconsistentStateException();
}
}
/// <summary> Delete / Clear state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ClearStateAsync"/>
public virtual async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Delete Keys={0} Etag={1}", StorageProviderUtils.PrintKeys(keys), grainState.ETag);
string key = HierarchicalKeyStore.MakeStoreKey(keys);
IMemoryStorageGrain storageGrain = GetStorageGrain(key);
try
{
await storageGrain.DeleteStateAsync(STATE_STORE_NAME, key, grainState.ETag);
grainState.ETag = null;
}
catch (MemoryStorageEtagMismatchException e)
{
throw e.AsInconsistentStateException();
}
}
private static IEnumerable<Tuple<string, string>> MakeKeys(string grainType, GrainReference grain)
{
return new[]
{
Tuple.Create("GrainType", grainType),
Tuple.Create("GrainId", grain.ToKeyString())
};
}
private IMemoryStorageGrain GetStorageGrain(string id)
{
int idx = StorageProviderUtils.PositiveHash(id.GetHashCode(), this.options.NumStorageGrains);
IMemoryStorageGrain storageGrain = storageGrains[idx].Value;
return storageGrain;
}
internal static Func<IDictionary<string, object>, bool> GetComparer<T>(string rangeParamName, T fromValue, T toValue) where T : IComparable
{
Comparer comparer = Comparer.DefaultInvariant;
bool sameRange = comparer.Compare(fromValue, toValue) == 0; // FromValue == ToValue
bool insideRange = comparer.Compare(fromValue, toValue) < 0; // FromValue < ToValue
Func<IDictionary<string, object>, bool> compareClause;
if (sameRange)
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) == 0;
};
}
else if (insideRange)
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) >= 0 && comparer.Compare(obj, toValue) <= 0;
};
}
else
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) >= 0 || comparer.Compare(obj, toValue) <= 0;
};
}
return compareClause;
}
public void Dispose()
{
for (int i = 0; i < this.options.NumStorageGrains; i++)
storageGrains[i] = null;
}
}
/// <summary>
/// Factory for creating MemoryGrainStorage
/// </summary>
public class MemoryGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
return ActivatorUtilities.CreateInstance<MemoryGrainStorage>(services,
services.GetRequiredService<IOptionsMonitor<MemoryGrainStorageOptions>>().Get(name), name);
}
}
}
| |
// #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2014 SmartsheetClient
// %%
// 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.
// %[license]
namespace Smartsheet.Api.Internal
{
using System;
using System.IO;
using System.ComponentModel;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using NLog;
using RestSharp;
using Api.Internal.Json;
using Api.Internal.Util;
using DefaultHttpClient = Api.Internal.Http.DefaultHttpClient;
using HttpClient = Api.Internal.Http.HttpClient;
using HttpResponse = Api.Internal.Http.HttpResponse;
using Utils = Api.Internal.Utility.Utility;
using System.Net;
/// <summary>
/// This is the implementation of Smartsheet interface.
///
/// Thread Safety: This class is thread safe because all its mutable fields are safe-guarded using AtomicReference to
/// ensure atomic modifications, and also the underlying HttpClient and JsonSerializer interfaces are thread safe.
/// </summary>
public class SmartsheetImpl : SmartsheetClient
{
/// <summary>
/// Represents the HttpClient.
///
/// It will be initialized in the constructor and will not change afterwards.
/// </summary>
private readonly HttpClient httpClient;
/// <summary>
/// Represents the JsonSerializer.
///
/// It will be initialized in the constructor and will not change afterwards.
/// </summary>
private JsonSerializer jsonSerializer;
/// <summary>
/// Represents the base URI of the Smartsheet REST API.
///
/// It will be initialized in the constructor and will not change afterwards.
/// </summary>
private System.Uri baseURI;
/// <summary>
/// Represents the AtomicReference for the access token.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and can be set via corresponding setter, therefore effectively the access token can be updated in the
/// SmartsheetImpl in thread safe manner.
/// </summary>
private string accessToken;
/// <summary>
/// Represents the AtomicReference for assumed user email.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and can be set via corresponding setter, therefore effectively the assumed user can be updated in the
/// SmartsheetImpl in thread safe manner.
/// </summary>
private string assumedUser;
/// <summary>
/// Represents the AtomicReference for the change agent.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and can be set via corresponding setter, therefore effectively the assumed user can be updated in the
/// SmartsheetImpl in thread safe manner.
/// </summary>
private string changeAgent;
/// <summary>
/// Represents the AtomicReference to HomeResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private HomeResources home;
/// <summary>
/// Represents the AtomicReference to WorkspaceResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private WorkspaceResources workspaces;
/// <summary>
/// Represents the AtomicReference to FolderResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null at the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private FolderResources folders;
/// <summary>
/// Represents the AtomicReference to TemplateResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null at the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private TemplateResources templates;
/// <summary>
/// Represents the AtomicReference to ReportResources.
///
/// It will be initialized in constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private ReportResources reports;
/// <summary>
/// Represents the AtomicReference to SheetResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private SheetResources sheets;
/// <summary>
/// Represents the AtomicReference to SightResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private SightResources sights;
/// <summary>
/// Represents the AtomicReference to WebhookResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private WebhookResources webhooks;
/// <summary>
/// Represents the AtomicReference to UserResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private UserResources users;
/// <summary>
/// Represents the AtomicReference to SearchResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private SearchResources search;
/// <summary>
/// Represents the AtomicReference to ServerInfoResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private ServerInfoResources serverInfo;
/// <summary>
/// Represents the AtomicReference to GroupResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private GroupResources groups;
/// <summary>
/// Represents the AtomicReference to FavoriteResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private FavoriteResources favorites;
/// <summary>
/// Represents the AtomicReference to TokenResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private TokenResources tokens;
/// <summary>
/// Represents the AtomicReference to ContactResources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and will be initialized to non-null the first time it is accessed via corresponding getter, therefore
/// effectively the underlying value is lazily created in a thread safe manner.
/// </summary>
private ContactResources contacts;
/// <summary>
/// Represents the AtomicReference for image Urls.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and can be set via corresponding setter, therefore effectively the assumed user can be updated in the
/// SmartsheetImpl in thread safe manner.
/// </summary>
private ImageUrlsResources imageUrls;
/// <summary>
/// Represents the AtomicReference for passthrough resources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and can be set via corresponding setter, therefore effectively the assumed user can be updated in the
/// SmartsheetImpl in thread safe manner.
/// </summary>
private PassthroughResources passthrough;
/// <summary>
/// Represents the AtomicReference for event resources.
///
/// It will be initialized in the constructor and will not change afterwards. The underlying value will be initially set
/// as null, and can be set via corresponding setter, therefore effectively the assumed user can be updated in the
/// SmartsheetImpl in thread safe manner.
/// </summary>
private EventResources events;
/// <summary>
/// static logger
/// </summary>
private static Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// Creates an instance with given server URI, HttpClient (optional), and JsonSerializer (optional)
///
/// Exceptions: - IllegalArgumentException : if serverURI/Version/AccessToken is null/empty
/// </summary>
/// <param name="baseURI"> the server uri </param>
/// <param name="accessToken"> the access token </param>
/// <param name="httpClient"> the HTTP client (optional) </param>
/// <param name="jsonSerializer"> the JSON serializer (optional) </param>
public SmartsheetImpl(string baseURI, string accessToken, HttpClient httpClient, JsonSerializer jsonSerializer)
: this(baseURI, accessToken, httpClient, jsonSerializer, false)
{
}
/// <summary>
/// Creates an instance with given server URI, HttpClient (optional), and JsonSerializer (optional)
///
/// Exceptions: - IllegalArgumentException : if serverURI/Version/AccessToken is null/empty
/// </summary>
/// <param name="baseURI"> the server uri </param>
/// <param name="accessToken"> the access token </param>
/// <param name="httpClient"> the HTTP client (optional) </param>
/// <param name="jsonSerializer"> the JSON serializer (optional) </param>
/// <param name="dateTimeFixOptOut"> opt out of deserializer string ==> DateTime conversion fix </param>
public SmartsheetImpl(string baseURI, string accessToken, HttpClient httpClient, JsonSerializer jsonSerializer, bool dateTimeFixOptOut)
{
Utils.ThrowIfNull(baseURI);
Utils.ThrowIfEmpty(baseURI);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
this.baseURI = new Uri(baseURI);
this.accessToken = accessToken;
if (jsonSerializer == null) {
JsonNetSerializer jsonNetSerializer = new JsonNetSerializer();
if(dateTimeFixOptOut)
jsonNetSerializer.DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTime;
jsonSerializer = jsonNetSerializer;
}
this.jsonSerializer = jsonSerializer;
this.httpClient = httpClient == null ? new DefaultHttpClient(new RestClient(), this.jsonSerializer) : httpClient;
this.UserAgent = null;
}
/// <summary>
/// Finalizes the object, this method is overridden to close the HttpClient.
/// </summary>
/// <exception cref="System.IO.IOException"> Signals that an I/O exception has occurred. </exception>
~SmartsheetImpl()
{
this.httpClient.Close();
}
/// <summary>
/// Getter of corresponding field.
/// </summary>
/// <returns> corresponding field. </returns>
public virtual HttpClient HttpClient
{
get { return httpClient; }
}
/// <summary>
/// Getter of corresponding field.
/// </summary>
/// <returns> corresponding field </returns>
public virtual JsonSerializer JsonSerializer
{
get { return jsonSerializer; }
}
/// <summary>
/// Getter of corresponding field.
///
/// Returns: corresponding field.
/// </summary>
/// <returns> the base uri </returns>
public Uri BaseURI
{
get { return baseURI; }
}
/// <summary>
/// Return the access token
/// </summary>
/// <returns> the access token </returns>
public string AccessToken
{
get { return accessToken; }
set { this.accessToken = value; }
}
/// <summary>
/// Return the assumed user.
/// </summary>
/// <returns> the assumed user </returns>
public string AssumedUser
{
get { return assumedUser; }
set { this.assumedUser = value; }
}
/// <summary>
/// Return the change agent
/// </summary>
/// <returns> the change agent </returns>
public string ChangeAgent
{
get { return changeAgent; }
set { this.changeAgent = value; }
}
/// <summary>
/// Set the RestSharp default user agent
/// </summary>
public string UserAgent
{
set {
if(this.httpClient is DefaultHttpClient)
((DefaultHttpClient)this.httpClient).SetUserAgent(GenerateUserAgent(value));
}
}
/// <summary>
/// Set the maximum retry timeout
/// </summary>
public long MaxRetryTimeout
{
set
{
if (this.httpClient is DefaultHttpClient)
((DefaultHttpClient)this.httpClient).SetMaxRetryTimeout(value);
}
}
/// <summary>
/// Returns the HomeResources instance that provides access to home resources.
/// </summary>
/// <returns> the home resources </returns>
public virtual HomeResources HomeResources
{
get
{
Interlocked.CompareExchange<HomeResources>(ref home, new HomeResourcesImpl(this), null);
return home;
}
}
/// <summary>
/// Returns the WorkspaceResources instance that provides access to workspace resources.
/// </summary>
/// <returns> the workspace resources </returns>
public virtual WorkspaceResources WorkspaceResources
{
get
{
Interlocked.CompareExchange<WorkspaceResources>(ref workspaces, new WorkspaceResourcesImpl(this), null);
return workspaces;
}
}
/// <summary>
/// Returns the FolderResources instance that provides access to folder resources.
/// </summary>
/// <returns> the folder resources </returns>
public virtual FolderResources FolderResources
{
get
{
Interlocked.CompareExchange<FolderResources>(ref folders, new FolderResourcesImpl(this), null);
return folders;
}
}
/// <summary>
/// Returns the TemplateResources instance that provides access to template resources.
/// </summary>
/// <returns> the template resources </returns>
public virtual TemplateResources TemplateResources
{
get
{
Interlocked.CompareExchange<TemplateResources>(ref templates, new TemplateResourcesImpl(this), null);
return templates;
}
}
/// <summary>
/// Returns the ReportResources instance that provides access to report resources.
/// </summary>
/// <returns> the report resources </returns>
public virtual ReportResources ReportResources
{
get
{
Interlocked.CompareExchange<ReportResources>(ref reports, new ReportResourcesImpl(this), null);
return reports;
}
}
/// <summary>
/// Returns the SheetResources instance that provides access to sheet resources.
/// </summary>
/// <returns> the sheet resources </returns>
public virtual SheetResources SheetResources
{
get
{
Interlocked.CompareExchange<SheetResources>(ref sheets, new SheetResourcesImpl(this), null);
return sheets;
}
}
/// <summary>
/// Returns the SightResources instance that provides access to Sight resources.
/// </summary>
/// <returns> the Sight resources </returns>
public virtual SightResources SightResources
{
get
{
Interlocked.CompareExchange<SightResources>(ref sights, new SightResourcesImpl(this), null);
return sights;
}
}
/// <summary>
/// Returns the WebhookResources instance that provides access to webhook resources.
/// </summary>
/// <returns> the webhook resources </returns>
public virtual WebhookResources WebhookResources
{
get
{
Interlocked.CompareExchange<WebhookResources>(ref webhooks, new WebhookResourcesImpl(this), null);
return webhooks;
}
}
/// <summary>
/// Returns the UserResources instance that provides access to user resources.
/// </summary>
/// <returns> the user resources </returns>
public virtual UserResources UserResources
{
get
{
Interlocked.CompareExchange<UserResources>(ref users, new UserResourcesImpl(this), null);
return users;
}
}
/// <summary>
/// Returns the SearchResources instance that provides access to searching resources.
/// </summary>
/// <returns> the search resources </returns>
public virtual SearchResources SearchResources
{
get
{
Interlocked.CompareExchange<SearchResources>(ref search, new SearchResourcesImpl(this), null);
return search;
}
}
/// <summary>
/// Returns the ServerInfoResources instance that provides access to server information resources.
/// </summary>
/// <returns> the server information resources </returns>
public virtual ServerInfoResources ServerInfoResources
{
get
{
Interlocked.CompareExchange<ServerInfoResources>(ref serverInfo, new ServerInfoResourcesImpl(this), null);
return serverInfo;
}
}
/// <summary>
/// Returns the GroupResources instance that provides access to group resources.
/// </summary>
/// <returns> the group resources </returns>
public virtual GroupResources GroupResources
{
get
{
Interlocked.CompareExchange<GroupResources>(ref groups, new GroupResourcesImpl(this), null);
return groups;
}
}
/// <summary>
/// Returns the FavoriteResources instance that provides access to favorite resources.
/// </summary>
/// <returns> the favorite resources </returns>
public virtual FavoriteResources FavoriteResources
{
get
{
Interlocked.CompareExchange<FavoriteResources>(ref favorites, new FavoriteResourcesImpl(this), null);
return favorites;
}
}
/// <summary>
/// Returns the TokenResources instance that provides access to token resources.
/// </summary>
/// <returns> the token resources </returns>
public virtual TokenResources TokenResources
{
get
{
Interlocked.CompareExchange<TokenResources>(ref tokens, new TokenResourcesImpl(this), null);
return tokens;
}
}
/// <summary>
/// Returns the ContactResources instance that provides access to contacts resources.
/// </summary>
/// <returns> the contacts resources </returns>
public virtual ContactResources ContactResources
{
get
{
Interlocked.CompareExchange<ContactResources>(ref contacts, new ContactResourcesImpl(this), null);
return contacts;
}
}
/// <summary>
/// Returns the ImageUrlResources instance that provides access to image URL resources.
/// </summary>
/// <returns> the image URL resources </returns>
public virtual ImageUrlsResources ImageUrlResources
{
get
{
Interlocked.CompareExchange<ImageUrlsResources>(ref imageUrls, new ImageUrlsResourcesImpl(this), null);
return imageUrls;
}
}
/// <summary>
/// Returns the PassthroughResources instance that provides access to passthrough resources.
/// </summary>
/// <returns> the passthrough resources </returns>
public virtual PassthroughResources PassthroughResources
{
get
{
Interlocked.CompareExchange<PassthroughResources>(ref passthrough, new PassthroughResourcesImpl(this), null);
return passthrough;
}
}
/// <summary>
/// Returns the EventResources instance that provides access to event resources.
/// </summary>
/// <returns> the event resources </returns>
public virtual EventResources EventResources
{
get
{
Interlocked.CompareExchange<EventResources>(ref events, new EventResourcesImpl(this), null);
return events;
}
}
/// <summary>
/// Compose a User-Agent string that represents this version of the SDK (along with platform info)
/// </summary>
/// <param name="userAgent"></param>
/// <returns> a User-Agent string </returns>
private string GenerateUserAgent(string userAgent)
{
// Set User Agent
string thisVersion = "";
string title = "";
Assembly assembly = Assembly.GetCallingAssembly();
if (assembly != null)
{
thisVersion = assembly.GetName().Version.ToString();
title = assembly.GetName().Name;
}
if (userAgent == null)
{
assembly = Assembly.GetEntryAssembly();
if (assembly != null)
{
string[] strings = assembly.GetName().ToString().Split(',');
if (strings.Length > 0)
userAgent = strings[0];
}
}
return title + "/" + thisVersion + "/" + userAgent + "/" + Utils.GetOSFriendlyName();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.Storage;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
namespace Orleans.Runtime
{
/// <summary>
/// Maintains additional per-activation state that is required for Orleans internal operations.
/// MUST lock this object for any concurrent access
/// Consider: compartmentalize by usage, e.g., using separate interfaces for data for catalog, etc.
/// </summary>
internal class ActivationData : IActivationData, IInvokable
{
// This class is used for activations that have extension invokers. It keeps a dictionary of
// invoker objects to use with the activation, and extend the default invoker
// defined for the grain class.
// Note that in all cases we never have more than one copy of an actual invoker;
// we may have a ExtensionInvoker per activation, in the worst case.
private class ExtensionInvoker : IGrainMethodInvoker
{
// Because calls to ExtensionInvoker are allways made within the activation context,
// we rely on the single-threading guarantee of the runtime and do not protect the map with a lock.
private Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>> extensionMap; // key is the extension interface ID
/// <summary>
/// Try to add an extension for the specific interface ID.
/// Fail and return false if there is already an extension for that interface ID.
/// Note that if an extension invoker handles multiple interface IDs, it can only be associated
/// with one of those IDs when added, and so only conflicts on that one ID will be detected and prevented.
/// </summary>
/// <param name="invoker"></param>
/// <param name="handler"></param>
/// <returns></returns>
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension handler)
{
if (extensionMap == null)
{
extensionMap = new Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>>(1);
}
if (extensionMap.ContainsKey(invoker.InterfaceId)) return false;
extensionMap.Add(invoker.InterfaceId, new Tuple<IGrainExtension, IGrainExtensionMethodInvoker>(handler, invoker));
return true;
}
/// <summary>
/// Removes all extensions for the specified interface id.
/// Returns true if the chained invoker no longer has any extensions and may be safely retired.
/// </summary>
/// <param name="extension"></param>
/// <returns>true if the chained invoker is now empty, false otherwise</returns>
public bool Remove(IGrainExtension extension)
{
int interfaceId = 0;
foreach(int iface in extensionMap.Keys)
if (extensionMap[iface].Item1 == extension)
{
interfaceId = iface;
break;
}
if (interfaceId == 0) // not found
throw new InvalidOperationException(String.Format("Extension {0} is not installed",
extension.GetType().FullName));
extensionMap.Remove(interfaceId);
return extensionMap.Count == 0;
}
public bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
if (extensionMap == null) return false;
foreach (var ext in extensionMap.Values)
if (extensionType == ext.Item1.GetType())
{
result = ext.Item1;
return true;
}
return false;
}
/// <summary>
/// Invokes the appropriate grain or extension method for the request interface ID and method ID.
/// First each extension invoker is tried; if no extension handles the request, then the base
/// invoker is used to handle the request.
/// The base invoker will throw an appropriate exception if the request is not recognized.
/// </summary>
/// <param name="grain"></param>
/// <param name="request"></param>
/// <returns></returns>
public Task<object> Invoke(IAddressable grain, InvokeMethodRequest request)
{
if (extensionMap == null || !extensionMap.ContainsKey(request.InterfaceId))
throw new InvalidOperationException(
String.Format("Extension invoker invoked with an unknown inteface ID:{0}.", request.InterfaceId));
var invoker = extensionMap[request.InterfaceId].Item2;
var extension = extensionMap[request.InterfaceId].Item1;
return invoker.Invoke(extension, request);
}
public bool IsExtensionInstalled(int interfaceId)
{
return extensionMap != null && extensionMap.ContainsKey(interfaceId);
}
public int InterfaceId
{
get { return 0; } // 0 indicates an extension invoker that may have multiple intefaces inplemented by extensions.
}
}
// This is the maximum amount of time we expect a request to continue processing
private static TimeSpan maxRequestProcessingTime;
private static NodeConfiguration nodeConfiguration;
public readonly TimeSpan CollectionAgeLimit;
private IGrainMethodInvoker lastInvoker;
// This is the maximum number of enqueued request messages for a single activation before we write a warning log or reject new requests.
private LimitValue maxEnqueuedRequestsLimit;
private HashSet<GrainTimer> timers;
private readonly TraceLogger logger;
public static void Init(ClusterConfiguration config, NodeConfiguration nodeConfig)
{
// Consider adding a config parameter for this
maxRequestProcessingTime = config.Globals.ResponseTimeout.Multiply(5);
nodeConfiguration = nodeConfig;
}
public ActivationData(ActivationAddress addr, string genericArguments, PlacementStrategy placedUsing, MultiClusterRegistrationStrategy registrationStrategy, IActivationCollector collector, TimeSpan ageLimit)
{
if (null == addr) throw new ArgumentNullException("addr");
if (null == placedUsing) throw new ArgumentNullException("placedUsing");
if (null == collector) throw new ArgumentNullException("collector");
logger = TraceLogger.GetLogger("ActivationData", TraceLogger.LoggerType.Runtime);
ResetKeepAliveRequest();
Address = addr;
State = ActivationState.Create;
PlacedUsing = placedUsing;
RegistrationStrategy = registrationStrategy;
if (!Grain.IsSystemTarget && !Constants.IsSystemGrain(Grain))
{
this.collector = collector;
}
CollectionAgeLimit = ageLimit;
GrainReference = GrainReference.FromGrainId(addr.Grain, genericArguments,
Grain.IsSystemTarget ? addr.Silo : null);
}
#region Method invocation
private ExtensionInvoker extensionInvoker;
public IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType=null)
{
// Return previous cached invoker, if applicable
if (lastInvoker != null && interfaceId == lastInvoker.InterfaceId) // extension invoker returns InterfaceId==0, so this condition will never be true if an extension is installed
return lastInvoker;
if (extensionInvoker != null && extensionInvoker.IsExtensionInstalled(interfaceId)) // HasExtensionInstalled(interfaceId)
// Shared invoker for all extensions installed on this grain
lastInvoker = extensionInvoker;
else
// Find the specific invoker for this interface / grain type
lastInvoker = RuntimeClient.Current.GetInvoker(interfaceId, genericGrainType);
return lastInvoker;
}
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension extension)
{
if(extensionInvoker == null)
extensionInvoker = new ExtensionInvoker();
return extensionInvoker.TryAddExtension(invoker, extension);
}
internal void RemoveExtension(IGrainExtension extension)
{
if (extensionInvoker != null)
{
if (extensionInvoker.Remove(extension))
extensionInvoker = null;
}
else
throw new InvalidOperationException("Grain extensions not installed.");
}
internal bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
return extensionInvoker != null && extensionInvoker.TryGetExtensionHandler(extensionType, out result);
}
#endregion
public string GrainTypeName
{
get
{
if (GrainInstanceType == null)
{
throw new ArgumentNullException("GrainInstanceType", "GrainInstanceType has not been set.");
}
return GrainInstanceType.FullName;
}
}
internal Type GrainInstanceType { get; private set; }
internal void SetGrainInstance(Grain grainInstance)
{
GrainInstance = grainInstance;
if (grainInstance != null)
{
GrainInstanceType = grainInstance.GetType();
// Don't ever collect system grains or reminder table grain or memory store grains.
bool doNotCollect = typeof(IReminderTableGrain).IsAssignableFrom(GrainInstanceType) || typeof(IMemoryStorageGrain).IsAssignableFrom(GrainInstanceType);
if (doNotCollect)
{
this.collector = null;
}
}
}
public IStorageProvider StorageProvider { get; set; }
private Streams.StreamDirectory streamDirectory;
internal Streams.StreamDirectory GetStreamDirectory()
{
return streamDirectory ?? (streamDirectory = new Streams.StreamDirectory());
}
internal bool IsUsingStreams
{
get { return streamDirectory != null; }
}
internal async Task DeactivateStreamResources()
{
if (streamDirectory == null) return; // No streams - Nothing to do.
if (extensionInvoker == null) return; // No installed extensions - Nothing to do.
if (StreamResourceTestControl.TestOnlySuppressStreamCleanupOnDeactivate)
{
logger.Warn(0, "Suppressing cleanup of stream resources during tests for {0}", this);
return;
}
await streamDirectory.Cleanup(true, false);
}
#region IActivationData
GrainReference IActivationData.GrainReference
{
get { return GrainReference; }
}
public GrainId Identity
{
get { return Grain; }
}
public Grain GrainInstance { get; private set; }
public ActivationId ActivationId { get { return Address.Activation; } }
public ActivationAddress Address { get; private set; }
public IDisposable RegisterTimer(Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period)
{
var timer = GrainTimer.FromTaskCallback(asyncCallback, state, dueTime, period);
AddTimer(timer);
timer.Start();
return timer;
}
#endregion
#region Catalog
internal readonly GrainReference GrainReference;
public SiloAddress Silo { get { return Address.Silo; } }
public GrainId Grain { get { return Address.Grain; } }
public ActivationState State { get; private set; }
public void SetState(ActivationState state)
{
State = state;
}
// Don't accept any new messages and stop all timers.
public void PrepareForDeactivation()
{
SetState(ActivationState.Deactivating);
StopAllTimers();
}
/// <summary>
/// If State == Invalid, this may contain a forwarding address for incoming messages
/// </summary>
public ActivationAddress ForwardingAddress { get; set; }
private IActivationCollector collector;
internal bool IsExemptFromCollection
{
get { return collector == null; }
}
public DateTime CollectionTicket { get; private set; }
private bool collectionCancelledFlag;
public bool TrySetCollectionCancelledFlag()
{
lock (this)
{
if (default(DateTime) == CollectionTicket || collectionCancelledFlag) return false;
collectionCancelledFlag = true;
return true;
}
}
public void ResetCollectionCancelledFlag()
{
lock (this)
{
collectionCancelledFlag = false;
}
}
public void ResetCollectionTicket()
{
CollectionTicket = default(DateTime);
}
public void SetCollectionTicket(DateTime ticket)
{
if (ticket == default(DateTime)) throw new ArgumentException("default(DateTime) is disallowed", "ticket");
if (CollectionTicket != default(DateTime))
{
throw new InvalidOperationException("call ResetCollectionTicket before calling SetCollectionTicket.");
}
CollectionTicket = ticket;
}
#endregion
#region Dispatcher
public PlacementStrategy PlacedUsing { get; private set; }
public MultiClusterRegistrationStrategy RegistrationStrategy { get; private set; }
// currently, the only supported multi-activation grain is one using the StatelessWorkerPlacement strategy.
internal bool IsStatelessWorker { get { return PlacedUsing is StatelessWorkerPlacement; } }
public Message Running { get; private set; }
// the number of requests that are currently executing on this activation.
// includes reentrant and non-reentrant requests.
private int numRunning;
private DateTime currentRequestStartTime;
private DateTime becameIdle;
public void RecordRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning++;
if (Running != null) return;
// This logic only works for non-reentrant activations
// Consider: Handle long request detection for reentrant activations.
Running = message;
currentRequestStartTime = DateTime.UtcNow;
}
public void ResetRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning--;
if (numRunning == 0)
{
becameIdle = DateTime.UtcNow;
if (!IsExemptFromCollection)
{
collector.TryRescheduleCollection(this);
}
}
// The below logic only works for non-reentrant activations.
if (Running != null && !message.Equals(Running)) return;
Running = null;
currentRequestStartTime = DateTime.MinValue;
}
private long inFlightCount;
private long enqueuedOnDispatcherCount;
/// <summary>
/// Number of messages that are actively being processed [as opposed to being in the Waiting queue].
/// In most cases this will be 0 or 1, but for Reentrant grains can be >1.
/// </summary>
public long InFlightCount { get { return Interlocked.Read(ref inFlightCount); } }
/// <summary>
/// Number of messages that are being received [as opposed to being in the scheduler queue or actively processed].
/// </summary>
public long EnqueuedOnDispatcherCount { get { return Interlocked.Read(ref enqueuedOnDispatcherCount); } }
/// <summary>Increment the number of in-flight messages currently being processed.</summary>
public void IncrementInFlightCount() { Interlocked.Increment(ref inFlightCount); }
/// <summary>Decrement the number of in-flight messages currently being processed.</summary>
public void DecrementInFlightCount() { Interlocked.Decrement(ref inFlightCount); }
/// <summary>Increment the number of messages currently in the prcess of being received.</summary>
public void IncrementEnqueuedOnDispatcherCount() { Interlocked.Increment(ref enqueuedOnDispatcherCount); }
/// <summary>Decrement the number of messages currently in the prcess of being received.</summary>
public void DecrementEnqueuedOnDispatcherCount() { Interlocked.Decrement(ref enqueuedOnDispatcherCount); }
/// <summary>
/// grouped by sending activation: responses first, then sorted by id
/// </summary>
private List<Message> waiting;
public int WaitingCount
{
get
{
return waiting == null ? 0 : waiting.Count;
}
}
/// <summary>
/// Insert in a FIFO order
/// </summary>
/// <param name="message"></param>
public bool EnqueueMessage(Message message)
{
lock (this)
{
if (State == ActivationState.Invalid)
{
logger.Warn(ErrorCode.Dispatcher_InvalidActivation,
"Cannot enqueue message to invalid activation {0} : {1}", this.ToDetailedString(), message);
return false;
}
// If maxRequestProcessingTime is never set, then we will skip this check
if (maxRequestProcessingTime.TotalMilliseconds > 0 && Running != null)
{
// Consider: Handle long request detection for reentrant activations -- this logic only works for non-reentrant activations
var currentRequestActiveTime = DateTime.UtcNow - currentRequestStartTime;
if (currentRequestActiveTime > maxRequestProcessingTime)
{
logger.Warn(ErrorCode.Dispatcher_ExtendedMessageProcessing,
"Current request has been active for {0} for activation {1}. Currently executing {2}. Trying to enqueue {3}.",
currentRequestActiveTime, this.ToDetailedString(), Running, message);
}
}
waiting = waiting ?? new List<Message>();
waiting.Add(message);
return true;
}
}
/// <summary>
/// Check whether this activation is overloaded.
/// Returns LimitExceededException if overloaded, otherwise <c>null</c>c>
/// </summary>
/// <param name="log">TraceLogger to use for reporting any overflow condition</param>
/// <returns>Returns LimitExceededException if overloaded, otherwise <c>null</c>c></returns>
public LimitExceededException CheckOverloaded(TraceLogger log)
{
LimitValue limitValue = GetMaxEnqueuedRequestLimit();
int maxRequestsHardLimit = limitValue.HardLimitThreshold;
int maxRequestsSoftLimit = limitValue.SoftLimitThreshold;
if (maxRequestsHardLimit <= 0 && maxRequestsSoftLimit <= 0) return null; // No limits are set
int count = GetRequestCount();
if (maxRequestsHardLimit > 0 && count > maxRequestsHardLimit) // Hard limit
{
log.Warn(ErrorCode.Catalog_Reject_ActivationTooManyRequests,
String.Format("Overload - {0} enqueued requests for activation {1}, exceeding hard limit rejection threshold of {2}",
count, this, maxRequestsHardLimit));
return new LimitExceededException(limitValue.Name, count, maxRequestsHardLimit, this.ToString());
}
if (maxRequestsSoftLimit > 0 && count > maxRequestsSoftLimit) // Soft limit
{
log.Warn(ErrorCode.Catalog_Warn_ActivationTooManyRequests,
String.Format("Hot - {0} enqueued requests for activation {1}, exceeding soft limit warning threshold of {2}",
count, this, maxRequestsSoftLimit));
return null;
}
return null;
}
internal int GetRequestCount()
{
lock (this)
{
long numInDispatcher = EnqueuedOnDispatcherCount;
long numActive = InFlightCount;
long numWaiting = WaitingCount;
return (int)(numInDispatcher + numActive + numWaiting);
}
}
private LimitValue GetMaxEnqueuedRequestLimit()
{
if (maxEnqueuedRequestsLimit != null) return maxEnqueuedRequestsLimit;
if (GrainInstanceType != null)
{
string limitName = CodeGeneration.GrainInterfaceUtils.IsStatelessWorker(GrainInstanceType)
? LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER
: LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS;
maxEnqueuedRequestsLimit = nodeConfiguration.LimitManager.GetLimit(limitName); // Cache for next time
return maxEnqueuedRequestsLimit;
}
return nodeConfiguration.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS);
}
public Message PeekNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0) return waiting[0];
return null;
}
public void DequeueNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0)
waiting.RemoveAt(0);
}
internal List<Message> DequeueAllWaitingMessages()
{
lock (this)
{
if (waiting == null) return null;
List<Message> tmp = waiting;
waiting = null;
return tmp;
}
}
#endregion
#region Activation collection
public bool IsInactive
{
get
{
return !IsCurrentlyExecuting && (waiting == null || waiting.Count == 0);
}
}
public bool IsCurrentlyExecuting
{
get
{
return numRunning > 0 ;
}
}
/// <summary>
/// Returns how long this activation has been idle.
/// </summary>
public TimeSpan GetIdleness(DateTime now)
{
if (now == default(DateTime))
throw new ArgumentException("default(DateTime) is not allowed; Use DateTime.UtcNow instead.", "now");
return now - becameIdle;
}
/// <summary>
/// Returns whether this activation has been idle long enough to be collected.
/// </summary>
public bool IsStale(DateTime now)
{
return GetIdleness(now) >= CollectionAgeLimit;
}
private DateTime keepAliveUntil;
public bool ShouldBeKeptAlive { get { return keepAliveUntil >= DateTime.UtcNow; } }
public void DelayDeactivation(TimeSpan timespan)
{
if (timespan <= TimeSpan.Zero)
{
// reset any current keepAliveUntill
ResetKeepAliveRequest();
}
else if (timespan == TimeSpan.MaxValue)
{
// otherwise creates negative time.
keepAliveUntil = DateTime.MaxValue;
}
else
{
keepAliveUntil = DateTime.UtcNow + timespan;
}
}
public void ResetKeepAliveRequest()
{
keepAliveUntil = DateTime.MinValue;
}
public List<Action> OnInactive { get; set; } // ActivationData
public void AddOnInactive(Action action) // ActivationData
{
lock (this)
{
if (OnInactive == null)
{
OnInactive = new List<Action>();
}
OnInactive.Add(action);
}
}
public void RunOnInactive()
{
lock (this)
{
if (OnInactive == null) return;
var actions = OnInactive;
OnInactive = null;
foreach (var action in actions)
{
action();
}
}
}
#endregion
#region In-grain Timers
internal void AddTimer(GrainTimer timer)
{
lock(this)
{
if (timers == null)
{
timers = new HashSet<GrainTimer>();
}
timers.Add(timer);
}
}
private void StopAllTimers()
{
lock (this)
{
if (timers == null) return;
foreach (var timer in timers)
{
timer.Stop();
}
}
}
internal void OnTimerDisposed(GrainTimer orleansTimerInsideGrain)
{
lock (this) // need to lock since dispose can be called on finalizer thread, outside garin context (not single threaded).
{
timers.Remove(orleansTimerInsideGrain);
}
}
internal Task WaitForAllTimersToFinish()
{
lock(this)
{
if (timers == null)
{
return TaskDone.Done;
}
var tasks = new List<Task>();
var timerCopy = timers.ToList(); // need to copy since OnTimerDisposed will change the timers set.
foreach (var timer in timerCopy)
{
// first call dispose, then wait to finish.
Utils.SafeExecute(timer.Dispose, logger, "timer.Dispose has thrown");
tasks.Add(timer.GetCurrentlyExecutingTickTask());
}
return Task.WhenAll(tasks);
}
}
#endregion
#region Printing functions
public string DumpStatus()
{
var sb = new StringBuilder();
lock (this)
{
sb.AppendFormat(" {0}", ToDetailedString());
if (Running != null)
{
sb.AppendFormat(" Processing message: {0}", Running);
}
if (waiting!=null && waiting.Count > 0)
{
sb.AppendFormat(" Messages queued within ActivationData: {0}", PrintWaitingQueue());
}
}
return sb.ToString();
}
public override string ToString()
{
return String.Format("[Activation: {0}{1}{2}{3} State={4}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString(),
State);
}
internal string ToDetailedString(bool includeExtraDetails = false)
{
return
String.Format(
"[Activation: {0}{1}{2}{3} State={4} NonReentrancyQueueSize={5} EnqueuedOnDispatcher={6} InFlightCount={7} NumRunning={8} IdlenessTimeSpan={9} CollectionAgeLimit={10}{11}]",
Silo.ToLongString(),
Grain.ToDetailedString(),
ActivationId,
GetActivationInfoString(),
State, // 4
WaitingCount, // 5 NonReentrancyQueueSize
EnqueuedOnDispatcherCount, // 6 EnqueuedOnDispatcher
InFlightCount, // 7 InFlightCount
numRunning, // 8 NumRunning
GetIdleness(DateTime.UtcNow), // 9 IdlenessTimeSpan
CollectionAgeLimit, // 10 CollectionAgeLimit
(includeExtraDetails && Running != null) ? " CurrentlyExecuting=" + Running : ""); // 11: Running
}
public string Name
{
get
{
return String.Format("[Activation: {0}{1}{2}{3}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString());
}
}
/// <summary>
/// Return string containing dump of the queue of waiting work items
/// </summary>
/// <returns></returns>
/// <remarks>Note: Caller must be holding lock on this activation while calling this method.</remarks>
internal string PrintWaitingQueue()
{
return Utils.EnumerableToString(waiting);
}
private string GetActivationInfoString()
{
var placement = PlacedUsing != null ? PlacedUsing.GetType().Name : String.Empty;
return GrainInstanceType == null ? placement :
String.Format(" #GrainType={0} Placement={1}", GrainInstanceType.FullName, placement);
}
#endregion
}
internal static class StreamResourceTestControl
{
internal static bool TestOnlySuppressStreamCleanupOnDeactivate;
}
}
| |
using System;
using System.Globalization;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using umbraco;
using umbraco.cms.businesslogic.web;
using RenderingEngine = Umbraco.Core.RenderingEngine;
namespace Umbraco.Web.Routing
{
/// <summary>
/// Represents a request for one specified Umbraco IPublishedContent to be rendered
/// by one specified template, using one specified Culture and RenderingEngine.
/// </summary>
public class PublishedContentRequest
{
private bool _readonly;
/// <summary>
/// Triggers once the published content request has been prepared, but before it is processed.
/// </summary>
/// <remarks>When the event triggers, preparation is done ie domain, culture, document, template,
/// rendering engine, etc. have been setup. It is then possible to change anything, before
/// the request is actually processed and rendered by Umbraco.</remarks>
public static event EventHandler<EventArgs> Prepared;
// the engine that does all the processing
// because in order to keep things clean and separated,
// the content request is just a data holder
private readonly PublishedContentRequestEngine _engine;
/// <summary>
/// Initializes a new instance of the <see cref="PublishedContentRequest"/> class with a specific Uri and routing context.
/// </summary>
/// <param name="uri">The request <c>Uri</c>.</param>
/// <param name="routingContext">A routing context.</param>
internal PublishedContentRequest(Uri uri, RoutingContext routingContext)
{
if (uri == null) throw new ArgumentNullException("uri");
if (routingContext == null) throw new ArgumentNullException("routingContext");
Uri = uri;
RoutingContext = routingContext;
_engine = new PublishedContentRequestEngine(this);
RenderingEngine = RenderingEngine.Unknown;
}
/// <summary>
/// Gets the engine associated to the request.
/// </summary>
internal PublishedContentRequestEngine Engine { get { return _engine; } }
/// <summary>
/// Prepares the request.
/// </summary>
internal void Prepare()
{
_engine.PrepareRequest();
ConfigureRequest();
}
/// <summary>
/// Called after the request is prepared - after content, templates, etc... have been assigned.
/// </summary>
/// <remarks>
/// This method must be called for the PCR to work, it is automatically called after the PCR is prepared.
/// This method has been exposed in case developers need to configure the request manually if they've manually assigned
/// a content instance to the PCR. (i.e. in EnsurePublishedContentRequestAttribute )
/// </remarks>
public void ConfigureRequest()
{
_engine.ConfigureRequest();
}
/// <summary>
/// Updates the request when there is no template to render the content.
/// </summary>
internal void UpdateOnMissingTemplate()
{
var __readonly = _readonly;
_readonly = false;
_engine.UpdateRequestOnMissingTemplate();
_readonly = __readonly;
}
/// <summary>
/// Triggers the Prepared event.
/// </summary>
internal void OnPrepared()
{
if (Prepared != null)
Prepared(this, EventArgs.Empty);
if (!HasPublishedContent)
Is404 = true; // safety
_readonly = true;
}
/// <summary>
/// Gets or sets the cleaned up Uri used for routing.
/// </summary>
/// <remarks>The cleaned up Uri has no virtual directory, no trailing slash, no .aspx extension, etc.</remarks>
public Uri Uri { get; private set; }
private void EnsureWriteable()
{
if (_readonly)
throw new InvalidOperationException("Cannot modify a PublishedContentRequest once it is read-only.");
}
#region PublishedContent
/// <summary>
/// The requested IPublishedContent, if any, else <c>null</c>.
/// </summary>
private IPublishedContent _publishedContent;
/// <summary>
/// The initial requested IPublishedContent, if any, else <c>null</c>.
/// </summary>
/// <remarks>The initial requested content is the content that was found by the finders,
/// before anything such as 404, redirect... took place.</remarks>
private IPublishedContent _initialPublishedContent;
/// <summary>
/// Gets or sets the requested content.
/// </summary>
/// <remarks>Setting the requested content clears <c>Template</c>.</remarks>
public IPublishedContent PublishedContent
{
get { return _publishedContent; }
set
{
EnsureWriteable();
_publishedContent = value;
IsInternalRedirectPublishedContent = false;
TemplateModel = null;
}
}
/// <summary>
/// Sets the requested content, following an internal redirect.
/// </summary>
/// <param name="content">The requested content.</param>
/// <remarks>Depending on <c>UmbracoSettings.InternalRedirectPreservesTemplate</c>, will
/// preserve or reset the template, if any.</remarks>
public void SetInternalRedirectPublishedContent(IPublishedContent content)
{
EnsureWriteable();
// unless a template has been set already by the finder,
// template should be null at that point.
// IsInternalRedirect if IsInitial, or already IsInternalRedirect
var isInternalRedirect = IsInitialPublishedContent || IsInternalRedirectPublishedContent;
// redirecting to self
if (content.Id == PublishedContent.Id) // neither can be null
{
// no need to set PublishedContent, we're done
IsInternalRedirectPublishedContent = isInternalRedirect;
return;
}
// else
// save
var template = _template;
var renderingEngine = RenderingEngine;
// set published content - this resets the template, and sets IsInternalRedirect to false
PublishedContent = content;
IsInternalRedirectPublishedContent = isInternalRedirect;
// must restore the template if it's an internal redirect & the config option is set
if (isInternalRedirect && UmbracoConfig.For.UmbracoSettings().WebRouting.InternalRedirectPreservesTemplate)
{
// restore
_template = template;
RenderingEngine = renderingEngine;
}
}
/// <summary>
/// Gets the initial requested content.
/// </summary>
/// <remarks>The initial requested content is the content that was found by the finders,
/// before anything such as 404, redirect... took place.</remarks>
public IPublishedContent InitialPublishedContent { get { return _initialPublishedContent; } }
/// <summary>
/// Gets value indicating whether the current published content is the initial one.
/// </summary>
public bool IsInitialPublishedContent
{
get
{
return _initialPublishedContent != null && _initialPublishedContent == _publishedContent;
}
}
/// <summary>
/// Indicates that the current PublishedContent is the initial one.
/// </summary>
public void SetIsInitialPublishedContent()
{
EnsureWriteable();
// note: it can very well be null if the initial content was not found
_initialPublishedContent = _publishedContent;
IsInternalRedirectPublishedContent = false;
}
/// <summary>
/// Gets or sets a value indicating whether the current published content has been obtained
/// from the initial published content following internal redirections exclusively.
/// </summary>
/// <remarks>Used by PublishedContentRequestEngine.FindTemplate() to figure out whether to
/// apply the internal redirect or not, when content is not the initial content.</remarks>
public bool IsInternalRedirectPublishedContent { get; private set; }
/// <summary>
/// Gets a value indicating whether the content request has a content.
/// </summary>
public bool HasPublishedContent
{
get { return PublishedContent != null; }
}
#endregion
#region Template
/// <summary>
/// The template model, if any, else <c>null</c>.
/// </summary>
private ITemplate _template;
/// <summary>
/// Gets or sets the template model to use to display the requested content.
/// </summary>
internal ITemplate TemplateModel
{
get
{
return _template;
}
set
{
_template = value;
RenderingEngine = RenderingEngine.Unknown; // reset
if (_template != null)
RenderingEngine = _engine.FindTemplateRenderingEngine(_template.Alias);
}
}
/// <summary>
/// Gets the alias of the template to use to display the requested content.
/// </summary>
public string TemplateAlias
{
get
{
return _template == null ? null : _template.Alias;
}
}
/// <summary>
/// Tries to set the template to use to display the requested content.
/// </summary>
/// <param name="alias">The alias of the template.</param>
/// <returns>A value indicating whether a valid template with the specified alias was found.</returns>
/// <remarks>
/// <para>Successfully setting the template does refresh <c>RenderingEngine</c>.</para>
/// <para>If setting the template fails, then the previous template (if any) remains in place.</para>
/// </remarks>
public bool TrySetTemplate(string alias)
{
EnsureWriteable();
if (string.IsNullOrWhiteSpace(alias))
{
TemplateModel = null;
return true;
}
// NOTE - can we stil get it with whitespaces in it due to old legacy bugs?
alias = alias.Replace(" ", "");
var model = ApplicationContext.Current.Services.FileService.GetTemplate(alias);
if (model == null)
return false;
TemplateModel = model;
return true;
}
/// <summary>
/// Sets the template to use to display the requested content.
/// </summary>
/// <param name="template">The template.</param>
/// <remarks>Setting the template does refresh <c>RenderingEngine</c>.</remarks>
public void SetTemplate(ITemplate template)
{
EnsureWriteable();
TemplateModel = template;
}
/// <summary>
/// Resets the template.
/// </summary>
/// <remarks>The <c>RenderingEngine</c> becomes unknown.</remarks>
public void ResetTemplate()
{
EnsureWriteable();
TemplateModel = null;
}
/// <summary>
/// Gets a value indicating whether the content request has a template.
/// </summary>
public bool HasTemplate
{
get { return _template != null; }
}
#endregion
#region Domain and Culture
/// <summary>
/// Gets or sets the content request's domain.
/// </summary>
public Domain Domain { get; internal set; }
/// <summary>
/// Gets or sets the content request's domain Uri.
/// </summary>
/// <remarks>The <c>Domain</c> may contain "example.com" whereas the <c>Uri</c> will be fully qualified eg "http://example.com/".</remarks>
public Uri DomainUri { get; internal set; }
/// <summary>
/// Gets a value indicating whether the content request has a domain.
/// </summary>
public bool HasDomain
{
get { return Domain != null; }
}
private CultureInfo _culture;
/// <summary>
/// Gets or sets the content request's culture.
/// </summary>
public CultureInfo Culture
{
get { return _culture; }
set
{
EnsureWriteable();
_culture = value;
}
}
// note: do we want to have an ordered list of alternate cultures,
// to allow for fallbacks when doing dictionnary lookup and such?
#endregion
#region Rendering
/// <summary>
/// Gets or sets whether the rendering engine is MVC or WebForms.
/// </summary>
public RenderingEngine RenderingEngine { get; internal set; }
#endregion
/// <summary>
/// Gets or sets the current RoutingContext.
/// </summary>
public RoutingContext RoutingContext { get; private set; }
/// <summary>
/// The "umbraco page" object.
/// </summary>
private page _umbracoPage;
/// <summary>
/// Gets or sets the "umbraco page" object.
/// </summary>
/// <remarks>
/// This value is only used for legacy/webforms code.
/// </remarks>
internal page UmbracoPage
{
get
{
if (_umbracoPage == null)
throw new InvalidOperationException("The UmbracoPage object has not been initialized yet.");
return _umbracoPage;
}
set { _umbracoPage = value; }
}
#region Status
/// <summary>
/// Gets or sets a value indicating whether the requested content could not be found.
/// </summary>
/// <remarks>This is set in the <c>PublishedContentRequestBuilder</c>.</remarks>
public bool Is404 { get; internal set; }
/// <summary>
/// Indicates that the requested content could not be found.
/// </summary>
/// <remarks>This is for public access, in custom content finders or <c>Prepared</c> event handlers,
/// where we want to allow developers to indicate a request is 404 but not to cancel it.</remarks>
public void SetIs404()
{
EnsureWriteable();
Is404 = true;
}
/// <summary>
/// Gets a value indicating whether the content request triggers a redirect (permanent or not).
/// </summary>
public bool IsRedirect { get { return !string.IsNullOrWhiteSpace(RedirectUrl); } }
/// <summary>
/// Gets or sets a value indicating whether the redirect is permanent.
/// </summary>
public bool IsRedirectPermanent { get; private set; }
/// <summary>
/// Gets or sets the url to redirect to, when the content request triggers a redirect.
/// </summary>
public string RedirectUrl { get; private set; }
/// <summary>
/// Indicates that the content request should trigger a redirect (302).
/// </summary>
/// <param name="url">The url to redirect to.</param>
/// <remarks>Does not actually perform a redirect, only registers that the response should
/// redirect. Redirect will or will not take place in due time.</remarks>
public void SetRedirect(string url)
{
EnsureWriteable();
RedirectUrl = url;
IsRedirectPermanent = false;
}
/// <summary>
/// Indicates that the content request should trigger a permanent redirect (301).
/// </summary>
/// <param name="url">The url to redirect to.</param>
/// <remarks>Does not actually perform a redirect, only registers that the response should
/// redirect. Redirect will or will not take place in due time.</remarks>
public void SetRedirectPermanent(string url)
{
EnsureWriteable();
RedirectUrl = url;
IsRedirectPermanent = true;
}
/// <summary>
/// Indicates that the content requet should trigger a redirect, with a specified status code.
/// </summary>
/// <param name="url">The url to redirect to.</param>
/// <param name="status">The status code (300-308).</param>
/// <remarks>Does not actually perform a redirect, only registers that the response should
/// redirect. Redirect will or will not take place in due time.</remarks>
public void SetRedirect(string url, int status)
{
EnsureWriteable();
if (status < 300 || status > 308)
throw new ArgumentOutOfRangeException("status", "Valid redirection status codes 300-308.");
RedirectUrl = url;
IsRedirectPermanent = (status == 301 || status == 308);
if (status != 301 && status != 302) // default redirect statuses
ResponseStatusCode = status;
}
/// <summary>
/// Gets or sets the content request http response status code.
/// </summary>
/// <remarks>Does not actually set the http response status code, only registers that the response
/// should use the specified code. The code will or will not be used, in due time.</remarks>
public int ResponseStatusCode { get; private set; }
/// <summary>
/// Gets or sets the content request http response status description.
/// </summary>
/// <remarks>Does not actually set the http response status description, only registers that the response
/// should use the specified description. The description will or will not be used, in due time.</remarks>
public string ResponseStatusDescription { get; private set; }
/// <summary>
/// Sets the http response status code, along with an optional associated description.
/// </summary>
/// <param name="code">The http status code.</param>
/// <param name="description">The description.</param>
/// <remarks>Does not actually set the http response status code and description, only registers that
/// the response should use the specified code and description. The code and description will or will
/// not be used, in due time.</remarks>
public void SetResponseStatus(int code, string description = null)
{
EnsureWriteable();
// .Status is deprecated
// .SubStatusCode is IIS 7+ internal, ignore
ResponseStatusCode = code;
ResponseStatusDescription = description;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Globalization
{
public static class __NumberFormatInfo
{
public static IObservable<System.Globalization.NumberFormatInfo> GetInstance(
IObservable<System.IFormatProvider> formatProvider)
{
return Observable.Select(formatProvider,
(formatProviderLambda) => System.Globalization.NumberFormatInfo.GetInstance(formatProviderLambda));
}
public static IObservable<System.Object> Clone(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.Clone());
}
public static IObservable<System.Object> GetFormat(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Type> formatType)
{
return Observable.Zip(NumberFormatInfoValue, formatType,
(NumberFormatInfoValueLambda, formatTypeLambda) =>
NumberFormatInfoValueLambda.GetFormat(formatTypeLambda));
}
public static IObservable<System.Globalization.NumberFormatInfo> ReadOnly(
IObservable<System.Globalization.NumberFormatInfo> nfi)
{
return Observable.Select(nfi, (nfiLambda) => System.Globalization.NumberFormatInfo.ReadOnly(nfiLambda));
}
public static IObservable<System.Globalization.NumberFormatInfo> get_InvariantInfo()
{
return ObservableExt.Factory(() => System.Globalization.NumberFormatInfo.InvariantInfo);
}
public static IObservable<System.Int32> get_CurrencyDecimalDigits(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.CurrencyDecimalDigits);
}
public static IObservable<System.String> get_CurrencyDecimalSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.CurrencyDecimalSeparator);
}
public static IObservable<System.Boolean> get_IsReadOnly(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.IsReadOnly);
}
public static IObservable<System.Int32[]> get_CurrencyGroupSizes(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.CurrencyGroupSizes);
}
public static IObservable<System.Int32[]> get_NumberGroupSizes(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.NumberGroupSizes);
}
public static IObservable<System.Int32[]> get_PercentGroupSizes(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PercentGroupSizes);
}
public static IObservable<System.String> get_CurrencyGroupSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.CurrencyGroupSeparator);
}
public static IObservable<System.String> get_CurrencySymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.CurrencySymbol);
}
public static IObservable<System.Globalization.NumberFormatInfo> get_CurrentInfo()
{
return ObservableExt.Factory(() => System.Globalization.NumberFormatInfo.CurrentInfo);
}
public static IObservable<System.String> get_NaNSymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.NaNSymbol);
}
public static IObservable<System.Int32> get_CurrencyNegativePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.CurrencyNegativePattern);
}
public static IObservable<System.Int32> get_NumberNegativePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.NumberNegativePattern);
}
public static IObservable<System.Int32> get_PercentPositivePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PercentPositivePattern);
}
public static IObservable<System.Int32> get_PercentNegativePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PercentNegativePattern);
}
public static IObservable<System.String> get_NegativeInfinitySymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.NegativeInfinitySymbol);
}
public static IObservable<System.String> get_NegativeSign(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.NegativeSign);
}
public static IObservable<System.Int32> get_NumberDecimalDigits(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.NumberDecimalDigits);
}
public static IObservable<System.String> get_NumberDecimalSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.NumberDecimalSeparator);
}
public static IObservable<System.String> get_NumberGroupSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.NumberGroupSeparator);
}
public static IObservable<System.Int32> get_CurrencyPositivePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.CurrencyPositivePattern);
}
public static IObservable<System.String> get_PositiveInfinitySymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PositiveInfinitySymbol);
}
public static IObservable<System.String> get_PositiveSign(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PositiveSign);
}
public static IObservable<System.Int32> get_PercentDecimalDigits(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PercentDecimalDigits);
}
public static IObservable<System.String> get_PercentDecimalSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PercentDecimalSeparator);
}
public static IObservable<System.String> get_PercentGroupSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PercentGroupSeparator);
}
public static IObservable<System.String> get_PercentSymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PercentSymbol);
}
public static IObservable<System.String> get_PerMilleSymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.PerMilleSymbol);
}
public static IObservable<System.String[]> get_NativeDigits(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.NativeDigits);
}
public static IObservable<System.Globalization.DigitShapes> get_DigitSubstitution(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue)
{
return Observable.Select(NumberFormatInfoValue,
(NumberFormatInfoValueLambda) => NumberFormatInfoValueLambda.DigitSubstitution);
}
public static IObservable<System.Reactive.Unit> set_CurrencyDecimalDigits(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.CurrencyDecimalDigits = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_CurrencyDecimalSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.CurrencyDecimalSeparator = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_CurrencyGroupSizes(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32[]> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.CurrencyGroupSizes = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_NumberGroupSizes(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32[]> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) => NumberFormatInfoValueLambda.NumberGroupSizes = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PercentGroupSizes(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32[]> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.PercentGroupSizes = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_CurrencyGroupSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.CurrencyGroupSeparator = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_CurrencySymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) => NumberFormatInfoValueLambda.CurrencySymbol = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_NaNSymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) => NumberFormatInfoValueLambda.NaNSymbol = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_CurrencyNegativePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.CurrencyNegativePattern = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_NumberNegativePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.NumberNegativePattern = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PercentPositivePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.PercentPositivePattern = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PercentNegativePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.PercentNegativePattern = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_NegativeInfinitySymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.NegativeInfinitySymbol = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_NegativeSign(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) => NumberFormatInfoValueLambda.NegativeSign = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_NumberDecimalDigits(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.NumberDecimalDigits = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_NumberDecimalSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.NumberDecimalSeparator = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_NumberGroupSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.NumberGroupSeparator = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_CurrencyPositivePattern(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.CurrencyPositivePattern = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PositiveInfinitySymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.PositiveInfinitySymbol = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PositiveSign(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) => NumberFormatInfoValueLambda.PositiveSign = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PercentDecimalDigits(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.PercentDecimalDigits = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PercentDecimalSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.PercentDecimalSeparator = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PercentGroupSeparator(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.PercentGroupSeparator = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PercentSymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) => NumberFormatInfoValueLambda.PercentSymbol = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PerMilleSymbol(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) => NumberFormatInfoValueLambda.PerMilleSymbol = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_NativeDigits(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.String[]> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) => NumberFormatInfoValueLambda.NativeDigits = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_DigitSubstitution(
this IObservable<System.Globalization.NumberFormatInfo> NumberFormatInfoValue,
IObservable<System.Globalization.DigitShapes> value)
{
return ObservableExt.ZipExecute(NumberFormatInfoValue, value,
(NumberFormatInfoValueLambda, valueLambda) =>
NumberFormatInfoValueLambda.DigitSubstitution = valueLambda);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for OriginsOperations.
/// </summary>
public static partial class OriginsOperationsExtensions
{
/// <summary>
/// Lists the existing CDN origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static IEnumerable<Origin> ListByEndpoint(this IOriginsOperations operations, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IOriginsOperations)s).ListByEndpointAsync(endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the existing CDN origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<Origin>> ListByEndpointAsync(this IOriginsOperations operations, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByEndpointWithHttpMessagesAsync(endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin, an arbitrary value but it needs to be unique under
/// endpoint
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Origin Get(this IOriginsOperations operations, string originName, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IOriginsOperations)s).GetAsync(originName, endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin, an arbitrary value but it needs to be unique under
/// endpoint
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> GetAsync(this IOriginsOperations operations, string originName, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(originName, endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin, an arbitrary value but it needs to be unique under
/// endpoint
/// </param>
/// <param name='originProperties'>
/// Origin properties
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Origin Create(this IOriginsOperations operations, string originName, OriginParameters originProperties, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IOriginsOperations)s).CreateAsync(originName, originProperties, endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin, an arbitrary value but it needs to be unique under
/// endpoint
/// </param>
/// <param name='originProperties'>
/// Origin properties
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> CreateAsync(this IOriginsOperations operations, string originName, OriginParameters originProperties, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(originName, originProperties, endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin, an arbitrary value but it needs to be unique under
/// endpoint
/// </param>
/// <param name='originProperties'>
/// Origin properties
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Origin BeginCreate(this IOriginsOperations operations, string originName, OriginParameters originProperties, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IOriginsOperations)s).BeginCreateAsync(originName, originProperties, endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin, an arbitrary value but it needs to be unique under
/// endpoint
/// </param>
/// <param name='originProperties'>
/// Origin properties
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> BeginCreateAsync(this IOriginsOperations operations, string originName, OriginParameters originProperties, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(originName, originProperties, endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin. Must be unique within endpoint.
/// </param>
/// <param name='originProperties'>
/// Origin properties
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Origin Update(this IOriginsOperations operations, string originName, OriginParameters originProperties, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IOriginsOperations)s).UpdateAsync(originName, originProperties, endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin. Must be unique within endpoint.
/// </param>
/// <param name='originProperties'>
/// Origin properties
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> UpdateAsync(this IOriginsOperations operations, string originName, OriginParameters originProperties, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(originName, originProperties, endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin. Must be unique within endpoint.
/// </param>
/// <param name='originProperties'>
/// Origin properties
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Origin BeginUpdate(this IOriginsOperations operations, string originName, OriginParameters originProperties, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IOriginsOperations)s).BeginUpdateAsync(originName, originProperties, endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin. Must be unique within endpoint.
/// </param>
/// <param name='originProperties'>
/// Origin properties
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> BeginUpdateAsync(this IOriginsOperations operations, string originName, OriginParameters originProperties, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(originName, originProperties, endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin. Must be unique within endpoint.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Origin DeleteIfExists(this IOriginsOperations operations, string originName, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IOriginsOperations)s).DeleteIfExistsAsync(originName, endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin. Must be unique within endpoint.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> DeleteIfExistsAsync(this IOriginsOperations operations, string originName, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteIfExistsWithHttpMessagesAsync(originName, endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin. Must be unique within endpoint.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
public static Origin BeginDeleteIfExists(this IOriginsOperations operations, string originName, string endpointName, string profileName, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IOriginsOperations)s).BeginDeleteIfExistsAsync(originName, endpointName, profileName, resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='originName'>
/// Name of the origin. Must be unique within endpoint.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint within the CDN profile.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile within the resource group.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group within the Azure subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Origin> BeginDeleteIfExistsAsync(this IOriginsOperations operations, string originName, string endpointName, string profileName, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDeleteIfExistsWithHttpMessagesAsync(originName, endpointName, profileName, resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// EntryPopup.cs
//
// Author:
// Neil Loknath <[email protected]>
//
// Copyright (C) 2009 Neil Loknath
//
// 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.Timers;
using Gdk;
using Gtk;
namespace Hyena.Widgets
{
public class EntryPopup : Gtk.Window
{
private Entry text_entry;
private HBox hbox;
private uint timeout_id = 0;
public event EventHandler<EventArgs> Changed;
public event EventHandler<KeyPressEventArgs> KeyPressed;
public EntryPopup (string text) : this ()
{
Text = text;
}
public EntryPopup () : base (Gtk.WindowType.Popup)
{
CanFocus = true;
Resizable = false;
TypeHint = Gdk.WindowTypeHint.Utility;
Modal = true;
Frame frame = new Frame ();
frame.ShadowType = ShadowType.EtchedIn;
Add (frame);
hbox = new HBox () { Spacing = 6 };
text_entry = new Entry();
hbox.PackStart (text_entry, true, true, 0);
hbox.BorderWidth = 3;
frame.Add (hbox);
frame.ShowAll ();
text_entry.Text = String.Empty;
text_entry.CanFocus = true;
//TODO figure out why this event does not get raised
text_entry.FocusOutEvent += (o, a) => {
if (hide_when_focus_lost) {
HidePopup ();
}
};
text_entry.KeyReleaseEvent += delegate (object o, KeyReleaseEventArgs args) {
if (args.Event.Key == Gdk.Key.Escape ||
args.Event.Key == Gdk.Key.Return ||
args.Event.Key == Gdk.Key.Tab) {
HidePopup ();
}
InitializeDelayedHide ();
};
text_entry.KeyPressEvent += (o, a) => OnKeyPressed (a);
text_entry.Changed += (o, a) => {
if (Window.IsVisible) {
OnChanged (a);
}
};
}
public new bool HasFocus {
get { return text_entry.HasFocus; }
set { text_entry.HasFocus = value; }
}
public string Text {
get { return text_entry.Text; }
set { text_entry.Text = value; }
}
public Entry Entry { get { return text_entry; } }
public HBox Box { get { return hbox; } }
private bool hide_after_timeout = true;
public bool HideAfterTimeout {
get { return hide_after_timeout; }
set { hide_after_timeout = value; }
}
private uint timeout = 5000;
public uint Timeout {
get { return timeout; }
set { timeout = value; }
}
private bool hide_when_focus_lost = true;
public bool HideOnFocusOut {
get { return hide_when_focus_lost; }
set { hide_when_focus_lost = value; }
}
private bool reset_when_hiding = true;
public bool ResetOnHide {
get { return reset_when_hiding; }
set { reset_when_hiding = value; }
}
protected override void Dispose (bool disposing)
{
text_entry.Dispose ();
base.Dispose (disposing);
}
public new void GrabFocus ()
{
text_entry.GrabFocus ();
}
public void Position (Gdk.Window eventWindow)
{
int x, y;
int widget_x, widget_y;
int widget_height, widget_width;
Realize ();
Gdk.Window widget_window = eventWindow;
Gdk.Screen widget_screen = widget_window.Screen;
Gtk.Requisition popup_req;
widget_window.GetOrigin (out widget_x, out widget_y);
widget_width = widget_window.Width;
widget_height = widget_window.Height;
popup_req = Requisition;
if (widget_x + widget_width > widget_screen.Width) {
x = widget_screen.Width - popup_req.Width;
} else if (widget_x + widget_width - popup_req.Width < 0) {
x = 0;
} else {
x = widget_x + widget_width - popup_req.Width;
}
if (widget_y + widget_height + popup_req.Height > widget_screen.Height) {
y = widget_screen.Height - popup_req.Height;
} else if (widget_y + widget_height < 0) {
y = 0;
} else {
y = widget_y + widget_height;
}
Move (x, y);
}
private void ResetDelayedHide ()
{
if (timeout_id > 0) {
GLib.Source.Remove (timeout_id);
timeout_id = 0;
}
}
private void InitializeDelayedHide ()
{
ResetDelayedHide ();
timeout_id = GLib.Timeout.Add (timeout, delegate {
HidePopup ();
return false;
});
}
private void HidePopup ()
{
ResetDelayedHide ();
Hide ();
if (reset_when_hiding) {
text_entry.Text = String.Empty;
}
}
protected virtual void OnChanged (EventArgs args)
{
var handler = Changed;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
protected virtual void OnKeyPressed (KeyPressEventArgs args)
{
var handler = KeyPressed;
if (handler != null) {
handler (this, args);
}
}
//TODO figure out why this event does not get raised
protected override bool OnFocusOutEvent (Gdk.EventFocus evnt)
{
if (hide_when_focus_lost) {
HidePopup ();
return true;
}
return base.OnFocusOutEvent (evnt);
}
protected override bool OnDrawn (Cairo.Context cr)
{
InitializeDelayedHide ();
return base.OnDrawn (cr);
}
protected override bool OnButtonReleaseEvent (Gdk.EventButton evnt)
{
if (!text_entry.HasFocus && hide_when_focus_lost) {
HidePopup ();
return true;
}
return base.OnButtonReleaseEvent (evnt);
}
protected override bool OnButtonPressEvent (Gdk.EventButton evnt)
{
if (!text_entry.HasFocus && hide_when_focus_lost) {
HidePopup ();
return true;
}
return base.OnButtonPressEvent (evnt);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Abc.Zebus.Routing;
namespace Abc.Zebus.Directory
{
public class PeerSubscriptionTree
{
private readonly SubscriptionNode _rootNode = new SubscriptionNode(0, false);
private List<Peer> _peersMatchingAllMessages = new List<Peer>();
public bool IsEmpty
{
get { return _rootNode.IsEmpty && _peersMatchingAllMessages.Count == 0; }
}
public void Add(Peer peer, BindingKey subscription)
{
UpdatePeerSubscription(peer, subscription, UpdateAction.Add);
}
public void Remove(Peer peer, BindingKey subscription)
{
UpdatePeerSubscription(peer, subscription, UpdateAction.Remove);
}
public IList<Peer> GetPeers(BindingKey routingKey)
{
var peerCollector = new PeerCollector(_peersMatchingAllMessages);
_rootNode.Accept(peerCollector, routingKey);
return peerCollector.GetPeers();
}
private void UpdatePeerSubscription(Peer peer, BindingKey subscription, UpdateAction action)
{
if (subscription.IsEmpty)
UpdatePeersMatchingAllMessages(peer, action);
else
_rootNode.Update(peer, subscription, action);
}
private void UpdatePeersMatchingAllMessages(Peer peer, UpdateAction action)
{
UpdateList(ref _peersMatchingAllMessages, peer, action);
}
private static void UpdateList(ref List<Peer> peers, Peer peer, UpdateAction action)
{
var newPeers = new List<Peer>(peers.Capacity);
newPeers.AddRange(peers.Where(x => x.Id != peer.Id));
if (action == UpdateAction.Add)
newPeers.Add(peer);
peers = newPeers;
}
private class PeerCollector
{
private readonly Dictionary<PeerId, Peer> _collectedPeers = new Dictionary<PeerId, Peer>();
private readonly List<Peer> _initialPeers;
public PeerCollector(List<Peer> initialPeers)
{
_initialPeers = initialPeers;
}
public void Offer(IEnumerable<Peer> peers)
{
foreach (var peer in peers)
{
_collectedPeers[peer.Id] = peer;
}
}
public List<Peer> GetPeers()
{
if (_collectedPeers.Count == 0)
return _initialPeers;
Offer(_initialPeers);
return _collectedPeers.Values.ToList();
}
}
private class SubscriptionNode
{
private static readonly Action<SubscriptionNode, string> _removeNode = (x, part) => x.RemoveChildNode(part);
private static readonly Action<SubscriptionNode, string> _removeSharpNode = (x, _) => x._sharpNode = null;
private static readonly Action<SubscriptionNode, string> _removeStarNode = (x, _) => x._starNode = null;
private readonly Func<string, SubscriptionNode> _createChildNode;
private readonly int _nextPartIndex;
private readonly bool _matchesAll;
private ConcurrentDictionary<string, SubscriptionNode> _childrenNodes;
private List<Peer> _peers = new List<Peer>();
private SubscriptionNode _sharpNode;
private SubscriptionNode _starNode;
private int _peerCountIncludingChildren;
public SubscriptionNode(int nextPartIndex, bool matchesAll)
{
_nextPartIndex = nextPartIndex;
_matchesAll = matchesAll;
_createChildNode = _ => new SubscriptionNode(_nextPartIndex + 1, false);
}
public bool IsEmpty
{
get { return _peerCountIncludingChildren == 0; }
}
public void Accept(PeerCollector peerCollector, BindingKey routingKey)
{
if (IsLeaf(routingKey) || _matchesAll)
{
peerCollector.Offer(_peers);
return;
}
if (_sharpNode != null)
_sharpNode.Accept(peerCollector, routingKey);
if (_starNode != null)
_starNode.Accept(peerCollector, routingKey);
var nextPart = routingKey.GetPart(_nextPartIndex);
if (nextPart == null)
return;
if (_childrenNodes == null)
return;
SubscriptionNode childNode;
if (_childrenNodes.TryGetValue(nextPart, out childNode))
childNode.Accept(peerCollector, routingKey);
}
public int Update(Peer peer, BindingKey subscription, UpdateAction action)
{
if (IsLeaf(subscription))
{
var update = UpdateList(peer, action);
_peerCountIncludingChildren += update;
return update;
}
var nextPart = subscription.GetPart(_nextPartIndex);
if (nextPart == "#" || nextPart == null)
{
var sharpNode = GetOrCreateSharpNode();
return UpdateChildNode(sharpNode, peer, subscription, action, null, _removeSharpNode);
}
if (nextPart == "*")
{
var starNode = GetOrCreateStarNode();
return UpdateChildNode(starNode, peer, subscription, action, null, _removeStarNode);
}
var childNode = GetOrAddChildNode(nextPart);
return UpdateChildNode(childNode, peer, subscription, action, nextPart, _removeNode);
}
private int UpdateChildNode(SubscriptionNode childNode, Peer peer, BindingKey subscription, UpdateAction action, string childNodePart, Action<SubscriptionNode, string> remover)
{
var update = childNode.Update(peer, subscription, action);
_peerCountIncludingChildren += update;
if (childNode.IsEmpty)
remover(this, childNodePart);
return update;
}
private bool IsLeaf(BindingKey bindingKey)
{
if (_nextPartIndex == 0)
return false;
if (bindingKey.IsEmpty)
return _nextPartIndex == 1;
return _nextPartIndex == bindingKey.PartCount;
}
private SubscriptionNode GetOrAddChildNode(string part)
{
if (_childrenNodes == null)
_childrenNodes = new ConcurrentDictionary<string, SubscriptionNode>();
return _childrenNodes.GetOrAdd(part, _createChildNode);
}
private void RemoveChildNode(string part)
{
if (_childrenNodes == null)
return;
SubscriptionNode node;
_childrenNodes.TryRemove(part, out node);
}
private SubscriptionNode GetOrCreateSharpNode()
{
return _sharpNode ?? (_sharpNode = new SubscriptionNode(_nextPartIndex + 1, true));
}
private SubscriptionNode GetOrCreateStarNode()
{
return _starNode ?? (_starNode = new SubscriptionNode(_nextPartIndex + 1, false));
}
private int UpdateList(Peer peer, UpdateAction action)
{
return action == UpdateAction.Add ? AddToList(peer) : RemoveFromList(peer);
}
private int AddToList(Peer peerToAdd)
{
var removed = false;
var newPeers = new List<Peer>(_peers.Capacity);
foreach (var peer in _peers)
{
if (peer.Id == peerToAdd.Id)
removed = true;
else
newPeers.Add(peer);
}
newPeers.Add(peerToAdd);
_peers = newPeers;
return removed ? 0 : 1;
}
private int RemoveFromList(Peer peerToRemove)
{
var removed = false;
var newPeers = new List<Peer>(_peers.Capacity);
foreach (var peer in _peers)
{
if (peer.Id == peerToRemove.Id)
removed = true;
else
newPeers.Add(peer);
}
_peers = newPeers;
return removed ? -1 : 0;
}
}
private enum UpdateAction
{
Add,
Remove,
}
}
}
| |
#if UNITY_WINRT && !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.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
internal enum JsonContractType
{
None,
Object,
Array,
Primitive,
String,
Dictionary,
Dynamic,
Linq
}
/// <summary>
/// Handles <see cref="JsonSerializer"/> serialization callback events.
/// </summary>
/// <param name="o">The object that raised the callback event.</param>
/// <param name="context">The streaming context.</param>
public delegate void SerializationCallback(object o, StreamingContext context);
/// <summary>
/// Handles <see cref="JsonSerializer"/> serialization error callback events.
/// </summary>
/// <param name="o">The object that raised the callback event.</param>
/// <param name="context">The streaming context.</param>
/// <param name="errorContext">The error context.</param>
public delegate void SerializationErrorCallback(object o, StreamingContext context, ErrorContext errorContext);
/// <summary>
/// Sets extension data for an object during deserialization.
/// </summary>
/// <param name="o">The object to set extension data on.</param>
/// <param name="key">The extension data key.</param>
/// <param name="value">The extension data value.</param>
public delegate void ExtensionDataSetter(object o, string key, object value);
/// <summary>
/// Gets extension data for an object during serialization.
/// </summary>
/// <param name="o">The object to set extension data on.</param>
public delegate IEnumerable<KeyValuePair<object, object>> ExtensionDataGetter(object o);
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public abstract class JsonContract
{
internal bool IsNullable;
internal bool IsConvertable;
internal bool IsSealed;
internal bool IsEnum;
internal Type NonNullableUnderlyingType;
internal ReadType InternalReadType;
internal JsonContractType ContractType;
internal bool IsReadOnlyOrFixedSize;
internal bool IsInstantiable;
private List<SerializationCallback> _onDeserializedCallbacks;
private IList<SerializationCallback> _onDeserializingCallbacks;
private IList<SerializationCallback> _onSerializedCallbacks;
private IList<SerializationCallback> _onSerializingCallbacks;
private IList<SerializationErrorCallback> _onErrorCallbacks;
/// <summary>
/// Gets the underlying type for the contract.
/// </summary>
/// <value>The underlying type for the contract.</value>
public Type UnderlyingType { get; private set; }
/// <summary>
/// Gets or sets the type created during deserialization.
/// </summary>
/// <value>The type created during deserialization.</value>
public Type CreatedType { get; set; }
/// <summary>
/// Gets or sets whether this type contract is serialized as a reference.
/// </summary>
/// <value>Whether this type contract is serialized as a reference.</value>
public bool? IsReference { get; set; }
/// <summary>
/// Gets or sets the default <see cref="JsonConverter" /> for this contract.
/// </summary>
/// <value>The converter.</value>
public JsonConverter Converter { get; set; }
// internally specified JsonConverter's to override default behavour
// checked for after passed in converters and attribute specified converters
internal JsonConverter InternalConverter { get; set; }
/// <summary>
/// Gets or sets all methods called immediately after deserialization of the object.
/// </summary>
/// <value>The methods called immediately after deserialization of the object.</value>
public IList<SerializationCallback> OnDeserializedCallbacks
{
get
{
if (_onDeserializedCallbacks == null)
_onDeserializedCallbacks = new List<SerializationCallback>();
return _onDeserializedCallbacks;
}
}
/// <summary>
/// Gets or sets all methods called during deserialization of the object.
/// </summary>
/// <value>The methods called during deserialization of the object.</value>
public IList<SerializationCallback> OnDeserializingCallbacks
{
get
{
if (_onDeserializingCallbacks == null)
_onDeserializingCallbacks = new List<SerializationCallback>();
return _onDeserializingCallbacks;
}
}
/// <summary>
/// Gets or sets all methods called after serialization of the object graph.
/// </summary>
/// <value>The methods called after serialization of the object graph.</value>
public IList<SerializationCallback> OnSerializedCallbacks
{
get
{
if (_onSerializedCallbacks == null)
_onSerializedCallbacks = new List<SerializationCallback>();
return _onSerializedCallbacks;
}
}
/// <summary>
/// Gets or sets all methods called before serialization of the object.
/// </summary>
/// <value>The methods called before serialization of the object.</value>
public IList<SerializationCallback> OnSerializingCallbacks
{
get
{
if (_onSerializingCallbacks == null)
_onSerializingCallbacks = new List<SerializationCallback>();
return _onSerializingCallbacks;
}
}
/// <summary>
/// Gets or sets all method called when an error is thrown during the serialization of the object.
/// </summary>
/// <value>The methods called when an error is thrown during the serialization of the object.</value>
public IList<SerializationErrorCallback> OnErrorCallbacks
{
get
{
if (_onErrorCallbacks == null)
_onErrorCallbacks = new List<SerializationErrorCallback>();
return _onErrorCallbacks;
}
}
/// <summary>
/// Gets or sets the method called immediately after deserialization of the object.
/// </summary>
/// <value>The method called immediately after deserialization of the object.</value>
[Obsolete("This property is obsolete and has been replaced by the OnDeserializedCallbacks collection.")]
public MethodInfo OnDeserialized
{
get { return (OnDeserializedCallbacks.Count > 0) ? OnDeserializedCallbacks[0].Method() : null; }
set
{
OnDeserializedCallbacks.Clear();
OnDeserializedCallbacks.Add(CreateSerializationCallback(value));
}
}
/// <summary>
/// Gets or sets the method called during deserialization of the object.
/// </summary>
/// <value>The method called during deserialization of the object.</value>
[Obsolete("This property is obsolete and has been replaced by the OnDeserializingCallbacks collection.")]
public MethodInfo OnDeserializing
{
get { return (OnDeserializingCallbacks.Count > 0) ? OnDeserializingCallbacks[0].Method() : null; }
set
{
OnDeserializingCallbacks.Clear();
OnDeserializingCallbacks.Add(CreateSerializationCallback(value));
}
}
/// <summary>
/// Gets or sets the method called after serialization of the object graph.
/// </summary>
/// <value>The method called after serialization of the object graph.</value>
[Obsolete("This property is obsolete and has been replaced by the OnSerializedCallbacks collection.")]
public MethodInfo OnSerialized
{
get { return (OnSerializedCallbacks.Count > 0) ? OnSerializedCallbacks[0].Method() : null; }
set
{
OnSerializedCallbacks.Clear();
OnSerializedCallbacks.Add(CreateSerializationCallback(value));
}
}
/// <summary>
/// Gets or sets the method called before serialization of the object.
/// </summary>
/// <value>The method called before serialization of the object.</value>
[Obsolete("This property is obsolete and has been replaced by the OnSerializingCallbacks collection.")]
public MethodInfo OnSerializing
{
get { return (OnSerializingCallbacks.Count > 0) ? OnSerializingCallbacks[0].Method() : null; }
set
{
OnSerializingCallbacks.Clear();
OnSerializingCallbacks.Add(CreateSerializationCallback(value));
}
}
/// <summary>
/// Gets or sets the method called when an error is thrown during the serialization of the object.
/// </summary>
/// <value>The method called when an error is thrown during the serialization of the object.</value>
[Obsolete("This property is obsolete and has been replaced by the OnErrorCallbacks collection.")]
public MethodInfo OnError
{
get { return (OnErrorCallbacks.Count > 0) ? OnErrorCallbacks[0].Method() : null; }
set
{
OnErrorCallbacks.Clear();
OnErrorCallbacks.Add(CreateSerializationErrorCallback(value));
}
}
/// <summary>
/// Gets or sets the default creator method used to create the object.
/// </summary>
/// <value>The default creator method used to create the object.</value>
public Func<object> DefaultCreator { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the default creator is non public.
/// </summary>
/// <value><c>true</c> if the default object creator is non-public; otherwise, <c>false</c>.</value>
public bool DefaultCreatorNonPublic { get; set; }
internal JsonContract(Type underlyingType)
{
ValidationUtils.ArgumentNotNull(underlyingType, "underlyingType");
UnderlyingType = underlyingType;
IsSealed = underlyingType.IsSealed();
IsInstantiable = !(underlyingType.IsInterface() || underlyingType.IsAbstract());
IsNullable = ReflectionUtils.IsNullable(underlyingType);
NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType;
CreatedType = NonNullableUnderlyingType;
IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType);
IsEnum = NonNullableUnderlyingType.IsEnum();
if (NonNullableUnderlyingType == typeof(byte[]))
{
InternalReadType = ReadType.ReadAsBytes;
}
else if (NonNullableUnderlyingType == typeof(int))
{
InternalReadType = ReadType.ReadAsInt32;
}
else if (NonNullableUnderlyingType == typeof(decimal))
{
InternalReadType = ReadType.ReadAsDecimal;
}
else if (NonNullableUnderlyingType == typeof(string))
{
InternalReadType = ReadType.ReadAsString;
}
else if (NonNullableUnderlyingType == typeof(DateTime))
{
InternalReadType = ReadType.ReadAsDateTime;
}
else if (NonNullableUnderlyingType == typeof(DateTimeOffset))
{
InternalReadType = ReadType.ReadAsDateTimeOffset;
}
else
{
InternalReadType = ReadType.Read;
}
}
internal void InvokeOnSerializing(object o, StreamingContext context)
{
if (_onSerializingCallbacks != null)
{
foreach (SerializationCallback callback in _onSerializingCallbacks)
{
callback(o, context);
}
}
}
internal void InvokeOnSerialized(object o, StreamingContext context)
{
if (_onSerializedCallbacks != null)
{
foreach (SerializationCallback callback in _onSerializedCallbacks)
{
callback(o, context);
}
}
}
internal void InvokeOnDeserializing(object o, StreamingContext context)
{
if (_onDeserializingCallbacks != null)
{
foreach (SerializationCallback callback in _onDeserializingCallbacks)
{
callback(o, context);
}
}
}
internal void InvokeOnDeserialized(object o, StreamingContext context)
{
if (_onDeserializedCallbacks != null)
{
foreach (SerializationCallback callback in _onDeserializedCallbacks)
{
callback(o, context);
}
}
}
internal void InvokeOnError(object o, StreamingContext context, ErrorContext errorContext)
{
if (_onErrorCallbacks != null)
{
foreach (SerializationErrorCallback callback in _onErrorCallbacks)
{
callback(o, context, errorContext);
}
}
}
internal static SerializationCallback CreateSerializationCallback(MethodInfo callbackMethodInfo)
{
return (o, context) => callbackMethodInfo.Invoke(o, new object[] { context });
}
internal static SerializationErrorCallback CreateSerializationErrorCallback(MethodInfo callbackMethodInfo)
{
return (o, context, econtext) => callbackMethodInfo.Invoke(o, new object[] { context, econtext });
}
}
}
#endif
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Axiom.Configuration;
using Axiom.FileSystem;
namespace Axiom.Core {
/// <summary>
/// Defines a generic resource handler.
/// </summary>
/// <remarks>
/// A resource manager is responsible for managing a pool of
/// resources of a particular type. It must index them, look
/// them up, load and destroy them. It may also need to stay within
/// a defined memory budget, and temporaily unload some resources
/// if it needs to to stay within this budget.
/// <p/>
/// Resource managers use a priority system to determine what can
/// be unloaded, and a Least Recently Used (LRU) policy within
/// resources of the same priority.
/// </remarks>
public abstract class ResourceManager : IDisposable {
#region Fields
/// <summary>
/// If overrideName is set, then when a request is made for a resource file named
/// filename.ext, we will first check for filename_overrideName.ext and return
/// it instead if it exists.
/// </summary>
protected string overrideName = null;
public const string ZipFileResourceType = "ZipFile";
public const string FolderResourceType = "Folder";
protected long memoryBudget;
protected long memoryUsage;
/// <summary>
/// A cached list of all resources in memory.
/// </summary>
protected Hashtable resourceList = CollectionsUtil.CreateCaseInsensitiveHashtable();
protected Hashtable resourceHandleMap = new Hashtable();
/// <summary>
/// A lookup table used to find a common archive associated with a filename.
/// </summary>
protected Hashtable filePaths = CollectionsUtil.CreateCaseInsensitiveHashtable();
/// <summary>
/// A cached list of archives specific to a resource type.
/// </summary>
protected ArrayList archives = new ArrayList();
/// <summary>
/// A lookup table used to find a archive associated with a filename.
/// </summary>
static protected Hashtable commonFilePaths = CollectionsUtil.CreateCaseInsensitiveHashtable();
/// <summary>
/// A cached list of archives common to all resource types.
/// </summary>
static protected ArrayList commonArchives = new ArrayList();
/// <summary>
/// Next available handle to assign to a new resource.
/// </summary>
static protected int nextHandle;
#endregion Fields
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public ResourceManager() {
memoryBudget = long.MaxValue;
memoryUsage = 0;
}
#endregion
#region Properties
public static ICollection CommonFilePaths { get { return commonFilePaths.Keys; } }
public ICollection FilePaths { get { return filePaths.Keys; } }
public ICollection ResourceNames { get { return resourceList.Keys; } }
public ICollection Resources { get { return resourceList.Values; } }
/// <summary>
/// If overrideName is set, then when a request is made for a resource file named
/// filename.ext, we will first check for filename_overrideName.ext and return
/// it instead if it exists.
/// </summary>
public string OverrideName
{
get
{
return overrideName;
}
set
{
overrideName = value;
}
}
/// <summary>
/// Sets a limit on the amount of memory this resource handler may use.
/// </summary>
/// <remarks>
/// If, when asked to load a new resource, the manager believes it will exceed this memory
/// budget, it will temporarily unload a resource to make room for the new one. This unloading
/// is not permanent and the Resource is not destroyed; it simply needs to be reloaded when
/// next used.
/// </remarks>
public long MemoryBudget {
//get { return memoryBudget; }
set {
memoryBudget = value;
CheckUsage();
}
}
/// <summary>
/// Gets/Sets the current memory usages by all resource managers.
/// </summary>
public long MemoryUsage {
get {
return memoryUsage;
}
set {
memoryUsage = value;
}
}
#endregion
#region Virtual/Abstract methods
/// <summary>
/// Add a resource to this manager; normally only done by subclasses.
/// </summary>
/// <param name="resource">Resource to add.</param>
public virtual void Add(Resource resource) {
resource.Handle = GetNextHandle();
// note: just overwriting existing for now
resourceList[resource.Name] = resource;
resourceHandleMap[resource.Handle] = resource;
}
public virtual void Remove(string name) {
Resource resource = (Resource)resourceList[name];
resourceList.Remove(resource.Name);
resourceHandleMap.Remove(resource.Handle);
}
/// <summary>
/// Creates a new blank resource, compatible with this manager.
/// </summary>
/// <remarks>
/// Resource managers handle disparate types of resources. This method returns a pointer to a
/// valid new instance of the kind of resource managed here. The caller should complete the
/// details of the returned resource and call ResourceManager.Load to load the resource. Note
/// that it is the CALLERS responsibility to destroy this object when it is no longer required
/// (after calling ResourceManager.Unload if it had been loaded).
/// </remarks>
/// <param name="name"></param>
/// <returns></returns>
public abstract Resource Create(string name, bool isManual);
public Resource Create(string name) {
return Create(name, false);
}
/// <summary>
/// Gets the next available unique resource handle.
/// </summary>
/// <returns></returns>
protected int GetNextHandle() {
return nextHandle++;
}
/// <summary>
/// Loads a resource. Resource will be subclasses of Resource.
/// </summary>
/// <param name="resource">Resource to load.</param>
/// <param name="priority"></param>
public virtual void Load(Resource resource, int priority) {
// load and touch the resource
resource.Load();
resource.Touch();
// cache the resource
Add(resource);
}
/// <summary>
/// Unloads a Resource from the managed resources list, calling it's Unload() method.
/// </summary>
/// <remarks>
/// This method removes a resource from the list maintained by this manager, and unloads it from
/// memory. It does NOT destroy the resource itself, although the memory used by it will be largely
/// freed up. This would allow you to reload the resource again if you wished.
/// </remarks>
/// <param name="resource"></param>
public virtual void Unload(Resource resource) {
// unload the resource
resource.Unload();
// remove the resource
resourceList.Remove(resource.Name);
// update memory usage
memoryUsage -= resource.Size;
}
/// <summary>
///
/// </summary>
public virtual void UnloadAndDestroyAll() {
foreach(Resource resource in resourceList.Values) {
// unload and dispose of resource
resource.Unload();
resource.Dispose();
}
// empty the resource list
resourceList.Clear();
filePaths.Clear();
commonArchives.Clear();
commonFilePaths.Clear();
archives.Clear();
}
#endregion
#region Public methods
/// <summary>
/// Adds a relative path to search for resources of this type.
/// </summary>
/// <remarks>
/// This method adds the supplied path to the list of relative locations that that will be searched for
/// a single type of resource only. Each subclass of ResourceManager will maintain it's own list of
/// specific subpaths, which it will append to the current path as it searches for matching files.
/// </remarks>
/// <param name="path"></param>
public void AddSearchPath(string path) {
AddArchive(path, "Folder");
}
/// <summary>
/// Adds a relative search path for resources of ALL types.
/// </summary>
/// <remarks>
/// This method has the same effect as ResourceManager.AddSearchPath, except that the path added
/// applies to ALL resources, not just the one managed by the subclass in question.
/// </remarks>
/// <param name="path"></param>
public static void AddCommonSearchPath(string path) {
// record the common file path
AddCommonArchive(path, "Folder");
}
public static StringCollection GetAllCommonNamesLike(string startPath, string extension) {
StringCollection allFiles = new StringCollection();
for(int i = 0; i < commonArchives.Count; i++) {
Archive archive = (Archive)commonArchives[i];
string[] files = archive.GetFileNamesLike(startPath, extension);
// add each one to the final list
foreach(string fileName in files) {
if (!allFiles.Contains(fileName))
allFiles.Add(fileName);
}
}
return allFiles;
}
private static Archive CreateArchive(string name, string type) {
IArchiveFactory factory = ArchiveManager.Instance.GetArchiveFactory(type);
if (factory == null) {
throw new AxiomException(string.Format("Archive type {0} is not a valid archive type.", type));
}
Archive archive = factory.CreateArchive(name);
// TODO: Shouldn't be calling this manually here, but good enough until the resource loading is rewritten
archive.Load();
return archive;
}
/// <summary>
/// Adds an archive to
/// </summary>
/// <param name="name"></param>
/// <param name="type"></param>
public void AddArchive(string name, string type) {
Archive archive = CreateArchive(name, type);
// add a lookup for all these files so they know what archive they are in
foreach (string file in archive.GetFileNamesLike("", "")) {
filePaths[file] = archive;
}
// add the archive to the common archives
archives.Add(archive);
}
/// <summary>
/// Adds an archive to
/// </summary>
/// <param name="name"></param>
/// <param name="type"></param>
public void AddArchive(List<string> directories, string type) {
foreach (string name in directories) {
Archive archive = CreateArchive(name, type);
// add a lookup for all these files so they know what archive they are in
foreach (string file in archive.GetFileNamesLike("", ""))
if (!filePaths.ContainsKey(file))
filePaths[file] = archive;
// add the archive to the common archives
archives.Add(archive);
}
}
/// <summary>
/// Adds an archive to
/// </summary>
/// <param name="name"></param>
/// <param name="type"></param>
public static void AddCommonArchive(string name, string type) {
Archive archive = CreateArchive(name, type);
// add a lookup for all these files so they know what archive they are in
foreach (string file in archive.GetFileNamesLike("", "")) {
commonFilePaths[file] = archive;
}
// add the archive to the common archives
commonArchives.Add(archive);
}
/// <summary>
/// Adds an archive to
/// </summary>
/// <param name="name"></param>
/// <param name="type"></param>
public static void AddCommonArchive(List<string> directories, string type) {
foreach (string name in directories) {
Archive archive = CreateArchive(name, type);
// add a lookup for all these files so they know what archive they are in
foreach (string file in archive.GetFileNamesLike("", ""))
if (!commonFilePaths.ContainsKey(file))
commonFilePaths[file] = archive;
// add the archive to the common archives
commonArchives.Add(archive);
}
}
/// <summary>
/// Gets a material with the specified name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public Resource LoadExisting(string name)
{
//get the resource
Resource resource = GetByName(name);
//ensure that it exists
if(resource == null)
throw new ArgumentException("There is no resource with the name '{0}' that already exists.",name);
//ensure that it is loaded
resource.Load();
return resource;
}
/// <summary>
/// Gets a resource with the given handle.
/// </summary>
/// <param name="handle">Handle of the resource to retrieve.</param>
/// <returns>A reference to a Resource with the given handle.</returns>
public virtual Resource GetByHandle(int handle) {
Debug.Assert(resourceHandleMap != null, "A resource was being retreived, but the list of Resources is null.", "");
Resource resource = null;
// find the resource in the Hashtable and return it
if(resourceHandleMap[handle] != null) {
resource = (Resource)resourceHandleMap[handle];
resource.Touch();
}
return resource;
}
/// <summary>
/// Gets a reference to the specified named resource.
/// </summary>
/// <param name="name">Name of the resource to retreive.</param>
/// <returns></returns>
public virtual Resource GetByName(string name) {
Debug.Assert(resourceList != null, "A resource was being retreived, but the list of Resources is null.", "");
Resource resource = null;
// find the resource in the Hashtable and return it
if(resourceList[name] != null) {
resource = (Resource)resourceList[name];
}
return resource;
}
#endregion
#region Protected methods
/// <summary>
/// Makes sure we are still within budget.
/// </summary>
protected void CheckUsage() {
// TODO: Implementation of CheckUsage.
// Keep a sorted list of resource by LastAccessed for easy removal of oldest?
}
public static bool HasCommonResourceData(string fileName)
{
return commonFilePaths.ContainsKey(fileName);
}
public bool HasResource(string name)
{
return resourceList.ContainsKey(name);
}
public bool HasResourceData(string fileName)
{
return filePaths.ContainsKey(fileName) || commonFilePaths.ContainsKey(fileName);
}
public string ResolveResourceData(string fileName)
{
if (filePaths.ContainsKey(fileName))
{
Archive archive = (Archive)filePaths[fileName];
if (archive is Folder)
return Path.Combine(archive.Name, fileName);
}
// search common file cache
if (commonFilePaths.ContainsKey(fileName))
{
Archive archive = (Archive)commonFilePaths[fileName];
if (archive is Folder)
return Path.Combine(archive.Name, fileName);
}
return null;
}
/// <summary>
/// Locates resource data within the archives known to the ResourceManager.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public Stream FindResourceData(string fileName) {
if (overrideName != null && overrideName.Length > 0 && fileName.Contains("."))
{
int extStart = fileName.LastIndexOf('.');
string baseName = fileName.Substring(0, extStart);
string ext = fileName.Substring(extStart + 1);
string overrideFileName = string.Format("{0}_{1}.{2}", baseName, overrideName, ext);
// look in local file cache first
if (filePaths.ContainsKey(overrideFileName))
{
Archive archive = (Archive)filePaths[overrideFileName];
return archive.ReadFile(overrideFileName);
}
// search common file cache
if (commonFilePaths.ContainsKey(overrideFileName))
{
Archive archive = (Archive)commonFilePaths[overrideFileName];
return archive.ReadFile(overrideFileName);
}
LogManager.Instance.Write("Unable to find override file: {0}", overrideFileName);
}
// look in local file cache first
if(filePaths.ContainsKey(fileName)) {
Archive archive = (Archive)filePaths[fileName];
return archive.ReadFile(fileName);
}
// search common file cache
if(commonFilePaths.ContainsKey(fileName)) {
Archive archive = (Archive)commonFilePaths[fileName];
return archive.ReadFile(fileName);
}
//not found in the cache, load the resource manually, but log the unsuggested practice
if(File.Exists(fileName))
{
string fileNameWithoutDirectory = Path.GetFileName(fileName);
if(filePaths.ContainsKey(fileNameWithoutDirectory) || commonFilePaths.ContainsKey(fileNameWithoutDirectory))
{
LogManager.Instance.Write("Resource names should not be relative file paths but just as a file name when located in searched directories, "
+ "however resource '{0}' is registered so it will be loaded for the specified resource name of '{1}'.", fileNameWithoutDirectory, fileName);
return FindResourceData(fileNameWithoutDirectory);
}
LogManager.Instance.Write("File '{0}' is being loaded manually since it exists, however it should be located in a registered media archive or directory.", fileNameWithoutDirectory);
return File.OpenRead(fileName);
}
// TODO: Load resources manually
throw new AxiomException(string.Format("Resource '{0}' could not be found. Be sure it is located in a known directory "
+ "or that it is not qualified by a directory name unless that directory is located inside a zip archive.", fileName));
}
public StringCollection GetResourceNamesWithExtension(string fileExtension)
{
StringCollection list = new StringCollection();
foreach(string name in filePaths.Keys)
{
if(name.EndsWith(fileExtension))
list.Add(name);
}
foreach(string name in commonFilePaths.Keys)
{
if(name.EndsWith(fileExtension))
list.Add(name);
}
return list;
}
public StringCollection GetResourceNamesWithExtension(params string[] fileExtensions)
{
StringCollection list = new StringCollection();
foreach(string name in filePaths.Keys)
{
foreach(string fileExtension in fileExtensions)
{
if(name.EndsWith(fileExtension))
{
list.Add(name);
break;
}
}
}
foreach(string name in commonFilePaths.Keys)
{
foreach(string fileExtension in fileExtensions)
{
if(name.EndsWith(fileExtension))
{
list.Add(name);
break;
}
}
}
return list;
}
public static string GetCommonResourceDataFilePath(string fileName)
{
// search common file cache
if (commonFilePaths.ContainsKey(fileName))
{
Archive archive = (Archive)commonFilePaths[fileName];
return Path.Combine(archive.Name, fileName);
}
throw new AxiomException(string.Format("Resource '{0}' could not be found. Be sure it is located in a known directory.", fileName));
}
/// <summary>
/// Locates resource data within the archives known to the ResourceManager.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static Stream FindCommonResourceData(string fileName) {
// search common file cache
if(commonFilePaths.ContainsKey(fileName)) {
Archive archive = (Archive)commonFilePaths[fileName];
return archive.ReadFile(fileName);
}
// not found in the cache, load the resource manually
// TODO: Load resources manually
throw new AxiomException(string.Format("Resource '{0}' could not be found. Be sure it is located in a known directory.", fileName));
}
public static string ResolveCommonResourceData(string fileName)
{
// search common file cache
if (commonFilePaths.ContainsKey(fileName))
{
Archive archive = (Archive)commonFilePaths[fileName];
if (archive is Folder)
return archive.Name + System.IO.Path.DirectorySeparatorChar + fileName;
}
return null;
}
#endregion
#region IDisposable Implementation
/// <summary>
/// Called when the engine is shutting down.
/// </summary>
public virtual void Dispose() {
// unload and destroy all resources
UnloadAndDestroyAll();
}
#endregion IDisposable Implementation
}
}
| |
//
// GoogleScholarSearchResult.cs
// s.im.pl serialization
//
// Generated by MetaMetadataDotNetTranslator.
// Copyright 2017 Interface Ecology Lab.
//
using Ecologylab.BigSemantics.Generated.Library.SearchNS;
using Ecologylab.BigSemantics.MetaMetadataNS;
using Ecologylab.BigSemantics.MetadataNS;
using Ecologylab.BigSemantics.MetadataNS.Builtins;
using Ecologylab.BigSemantics.MetadataNS.Scalar;
using Ecologylab.Collections;
using Simpl.Fundamental.Generic;
using Simpl.Serialization;
using Simpl.Serialization.Attributes;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Ecologylab.BigSemantics.Generated.Library.SearchNS
{
/// <summary>
/// A google scholar search result
/// </summary>
[SimplInherit]
public class GoogleScholarSearchResult : RichDocument
{
[SimplComposite]
[MmName("destination_page")]
private RichDocument destinationPage;
[SimplScalar]
private MetadataString destinationType;
[SimplScalar]
private MetadataString sourceInfo;
[SimplCollection("rich_document")]
[MmName("google_authors")]
private List<RichDocument> googleAuthors;
[SimplScalar]
private MetadataInteger citationCount;
[SimplComposite]
[MmName("citations_page")]
private GoogleScholarSearch citationsPage;
[SimplComposite]
[MmName("related_articles_page")]
private GoogleScholarSearch relatedArticlesPage;
[SimplScalar]
private MetadataInteger versionCount;
[SimplComposite]
[MmName("versions_page")]
private GoogleScholarSearch versionsPage;
[SimplCollection("rich_document")]
[MmName("access_links")]
private List<RichDocument> accessLinks;
public GoogleScholarSearchResult()
{ }
public GoogleScholarSearchResult(MetaMetadataCompositeField mmd) : base(mmd) { }
public RichDocument DestinationPage
{
get{return destinationPage;}
set
{
if (this.destinationPage != value)
{
this.destinationPage = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
public MetadataString DestinationType
{
get{return destinationType;}
set
{
if (this.destinationType != value)
{
this.destinationType = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
public MetadataString SourceInfo
{
get{return sourceInfo;}
set
{
if (this.sourceInfo != value)
{
this.sourceInfo = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
public List<RichDocument> GoogleAuthors
{
get{return googleAuthors;}
set
{
if (this.googleAuthors != value)
{
this.googleAuthors = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
public MetadataInteger CitationCount
{
get{return citationCount;}
set
{
if (this.citationCount != value)
{
this.citationCount = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
public GoogleScholarSearch CitationsPage
{
get{return citationsPage;}
set
{
if (this.citationsPage != value)
{
this.citationsPage = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
public GoogleScholarSearch RelatedArticlesPage
{
get{return relatedArticlesPage;}
set
{
if (this.relatedArticlesPage != value)
{
this.relatedArticlesPage = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
public MetadataInteger VersionCount
{
get{return versionCount;}
set
{
if (this.versionCount != value)
{
this.versionCount = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
public GoogleScholarSearch VersionsPage
{
get{return versionsPage;}
set
{
if (this.versionsPage != value)
{
this.versionsPage = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
public List<RichDocument> AccessLinks
{
get{return accessLinks;}
set
{
if (this.accessLinks != value)
{
this.accessLinks = value;
// TODO we need to implement our property change notification mechanism.
}
}
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using System;
namespace VirtualRealityEngine.Config.Parser
{
public class Parser {
public const int _EOF = 0;
public const int _T_SCALAR = 1;
public const int _T_HEX = 2;
public const int _T_STRING = 3;
public const int _T_STRINGTABLESTRING = 4;
public const int _T_IDENT = 5;
public const int maxT = 39;
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 Parser(Scanner scanner) {
this.scanner = scanner;
errors = new Errors();
}
bool peekCompare(params int[] values)
{
Token t = la;
foreach(int i in values)
{
if(i != -1 && t.kind != i)
{
scanner.ResetPeek();
return false;
}
if (t.next == null)
t = scanner.Peek();
else
t = t.next;
}
scanner.ResetPeek();
return true;
}
bool peekString(int count, params string[] values)
{
Token t = la;
for(; count > 0; count --)
t = scanner.Peek();
foreach(var it in values)
{
if(t.val == it)
{
scanner.ResetPeek();
return true;
}
}
scanner.ResetPeek();
return false;
}
void SynErr (int n) {
if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n, t.charPos, t == null ? 0 : t.val.Length);
errDist = 0;
}
void Warning (string msg) {
errors.Warning(la.line, la.col, msg);
}
public void SemErr (string msg) {
if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg, t.charPos, t == null ? 0 : t.val.Length);
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 SQFDOCUMENT() {
STATEMENT();
while (la.kind == 8) {
SEMICOLON();
if (StartOf(1)) {
STATEMENT();
}
}
}
void STATEMENT() {
if (_T_IDENT == la.kind && peekString(1, "=") || peekString(1, "private") ) {
ASSIGNMENT();
} else if (peekString(0, "private") && peekString(1, "[") ) {
EXPRESSION();
} else if (StartOf(1)) {
EXPRESSION();
} else SynErr(40);
}
void SEMICOLON() {
Expect(8);
while (la.kind == 8) {
Get();
}
}
void EXP_CODE() {
Expect(6);
if (StartOf(1)) {
STATEMENT();
while (la.kind == 8) {
SEMICOLON();
if (StartOf(1)) {
STATEMENT();
}
}
}
Expect(7);
}
void ASSIGNMENT() {
if (la.kind == 9) {
Get();
}
Expect(5);
Expect(10);
EXPRESSION();
}
void EXPRESSION() {
EXP_OR();
}
void EXP_OR() {
EXP_AND();
if (la.kind == 11 || la.kind == 12) {
if (la.kind == 11) {
Get();
} else {
Get();
}
EXP_OR();
}
}
void EXP_AND() {
EXP_COMPARISON();
if (la.kind == 13 || la.kind == 14) {
if (la.kind == 13) {
Get();
} else {
Get();
}
EXP_AND();
}
}
void EXP_COMPARISON() {
EXP_BINARY();
if (StartOf(2)) {
switch (la.kind) {
case 15: {
Get();
break;
}
case 16: {
Get();
break;
}
case 17: {
Get();
break;
}
case 18: {
Get();
break;
}
case 19: {
Get();
break;
}
case 20: {
Get();
break;
}
case 21: {
Get();
break;
}
}
EXP_COMPARISON();
}
}
void EXP_BINARY() {
EXP_ELSE();
if (la.kind == 5) {
Get();
EXP_BINARY();
}
}
void EXP_ELSE() {
EXP_ADDITION();
if (la.kind == 22) {
Get();
EXP_ELSE();
}
}
void EXP_ADDITION() {
EXP_MULTIPLICATION();
if (StartOf(3)) {
if (la.kind == 23) {
Get();
} else if (la.kind == 24) {
Get();
} else if (la.kind == 25) {
Get();
} else {
Get();
}
EXP_ADDITION();
}
}
void EXP_MULTIPLICATION() {
EXP_POWER();
if (StartOf(4)) {
if (la.kind == 27) {
Get();
} else if (la.kind == 28) {
Get();
} else if (la.kind == 29) {
Get();
} else if (la.kind == 30) {
Get();
} else {
Get();
}
EXP_MULTIPLICATION();
}
}
void EXP_POWER() {
EXP_HIGHEST();
if (la.kind == 32) {
Get();
EXP_POWER();
}
}
void EXP_HIGHEST() {
if (la.kind == 5 || la.kind == 9 || la.kind == 35) {
EXP_UNARYNULL();
} else if (la.kind == 1 || la.kind == 2 || la.kind == 3) {
EXP_VALUES();
} else if (la.kind == 33) {
Get();
EXPRESSION();
Expect(34);
} else if (la.kind == 6) {
EXP_CODE();
} else if (la.kind == 36) {
EXP_ARRAY();
} else SynErr(41);
}
void EXP_UNARYNULL() {
if (la.kind == 5) {
Get();
} else if (la.kind == 9) {
Get();
} else if (la.kind == 35) {
Get();
} else SynErr(42);
if (StartOf(1)) {
EXP_HIGHEST();
}
}
void EXP_VALUES() {
if (la.kind == 1) {
Get();
} else if (la.kind == 2) {
Get();
} else if (la.kind == 3) {
Get();
} else SynErr(43);
}
void EXP_ARRAY() {
Expect(36);
if (StartOf(1)) {
EXPRESSION();
while (la.kind == 37) {
Get();
EXPRESSION();
}
}
Expect(38);
}
public void Parse() {
la = new Token();
la.val = "";
Get();
SQFDOCUMENT();
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, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_T,_T,_T, _x,_T,_T,_x, _x,_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,_x,_T, _T,_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,_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,_x, _x,_x,_x,_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,_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}
};
} // end Parser
public class Errors {
//private static Logger logger = LogManager.GetCurrentClassLogger();
public int Count { get { return this.ErrorList.Count; } }
public List<Tuple<int, int, string>> ErrorList;
public string errMsgFormat = "line {0} col {1}: {2}"; // 0=line, 1=column, 2=text
public Errors()
{
ErrorList = new List<Tuple<int, int, string>>();
}
public virtual void SynErr (int line, int col, int n, int offset, int length) {
string s;
switch (n) {
case 0: s = "EOF expected"; break;
case 1: s = "T_SCALAR expected"; break;
case 2: s = "T_HEX expected"; break;
case 3: s = "T_STRING expected"; break;
case 4: s = "T_STRINGTABLESTRING expected"; break;
case 5: s = "T_IDENT expected"; break;
case 6: s = "\"{\" expected"; break;
case 7: s = "\"}\" expected"; break;
case 8: s = "\";\" expected"; break;
case 9: s = "\"private\" expected"; break;
case 10: s = "\"=\" expected"; break;
case 11: s = "\"||\" expected"; break;
case 12: s = "\"or\" expected"; break;
case 13: s = "\"&&\" expected"; break;
case 14: s = "\"and\" expected"; break;
case 15: s = "\"==\" expected"; break;
case 16: s = "\"!=\" expected"; break;
case 17: s = "\">\" expected"; break;
case 18: s = "\"<\" expected"; break;
case 19: s = "\">=\" expected"; break;
case 20: s = "\"<=\" expected"; break;
case 21: s = "\">>\" expected"; break;
case 22: s = "\"else\" expected"; break;
case 23: s = "\"+\" expected"; break;
case 24: s = "\"-\" expected"; break;
case 25: s = "\"max\" expected"; break;
case 26: s = "\"min\" expected"; break;
case 27: s = "\"*\" expected"; break;
case 28: s = "\"/\" expected"; break;
case 29: s = "\"%\" expected"; break;
case 30: s = "\"mod\" expected"; break;
case 31: s = "\"atan2\" expected"; break;
case 32: s = "\"^\" expected"; break;
case 33: s = "\"(\" expected"; break;
case 34: s = "\")\" expected"; break;
case 35: s = "\"!\" expected"; break;
case 36: s = "\"[\" expected"; break;
case 37: s = "\",\" expected"; break;
case 38: s = "\"]\" expected"; break;
case 39: s = "??? expected"; break;
case 40: s = "invalid STATEMENT"; break;
case 41: s = "invalid EXP_HIGHEST"; break;
case 42: s = "invalid EXP_UNARYNULL"; break;
case 43: s = "invalid EXP_VALUES"; break;
default: s = "error " + n; break;
}
//logger.Error(string.Format(errMsgFormat, line, col, s));
ErrorList.Add(new Tuple<int, int, string>(offset, length, s));
System.Diagnostics.Debugger.Break();
}
public virtual void SemErr (int line, int col, string s, int offset, int length) {
//logger.Error(string.Format(errMsgFormat, line, col, s));
ErrorList.Add(new Tuple<int, int, string>(offset, length, s));
}
public virtual void SemErr (string s) {
//logger.Error(s);
}
public virtual void Warning (int line, int col, string s) {
//logger.Warn(string.Format(errMsgFormat, line, col, s));
}
public virtual void Warning(string s) {
//logger.Warn(s);
}
}
public class FatalError: Exception {
public FatalError(string m): base(m) {}
}
}
| |
// 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 gcbv = Google.Cloud.Billing.V1;
using sys = System;
namespace Google.Cloud.Billing.V1
{
/// <summary>Resource name for the <c>Service</c> resource.</summary>
public sealed partial class ServiceName : gax::IResourceName, sys::IEquatable<ServiceName>
{
/// <summary>The possible contents of <see cref="ServiceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>services/{service}</c>.</summary>
Service = 1,
}
private static gax::PathTemplate s_service = new gax::PathTemplate("services/{service}");
/// <summary>Creates a <see cref="ServiceName"/> 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="ServiceName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static ServiceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ServiceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="ServiceName"/> with the pattern <c>services/{service}</c>.</summary>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns>
public static ServiceName FromService(string serviceId) =>
new ServiceName(ResourceNameType.Service, serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>services/{service}</c>.
/// </summary>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern <c>services/{service}</c>.
/// </returns>
public static string Format(string serviceId) => FormatService(serviceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>services/{service}</c>.
/// </summary>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern <c>services/{service}</c>.
/// </returns>
public static string FormatService(string serviceId) =>
s_service.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>Parses the given resource name string into a new <see cref="ServiceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>services/{service}</c></description></item></list>
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ServiceName"/> if successful.</returns>
public static ServiceName Parse(string serviceName) => Parse(serviceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ServiceName"/> 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>services/{service}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceName">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="ServiceName"/> if successful.</returns>
public static ServiceName Parse(string serviceName, bool allowUnparsed) =>
TryParse(serviceName, allowUnparsed, out ServiceName 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="ServiceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>services/{service}</c></description></item></list>
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ServiceName"/>, 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 serviceName, out ServiceName result) => TryParse(serviceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ServiceName"/> 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>services/{service}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceName">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="ServiceName"/>, 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 serviceName, bool allowUnparsed, out ServiceName result)
{
gax::GaxPreconditions.CheckNotNull(serviceName, nameof(serviceName));
gax::TemplatedResourceName resourceName;
if (s_service.TryParseName(serviceName, out resourceName))
{
result = FromService(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(serviceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ServiceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string serviceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ServiceId = serviceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ServiceName"/> class from the component parts of pattern
/// <c>services/{service}</c>
/// </summary>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
public ServiceName(string serviceId) : this(ResourceNameType.Service, serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)))
{
}
/// <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>Service</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ServiceId { 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.Service: return s_service.Expand(ServiceId);
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 ServiceName);
/// <inheritdoc/>
public bool Equals(ServiceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ServiceName a, ServiceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ServiceName a, ServiceName b) => !(a == b);
}
/// <summary>Resource name for the <c>Sku</c> resource.</summary>
public sealed partial class SkuName : gax::IResourceName, sys::IEquatable<SkuName>
{
/// <summary>The possible contents of <see cref="SkuName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>services/{service}/skus/{sku}</c>.</summary>
ServiceSku = 1,
}
private static gax::PathTemplate s_serviceSku = new gax::PathTemplate("services/{service}/skus/{sku}");
/// <summary>Creates a <see cref="SkuName"/> 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="SkuName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static SkuName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SkuName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="SkuName"/> with the pattern <c>services/{service}/skus/{sku}</c>.</summary>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="skuId">The <c>Sku</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SkuName"/> constructed from the provided ids.</returns>
public static SkuName FromServiceSku(string serviceId, string skuId) =>
new SkuName(ResourceNameType.ServiceSku, serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), skuId: gax::GaxPreconditions.CheckNotNullOrEmpty(skuId, nameof(skuId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SkuName"/> with pattern
/// <c>services/{service}/skus/{sku}</c>.
/// </summary>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="skuId">The <c>Sku</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SkuName"/> with pattern <c>services/{service}/skus/{sku}</c>.
/// </returns>
public static string Format(string serviceId, string skuId) => FormatServiceSku(serviceId, skuId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SkuName"/> with pattern
/// <c>services/{service}/skus/{sku}</c>.
/// </summary>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="skuId">The <c>Sku</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SkuName"/> with pattern <c>services/{service}/skus/{sku}</c>.
/// </returns>
public static string FormatServiceSku(string serviceId, string skuId) =>
s_serviceSku.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(skuId, nameof(skuId)));
/// <summary>Parses the given resource name string into a new <see cref="SkuName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>services/{service}/skus/{sku}</c></description></item></list>
/// </remarks>
/// <param name="skuName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SkuName"/> if successful.</returns>
public static SkuName Parse(string skuName) => Parse(skuName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SkuName"/> 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>services/{service}/skus/{sku}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="skuName">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="SkuName"/> if successful.</returns>
public static SkuName Parse(string skuName, bool allowUnparsed) =>
TryParse(skuName, allowUnparsed, out SkuName 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="SkuName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>services/{service}/skus/{sku}</c></description></item></list>
/// </remarks>
/// <param name="skuName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SkuName"/>, 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 skuName, out SkuName result) => TryParse(skuName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SkuName"/> 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>services/{service}/skus/{sku}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="skuName">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="SkuName"/>, 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 skuName, bool allowUnparsed, out SkuName result)
{
gax::GaxPreconditions.CheckNotNull(skuName, nameof(skuName));
gax::TemplatedResourceName resourceName;
if (s_serviceSku.TryParseName(skuName, out resourceName))
{
result = FromServiceSku(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(skuName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SkuName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string serviceId = null, string skuId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ServiceId = serviceId;
SkuId = skuId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SkuName"/> class from the component parts of pattern
/// <c>services/{service}/skus/{sku}</c>
/// </summary>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="skuId">The <c>Sku</c> ID. Must not be <c>null</c> or empty.</param>
public SkuName(string serviceId, string skuId) : this(ResourceNameType.ServiceSku, serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), skuId: gax::GaxPreconditions.CheckNotNullOrEmpty(skuId, nameof(skuId)))
{
}
/// <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>Service</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ServiceId { get; }
/// <summary>
/// The <c>Sku</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SkuId { 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.ServiceSku: return s_serviceSku.Expand(ServiceId, SkuId);
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 SkuName);
/// <inheritdoc/>
public bool Equals(SkuName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SkuName a, SkuName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SkuName a, SkuName b) => !(a == b);
}
public partial class Service
{
/// <summary>
/// <see cref="gcbv::ServiceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbv::ServiceName ServiceName
{
get => string.IsNullOrEmpty(Name) ? null : gcbv::ServiceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Sku
{
/// <summary>
/// <see cref="gcbv::SkuName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbv::SkuName SkuName
{
get => string.IsNullOrEmpty(Name) ? null : gcbv::SkuName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListSkusRequest
{
/// <summary>
/// <see cref="ServiceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public ServiceName ParentAsServiceName
{
get => string.IsNullOrEmpty(Parent) ? null : ServiceName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Demo.AutoFac.WebApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>OfflineUserDataJob</c> resource.</summary>
public sealed partial class OfflineUserDataJobName : gax::IResourceName, sys::IEquatable<OfflineUserDataJobName>
{
/// <summary>The possible contents of <see cref="OfflineUserDataJobName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c>.
/// </summary>
CustomerOfflineUserDataUpdate = 1,
}
private static gax::PathTemplate s_customerOfflineUserDataUpdate = new gax::PathTemplate("customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}");
/// <summary>Creates a <see cref="OfflineUserDataJobName"/> 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="OfflineUserDataJobName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static OfflineUserDataJobName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new OfflineUserDataJobName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="OfflineUserDataJobName"/> with the pattern
/// <c>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="offlineUserDataUpdateId">
/// The <c>OfflineUserDataUpdate</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>A new instance of <see cref="OfflineUserDataJobName"/> constructed from the provided ids.</returns>
public static OfflineUserDataJobName FromCustomerOfflineUserDataUpdate(string customerId, string offlineUserDataUpdateId) =>
new OfflineUserDataJobName(ResourceNameType.CustomerOfflineUserDataUpdate, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), offlineUserDataUpdateId: gax::GaxPreconditions.CheckNotNullOrEmpty(offlineUserDataUpdateId, nameof(offlineUserDataUpdateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="OfflineUserDataJobName"/> with pattern
/// <c>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="offlineUserDataUpdateId">
/// The <c>OfflineUserDataUpdate</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="OfflineUserDataJobName"/> with pattern
/// <c>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c>.
/// </returns>
public static string Format(string customerId, string offlineUserDataUpdateId) =>
FormatCustomerOfflineUserDataUpdate(customerId, offlineUserDataUpdateId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="OfflineUserDataJobName"/> with pattern
/// <c>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="offlineUserDataUpdateId">
/// The <c>OfflineUserDataUpdate</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="OfflineUserDataJobName"/> with pattern
/// <c>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c>.
/// </returns>
public static string FormatCustomerOfflineUserDataUpdate(string customerId, string offlineUserDataUpdateId) =>
s_customerOfflineUserDataUpdate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(offlineUserDataUpdateId, nameof(offlineUserDataUpdateId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="OfflineUserDataJobName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="offlineUserDataJobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="OfflineUserDataJobName"/> if successful.</returns>
public static OfflineUserDataJobName Parse(string offlineUserDataJobName) => Parse(offlineUserDataJobName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="OfflineUserDataJobName"/> 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>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="offlineUserDataJobName">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="OfflineUserDataJobName"/> if successful.</returns>
public static OfflineUserDataJobName Parse(string offlineUserDataJobName, bool allowUnparsed) =>
TryParse(offlineUserDataJobName, allowUnparsed, out OfflineUserDataJobName 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="OfflineUserDataJobName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="offlineUserDataJobName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="OfflineUserDataJobName"/>, 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 offlineUserDataJobName, out OfflineUserDataJobName result) =>
TryParse(offlineUserDataJobName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="OfflineUserDataJobName"/> 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>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="offlineUserDataJobName">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="OfflineUserDataJobName"/>, 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 offlineUserDataJobName, bool allowUnparsed, out OfflineUserDataJobName result)
{
gax::GaxPreconditions.CheckNotNull(offlineUserDataJobName, nameof(offlineUserDataJobName));
gax::TemplatedResourceName resourceName;
if (s_customerOfflineUserDataUpdate.TryParseName(offlineUserDataJobName, out resourceName))
{
result = FromCustomerOfflineUserDataUpdate(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(offlineUserDataJobName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private OfflineUserDataJobName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string offlineUserDataUpdateId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
OfflineUserDataUpdateId = offlineUserDataUpdateId;
}
/// <summary>
/// Constructs a new instance of a <see cref="OfflineUserDataJobName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="offlineUserDataUpdateId">
/// The <c>OfflineUserDataUpdate</c> ID. Must not be <c>null</c> or empty.
/// </param>
public OfflineUserDataJobName(string customerId, string offlineUserDataUpdateId) : this(ResourceNameType.CustomerOfflineUserDataUpdate, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), offlineUserDataUpdateId: gax::GaxPreconditions.CheckNotNullOrEmpty(offlineUserDataUpdateId, nameof(offlineUserDataUpdateId)))
{
}
/// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>OfflineUserDataUpdate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string OfflineUserDataUpdateId { 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.CustomerOfflineUserDataUpdate: return s_customerOfflineUserDataUpdate.Expand(CustomerId, OfflineUserDataUpdateId);
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 OfflineUserDataJobName);
/// <inheritdoc/>
public bool Equals(OfflineUserDataJobName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(OfflineUserDataJobName a, OfflineUserDataJobName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(OfflineUserDataJobName a, OfflineUserDataJobName b) => !(a == b);
}
public partial class OfflineUserDataJob
{
/// <summary>
/// <see cref="OfflineUserDataJobName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal OfflineUserDataJobName ResourceNameAsOfflineUserDataJobName
{
get => string.IsNullOrEmpty(ResourceName) ? null : OfflineUserDataJobName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
#region Header
/**
* JsonMapper.cs
* JSON to .Net object and object to JSON conversions.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace LitJson
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
public class JsonMapper
{
#region Fields
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
if (type.GetInterface ("System.Collections.IList") != null)
data.IsList = true;
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
if (type.GetInterface ("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (string))
data.ElementType = p_info.PropertyType;
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = t1.GetMethod (
"op_Implicit", new Type[] { t2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
Type underlying_type = Nullable.GetUnderlyingType(inst_type);
Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_type.IsClass || underlying_type != null) {
return null;
}
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean||
reader.Token==JsonToken.Float) {
Type json_type = reader.Value.GetType ();
//int32 cast to int64 add by Melon
if (json_type.Name.Equals("Int32") && inst_type.Name.Equals("Int64"))
{
return reader.Value;
}
//int cast to float or double add by Melon
//if ((json_type.Name.Equals("Double") || json_type.Name.Equals("Float")) && inst_type.Name.Equals("Single"))
//{
// return reader.Value;
//}
if (value_type.IsAssignableFrom (json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
custom_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
base_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe it's an enum
if (value_type.IsEnum)
return Enum.ToObject (value_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (value_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (value_type);
ObjectMetadata t_data = object_metadata[value_type];
instance = Activator.CreateInstance (value_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite){
//p_info.SetValue(
// instance,
// ReadValue(prop_data.Type, reader),
// null);
//use the getSetMethod.invoke instead of SetValue is to suport more platform
// such as mono run in ios,jit is forbidden,so the p_info.setValue cannot be used
p_info.GetSetMethod().Invoke(instance, new object[] { ReadValue(prop_data.Type, reader) });
}
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary) {
if (! reader.SkipNonMembers) {
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
} else {
ReadSkip (reader);
continue;
}
}
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Float)
{
instance.SetFloat((float)reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void ReadSkip (JsonReader reader)
{
ToWrapper (
delegate { return new JsonMockWrapper (); }, reader);
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
base_exporters_table[typeof(float)] =
delegate(object obj, JsonWriter writer)
{
writer.Write((float)obj);
};
base_exporters_table[typeof(Int64)] =
delegate(object obj, JsonWriter writer)
{
writer.Write((Int64)obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate(object input)
{
return Convert.ToSingle((float)input);
};
RegisterImporter(base_importers_table,typeof(float),
typeof(decimal), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is float)
{
writer.Write((float)obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
public static partial class GlobalModelOperationsExtensions
{
/// <summary>
/// Gets publishing credentials for the subscription owner
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static User GetSubscriptionPublishingCredentials(this IGlobalModelOperations operations)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).GetSubscriptionPublishingCredentialsAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets publishing credentials for the subscription owner
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> GetSubscriptionPublishingCredentialsAsync( this IGlobalModelOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSubscriptionPublishingCredentialsWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates publishing credentials for the subscription owner
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='requestMessage'>
/// requestMessage with new publishing credentials
/// </param>
public static User UpdateSubscriptionPublishingCredentials(this IGlobalModelOperations operations, User requestMessage)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).UpdateSubscriptionPublishingCredentialsAsync(requestMessage), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates publishing credentials for the subscription owner
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='requestMessage'>
/// requestMessage with new publishing credentials
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> UpdateSubscriptionPublishingCredentialsAsync( this IGlobalModelOperations operations, User requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateSubscriptionPublishingCredentialsWithHttpMessagesAsync(requestMessage, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets list of available geo regions
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sku'>
/// Filter only to regions that support this sku
/// </param>
public static GeoRegionCollection GetSubscriptionGeoRegions(this IGlobalModelOperations operations, string sku = default(string))
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).GetSubscriptionGeoRegionsAsync(sku), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets list of available geo regions
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sku'>
/// Filter only to regions that support this sku
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GeoRegionCollection> GetSubscriptionGeoRegionsAsync( this IGlobalModelOperations operations, string sku = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSubscriptionGeoRegionsWithHttpMessagesAsync(sku, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get all certificates for a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static CertificateCollection GetAllCertificates(this IGlobalModelOperations operations)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).GetAllCertificatesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get all certificates for 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<CertificateCollection> GetAllCertificatesAsync( this IGlobalModelOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAllCertificatesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all App Service Plans for a subcription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='detailed'>
/// False to return a subset of App Service Plan properties, true to return
/// all of the properties.
/// Retrieval of all properties may increase the API latency.
/// </param>
public static ServerFarmCollection GetAllServerFarms(this IGlobalModelOperations operations, bool? detailed = default(bool?))
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).GetAllServerFarmsAsync(detailed), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all App Service Plans for a subcription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='detailed'>
/// False to return a subset of App Service Plan properties, true to return
/// all of the properties.
/// Retrieval of all properties may increase the API latency.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServerFarmCollection> GetAllServerFarmsAsync( this IGlobalModelOperations operations, bool? detailed = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAllServerFarmsWithHttpMessagesAsync(detailed, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all Web Apps for a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static SiteCollection GetAllSites(this IGlobalModelOperations operations)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).GetAllSitesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all Web Apps for 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<SiteCollection> GetAllSitesAsync( this IGlobalModelOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAllSitesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all hostingEnvironments (App Service Environment) for a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static HostingEnvironmentCollection GetAllHostingEnvironments(this IGlobalModelOperations operations)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).GetAllHostingEnvironmentsAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all hostingEnvironments (App Service Environment) for 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<HostingEnvironmentCollection> GetAllHostingEnvironmentsAsync( this IGlobalModelOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAllHostingEnvironmentsWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all managed hosting environments for a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static ManagedHostingEnvironmentCollection GetAllManagedHostingEnvironments(this IGlobalModelOperations operations)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).GetAllManagedHostingEnvironmentsAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all managed hosting environments for 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<ManagedHostingEnvironmentCollection> GetAllManagedHostingEnvironmentsAsync( this IGlobalModelOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAllManagedHostingEnvironmentsWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all mobile services for a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static ClassicMobileServiceCollection GetAllClassicMobileServices(this IGlobalModelOperations operations)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).GetAllClassicMobileServicesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all mobile services for 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<ClassicMobileServiceCollection> GetAllClassicMobileServicesAsync( this IGlobalModelOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAllClassicMobileServicesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List premier add on offers
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static object ListPremierAddOnOffers(this IGlobalModelOperations operations)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).ListPremierAddOnOffersAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List premier add on offers
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<object> ListPremierAddOnOffersAsync( this IGlobalModelOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListPremierAddOnOffersWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Whether hosting environment name is available
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// Hosting environment name
/// </param>
public static object IsHostingEnvironmentNameAvailable(this IGlobalModelOperations operations, string name)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).IsHostingEnvironmentNameAvailableAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Whether hosting environment name is available
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// Hosting environment name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<object> IsHostingEnvironmentNameAvailableAsync( this IGlobalModelOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.IsHostingEnvironmentNameAvailableWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Whether hosting environment name is available
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// Hosting environment name
/// </param>
public static object IsHostingEnvironmentWithLegacyNameAvailable(this IGlobalModelOperations operations, string name)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).IsHostingEnvironmentWithLegacyNameAvailableAsync(name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Whether hosting environment name is available
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// Hosting environment name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<object> IsHostingEnvironmentWithLegacyNameAvailableAsync( this IGlobalModelOperations operations, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.IsHostingEnvironmentWithLegacyNameAvailableWithHttpMessagesAsync(name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Check if resource name is available
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='request'>
/// Name availability request
/// </param>
public static ResourceNameAvailability CheckNameAvailability(this IGlobalModelOperations operations, ResourceNameAvailabilityRequest request)
{
return Task.Factory.StartNew(s => ((IGlobalModelOperations)s).CheckNameAvailabilityAsync(request), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Check if resource name is available
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='request'>
/// Name availability request
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceNameAvailability> CheckNameAvailabilityAsync( this IGlobalModelOperations operations, ResourceNameAvailabilityRequest request, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(request, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
namespace Boo.Lang.Resources
{
public static class StringResources
{
public const string BCE0000 = "'{0}'";
public const string BCE0001 = "The class '{0}' already has '{1}' as its super class.";
public const string BCE0002 = "Parameter name must be an identifier.";
public const string BCE0003 = "Named arguments are only allowed when creating objects.";
public const string BCE0004 = "Ambiguous reference '{0}': {1}.";
public const string BCE0005 = "Unknown identifier: '{0}'.";
public const string BCE0006 = "'{0}' is a value type. The 'as' operator can only be used with reference types.";
public const string BCE0007 = "The name '{0}' does not represent a writable public property or field of the type '{1}'.";
public const string BCE0008 = "The '{0}' type does not have a constructor with the signature '{1}'.";
public const string BCE0009 = "An error occurred during the resolution of the '{0}' ast attribute: '{1}'.";
public const string BCE0010 = "'{0}' is an internal type. Ast attributes must be compiled to a separate assembly before they can be used.";
public const string BCE0011 = "An error occurred during the execution of the step '{0}': '{1}'.";
public const string BCE0012 = "The type '{0}' does not implement the ICompilerStep interface.";
public const string BCE0013 = "The element '{0}' must specify the attribute '{1}'.";
public const string BCE0014 = "AssemblyBuilder was not correctly set up.";
public const string BCE0015 = "Node '{0}' has not been correctly processed.";
public const string BCE0016 = "No overload of the method '{0}' takes '{1}' parameter(s).";
public const string BCE0017 = "The best overload for the method '{0}' is not compatible with the argument list '{1}'.";
public const string BCE0018 = "The name '{0}' does not denote a valid type ('{1}'). {2}";
public const string BCE0019 = "'{0}' is not a member of '{1}'. {2}";
public const string BCE0020 = "An instance of type '{0}' is required to access non static member '{1}'.";
public const string BCE0021 = "Namespace '{0}' not found, maybe you forgot to add an assembly reference?";
public const string BCE0022 = "Cannot convert '{1}' to '{0}'.";
public const string BCE0023 = "No appropriate version of '{1}' for the argument list '{0}' was found.";
public const string BCE0024 = "The type '{0}' does not have a visible constructor that matches the argument list '{1}'.";
public const string BCE0025 = "Only uni-dimensional arrays are supported.";
public const string BCE0026 = "'{0}' cannot be used in a boolean context.";
public const string BCE0027 = "Ambiguous type reference, it could be any of the following: '{0}'.";
public const string BCE0028 = "No entry point found.";
public const string BCE0029 = "More than one entry point found.";
public const string BCE0030 = "The node '{0}' is not in the collection.";
public const string BCE0031 = "Language feature not implemented: {0}.";
public const string BCE0032 = "The event '{0}' expects a {2} reference compatible with '{1}'.";
public const string BCE0033 = "The type '{0}' is not a valid attribute.";
public const string BCE0034 = "Expressions in statements must only be executed for their side-effects.";
public const string BCE0035 = "'{0}' conflicts with inherited member '{1}'.";
public const string BCE0036 = "typeof must be used with a type reference as its single argument.";
public const string BCE0037 = "Unknown macro: '{0}'.";
public const string BCE0038 = "'{0}' is not a valid macro.";
public const string BCE0039 = "Internal macro '{0}' could not be compiled. Errors were reported.";
public const string BCE0040 = "Generic error.";
public const string BCE0041 = "Failed to load assembly '{0}'.";
public const string BCE0042 = "Error reading from '{0}': '{1}'.";
public const string BCE0043 = "Unexpected token: {0}.";
public const string BCE0044 = "{0}.";
public const string BCE0045 = "Macro expansion error: {0}.";
public const string BCE0046 = "'{0}' can't be used with a value type ('{1}')";
public const string BCE0047 = "Non virtual method '{0}' cannot be overridden.";
public const string BCE0048 = "Type '{0}' does not support slicing.";
public const string BCE0049 = "Expression '{0}' cannot be assigned to.";
public const string BCE0050 = "Operator '{0}' cannot be used with an expression of type '{1}'.";
public const string BCE0051 = "Operator '{0}' cannot be used with a left hand side of type '{1}' and a right hand side of type '{2}'.";
public const string BCE0052 = "Type '{0}' is not a valid argument for 'len'.";
public const string BCE0053 = "Property '{0}' is read only.";
public const string BCE0054 = "'{0}' expects a type reference, a System.Type instance or a type array.";
public const string BCE0055 = "Internal compiler error: {0}.";
public const string BCE0056 = "File '{0}' was not found.";
public const string BCE0057 = "Primitive '{0}' can't be redefined.";
public const string BCE0058 = "'{0}' is not valid in a static method, static property, or static field initializer.";
public const string BCE0059 = "The 'lock' macro expects at least one argument.";
public const string BCE0060 = "'{0}': no suitable method found to override. {1}";
public const string BCE0060_IncompatibleSignature = "Method of same name has been found with incompatible signature(s).";
public const string BCE0061 = "'{0}' is not an override.";
public const string BCE0062 = "Could not infer the return type for the method '{0}'.";
public const string BCE0063 = "No enclosing loop out of which to break or continue.";
public const string BCE0064 = "No attribute with the name '{0}' or '{0}Attribute' was found (attribute names are case insensitive). {1}";
public const string BCE0065 = "Cannot iterate over expression of type '{0}'.";
public const string BCE0066 = "The attribute '{0}' can only be applied to '{1}' nodes.";
public const string BCE0067 = "There is already a local variable with the name '{0}'.";
public const string BCE0068 = "The property '{0}' cannot be used without parameters.";
public const string BCE0069 = "Interface '{0}' can only inherit from another interface but the type '{1}' is not an interface.";
public const string BCE0070 = "Definition of '{0}' depends on '{1}' whose type could not be resolved because of a cycle. Explicitly declare the type of either one to break the cycle.";
public const string BCE0071 = "Inheritance cycle detected: '{0}'.";
public const string BCE0072 = "Overridden method '{0}' has a return type of '{1}' not '{2}'.";
public const string BCE0073 = "Abstract method '{0}' cannot have a body.";
public const string BCE0074 = "'{0}' cannot be used outside a method.";
public const string BCE0075 = "'{0}' is a namespace. Namespaces cannot be used as expressions.";
public const string BCE0076 = "Run-time and PInvoke methods must have an empty body.";
public const string BCE0077 = "It is not possible to invoke an expression of type '{0}'.";
public const string BCE0078 = "A method reference was expected.";
public const string BCE0079 = "__addressof__ built-in function can only be used in delegate constructors.";
public const string BCE0080 = "'{0}' built-in function cannot be used as an expression.";
public const string BCE0081 = "A {0} statement with no arguments is not allowed outside an exception handler.";
public const string BCE0082 = "'{0}' is not a {1} type. Event type must be a {1} type.";
public const string BCE0083 = "Static constructors must be private.";
public const string BCE0084 = "Static constructors cannot declare parameters.";
public const string BCE0085 = "Cannot create instance of abstract class '{0}'.";
public const string BCE0086 = "Cannot create instance of interface '{0}'.";
public const string BCE0087 = "Cannot create instance of enum '{0}'.";
public const string BCE0089 = "Type '{0}' already has a definition for '{1}'.";
public const string BCE0090 = "Derived method '{0}' can not reduce the accessibility of '{1}' from '{2}' to '{3}'.";
public const string BCE0091 = "Event reference '{0}' cannot be used as an expression.";
public const string BCE0092 = "'{0}' is not a valid argument type for {1}, only strings and exceptions are allowed.";
public const string BCE0093 = "Cannot branch into {0} block.";
public const string BCE0094 = "Cannot branch into exception handler.";
public const string BCE0095 = "No such label '{0}'.";
public const string BCE0096 = "Method '{0}' already has a label '{1}'.";
public const string BCE0097 = "Cannot branch into {0} block.";
public const string BCE0098 = "Invalid arguments for __switch__.";
public const string BCE0099 = "yield cannot be used inside a {0}, {1} or {2} block.";
public const string BCE0100 = "yield cannot be used inside constructors.";
public const string BCE0101 = "Return type '{0}' cannot be used on a generator. Did you mean '{1}'? You can also use 'System.Collections.IEnumerable' or 'object'.";
public const string BCE0102 = "Generators cannot return values.";
public const string BCE0103 = "Cannot extend final type '{0}'.";
public const string BCE0104 = "'transient' can only be applied to class, field and event definitions.";
public const string BCE0105 = "'abstract' can only be applied to class, method, property and event definitions.";
public const string BCE0106 = "Failed to access the types defined in assembly {0}.";
public const string BCE0107 = "Value types cannot declare parameter-less constructors.";
public const string BCE0108 = "Value type fields cannot have initializers.";
public const string BCE0109 = "Array '{0}' is rank '{1}', not rank '{2}'.";
public const string BCE0110 = "'{0}' is not a namespace.";
public const string BCE0111 = "Destructors cannot have any attributes or modifiers";
public const string BCE0112 = "Destructors cannot be passed parameters";
public const string BCE0113 = "Invalid character literal: '{0}'";
public const string BCE0114 = "Explicit interface implementation for non interface type '{0}'";
public const string BCE0115 = "Cannot implement interface item '{0}.{1}' when not implementing the interface '{0}'";
public const string BCE0116 = "Explicit member implementation for '{0}.{1}' must not declare any modifiers.";
public const string BCE0117 = "Field '{0}' is read only.";
public const string BCE0118 = "Target of explode expression must be an array.";
public const string BCE0119 = "Explode expression can only be used as the last argument to {0} that takes a variable number of arguments.";
public const string BCE0120 = "'{0}' is inaccessible due to its protection level.";
public const string BCE0121 = "'super' is not valid in this context.";
public const string BCE0122 = "Value type '{0}' does not provide an implementation for '{1}'. Value types cannot have abstract members.";
public const string BCE0123 = "Invalid {1}parameter type '{0}'.";
public const string BCE0124 = "Invalid field type '{0}'.";
public const string BCE0125 = "Invalid declaration type '{0}'.";
public const string BCE0126 = "It is not possible to evaluate an expression of type '{0}'.";
public const string BCE0127 = "A ref or out argument must be an lvalue: '{0}'";
public const string BCE0128 = "'{0}' block must be followed by at least one '{1}' block or either a '{2}' or '{3}' block.";
public const string BCE0129 = "Invalid extension definition, only static methods with at least one argument are allowed.";
public const string BCE0130 = "'partial' can only be applied to top level class, interface and enum definitions.";
public const string BCE0131 = "Invalid combination of modifiers on '{0}': {1}.";
public const string BCE0132 = "The namespace '{0}' already contains a definition for '{1}'.";
public const string BCE0133 = "Invalid signature for Main. It should be one of: 'Main() as void', 'Main() as int', 'Main(argv as (string)) as void', 'Main(argv as (string)) as int'.";
public const string BCE0134 = "'{0}' cannot return values.";
public const string BCE0135 = "Invalid name: '{0}'";
public const string BCE0136 = "Use a colon (:) instead of equal sign (=) for named parameters.";
public const string BCE0137 = "Property '{0}' is write only.";
public const string BCE0138 = "'{0}' is not a generic definition.";
public const string BCE0139 = "'{0}' requires '{1}' arguments.";
public const string BCE0140 = "Yield statement type '{0}' does not match generator element type '{1}'.";
public const string BCE0141 = "Duplicate parameter name '{0}' in '{1}'.";
public const string BCE0142 = "Cannot bind [default] attribute to value type parameter '{0}' in '{1}'.";
public const string BCE0143 = "Cannot return from an {0} block.";
public const string BCE0144 = "'{0}' is obsolete. {1}";
public const string BCE0145 = "Cannot catch type '{0}'; '{1}' blocks can only catch exceptions derived from 'System.Exception'. To catch non-CLS compliant exceptions, use a default exception handler or catch 'System.Runtime.CompilerServices.RuntimeWrappedException'.";
public const string BCE0146 = "The type '{0}' must be a reference type in order to substitute the generic parameter '{1}' in '{2}'.";
public const string BCE0147 = "The type '{0}' must be a value type in order to substitute the generic parameter '{1}' in '{2}'.";
public const string BCE0148 = "The type '{0}' must have a public default constructor in order to substitute the generic parameter '{1}' in '{2}'.";
public const string BCE0149 = "The type '{0}' must derive from '{1}' in order to substitute the generic parameter '{2}' in '{3}'.";
public const string BCE0150 = "'final' cannot be applied to interface, struct, or enum definitions.";
public const string BCE0151 = "'static' cannot be applied to interface, struct, or enum definitions.";
public const string BCE0152 = "Constructors cannot be marked virtual, abstract, or override: '{0}'.";
public const string BCE0153 = "'{0}' can be applied on one of these targets only : {1}.";
public const string BCE0154 = "'{0}' cannot be applied multiple times on the same target.";
public const string BCE0155 = "Instantiating generic parameters is not yet supported.";
public const string BCE0156 = "Event '{0}' can only be triggered from within its declaring type ('{1}').";
public const string BCE0157 = "Generic types without all generic parameters defined cannot be instantiated.";
public const string BCE0158 = "Cannot invoke instance method '{0}' before object initialization. Move your call after '{1}' or 'super'.";
public const string BCE0159 = "Generic parameter '{0}' cannot have both a reference type constraint and a value type constraint.";
public const string BCE0160 = "Generic parameter '{0}' cannot have both a value type constraint and a default constructor constraint.";
public const string BCE0161 = "Type constraint '{1}' cannot be used together with the '{2}' constraint on generic parameter '{0}'.";
public const string BCE0162 = "Type '{1}' must be an interface type or a non-final class type to be used as a type constraint on generic parameter '{0}'.";
public const string BCE0163 = "Type constraint '{1}' on generic parameter '{0}' conflicts with type constraint '{2}'. At most one non-interface type constraint can be specified for a generic parameter.";
public const string BCE0164 = "Cannot infer generic arguments for method '{0}'. Provide stronger type information through arguments, or explicitly state the generic arguments.";
public const string BCE0165 = "'{0}' is already handled by {3} block for '{1}' at {2}.";
public const string BCE0166 = "Unknown macro '{0}'. Did you mean to declare the field '{0} as object'?";
public const string BCE0167 = "Namespace '{0}' not found in assembly '{1}'";
public const string BCE0168 = "Cannot take the address of, get the size of, or declare a pointer to managed type `{0}'.";
public const string BCE0169 = "`{0}' in explicit interface declaration is not a member of interface `{1}'.";
public const string BCE0170 = "An enum member must be a constant integer value.";
public const string BCE0171 = "Constant value `{0}' cannot be converted to a `{1}'.";
public const string BCE0172 = "`{0}' interface member implementation must be public or explicit.";
public const string BCE0173 = "`{0}' is not a regex option. Valid options are: g, i, m, s, x, l, n, c and e.";
public const string BCE0174 = "'{0}' is not an interface. Only interface members can be explicitly implemented.";
public const string BCE0175 = "Nested type '{0}' cannot extend enclosing type '{1}'.";
public const string BCE0176 = "Incompatible partial definition for type '{0}', expecting '{1}' but got '{2}'.";
public const string BCW0000 = "WARNING: {0}";
public const string BCW0001 = "WARNING: Type '{0}' does not provide an implementation for '{1}' and will be marked abstract.";
public const string BCW0002 = "WARNING: Statement modifiers have no effect in labels.";
public const string BCW0003 = "WARNING: Unused local variable '{0}'.";
public const string BCW0004 = "WARNING: Right hand side of '{0}' operator is a type reference, are you sure you do not want to use '{1}' instead?";
public const string BCW0005 = "WARNING: Unsubscribing from event '{0}' with an adapted method reference. Either change the signature of the method to '{1}' or use a cached reference of the correct type.";
public const string BCW0006 = "WARNING: Assignment to temporary.";
public const string BCW0007 = "WARNING: Assignment inside a conditional. Did you mean '==' instead of '=' here: '{0}'?";
public const string BCW0008 = "WARNING: Duplicate namespace: '{0}'.";
public const string BCW0009 = "WARNING: The -keyfile option will override your AssemblyKeyFile attribute.";
public const string BCW0010 = "WARNING: The -keycontainer option will override your AssemblyKeyName attribute.";
public const string BCW0011 = "WARNING: Type '{0}' does not provide an implementation for '{1}', a stub has been created.";
public const string BCW0012 = "WARNING: '{0}' is obsolete. {1}";
public const string BCW0013 = "WARNING: '{1}' on static type '{0}' is redundantly marked static. All members of static types are automatically assumed to be static.";
public const string BCW0014 = "WARNING: {0} {1} '{2}' is never used.";
public const string BCW0015 = "WARNING: Unreachable code detected.";
public const string BCW0016 = "WARNING: Namespace '{0}' is never used.";
public const string BCW0017 = "WARNING: New protected {0} '{1}' declared in sealed class '{2}'.";
public const string BCW0018 = "WARNING: Overriding 'object.Finalize()' is bad practice. You should use destructor syntax instead.";
public const string BCW0019 = "WARNING: 'except {0}:' is ambiguous. Did you mean 'except as {0}:'?";
public const string BCW0020 = "WARNING: Assignment made to same expression. Did you mean to assign to something else?";
public const string BCW0021 = "WARNING: Comparison made with same expression. Did you mean to compare with something else?";
public const string BCW0022 = "WARNING: Boolean expression will always have the same value.";
public const string BCW0023 = "WARNING: This method could return default value implicitly.";
public const string BCW0024 = "WARNING: Visible {0} does not declare {1} type explicitely.";
public const string BCW0025 = "WARNING: Variable '{0}' has the same name as a private field of super type '{1}'. Did you mean to use the field?";
public const string BCW0026 = "WARNING: Likely typo in member name '{0}'. Did you mean '{1}'?";
public const string BCW0027 = "WARNING: Obsolete syntax '{0}'. Use '{1}'.";
public const string BCW0028 = "WARNING: Implicit downcast from '{0}' to '{1}'.";
public const string BCW0029 = "WARNING: Method '{0}' hides inherited non virtual method '{1}'. Declare '{0}' as a 'new' method.";
public const string BCE0500 = "Response file '{0}' listed more than once.";
public const string BCE0501 = "Response file '{0}' could not be found.";
public const string BCE0502 = "An error occurred while loading response file '{0}'.";
public const string Boo_Lang_Compiler_GlobalNamespaceIsNotSet = "Global namespace is not set!";
public const string BooC_Errors = "{0} error(s).";
public const string BooC_Warnings = "{0} warning(s).";
public const string BooC_ProcessingTime = "{0} module(s) processed in {1}ms after {2}ms of environment setup.";
public const string BooC_FatalError = "Fatal error: {0}.";
public const string BooC_InvalidOption = "Invalid option: {0}. {1}";
public const string BooC_CantRunWithoutPipeline = "A pipeline must be specified!";
public const string BooC_InvalidPipeline = "'{0}' is neither a built-in pipeline nor a valid custom pipeline name.";
public const string BooC_VerifyPipelineUnsupported = "PEVerify pipeline is not supported on this platform.";
public const string BooC_UnableToLoadPipeline = "Failed to load pipeline {0}, cause: {1}.";
public const string BooC_NoPipeline = "No compilation pipeline specified (/p:<PIPELINE>)";
public const string BooC_NoInputSpecified = "No inputs specified";
public const string BooC_NoOutputSpecified = "No output specified";
public const string BooC_UnableToLoadAssembly = "Unable to load assembly: {0}";
public const string BooC_BadFormat = "Unable to load assembly (bad file format): {0}";
public const string BooC_NullAssembly = "Unable to load assembly (null argument)";
public const string BooC_CannotFindAssembly = "Cannot find assembly: '{0}'";
public const string BooC_NoSystemPath = "Cannot find path to mscorlib.";
public const string BooC_BadLibPath = "Not a valid directory for -lib argument: '{0}'";
public const string BooC_PkgConfigNotFound = "Cannot execute pkg-config, is it in your PATH ?";
public const string BooC_PkgConfigReportedErrors = "pkg-config returned errors: {0}";
public const string BooC_DidYouMean = "Did you mean '{0}'?";
public const string BooC_Return = "return";
public const string BooC_NamedArgument = "'{0}' argument";
public const string BooC_InvalidNestedMacroContext = "Invalid nested macro context. Check your macro hierarchy";
public const string ListWasModified = "The list was modified.";
public const string ArgumentNotEnumerable = "Argument is not enumerable (does not implement System.Collections.IEnumerable).";
public const string CantEnumerateNull = "Cannot enumerate null.";
public const string UnpackListOfWrongSize = "Unpack list of wrong size.";
public const string CantUnpackNull = "Cannot unpack null.";
public const string UnpackArrayOfWrongSize = "Unpack array of wrong size (expected={0}, actual={1}).";
public const string CantCompareItems = "At least one side must implement IComparable or both sides should implement IEnumerable.";
public const string AssertArgCount = "expecting 1 or 2 args to assert; got {0}";
public const string boo_CommandLine_culture = "the culture {code} to use when running the application";
public const string boo_CommandLine_debug = "emit debugging information";
public const string boo_CommandLine_ducky = "treat object references as duck";
public const string boo_CommandLine_embedres = "embeds the specified file as a unmanaged resource";
public const string boo_CommandLine_output = "file name for the generated assembly";
public const string boo_CommandLine_pipeline = "which compilation pipeline to use, it can be either the name of a built-in pipeline like 'boo' or a full type name";
public const string boo_CommandLine_reference = "references an assembly";
public const string boo_CommandLine_resource = "adds a managed resource";
public const string boo_CommandLine_target = "one of exe, winexe, library";
public const string boo_CommandLine_utf8 = "use UTF8 when writing to the console";
public const string boo_CommandLine_wsa = "use the white space agnostic parser";
public const string boo_CommandLine_help = "display help information and exit";
public const string boo_CommandLine_header = "boo command line utility";
public const string boo_CommandLine_usage = "Usage: boo [options] [source files]";
public const string AbortedDueToUserRequest = "Aborted due to user request.";
}
}
| |
#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.Collections.Specialized;
using System.ComponentModel;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json.Linq;
using System.IO;
using System.Collections;
#if !PocketPC && !SILVERLIGHT && !NETFX_CORE
using System.Web.UI;
#endif
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JObjectTests : TestFixtureBase
{
[Test]
public void Keys()
{
var o = new JObject();
var d = (IDictionary<string, JToken>) o;
Assert.AreEqual(0, d.Keys.Count);
o["value"] = true;
Assert.AreEqual(1, d.Keys.Count);
}
[Test]
public void TryGetValue()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(false, o.TryGetValue("sdf", out t));
Assert.AreEqual(null, t);
Assert.AreEqual(false, o.TryGetValue(null, out t));
Assert.AreEqual(null, t);
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
}
[Test]
public void DictionaryItemShouldSet()
{
JObject o = new JObject();
o["PropertyNameValue"] = new JValue(1);
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
o["PropertyNameValue"] = new JValue(2);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t));
o["PropertyNameValue"] = null;
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue((object)null), t));
}
[Test]
public void Remove()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, o.Remove("sdf"));
Assert.AreEqual(false, o.Remove(null));
Assert.AreEqual(true, o.Remove("PropertyNameValue"));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
public void GenericCollectionRemove()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))));
Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v)));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
public void DuplicatePropertyNameShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", null);
o.Add("PropertyNameValue", null);
});
}
[Test]
public void GenericDictionaryAdd()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
o.Add("PropertyNameValue1", null);
Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value);
Assert.AreEqual(2, o.Children().Count());
}
[Test]
public void GenericCollectionAdd()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string,JToken>>)o).Add(new KeyValuePair<string,JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
Assert.AreEqual(1, o.Children().Count());
}
[Test]
public void GenericCollectionClear()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JProperty p = (JProperty)o.Children().ElementAt(0);
((ICollection<KeyValuePair<string, JToken>>)o).Clear();
Assert.AreEqual(0, o.Children().Count());
Assert.AreEqual(null, p.Parent);
}
[Test]
public void GenericCollectionContains()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v));
Assert.AreEqual(true, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>));
Assert.AreEqual(false, contains);
}
[Test]
public void GenericDictionaryContains()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue");
Assert.AreEqual(true, contains);
}
[Test]
public void GenericCollectionCopyTo()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
Assert.AreEqual(3, o.Children().Count());
KeyValuePair<string, JToken>[] a = new KeyValuePair<string,JToken>[5];
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1);
Assert.AreEqual(default(KeyValuePair<string,JToken>), a[0]);
Assert.AreEqual("PropertyNameValue", a[1].Key);
Assert.AreEqual(1, (int)a[1].Value);
Assert.AreEqual("PropertyNameValue2", a[2].Key);
Assert.AreEqual(2, (int)a[2].Value);
Assert.AreEqual("PropertyNameValue3", a[3].Key);
Assert.AreEqual(3, (int)a[3].Value);
Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]);
}
[Test]
public void GenericCollectionCopyToNullArrayShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(
@"Value cannot be null.
Parameter name: array",
() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0);
});
}
[Test]
public void GenericCollectionCopyToNegativeArrayIndexShouldThrow()
{
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"arrayIndex is less than 0.
Parameter name: arrayIndex",
() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1);
});
}
[Test]
public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(
@"arrayIndex is equal to or greater than the length of array.",
() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1);
});
}
[Test]
public void GenericCollectionCopyToInsufficientArrayCapacity()
{
ExceptionAssert.Throws<ArgumentException>(
@"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.",
() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
});
}
[Test]
public void FromObjectRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
Assert.AreEqual("FirstNameValue", (string)o["first_name"]);
Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type);
Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]);
Assert.AreEqual("LastNameValue", (string)o["last_name"]);
}
[Test]
public void JTokenReader()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Raw, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void DeserializeFromRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
JsonSerializer serializer = new JsonSerializer();
raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw));
Assert.AreEqual("FirstNameValue", raw.FirstName);
Assert.AreEqual("LastNameValue", raw.LastName);
Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value);
}
[Test]
public void Parse_ShouldThrowOnUnexpectedToken()
{
ExceptionAssert.Throws<JsonReaderException>("Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.",
() =>
{
string json = @"[""prop""]";
JObject.Parse(json);
});
}
[Test]
public void ParseJavaScriptDate()
{
string json = @"[new Date(1207285200000)]";
JArray a = (JArray)JsonConvert.DeserializeObject(json);
JValue v = (JValue)a[0];
Assert.AreEqual(JsonConvert.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v);
}
[Test]
public void GenericValueCast()
{
string json = @"{""foo"":true}";
JObject o = (JObject)JsonConvert.DeserializeObject(json);
bool? value = o.Value<bool?>("foo");
Assert.AreEqual(true, value);
json = @"{""foo"":null}";
o = (JObject)JsonConvert.DeserializeObject(json);
value = o.Value<bool?>("foo");
Assert.AreEqual(null, value);
}
[Test]
public void Blog()
{
ExceptionAssert.Throws<JsonReaderException>(
"Invalid property identifier character: ]. Path 'name', line 3, position 5.",
() =>
{
JObject.Parse(@"{
""name"": ""James"",
]!#$THIS IS: BAD JSON![{}}}}]
}");
});
}
[Test]
public void RawChildValues()
{
JObject o = new JObject();
o["val1"] = new JRaw("1");
o["val2"] = new JRaw("1");
string json = o.ToString();
Assert.AreEqual(@"{
""val1"": 1,
""val2"": 1
}", json);
}
[Test]
public void Iterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
JToken t = o;
int i = 1;
foreach (JProperty property in t)
{
Assert.AreEqual("PropertyNameValue" + i, property.Name);
Assert.AreEqual(i, (int)property.Value);
i++;
}
}
[Test]
public void KeyValuePairIterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
int i = 1;
foreach (KeyValuePair<string, JToken> pair in o)
{
Assert.AreEqual("PropertyNameValue" + i, pair.Key);
Assert.AreEqual(i, (int)pair.Value);
i++;
}
}
[Test]
public void WriteObjectNullStringValue()
{
string s = null;
JValue v = new JValue(s);
Assert.AreEqual(null, v.Value);
Assert.AreEqual(JTokenType.String, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
Assert.AreEqual(@"{
""title"": null
}", output);
}
[Test]
public void Example()
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
Console.WriteLine(name);
Console.WriteLine(smallest);
}
[Test]
public void DeserializeClassManually()
{
string jsonText = @"{
""short"":
{
""original"":""http://www.foo.com/"",
""short"":""krehqk"",
""error"":
{
""code"":0,
""msg"":""No action taken""
}
}
}";
JObject json = JObject.Parse(jsonText);
Shortie shortie = new Shortie
{
Original = (string)json["short"]["original"],
Short = (string)json["short"]["short"],
Error = new ShortieException
{
Code = (int)json["short"]["error"]["code"],
ErrorMessage = (string)json["short"]["error"]["msg"]
}
};
Console.WriteLine(shortie.Original);
// http://www.foo.com/
Console.WriteLine(shortie.Error.ErrorMessage);
// No action taken
Assert.AreEqual("http://www.foo.com/", shortie.Original);
Assert.AreEqual("krehqk", shortie.Short);
Assert.AreEqual(null, shortie.Shortened);
Assert.AreEqual(0, shortie.Error.Code);
Assert.AreEqual("No action taken", shortie.Error.ErrorMessage);
}
[Test]
public void JObjectContainingHtml()
{
JObject o = new JObject();
o["rc"] = new JValue(200);
o["m"] = new JValue("");
o["o"] = new JValue(@"<div class='s1'>
<div class='avatar'>
<a href='asdf'>asdf</a><br />
<strong>0</strong>
</div>
<div class='sl'>
<p>
444444444
</p>
</div>
<div class='clear'>
</div>
</div>");
Assert.AreEqual(@"{
""rc"": 200,
""m"": """",
""o"": ""<div class='s1'>\r\n <div class='avatar'> \r\n <a href='asdf'>asdf</a><br />\r\n <strong>0</strong>\r\n </div>\r\n <div class='sl'>\r\n <p>\r\n 444444444\r\n </p>\r\n </div>\r\n <div class='clear'>\r\n </div> \r\n</div>""
}", o.ToString());
}
[Test]
public void ImplicitValueConversions()
{
JObject moss = new JObject();
moss["FirstName"] = new JValue("Maurice");
moss["LastName"] = new JValue("Moss");
moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30));
moss["Department"] = new JValue("IT");
moss["JobTitle"] = new JValue("Support");
Console.WriteLine(moss.ToString());
//{
// "FirstName": "Maurice",
// "LastName": "Moss",
// "BirthDate": "\/Date(252241200000+1300)\/",
// "Department": "IT",
// "JobTitle": "Support"
//}
JObject jen = new JObject();
jen["FirstName"] = "Jen";
jen["LastName"] = "Barber";
jen["BirthDate"] = new DateTime(1978, 3, 15);
jen["Department"] = "IT";
jen["JobTitle"] = "Manager";
Console.WriteLine(jen.ToString());
//{
// "FirstName": "Jen",
// "LastName": "Barber",
// "BirthDate": "\/Date(258721200000+1300)\/",
// "Department": "IT",
// "JobTitle": "Manager"
//}
}
[Test]
public void ReplaceJPropertyWithJPropertyWithSameName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
IList l = o;
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p2, l[1]);
JProperty p3 = new JProperty("Test1", "III");
p1.Replace(p3);
Assert.AreEqual(null, p1.Parent);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
Assert.AreEqual(2, l.Count);
Assert.AreEqual(2, o.Properties().Count());
JProperty p4 = new JProperty("Test4", "IV");
p2.Replace(p4);
Assert.AreEqual(null, p2.Parent);
Assert.AreEqual(l, p4.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p4, l[1]);
}
#if !(SILVERLIGHT || NET20 || NETFX_CORE || PORTABLE)
[Test]
public void PropertyChanging()
{
object changing = null;
object changed = null;
int changingCount = 0;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanging += (sender, args) =>
{
JObject s = (JObject) sender;
changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changingCount++;
};
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual(null, changing);
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value1", changing);
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changingCount);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual("value2", changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changingCount);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(new JValue((object)null), o["NullValue"]);
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
}
#endif
[Test]
public void PropertyChanged()
{
object changed = null;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(new JValue((object)null), o["NullValue"]);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changedCount);
}
[Test]
public void IListContains()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void IListIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void IListClear()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
object[] a = new object[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void IListAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
public void IListAddBadToken()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
});
}
[Test]
public void IListAddBadValue()
{
ExceptionAssert.Throws<ArgumentException>(
"Argument is not a JToken.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add("Bad!");
});
}
[Test]
public void IListAddPropertyWithExistingName()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
});
}
[Test]
public void IListRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
l.Remove(p3);
Assert.AreEqual(2, l.Count);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
l.Remove(p2);
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void IListRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void IListIsReadOnly()
{
IList l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void IListIsFixedSize()
{
IList l = new JObject();
Assert.IsFalse(l.IsFixedSize);
}
[Test]
public void IListSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
public void IListSetItemAlreadyExists()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
});
}
[Test]
public void IListSetItemInvalid()
{
ExceptionAssert.Throws<ArgumentException>(
@"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l[0] = new JValue(true);
});
}
[Test]
public void IListSyncRoot()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsNotNull(l.SyncRoot);
}
[Test]
public void IListIsSynchronized()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsFalse(l.IsSynchronized);
}
[Test]
public void GenericListJTokenContains()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenClear()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JToken[] a = new JToken[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void GenericListJTokenAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
public void GenericListJTokenAddBadToken()
{
ExceptionAssert.Throws<ArgumentException>("Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
});
}
[Test]
public void GenericListJTokenAddBadValue()
{
ExceptionAssert.Throws<ArgumentException>("Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// string is implicitly converted to JValue
l.Add("Bad!");
});
}
[Test]
public void GenericListJTokenAddPropertyWithExistingName()
{
ExceptionAssert.Throws<ArgumentException>("Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
});
}
[Test]
public void GenericListJTokenRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
Assert.IsFalse(l.Remove(p3));
Assert.AreEqual(2, l.Count);
Assert.IsTrue(l.Remove(p1));
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
Assert.IsTrue(l.Remove(p2));
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void GenericListJTokenRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void GenericListJTokenIsReadOnly()
{
IList<JToken> l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void GenericListJTokenSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
public void GenericListJTokenSetItemAlreadyExists()
{
ExceptionAssert.Throws<ArgumentException>("Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
});
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
[Test]
public void IBindingListSortDirection()
{
IBindingList l = new JObject();
Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection);
}
[Test]
public void IBindingListSortProperty()
{
IBindingList l = new JObject();
Assert.AreEqual(null, l.SortProperty);
}
[Test]
public void IBindingListSupportsChangeNotification()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.SupportsChangeNotification);
}
[Test]
public void IBindingListSupportsSearching()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSearching);
}
[Test]
public void IBindingListSupportsSorting()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSorting);
}
[Test]
public void IBindingListAllowEdit()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowEdit);
}
[Test]
public void IBindingListAllowNew()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowNew);
}
[Test]
public void IBindingListAllowRemove()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowRemove);
}
[Test]
public void IBindingListAddIndex()
{
IBindingList l = new JObject();
// do nothing
l.AddIndex(null);
}
[Test]
public void IBindingListApplySort()
{
ExceptionAssert.Throws<NotSupportedException>(
"Specified method is not supported.",
() =>
{
IBindingList l = new JObject();
l.ApplySort(null, ListSortDirection.Ascending);
});
}
[Test]
public void IBindingListRemoveSort()
{
ExceptionAssert.Throws<NotSupportedException>(
"Specified method is not supported.",
() =>
{
IBindingList l = new JObject();
l.RemoveSort();
});
}
[Test]
public void IBindingListRemoveIndex()
{
IBindingList l = new JObject();
// do nothing
l.RemoveIndex(null);
}
[Test]
public void IBindingListFind()
{
ExceptionAssert.Throws<NotSupportedException>(
"Specified method is not supported.",
() =>
{
IBindingList l = new JObject();
l.Find(null, null);
});
}
[Test]
public void IBindingListIsSorted()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.IsSorted);
}
[Test]
public void IBindingListAddNew()
{
ExceptionAssert.Throws<JsonException>(
"Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.",
() =>
{
IBindingList l = new JObject();
l.AddNew();
});
}
[Test]
public void IBindingListAddNewWithEvent()
{
JObject o = new JObject();
o.AddingNew += (s, e) => e.NewObject = new JProperty("Property!");
IBindingList l = o;
object newObject = l.AddNew();
Assert.IsNotNull(newObject);
JProperty p = (JProperty) newObject;
Assert.AreEqual("Property!", p.Name);
Assert.AreEqual(o, p.Parent);
}
[Test]
public void ITypedListGetListName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
Assert.AreEqual(string.Empty, l.GetListName(null));
}
[Test]
public void ITypedListGetItemProperties()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null);
Assert.IsNull(propertyDescriptors);
}
[Test]
public void ListChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
ListChangedType? changedType = null;
int? index = null;
o.ListChanged += (s, a) =>
{
changedType = a.ListChangedType;
index = a.NewIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, ListChangedType.ItemAdded);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>) o)[index.Value] = p4;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#endif
#if SILVERLIGHT || !(NET20 || NET35 || PORTABLE)
[Test]
public void CollectionChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
NotifyCollectionChangedAction? changedType = null;
int? index = null;
o.CollectionChanged += (s, a) =>
{
changedType = a.Action;
index = a.NewStartingIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>)o)[index.Value] = p4;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#endif
[Test]
public void GetGeocodeAddress()
{
string json = @"{
""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"",
""Status"": {
""code"": 200,
""request"": ""geocode""
},
""Placemark"": [ {
""id"": ""p1"",
""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"",
""AddressDetails"": {
""Accuracy"" : 8,
""Country"" : {
""AdministrativeArea"" : {
""AdministrativeAreaName"" : ""IL"",
""SubAdministrativeArea"" : {
""Locality"" : {
""LocalityName"" : ""Rockford"",
""PostalCode"" : {
""PostalCodeNumber"" : ""61107""
},
""Thoroughfare"" : {
""ThoroughfareName"" : ""435 N Mulford Rd""
}
},
""SubAdministrativeAreaName"" : ""Winnebago""
}
},
""CountryName"" : ""USA"",
""CountryNameCode"" : ""US""
}
},
""ExtendedData"": {
""LatLonBox"": {
""north"": 42.2753076,
""south"": 42.2690124,
""east"": -88.9964645,
""west"": -89.0027597
}
},
""Point"": {
""coordinates"": [ -88.9995886, 42.2721596, 0 ]
}
} ]
}";
JObject o = JObject.Parse(json);
string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"];
Assert.AreEqual("435 N Mulford Rd", searchAddress);
}
[Test]
public void SetValueWithInvalidPropertyName()
{
ExceptionAssert.Throws<ArgumentException>("Set JObject values with invalid key value: 0. Object property name expected.",
() =>
{
JObject o = new JObject();
o[0] = new JValue(3);
});
}
[Test]
public void SetValue()
{
object key = "TestKey";
JObject o = new JObject();
o[key] = new JValue(3);
Assert.AreEqual(3, (int)o[key]);
}
[Test]
public void ParseMultipleProperties()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JObject o = JObject.Parse(json);
string value = (string)o["Name"];
Assert.AreEqual("Name2", value);
}
#if !(NETFX_CORE || PORTABLE)
[Test]
public void WriteObjectNullDBNullValue()
{
DBNull dbNull = DBNull.Value;
JValue v = new JValue(dbNull);
Assert.AreEqual(DBNull.Value, v.Value);
Assert.AreEqual(JTokenType.Null, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
Assert.AreEqual(@"{
""title"": null
}", output);
}
#endif
[Test]
public void InvalidValueCastExceptionMessage()
{
ExceptionAssert.Throws<ArgumentException>("Can not convert Object to String.",
() =>
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o["responseData"];
});
}
[Test]
public void InvalidPropertyValueCastExceptionMessage()
{
ExceptionAssert.Throws<ArgumentException>("Can not convert Object to String.",
() =>
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o.Property("responseData");
});
}
[Test]
public void NumberTooBigForInt64()
{
ExceptionAssert.Throws<JsonReaderException>("JSON integer 307953220000517141511 is too large or small for an Int64. Path 'code', line 1, position 30.",
() =>
{
string json = @"{""code"": 307953220000517141511}";
JObject.Parse(json);
});
}
[Test]
public void ParseIncomplete()
{
ExceptionAssert.Throws<Exception>("Unexpected end of content while loading JObject. Path 'foo', line 1, position 6.",
() =>
{
JObject.Parse("{ foo:");
});
}
[Test]
public void LoadFromNestedObject()
{
string jsonText = @"{
""short"":
{
""error"":
{
""code"":0,
""msg"":""No action taken""
}
}
}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
reader.Read();
reader.Read();
reader.Read();
reader.Read();
reader.Read();
JObject o = (JObject)JToken.ReadFrom(reader);
Assert.IsNotNull(o);
Assert.AreEqual(@"{
""code"": 0,
""msg"": ""No action taken""
}", o.ToString(Formatting.Indented));
}
[Test]
public void LoadFromNestedObjectIncomplete()
{
ExceptionAssert.Throws<JsonReaderException>("Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 15.",
() =>
{
string jsonText = @"{
""short"":
{
""error"":
{
""code"":0";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
reader.Read();
reader.Read();
reader.Read();
reader.Read();
reader.Read();
JToken.ReadFrom(reader);
});
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
[Test]
public void GetProperties()
{
JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}");
ICustomTypeDescriptor descriptor = o;
PropertyDescriptorCollection properties = descriptor.GetProperties();
Assert.AreEqual(4, properties.Count);
PropertyDescriptor prop1 = properties[0];
Assert.AreEqual("prop1", prop1.Name);
Assert.AreEqual(typeof(long), prop1.PropertyType);
Assert.AreEqual(typeof(JObject), prop1.ComponentType);
Assert.AreEqual(false, prop1.CanResetValue(o));
Assert.AreEqual(false, prop1.ShouldSerializeValue(o));
PropertyDescriptor prop2 = properties[1];
Assert.AreEqual("prop2", prop2.Name);
Assert.AreEqual(typeof(string), prop2.PropertyType);
Assert.AreEqual(typeof(JObject), prop2.ComponentType);
Assert.AreEqual(false, prop2.CanResetValue(o));
Assert.AreEqual(false, prop2.ShouldSerializeValue(o));
PropertyDescriptor prop3 = properties[2];
Assert.AreEqual("prop3", prop3.Name);
Assert.AreEqual(typeof(object), prop3.PropertyType);
Assert.AreEqual(typeof(JObject), prop3.ComponentType);
Assert.AreEqual(false, prop3.CanResetValue(o));
Assert.AreEqual(false, prop3.ShouldSerializeValue(o));
PropertyDescriptor prop4 = properties[3];
Assert.AreEqual("prop4", prop4.Name);
Assert.AreEqual(typeof(JArray), prop4.PropertyType);
Assert.AreEqual(typeof(JObject), prop4.ComponentType);
Assert.AreEqual(false, prop4.CanResetValue(o));
Assert.AreEqual(false, prop4.ShouldSerializeValue(o));
}
#endif
[Test]
public void ParseEmptyObjectWithComment()
{
JObject o = JObject.Parse("{ /* A Comment */ }");
Assert.AreEqual(0, o.Count);
}
[Test]
public void FromObjectTimeSpan()
{
JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1));
Assert.AreEqual(v.Value, TimeSpan.FromDays(1));
Assert.AreEqual("1.00:00:00", v.ToString());
}
[Test]
public void FromObjectUri()
{
JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz"));
Assert.AreEqual(v.Value, new Uri("http://www.stuff.co.nz"));
Assert.AreEqual("http://www.stuff.co.nz/", v.ToString());
}
[Test]
public void FromObjectGuid()
{
JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35"));
Assert.AreEqual(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35"));
Assert.AreEqual("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString());
}
[Test]
public void ParseAdditionalContent()
{
ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 2.",
() =>
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}, 987987";
JObject o = JObject.Parse(json);
});
}
[Test]
public void DeepEqualsIgnoreOrder()
{
JObject o1 = new JObject(
new JProperty("null", null),
new JProperty("integer", 1),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("array", new JArray(1, 2)));
Assert.IsTrue(o1.DeepEquals(o1));
JObject o2 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 1),
new JProperty("array", new JArray(1, 2)));
Assert.IsTrue(o1.DeepEquals(o2));
JObject o3 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 2),
new JProperty("array", new JArray(1, 2)));
Assert.IsFalse(o1.DeepEquals(o3));
JObject o4 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 1),
new JProperty("array", new JArray(2, 1)));
Assert.IsFalse(o1.DeepEquals(o4));
JObject o5 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 1));
Assert.IsFalse(o1.DeepEquals(o5));
Assert.IsFalse(o1.DeepEquals(null));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
//
// Purpose: This class implements a set of methods for comparing
// strings.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Buffers;
using Internal.Runtime.CompilerServices;
namespace System.Globalization
{
[Flags]
public enum CompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreSymbols = 0x00000004,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags.
StringSort = 0x20000000, // use string sort method
Ordinal = 0x40000000, // This flag can not be used with other flags.
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial class CompareInfo : IDeserializationCallback
{
// Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags.
private const CompareOptions ValidIndexMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if Compare() has the right flags.
private const CompareOptions ValidCompareMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Mask used to check if GetHashCodeOfString() has the right flags.
private const CompareOptions ValidHashCodeOfStringMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if we have the right flags.
private const CompareOptions ValidSortkeyCtorMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Cache the invariant CompareInfo
internal static readonly CompareInfo Invariant = CultureInfo.InvariantCulture.CompareInfo;
//
// CompareInfos have an interesting identity. They are attached to the locale that created them,
// ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US.
// The interesting part is that since haw-US doesn't have its own sort, it has to point at another
// locale, which is what SCOMPAREINFO does.
[OptionalField(VersionAdded = 2)]
private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization)
[NonSerialized]
private string _sortName; // The name that defines our behavior
[OptionalField(VersionAdded = 3)]
private SortVersion m_SortVersion; // Do not rename (binary serialization)
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
[NonSerialized]
private readonly bool _invariantMode = GlobalizationMode.Invariant;
private int culture; // Do not rename (binary serialization). The fields sole purpose is to support Desktop serialization.
internal CompareInfo(CultureInfo culture)
{
m_name = culture._name;
InitSort(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** Warning: The assembly versioning mechanism is dead!
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArgumentNullException when the assembly is null
** ArgumentException if culture is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(int culture, Assembly assembly)
{
// Parameter checking.
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (assembly != typeof(object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** The purpose of this method is to provide version for CompareInfo tables.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArgumentNullException when the assembly is null
** ArgumentException if name is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(string name, Assembly assembly)
{
if (name == null || assembly == null)
{
throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly));
}
if (assembly != typeof(object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(name);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
** This method is provided for ease of integration with NLS-based software.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture.
**Exceptions:
** ArgumentException if culture is invalid.
============================================================================*/
// People really shouldn't be calling LCID versions, no custom support
public static CompareInfo GetCompareInfo(int culture)
{
if (CultureData.IsCustomCultureId(culture))
{
// Customized culture cannot be created by the LCID.
throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture));
}
return CultureInfo.GetCultureInfo(culture).CompareInfo;
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture.
**Exceptions:
** ArgumentException if name is invalid.
============================================================================*/
public static CompareInfo GetCompareInfo(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
public static unsafe bool IsSortable(char ch)
{
if (GlobalizationMode.Invariant)
{
return true;
}
char *pChar = &ch;
return IsSortable(pChar, 1);
}
public static unsafe bool IsSortable(string text)
{
if (text == null)
{
// A null param is invalid here.
throw new ArgumentNullException(nameof(text));
}
if (text.Length == 0)
{
// A zero length string is not invalid, but it is also not sortable.
return (false);
}
if (GlobalizationMode.Invariant)
{
return true;
}
fixed (char *pChar = text)
{
return IsSortable(pChar, text.Length);
}
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
m_name = null;
}
void IDeserializationCallback.OnDeserialization(object sender)
{
OnDeserialized();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
}
private void OnDeserialized()
{
// If we didn't have a name, use the LCID
if (m_name == null)
{
// From whidbey, didn't have a name
CultureInfo ci = CultureInfo.GetCultureInfo(this.culture);
m_name = ci._name;
}
else
{
InitSort(CultureInfo.GetCultureInfo(m_name));
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
// This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more.
culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort)
Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
}
///////////////////////////----- Name -----/////////////////////////////////
//
// Returns the name of the culture (well actually, of the sort).
// Very important for providing a non-LCID way of identifying
// what the sort is.
//
// Note that this name isn't dereferenced in case the CompareInfo is a different locale
// which is consistent with the behaviors of earlier versions. (so if you ask for a sort
// and the locale's changed behavior, then you'll get changed behavior, which is like
// what happens for a version update)
//
////////////////////////////////////////////////////////////////////////
public virtual string Name
{
get
{
Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set");
if (m_name == "zh-CHT" || m_name == "zh-CHS")
{
return m_name;
}
return _sortName;
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two strings with the given options. Returns 0 if the
// two strings are equal, a number less than 0 if string1 is less
// than string2, and a number greater than 0 if string1 is greater
// than string2.
//
////////////////////////////////////////////////////////////////////////
public virtual int Compare(string string1, string string2)
{
return Compare(string1, string2, CompareOptions.None);
}
public virtual int Compare(string string1, string string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return string.Compare(string1, string2, StringComparison.OrdinalIgnoreCase);
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return string.CompareOrdinal(string1, string2);
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//Our paradigm is that null sorts less than any other string and
//that two nulls sort as equal.
if (string1 == null)
{
if (string2 == null)
{
return (0); // Equal
}
return (-1); // null < non-null
}
if (string2 == null)
{
return (1); // non-null > null
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(string1, string2);
return string.CompareOrdinal(string1, string2);
}
return CompareString(string1.AsSpan(), string2.AsSpan(), options);
}
// TODO https://github.com/dotnet/coreclr/issues/13827:
// This method shouldn't be necessary, as we should be able to just use the overload
// that takes two spans. But due to this issue, that's adding significant overhead.
internal int Compare(ReadOnlySpan<char> string1, string string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return CompareOrdinalIgnoreCase(string1, string2.AsSpan());
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return string.CompareOrdinal(string1, string2.AsSpan());
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
// null sorts less than any other string.
if (string2 == null)
{
return 1;
}
if (_invariantMode)
{
return (options & CompareOptions.IgnoreCase) != 0 ?
CompareOrdinalIgnoreCase(string1, string2.AsSpan()) :
string.CompareOrdinal(string1, string2.AsSpan());
}
return CompareString(string1, string2, options);
}
internal int CompareOptionNone(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2)
{
// Check for empty span or span from a null string
if (string1.Length == 0 || string2.Length == 0)
return string1.Length - string2.Length;
return _invariantMode ?
string.CompareOrdinal(string1, string2) :
CompareString(string1, string2, CompareOptions.None);
}
internal int CompareOptionIgnoreCase(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2)
{
// Check for empty span or span from a null string
if (string1.Length == 0 || string2.Length == 0)
return string1.Length - string2.Length;
return _invariantMode ?
CompareOrdinalIgnoreCase(string1, string2) :
CompareString(string1, string2, CompareOptions.IgnoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the specified regions of the two strings with the given
// options.
// Returns 0 if the two strings are equal, a number less than 0 if
// string1 is less than string2, and a number greater than 0 if
// string1 is greater than string2.
//
////////////////////////////////////////////////////////////////////////
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
return Compare(string1, offset1, length1, string2, offset2, length2, 0);
}
public virtual int Compare(string string1, int offset1, string string2, int offset2, CompareOptions options)
{
return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1,
string2, offset2, string2 == null ? 0 : string2.Length - offset2, options);
}
public virtual int Compare(string string1, int offset1, string string2, int offset2)
{
return Compare(string1, offset1, string2, offset2, 0);
}
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
int result = string.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase);
if ((length1 != length2) && result == 0)
return (length1 > length2 ? 1 : -1);
return (result);
}
// Verify inputs
if (length1 < 0 || length2 < 0)
{
throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 < 0 || offset2 < 0)
{
throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 > (string1 == null ? 0 : string1.Length) - length1)
{
throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength);
}
if (offset2 > (string2 == null ? 0 : string2.Length) - length2)
{
throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength);
}
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal,
nameof(options));
}
}
else if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//
// Check for the null case.
//
if (string1 == null)
{
if (string2 == null)
{
return (0);
}
return (-1);
}
if (string2 == null)
{
return (1);
}
ReadOnlySpan<char> span1 = string1.AsSpan(offset1, length1);
ReadOnlySpan<char> span2 = string2.AsSpan(offset2, length2);
if (options == CompareOptions.Ordinal)
{
return string.CompareOrdinal(span1, span2);
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(span1, span2);
return string.CompareOrdinal(span1, span2);
}
return CompareString(span1, span2, options);
}
//
// CompareOrdinalIgnoreCase compare two string ordinally with ignoring the case.
// it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by
// calling the OS.
//
internal static int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
{
Debug.Assert(indexA + lengthA <= strA.Length);
Debug.Assert(indexB + lengthB <= strB.Length);
return CompareOrdinalIgnoreCase(
ref Unsafe.Add(ref strA.GetRawStringData(), indexA),
lengthA,
ref Unsafe.Add(ref strB.GetRawStringData(), indexB),
lengthB);
}
internal static int CompareOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
{
return CompareOrdinalIgnoreCase(ref MemoryMarshal.GetReference(strA), strA.Length, ref MemoryMarshal.GetReference(strB), strB.Length);
}
internal static int CompareOrdinalIgnoreCase(string strA, string strB)
{
return CompareOrdinalIgnoreCase(ref strA.GetRawStringData(), strA.Length, ref strB.GetRawStringData(), strB.Length);
}
internal static int CompareOrdinalIgnoreCase(ref char strA, int lengthA, ref char strB, int lengthB)
{
int length = Math.Min(lengthA, lengthB);
int range = length;
ref char charA = ref strA;
ref char charB = ref strB;
// in InvariantMode we support all range and not only the ascii characters.
char maxChar = (GlobalizationMode.Invariant ? (char)0xFFFF : (char)0x7F);
while (length != 0 && charA <= maxChar && charB <= maxChar)
{
// Ordinal equals or lowercase equals if the result ends up in the a-z range
if (charA == charB ||
((charA | 0x20) == (charB | 0x20) &&
(uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a')))
{
length--;
charA = ref Unsafe.Add(ref charA, 1);
charB = ref Unsafe.Add(ref charB, 1);
}
else
{
int currentA = charA;
int currentB = charB;
// Uppercase both chars if needed
if ((uint)(charA - 'a') <= 'z' - 'a')
currentA -= 0x20;
if ((uint)(charB - 'a') <= 'z' - 'a')
currentB -= 0x20;
// Return the (case-insensitive) difference between them.
return currentA - currentB;
}
}
if (length == 0)
return lengthA - lengthB;
Debug.Assert(!GlobalizationMode.Invariant);
range -= length;
return CompareStringOrdinalIgnoreCase(ref charA, lengthA - range, ref charB, lengthB - range);
}
internal static bool EqualsOrdinalIgnoreCase(ref char strA, ref char strB, int length)
{
ref char charA = ref strA;
ref char charB = ref strB;
// in InvariantMode we support all range and not only the ascii characters.
char maxChar = (GlobalizationMode.Invariant ? (char)0xFFFF : (char)0x7F);
while (length != 0 && charA <= maxChar && charB <= maxChar)
{
// Ordinal equals or lowercase equals if the result ends up in the a-z range
if (charA == charB ||
((charA | 0x20) == (charB | 0x20) &&
(uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a')))
{
length--;
charA = ref Unsafe.Add(ref charA, 1);
charB = ref Unsafe.Add(ref charB, 1);
}
else
{
return false;
}
}
if (length == 0)
return true;
Debug.Assert(!GlobalizationMode.Invariant);
return CompareStringOrdinalIgnoreCase(ref charA, length, ref charB, length) == 0;
}
////////////////////////////////////////////////////////////////////////
//
// IsPrefix
//
// Determines whether prefix is a prefix of string. If prefix equals
// string.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsPrefix(string source, string prefix, CompareOptions options)
{
if (source == null || prefix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)),
SR.ArgumentNull_String);
}
if (prefix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.StartsWith(prefix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return source.StartsWith(prefix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return StartsWith(source, prefix, options);
}
internal bool IsPrefix(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options)
{
Debug.Assert(prefix.Length != 0);
Debug.Assert(source.Length != 0);
Debug.Assert((options & ValidIndexMaskOffFlags) == 0);
Debug.Assert(!_invariantMode);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return StartsWith(source, prefix, options);
}
public virtual bool IsPrefix(string source, string prefix)
{
return (IsPrefix(source, prefix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IsSuffix
//
// Determines whether suffix is a suffix of string. If suffix equals
// string.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsSuffix(string source, string suffix, CompareOptions options)
{
if (source == null || suffix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)),
SR.ArgumentNull_String);
}
if (suffix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.EndsWith(suffix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return source.EndsWith(suffix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return EndsWith(source, suffix, options);
}
internal bool IsSuffix(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options)
{
Debug.Assert(suffix.Length != 0);
Debug.Assert(source.Length != 0);
Debug.Assert((options & ValidIndexMaskOffFlags) == 0);
Debug.Assert(!_invariantMode);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return EndsWith(source, suffix, options);
}
public virtual bool IsSuffix(string source, string suffix)
{
return (IsSuffix(source, suffix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IndexOf
//
// Returns the first index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals string.Empty,
// startIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public virtual int IndexOf(string source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, string value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, char value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, string value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, string value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, char value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int IndexOf(string source, string value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int IndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (source.Length == 0)
{
return -1;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
if (_invariantMode)
return IndexOfOrdinal(source, new string(value, 1), startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return IndexOfCore(source, new string(value, 1), startIndex, count, options, null);
}
public unsafe virtual int IndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex > source.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
// In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here.
// We return 0 if both source and value are empty strings for Everett compatibility too.
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
if (_invariantMode)
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return IndexOfCore(source, value, startIndex, count, options, null);
}
internal int IndexOfOrdinal(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!value.IsEmpty);
return IndexOfOrdinalCore(source, value, ignoreCase, fromBeginning: true);
}
internal int LastIndexOfOrdinal(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!value.IsEmpty);
return IndexOfOrdinalCore(source, value, ignoreCase, fromBeginning: false);
}
internal unsafe int IndexOf(ReadOnlySpan<char> source, ReadOnlySpan<char> value, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!value.IsEmpty);
return IndexOfCore(source, value, options, null, fromBeginning: true);
}
internal unsafe int LastIndexOf(ReadOnlySpan<char> source, ReadOnlySpan<char> value, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!value.IsEmpty);
return IndexOfCore(source, value, options, null, fromBeginning: false);
}
// The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated
// and the caller is passing a valid matchLengthPtr pointer.
internal unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0);
Debug.Assert(matchLengthPtr != null);
*matchLengthPtr = 0;
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex >= source.Length)
{
return -1;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
if (_invariantMode)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
return IndexOfCore(source, value, startIndex, count, options, matchLengthPtr);
}
internal int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantIndexOf(source, value, startIndex, count, ignoreCase);
}
return IndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// LastIndexOf
//
// Returns the last index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals string.Empty,
// endIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public virtual int LastIndexOf(string source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, options);
}
public virtual int LastIndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1, source.Length, options);
}
public virtual int LastIndexOf(string source, char value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, string value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
if (_invariantMode)
return InvariantLastIndexOf(source, new string(value, 1), startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value.ToString(), startIndex, count, options);
}
public virtual int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return (value.Length == 0) ? 0 : -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
// If we are looking for nothing, just return 0
if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0)
return startIndex;
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
if (_invariantMode)
return InvariantLastIndexOf(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value, startIndex, count, options);
}
internal int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantLastIndexOf(source, value, startIndex, count, ignoreCase);
}
return LastIndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// GetSortKey
//
// Gets the SortKey for the given string with the given options.
//
////////////////////////////////////////////////////////////////////////
public virtual SortKey GetSortKey(string source, CompareOptions options)
{
if (_invariantMode)
return InvariantCreateSortKey(source, options);
return CreateSortKey(source, options);
}
public virtual SortKey GetSortKey(string source)
{
if (_invariantMode)
return InvariantCreateSortKey(source, CompareOptions.None);
return CreateSortKey(source, CompareOptions.None);
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CompareInfo as the current
// instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(object value)
{
CompareInfo that = value as CompareInfo;
if (that != null)
{
return this.Name == that.Name;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CompareInfo. The hash code is guaranteed to be the same for
// CompareInfo A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCodeOfString
//
// This internal method allows a method that allows the equivalent of creating a Sortkey for a
// string from CompareInfo, and generate a hashcode value from it. It is not very convenient
// to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed.
//
// The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both
// the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects
// treat the string the same way, this implementation will treat them differently (the same way that
// Sortkey does at the moment).
//
// This method will never be made public itself, but public consumers of it could be created, e.g.:
//
// string.GetHashCode(CultureInfo)
// string.GetHashCode(CompareInfo)
// string.GetHashCode(CultureInfo, CompareOptions)
// string.GetHashCode(CompareInfo, CompareOptions)
// etc.
//
// (the methods above that take a CultureInfo would use CultureInfo.CompareInfo)
//
////////////////////////////////////////////////////////////////////////
internal int GetHashCodeOfString(string source, CompareOptions options)
{
//
// Parameter validation
//
if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
if ((options & ValidHashCodeOfStringMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return ((options & CompareOptions.IgnoreCase) != 0) ? source.GetHashCodeOrdinalIgnoreCase() : source.GetHashCode();
}
return GetHashCodeOfStringCore(source, options);
}
public virtual int GetHashCode(string source, CompareOptions options)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (options == CompareOptions.Ordinal)
{
return source.GetHashCode();
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.GetHashCodeOrdinalIgnoreCase();
}
//
// GetHashCodeOfString does more parameters validation. basically will throw when
// having Ordinal, OrdinalIgnoreCase and StringSort
//
return GetHashCodeOfString(source, options);
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// CompareInfo.
//
////////////////////////////////////////////////////////////////////////
public override string ToString()
{
return ("CompareInfo - " + this.Name);
}
public SortVersion Version
{
get
{
if (m_SortVersion == null)
{
if (_invariantMode)
{
m_SortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0,
(byte) (CultureInfo.LOCALE_INVARIANT >> 24),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8),
(byte) (CultureInfo.LOCALE_INVARIANT & 0xFF)));
}
else
{
m_SortVersion = GetSortVersion();
}
}
return m_SortVersion;
}
}
public int LCID
{
get
{
return CultureInfo.GetCultureInfo(Name).LCID;
}
}
}
}
| |
/********************************************************************
*
* PropertyBag.cs
* --------------
* Copyright (C) 2002 Tony Allowatt
* Last Update: 12/14/2002
*
* THE SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS", WITHOUT WARRANTY
* OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THIS
* SOFTWARE.
*
* Public types defined in this file:
* ----------------------------------
* namespace Flobbster.Windows.Forms
* class PropertySpec
* class PropertySpecEventArgs
* delegate PropertySpecEventHandler
* class PropertyBag
* class PropertyBag.PropertySpecCollection
* class PropertyTable
*
********************************************************************/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing.Design;
using FrwSoftware;
namespace Flobbster.Windows.Forms
{
/// <summary>
/// Represents a single property in a PropertySpec.
/// </summary>
public class PropertySpec
{
private Attribute[] attributes;
private string category;
private object defaultValue;
private string description;
private string editor;
private string name;
private string type;
private string typeConverter;
//attributes added by just
//public string ItemDataFieldSysname { get; set; }
//public string OriginalName { get; set; }
//public JItemData ItemData { get; set; }
public object PropTag { get; set; }
//end
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
public PropertySpec(string name, string type) : this(name, type, null, null, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
public PropertySpec(string name, Type type) :
this(name, type.AssemblyQualifiedName, null, null, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
public PropertySpec(string name, string type, string category) : this(name, type, category, null, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category"></param>
public PropertySpec(string name, Type type, string category) :
this(name, type.AssemblyQualifiedName, category, null, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
public PropertySpec(string name, string type, string category, string description) :
this(name, type, category, description, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
public PropertySpec(string name, Type type, string category, string description) :
this(name, type.AssemblyQualifiedName, category, description, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue)
{
this.name = name;
this.type = type;
this.category = category;
this.description = description;
this.defaultValue = defaultValue;
this.attributes = null;
}
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue) :
this(name, type.AssemblyQualifiedName, category, description, defaultValue) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The fully qualified name of the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The fully qualified name of the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue,
string editor, string typeConverter) : this(name, type, category, description, defaultValue)
{
this.editor = editor;
this.typeConverter = typeConverter;
}
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The fully qualified name of the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The fully qualified name of the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue,
string editor, string typeConverter) :
this(name, type.AssemblyQualifiedName, category, description, defaultValue, editor, typeConverter) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The Type that represents the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The fully qualified name of the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue,
Type editor, string typeConverter) :
this(name, type, category, description, defaultValue, editor.AssemblyQualifiedName,
typeConverter) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The Type that represents the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The fully qualified name of the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue,
Type editor, string typeConverter) :
this(name, type.AssemblyQualifiedName, category, description, defaultValue,
editor.AssemblyQualifiedName, typeConverter) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The fully qualified name of the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The Type that represents the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue,
string editor, Type typeConverter) :
this(name, type, category, description, defaultValue, editor, typeConverter.AssemblyQualifiedName) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The fully qualified name of the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The Type that represents the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue,
string editor, Type typeConverter) :
this(name, type.AssemblyQualifiedName, category, description, defaultValue, editor,
typeConverter.AssemblyQualifiedName) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The Type that represents the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The Type that represents the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue,
Type editor, Type typeConverter) :
this(name, type, category, description, defaultValue, editor.AssemblyQualifiedName,
typeConverter.AssemblyQualifiedName) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The Type that represents the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The Type that represents the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue,
Type editor, Type typeConverter) :
this(name, type.AssemblyQualifiedName, category, description, defaultValue,
editor.AssemblyQualifiedName, typeConverter.AssemblyQualifiedName) { }
/// <summary>
/// Gets or sets a collection of additional Attributes for this property. This can
/// be used to specify attributes beyond those supported intrinsically by the
/// PropertySpec class, such as ReadOnly and Browsable.
/// </summary>
public Attribute[] Attributes
{
get { return attributes; }
set { attributes = value; }
}
/// <summary>
/// Gets or sets the category name of this property.
/// </summary>
public string Category
{
get { return category; }
set { category = value; }
}
/// <summary>
/// Gets or sets the fully qualified name of the type converter
/// type for this property.
/// </summary>
public string ConverterTypeName
{
get { return typeConverter; }
set { typeConverter = value; }
}
/// <summary>
/// Gets or sets the default value of this property.
/// </summary>
public object DefaultValue
{
get { return defaultValue; }
set { defaultValue = value; }
}
/// <summary>
/// Gets or sets the help text description of this property.
/// </summary>
public string Description
{
get { return description; }
set { description = value; }
}
/// <summary>
/// Gets or sets the fully qualified name of the editor type for
/// this property.
/// </summary>
public string EditorTypeName
{
get { return editor; }
set { editor = value; }
}
/// <summary>
/// Gets or sets the name of this property.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// Gets or sets the fully qualfied name of the type of this
/// property.
/// </summary>
public string TypeName
{
get { return type; }
set { type = value; }
}
}
/// <summary>
/// Provides data for the GetValue and SetValue events of the PropertyBag class.
/// </summary>
public class PropertySpecEventArgs : EventArgs
{
private PropertySpec property;
private object val;
/// <summary>
/// Initializes a new instance of the PropertySpecEventArgs class.
/// </summary>
/// <param name="property">The PropertySpec that represents the property whose
/// value is being requested or set.</param>
/// <param name="val">The current value of the property.</param>
public PropertySpecEventArgs(PropertySpec property, object val)
{
this.property = property;
this.val = val;
}
/// <summary>
/// Gets the PropertySpec that represents the property whose value is being
/// requested or set.
/// </summary>
public PropertySpec Property
{
get { return property; }
}
/// <summary>
/// Gets or sets the current value of the property.
/// </summary>
public object Value
{
get { return val; }
set { val = value; }
}
}
/// <summary>
/// Represents the method that will handle the GetValue and SetValue events of the
/// PropertyBag class.
/// </summary>
public delegate void PropertySpecEventHandler(object sender, PropertySpecEventArgs e);
public class PropertySpecDescriptor : PropertyDescriptor
{
private PropertyBag bag;
private PropertySpec item;
public PropertySpecDescriptor(PropertySpec item, PropertyBag bag, string name, Attribute[] attrs) :
base(name, attrs)
{
this.bag = bag;
this.item = item;
}
public object PropTag
{
get
{
return this.item.PropTag;
}
}
public override Type ComponentType
{
get { return item.GetType(); }
}
public override bool IsReadOnly
{
get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); }
}
public override Type PropertyType
{
get
{
//return Type.GetType(item.TypeName);
return TypeHelper.FindType(item.TypeName);
}
}
public override bool CanResetValue(object component)
{
if (item.DefaultValue == null)
return false;
else
return !this.GetValue(component).Equals(item.DefaultValue);
}
public override object GetValue(object component)
{
// Have the property bag raise an event to get the current value
// of the property.
PropertySpecEventArgs e = new PropertySpecEventArgs(item, null);
bag.OnGetValue(e);
return e.Value;
}
public override void ResetValue(object component)
{
SetValue(component, item.DefaultValue);
}
public override void SetValue(object component, object value)
{
// Have the property bag raise an event to set the current value
// of the property.
PropertySpecEventArgs e = new PropertySpecEventArgs(item, value);
bag.OnSetValue(e);
}
public override bool ShouldSerializeValue(object component)
{
object val = this.GetValue(component);
if (item.DefaultValue == null && val == null)
return false;
else
return !val.Equals(item.DefaultValue);
}
}
/// <summary>
/// Represents a collection of custom properties that can be selected into a
/// PropertyGrid to provide functionality beyond that of the simple reflection
/// normally used to query an object's properties.
/// </summary>
public class PropertyBag : ICustomTypeDescriptor
{
public object SourceObject { get; set; }
public Type SourceObjectType { get; set; }//added j
#region PropertySpecCollection class definition
/// <summary>
/// Encapsulates a collection of PropertySpec objects.
/// </summary>
[Serializable]
public class PropertySpecCollection : IList
{
private ArrayList innerArray;
/// <summary>
/// Initializes a new instance of the PropertySpecCollection class.
/// </summary>
public PropertySpecCollection()
{
innerArray = new ArrayList();
}
/// <summary>
/// Gets the number of elements in the PropertySpecCollection.
/// </summary>
/// <value>
/// The number of elements contained in the PropertySpecCollection.
/// </value>
public int Count
{
get { return innerArray.Count; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection has a fixed size.
/// </summary>
/// <value>
/// true if the PropertySpecCollection has a fixed size; otherwise, false.
/// </value>
public bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection is read-only.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <value>
/// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false.
/// </value>
public bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
/// <value>
/// An object that can be used to synchronize access to the collection.
/// </value>
object ICollection.SyncRoot
{
get { return null; }
}
/// <summary>
/// Gets or sets the element at the specified index.
/// In C#, this property is the indexer for the PropertySpecCollection class.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <value>
/// The element at the specified index.
/// </value>
public PropertySpec this[int index]
{
get { return (PropertySpec)innerArray[index]; }
set { innerArray[index] = value; }
}
/// <summary>
/// Adds a PropertySpec to the end of the PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param>
/// <returns>The PropertySpecCollection index at which the value has been added.</returns>
public int Add(PropertySpec value)
{
int index = innerArray.Add(value);
return index;
}
/// <summary>
/// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection.
/// </summary>
/// <param name="array">The PropertySpec array whose elements should be added to the end of the
/// PropertySpecCollection.</param>
public void AddRange(PropertySpec[] array)
{
innerArray.AddRange(array);
}
/// <summary>
/// Removes all elements from the PropertySpecCollection.
/// </summary>
public void Clear()
{
innerArray.Clear();
}
/// <summary>
/// Determines whether a PropertySpec is in the PropertySpecCollection.
/// </summary>
/// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate
/// can be a null reference (Nothing in Visual Basic).</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(PropertySpec item)
{
return innerArray.Contains(item);
}
/// <summary>
/// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(string name)
{
foreach(PropertySpec spec in innerArray)
if(spec.Name == name)
return true;
return false;
}
/// <summary>
/// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the
/// beginning of the target array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from PropertySpecCollection. The Array must have zero-based indexing.</param>
public void CopyTo(PropertySpec[] array)
{
innerArray.CopyTo(array);
}
/// <summary>
/// Copies the PropertySpecCollection or a portion of it to a one-dimensional array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from the collection.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
public void CopyTo(PropertySpec[] array, int index)
{
innerArray.CopyTo(array, index);
}
/// <summary>
/// Returns an enumerator that can iterate through the PropertySpecCollection.
/// </summary>
/// <returns>An IEnumerator for the entire PropertySpecCollection.</returns>
public IEnumerator GetEnumerator()
{
return innerArray.GetEnumerator();
}
/// <summary>
/// Searches for the specified PropertySpec and returns the zero-based index of the first
/// occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(PropertySpec value)
{
return innerArray.IndexOf(value);
}
/// <summary>
/// Searches for the PropertySpec with the specified name and returns the zero-based index of
/// the first occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(string name)
{
int i = 0;
foreach(PropertySpec spec in innerArray)
{
if(spec.Name == name)
return i;
i++;
}
return -1;
}
/// <summary>
/// Inserts a PropertySpec object into the PropertySpecCollection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The PropertySpec to insert.</param>
public void Insert(int index, PropertySpec value)
{
innerArray.Insert(index, value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the PropertySpecCollection.
/// </summary>
/// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(PropertySpec obj)
{
innerArray.Remove(obj);
}
/// <summary>
/// Removes the property with the specified name from the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(string name)
{
int index = IndexOf(name);
RemoveAt(index);
}
/// <summary>
/// Removes the object at the specified index of the PropertySpecCollection.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
public void RemoveAt(int index)
{
innerArray.RemoveAt(index);
}
/// <summary>
/// Copies the elements of the PropertySpecCollection to a new PropertySpec array.
/// </summary>
/// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns>
public PropertySpec[] ToArray()
{
return (PropertySpec[])innerArray.ToArray(typeof(PropertySpec));
}
#region Explicit interface implementations for ICollection and IList
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
CopyTo((PropertySpec[])array, index);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.Add(object value)
{
return Add((PropertySpec)value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
bool IList.Contains(object obj)
{
return Contains((PropertySpec)obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
object IList.this[int index]
{
get
{
return ((PropertySpecCollection)this)[index];
}
set
{
((PropertySpecCollection)this)[index] = (PropertySpec)value;
}
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.IndexOf(object obj)
{
return IndexOf((PropertySpec)obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Insert(int index, object value)
{
Insert(index, (PropertySpec)value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Remove(object value)
{
Remove((PropertySpec)value);
}
#endregion
}
#endregion
#region PropertySpecDescriptor class definition
#endregion
private string defaultProperty;
private PropertySpecCollection properties;
/// <summary>
/// Initializes a new instance of the PropertyBag class.
/// </summary>
public PropertyBag()
{
defaultProperty = null;
properties = new PropertySpecCollection();
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public string DefaultProperty
{
get { return defaultProperty; }
set { defaultProperty = value; }
}
/// <summary>
/// Gets the collection of properties contained within this PropertyBag.
/// </summary>
public PropertySpecCollection Properties
{
get { return properties; }
}
/// <summary>
/// Occurs when a PropertyGrid requests the value of a property.
/// </summary>
public event PropertySpecEventHandler GetValue;
/// <summary>
/// Occurs when the user changes the value of a property in a PropertyGrid.
/// </summary>
public event PropertySpecEventHandler SetValue;
public event PropertySpecEventHandler ValueModified;
/// <summary>
/// Raises the GetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
public virtual void OnGetValue(PropertySpecEventArgs e)
{
if(GetValue != null)
GetValue(this, e);
}
/// <summary>
/// Raises the SetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
public virtual void OnSetValue(PropertySpecEventArgs e)
{
if(SetValue != null)
SetValue(this, e);
}
public void OnValueModified(PropertySpecEventArgs e)
{
if (ValueModified != null)
ValueModified(this, e);
}
#region ICustomTypeDescriptor explicit interface definitions
// Most of the functions required by the ICustomTypeDescriptor are
// merely pssed on to the default TypeDescriptor for this type,
// which will do something appropriate. The exceptions are noted
// below.
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
try
{
// This function searches the property list for the property
// with the same name as the DefaultProperty specified, and
// returns a property descriptor for it. If no property is
// found that matches DefaultProperty, a null reference is
// returned instead.
PropertySpec propertySpec = null;
if (defaultProperty != null)
{
int index = properties.IndexOf(defaultProperty);
propertySpec = properties[index];
}
if (propertySpec != null)
return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null);
else
return null;
}
catch(Exception ex)
{
Log.ShowError(ex);
return null;
}
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(new Attribute[0]);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
try
{
// Rather than passing this function on to the default TypeDescriptor,
// which would return the actual properties of PropertyBag, I construct
// a list here that contains property descriptors for the elements of the
// Properties list in the bag.
ArrayList props = new ArrayList();
foreach (PropertySpec property in properties)
{
ArrayList attrs = new ArrayList();
// If a category, description, editor, or type converter are specified
// in the PropertySpec, create attributes to define that relationship.
if (property.Category != null)
attrs.Add(new CategoryAttribute(property.Category));
if (property.Description != null)
attrs.Add(new DescriptionAttribute(property.Description));
if (property.EditorTypeName != null)
attrs.Add(new EditorAttribute(property.EditorTypeName, typeof(UITypeEditor)));
if (property.ConverterTypeName != null)
attrs.Add(new TypeConverterAttribute(property.ConverterTypeName));
// Additionally, append the custom attributes associated with the
// PropertySpec, if any.
if (property.Attributes != null)
attrs.AddRange(property.Attributes);
Attribute[] attrArray = (Attribute[])attrs.ToArray(typeof(Attribute));
// Create a new property descriptor for the property item, and add
// it to the list.
try
{
PropertySpecDescriptor pd = new PropertySpecDescriptor(property,
this, property.Name, attrArray);
props.Add(pd);
}
catch (Exception ex)
{
Log.LogError("Error create property " + property.PropTag, ex);
}
}
// Convert the list of PropertyDescriptors to a collection that the
// ICustomTypeDescriptor can use, and return it.
PropertyDescriptor[] propArray = (PropertyDescriptor[])props.ToArray(
typeof(PropertyDescriptor));
return new PropertyDescriptorCollection(propArray);
}
catch (Exception ex)
{
Log.ShowError(ex);
return new PropertyDescriptorCollection(new PropertyDescriptor[] { });
}
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
/// <summary>
/// An extension of PropertyBag that manages a table of property values, in
/// addition to firing events when property values are requested or set.
/// </summary>
public class PropertyTable : PropertyBag
{
private Hashtable propValues;
/// <summary>
/// Initializes a new instance of the PropertyTable class.
/// </summary>
public PropertyTable()
{
propValues = new Hashtable();
}
/// <summary>
/// Gets or sets the value of the property with the specified name.
/// <p>In C#, this property is the indexer of the PropertyTable class.</p>
/// </summary>
public object this[string key]
{
get { return propValues[key]; }
set { propValues[key] = value; }
}
/// <summary>
/// This member overrides PropertyBag.OnGetValue.
/// </summary>
public override void OnGetValue(PropertySpecEventArgs e)
{
e.Value = propValues[e.Property.Name];
base.OnGetValue(e);
}
/// <summary>
/// This member overrides PropertyBag.OnSetValue.
/// </summary>
public override void OnSetValue(PropertySpecEventArgs e)
{
propValues[e.Property.Name] = e.Value;
base.OnSetValue(e);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using log4net;
using OpenSim.Framework.ServiceAuth;
namespace OpenSim.Framework
{
/// <summary>
/// Implementation of a generic REST client
/// </summary>
/// <remarks>
/// This class is a generic implementation of a REST (Representational State Transfer) web service. This
/// class is designed to execute both synchronously and asynchronously.
///
/// Internally the implementation works as a two stage asynchronous web-client.
/// When the request is initiated, RestClient will query asynchronously for for a web-response,
/// sleeping until the initial response is returned by the server. Once the initial response is retrieved
/// the second stage of asynchronous requests will be triggered, in an attempt to read of the response
/// object into a memorystream as a sequence of asynchronous reads.
///
/// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
/// other threads to execute, while it waits for a response from the web-service. RestClient itself can be
/// invoked by the caller in either synchronous mode or asynchronous modes.
/// </remarks>
public class RestClient : IDisposable
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private string realuri;
#region member variables
/// <summary>
/// The base Uri of the web-service e.g. http://www.google.com
/// </summary>
private string _url;
/// <summary>
/// Path elements of the query
/// </summary>
private List<string> _pathElements = new List<string>();
/// <summary>
/// Parameter elements of the query, e.g. min=34
/// </summary>
private Dictionary<string, string> _parameterElements = new Dictionary<string, string>();
/// <summary>
/// Request method. E.g. GET, POST, PUT or DELETE
/// </summary>
private string _method;
/// <summary>
/// Temporary buffer used to store bytes temporarily as they come in from the server
/// </summary>
private byte[] _readbuf;
/// <summary>
/// MemoryStream representing the resulting resource
/// </summary>
private Stream _resource;
/// <summary>
/// WebRequest object, held as a member variable
/// </summary>
private HttpWebRequest _request;
/// <summary>
/// WebResponse object, held as a member variable, so we can close it
/// </summary>
private HttpWebResponse _response;
/// <summary>
/// This flag will help block the main synchroneous method, in case we run in synchroneous mode
/// </summary>
//public static ManualResetEvent _allDone = new ManualResetEvent(false);
/// <summary>
/// Default time out period
/// </summary>
//private const int DefaultTimeout = 10*1000; // 10 seconds timeout
/// <summary>
/// Default Buffer size of a block requested from the web-server
/// </summary>
private const int BufferSize = 4096; // Read blocks of 4 KB.
/// <summary>
/// if an exception occours during async processing, we need to save it, so it can be
/// rethrown on the primary thread;
/// </summary>
private Exception _asyncException;
#endregion member variables
#region constructors
/// <summary>
/// Instantiate a new RestClient
/// </summary>
/// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
public RestClient(string url)
{
_url = url;
_readbuf = new byte[BufferSize];
_resource = new MemoryStream();
_request = null;
_response = null;
_lock = new object();
}
private object _lock;
#endregion constructors
#region Dispose
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
_resource.Dispose();
}
disposed = true;
}
#endregion Dispose
/// <summary>
/// Add a path element to the query, e.g. assets
/// </summary>
/// <param name="element">path entry</param>
public void AddResourcePath(string element)
{
if (isSlashed(element))
_pathElements.Add(element.Substring(0, element.Length - 1));
else
_pathElements.Add(element);
}
/// <summary>
/// Add a query parameter to the Url
/// </summary>
/// <param name="name">Name of the parameter, e.g. min</param>
/// <param name="value">Value of the parameter, e.g. 42</param>
public void AddQueryParameter(string name, string value)
{
try
{
_parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
}
catch (ArgumentException)
{
m_log.Error("[REST]: Query parameter " + name + " is already added.");
}
catch (Exception e)
{
m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
}
}
/// <summary>
/// Add a query parameter to the Url
/// </summary>
/// <param name="name">Name of the parameter, e.g. min</param>
public void AddQueryParameter(string name)
{
try
{
_parameterElements.Add(HttpUtility.UrlEncode(name), null);
}
catch (ArgumentException)
{
m_log.Error("[REST]: Query parameter " + name + " is already added.");
}
catch (Exception e)
{
m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
}
}
/// <summary>
/// Web-Request method, e.g. GET, PUT, POST, DELETE
/// </summary>
public string RequestMethod
{
get { return _method; }
set { _method = value; }
}
/// <summary>
/// True if string contains a trailing slash '/'
/// </summary>
/// <param name="s">string to be examined</param>
/// <returns>true if slash is present</returns>
private static bool isSlashed(string s)
{
return s.Substring(s.Length - 1, 1) == "/";
}
/// <summary>
/// Build a Uri based on the initial Url, path elements and parameters
/// </summary>
/// <returns>fully constructed Uri</returns>
private Uri buildUri()
{
StringBuilder sb = new StringBuilder();
sb.Append(_url);
foreach (string e in _pathElements)
{
sb.Append("/");
sb.Append(e);
}
bool firstElement = true;
foreach (KeyValuePair<string, string> kv in _parameterElements)
{
if (firstElement)
{
sb.Append("?");
firstElement = false;
}
else
sb.Append("&");
sb.Append(kv.Key);
if (!string.IsNullOrEmpty(kv.Value))
{
sb.Append("=");
sb.Append(kv.Value);
}
}
// realuri = sb.ToString();
//m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri);
return new Uri(sb.ToString());
}
#region Async communications with server
/// <summary>
/// Async method, invoked when a block of data has been received from the service
/// </summary>
/// <param name="ar"></param>
private void StreamIsReadyDelegate(IAsyncResult ar)
{
try
{
Stream s = (Stream) ar.AsyncState;
int read = s.EndRead(ar);
if (read > 0)
{
_resource.Write(_readbuf, 0, read);
// IAsyncResult asynchronousResult =
// s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
// TODO! Implement timeout, without killing the server
//ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
}
else
{
s.Close();
//_allDone.Set();
}
}
catch (Exception e)
{
//_allDone.Set();
_asyncException = e;
}
}
#endregion Async communications with server
/// <summary>
/// Perform a synchronous request
/// </summary>
public Stream Request()
{
return Request(null);
}
/// <summary>
/// Perform a synchronous request
/// </summary>
public Stream Request(IServiceAuth auth)
{
lock (_lock)
{
_request = (HttpWebRequest) WebRequest.Create(buildUri());
_request.KeepAlive = false;
_request.ContentType = "application/xml";
_request.Timeout = 200000;
_request.Method = RequestMethod;
_asyncException = null;
if (auth != null)
auth.AddAuthorization(_request.Headers);
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
// IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
try
{
using (_response = (HttpWebResponse) _request.GetResponse())
{
using (Stream src = _response.GetResponseStream())
{
int length = src.Read(_readbuf, 0, BufferSize);
while (length > 0)
{
_resource.Write(_readbuf, 0, length);
length = src.Read(_readbuf, 0, BufferSize);
}
// TODO! Implement timeout, without killing the server
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
//ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
// _allDone.WaitOne();
}
}
}
catch (WebException e)
{
using (HttpWebResponse errorResponse = e.Response as HttpWebResponse)
{
if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode)
{
// This is often benign. E.g., requesting a missing asset will return 404.
m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", _request.Address.ToString());
}
else
{
m_log.Error(string.Format("[REST CLIENT] Error fetching resource from server: {0} ", _request.Address.ToString()), e);
}
}
return null;
}
if (_asyncException != null)
throw _asyncException;
if (_resource != null)
{
_resource.Flush();
_resource.Seek(0, SeekOrigin.Begin);
}
if (WebUtil.DebugLevel >= 5)
WebUtil.LogResponseDetail(reqnum, _resource);
return _resource;
}
}
public Stream Request(Stream src, IServiceAuth auth)
{
_request = (HttpWebRequest) WebRequest.Create(buildUri());
_request.KeepAlive = false;
_request.ContentType = "application/xml";
_request.Timeout = 90000;
_request.Method = RequestMethod;
_asyncException = null;
_request.ContentLength = src.Length;
if (auth != null)
auth.AddAuthorization(_request.Headers);
src.Seek(0, SeekOrigin.Begin);
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
if (WebUtil.DebugLevel >= 5)
WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src);
using (Stream dst = _request.GetRequestStream())
{
m_log.Debug("[REST]: GetRequestStream is ok");
byte[] buf = new byte[1024];
int length = src.Read(buf, 0, 1024);
m_log.Debug("[REST]: First Read is ok");
while (length > 0)
{
dst.Write(buf, 0, length);
length = src.Read(buf, 0, 1024);
}
}
try
{
_response = (HttpWebResponse)_request.GetResponse();
}
catch (WebException e)
{
m_log.WarnFormat("[REST]: Request {0} {1} failed with status {2} and message {3}",
RequestMethod, _request.RequestUri, e.Status, e.Message);
return null;
}
catch (Exception e)
{
m_log.WarnFormat(
"[REST]: Request {0} {1} failed with exception {2} {3}",
RequestMethod, _request.RequestUri, e.Message, e.StackTrace);
return null;
}
if (WebUtil.DebugLevel >= 5)
{
using (Stream responseStream = _response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseStr = reader.ReadToEnd();
WebUtil.LogResponseDetail(reqnum, responseStr);
}
}
}
if (_response != null)
_response.Close();
// IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
// TODO! Implement timeout, without killing the server
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
//ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
return null;
}
#region Async Invocation
public IAsyncResult BeginRequest(AsyncCallback callback, object state)
{
/// <summary>
/// In case, we are invoked asynchroneously this object will keep track of the state
/// </summary>
AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state);
Util.FireAndForget(RequestHelper, ar, "RestClient.BeginRequest");
return ar;
}
public Stream EndRequest(IAsyncResult asyncResult)
{
AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
// Wait for operation to complete, then return result or
// throw exception
return ar.EndInvoke();
}
private void RequestHelper(Object asyncResult)
{
// We know that it's really an AsyncResult<DateTime> object
AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
try
{
// Perform the operation; if sucessful set the result
Stream s = Request(null);
ar.SetAsCompleted(s, false);
}
catch (Exception e)
{
// If operation fails, set the exception
ar.HandleException(e, false);
}
}
#endregion Async Invocation
}
internal class SimpleAsyncResult : IAsyncResult
{
private readonly AsyncCallback m_callback;
/// <summary>
/// Is process completed?
/// </summary>
/// <remarks>Should really be boolean, but VolatileRead has no boolean method</remarks>
private byte m_completed;
/// <summary>
/// Did process complete synchronously?
/// </summary>
/// <remarks>I have a hard time imagining a scenario where this is the case, again, same issue about
/// booleans and VolatileRead as m_completed
/// </remarks>
private byte m_completedSynchronously;
private readonly object m_asyncState;
private ManualResetEvent m_waitHandle;
private Exception m_exception;
internal SimpleAsyncResult(AsyncCallback cb, object state)
{
m_callback = cb;
m_asyncState = state;
m_completed = 0;
m_completedSynchronously = 1;
}
#region IAsyncResult Members
public object AsyncState
{
get { return m_asyncState; }
}
public WaitHandle AsyncWaitHandle
{
get
{
if (m_waitHandle == null)
{
bool done = IsCompleted;
ManualResetEvent mre = new ManualResetEvent(done);
if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null)
{
mre.Close();
}
else
{
if (!done && IsCompleted)
{
m_waitHandle.Set();
}
}
}
return m_waitHandle;
}
}
public bool CompletedSynchronously
{
get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; }
}
public bool IsCompleted
{
get { return Thread.VolatileRead(ref m_completed) == 1; }
}
#endregion
#region class Methods
internal void SetAsCompleted(bool completedSynchronously)
{
m_completed = 1;
if (completedSynchronously)
m_completedSynchronously = 1;
else
m_completedSynchronously = 0;
SignalCompletion();
}
internal void HandleException(Exception e, bool completedSynchronously)
{
m_completed = 1;
if (completedSynchronously)
m_completedSynchronously = 1;
else
m_completedSynchronously = 0;
m_exception = e;
SignalCompletion();
}
private void SignalCompletion()
{
if (m_waitHandle != null) m_waitHandle.Set();
if (m_callback != null) m_callback(this);
}
public void EndInvoke()
{
// This method assumes that only 1 thread calls EndInvoke
if (!IsCompleted)
{
// If the operation isn't done, wait for it
AsyncWaitHandle.WaitOne();
AsyncWaitHandle.Close();
m_waitHandle.Close();
m_waitHandle = null; // Allow early GC
}
// Operation is done: if an exception occured, throw it
if (m_exception != null) throw m_exception;
}
#endregion
}
internal class AsyncResult<T> : SimpleAsyncResult
{
private T m_result = default(T);
public AsyncResult(AsyncCallback asyncCallback, Object state) :
base(asyncCallback, state)
{
}
public void SetAsCompleted(T result, bool completedSynchronously)
{
// Save the asynchronous operation's result
m_result = result;
// Tell the base class that the operation completed
// sucessfully (no exception)
base.SetAsCompleted(completedSynchronously);
}
public new T EndInvoke()
{
base.EndInvoke();
return m_result;
}
}
}
| |
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
class HairGUI : BaseHairGUI
{
protected static class Styles
{
public static string InputsText = "Inputs";
public static GUIContent diffuseColorText = new GUIContent("Diffuse Color + Opacity", "Albedo (RGB) and Opacity (A)");
public static GUIContent diffuseColorSmoothnessText = new GUIContent("Diffuse Color + Smoothness", "Albedo (RGB) and Smoothness (A)");
public static GUIContent smoothnessMapChannelText = new GUIContent("Smoothness Source", "Smoothness texture and channel");
public static GUIContent smoothnessText = new GUIContent("Smoothness", "Smoothness scale factor");
public static GUIContent maskMapESText = new GUIContent("Mask Map - M(R), AO(G), E(B), S(A)", "Mask map");
public static GUIContent maskMapSText = new GUIContent("Mask Map - M(R), AO(G), S(A)", "Mask map");
public static GUIContent normalMapSpaceText = new GUIContent("Normal/Tangent Map space", "");
public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map (DXT5) - Need to implement BC5");
public static GUIContent specularOcclusionMapText = new GUIContent("Specular Occlusion Map (RGBA)", "Specular Occlusion Map");
public static GUIContent horizonFadeText = new GUIContent("Horizon Fade (Spec occlusion)", "horizon fade is use to control specular occlusion");
public static GUIContent tangentMapText = new GUIContent("Tangent Map", "Tangent Map (BC5) - DXT5 for test");
public static GUIContent anisotropyText = new GUIContent("Anisotropy", "Anisotropy scale factor");
public static GUIContent anisotropyMapText = new GUIContent("Anisotropy Map (B)", "Anisotropy");
public static string textureControlText = "Input textures control";
public static GUIContent UVBaseMappingText = new GUIContent("Base UV mapping", "");
public static GUIContent texWorldScaleText = new GUIContent("World scale", "Tiling factor applied to Planar/Trilinear mapping");
// Details
public static string detailText = "Inputs Detail";
public static GUIContent UVDetailMappingText = new GUIContent("Detail UV mapping", "");
public static GUIContent detailMapNormalText = new GUIContent("Detail Map A(R) Ny(G) S(B) Nx(A)", "Detail Map");
public static GUIContent detailMaskText = new GUIContent("Detail Mask (G)", "Mask for detailMap");
public static GUIContent detailAlbedoScaleText = new GUIContent("Detail AlbedoScale", "Detail Albedo Scale factor");
public static GUIContent detailNormalScaleText = new GUIContent("Detail NormalScale", "Normal Scale factor");
public static GUIContent detailSmoothnessScaleText = new GUIContent("Detail SmoothnessScale", "Smoothness Scale factor");
// Emissive
public static string lightingText = "Inputs Lighting";
public static GUIContent emissiveText = new GUIContent("Emissive Color", "Emissive");
public static GUIContent emissiveIntensityText = new GUIContent("Emissive Intensity", "Emissive");
public static GUIContent emissiveColorModeText = new GUIContent("Emissive Color Usage", "Use emissive color or emissive mask");
public static GUIContent normalMapSpaceWarning = new GUIContent("Object space normal can't be use with triplanar mapping.");
}
public enum UVBaseMapping
{
UV0,
Planar,
Triplanar
}
public enum NormalMapSpace
{
TangentSpace,
ObjectSpace,
}
public enum UVDetailMapping
{
UV0,
UV1,
UV2,
UV3
}
public enum EmissiveColorMode
{
UseEmissiveColor,
UseEmissiveMask,
}
protected MaterialProperty UVBase = null;
protected const string kUVBase = "_UVBase";
protected MaterialProperty TexWorldScale = null;
protected const string kTexWorldScale = "_TexWorldScale";
protected MaterialProperty UVMappingMask = null;
protected const string kUVMappingMask = "_UVMappingMask";
protected MaterialProperty diffuseColor = null;
protected const string kDiffuseColor = "_DiffuseColor";
protected MaterialProperty diffuseColorMap = null;
protected const string kDiffuseColorMap = "_DiffuseColorMap";
protected MaterialProperty smoothness = null;
protected const string kSmoothness = "_Smoothness";
protected MaterialProperty maskMap = null;
protected const string kMaskMap = "_MaskMap";
protected MaterialProperty specularOcclusionMap = null;
protected const string kSpecularOcclusionMap = "_SpecularOcclusionMap";
protected MaterialProperty horizonFade = null;
protected const string kHorizonFade = "_HorizonFade";
protected MaterialProperty normalMap = null;
protected const string kNormalMap = "_NormalMap";
protected MaterialProperty normalScale = null;
protected const string kNormalScale = "_NormalScale";
protected MaterialProperty normalMapSpace = null;
protected const string kNormalMapSpace = "_NormalMapSpace";
protected MaterialProperty tangentMap = null;
protected const string kTangentMap = "_TangentMap";
protected MaterialProperty anisotropy = null;
protected const string kAnisotropy = "_Anisotropy";
protected MaterialProperty anisotropyMap = null;
protected const string kAnisotropyMap = "_AnisotropyMap";
protected MaterialProperty UVDetail = null;
protected const string kUVDetail = "_UVDetail";
protected MaterialProperty UVDetailsMappingMask = null;
protected const string kUVDetailsMappingMask = "_UVDetailsMappingMask";
protected MaterialProperty detailMap = null;
protected const string kDetailMap = "_DetailMap";
protected MaterialProperty detailMask = null;
protected const string kDetailMask = "_DetailMask";
protected MaterialProperty detailAlbedoScale = null;
protected const string kDetailAlbedoScale = "_DetailAlbedoScale";
protected MaterialProperty detailNormalScale = null;
protected const string kDetailNormalScale = "_DetailNormalScale";
protected MaterialProperty detailSmoothnessScale = null;
protected const string kDetailSmoothnessScale = "_DetailSmoothnessScale";
protected MaterialProperty emissiveColorMode = null;
protected const string kEmissiveColorMode = "_EmissiveColorMode";
protected MaterialProperty emissiveColor = null;
protected const string kEmissiveColor = "_EmissiveColor";
protected MaterialProperty emissiveColorMap = null;
protected const string kEmissiveColorMap = "_EmissiveColorMap";
protected MaterialProperty emissiveIntensity = null;
protected const string kEmissiveIntensity = "_EmissiveIntensity";
protected override void FindMaterialProperties(MaterialProperty[] props)
{
UVBase = FindProperty(kUVBase, props);
TexWorldScale = FindProperty(kTexWorldScale, props);
UVMappingMask = FindProperty(kUVMappingMask, props);
diffuseColor = FindProperty(kDiffuseColor, props);
diffuseColorMap = FindProperty(kDiffuseColorMap, props);
smoothness = FindProperty(kSmoothness, props);
maskMap = FindProperty(kMaskMap, props);
specularOcclusionMap = FindProperty(kSpecularOcclusionMap, props);
horizonFade = FindProperty(kHorizonFade, props);
normalMap = FindProperty(kNormalMap, props);
normalScale = FindProperty(kNormalScale, props);
normalMapSpace = FindProperty(kNormalMapSpace, props);
tangentMap = FindProperty(kTangentMap, props);
anisotropy = FindProperty(kAnisotropy, props);
anisotropyMap = FindProperty(kAnisotropyMap, props);
// Details
UVDetail = FindProperty(kUVDetail, props);
UVDetailsMappingMask = FindProperty(kUVDetailsMappingMask, props);
detailMap = FindProperty(kDetailMap, props);
detailMask = FindProperty(kDetailMask, props);
detailAlbedoScale = FindProperty(kDetailAlbedoScale, props);
detailNormalScale = FindProperty(kDetailNormalScale, props);
detailSmoothnessScale = FindProperty(kDetailSmoothnessScale, props);
// Emissive
emissiveColorMode = FindProperty(kEmissiveColorMode, props);
emissiveColor = FindProperty(kEmissiveColor, props);
emissiveColorMap = FindProperty(kEmissiveColorMap, props);
emissiveIntensity = FindProperty(kEmissiveIntensity, props);
}
protected void ShaderStandardInputGUI()
{
m_MaterialEditor.TexturePropertySingleLine(Styles.tangentMapText, tangentMap);
m_MaterialEditor.ShaderProperty(anisotropy, Styles.anisotropyText);
m_MaterialEditor.TexturePropertySingleLine(Styles.anisotropyMapText, anisotropyMap);
}
protected override void MaterialPropertiesGUI(Material material)
{
bool useEmissiveMask = (EmissiveColorMode)emissiveColorMode.floatValue == EmissiveColorMode.UseEmissiveMask;
GUILayout.Label(Styles.InputsText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(Styles.diffuseColorText, diffuseColorMap, diffuseColor);
m_MaterialEditor.ShaderProperty(smoothness, Styles.smoothnessText);
if (useEmissiveMask)
m_MaterialEditor.TexturePropertySingleLine(Styles.maskMapESText, maskMap);
else
m_MaterialEditor.TexturePropertySingleLine(Styles.maskMapSText, maskMap);
m_MaterialEditor.TexturePropertySingleLine(Styles.specularOcclusionMapText, specularOcclusionMap);
m_MaterialEditor.ShaderProperty(horizonFade, Styles.horizonFadeText);
m_MaterialEditor.ShaderProperty(normalMapSpace, Styles.normalMapSpaceText);
// Triplanar only work with tangent space normal
if ((NormalMapSpace)normalMapSpace.floatValue == NormalMapSpace.ObjectSpace && ((UVBaseMapping)UVBase.floatValue == UVBaseMapping.Triplanar))
{
EditorGUILayout.HelpBox(Styles.normalMapSpaceWarning.text, MessageType.Error);
}
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, normalMap, normalScale);
ShaderStandardInputGUI();
EditorGUILayout.Space();
GUILayout.Label(" " + Styles.textureControlText, EditorStyles.label);
m_MaterialEditor.ShaderProperty(UVBase, Styles.UVBaseMappingText);
// UVSet0 is always set, planar and triplanar will override it.
UVMappingMask.colorValue = new Color(1.0f, 0.0f, 0.0f, 0.0f); // This is override in the shader anyway but just in case.
if (((UVBaseMapping)UVBase.floatValue == UVBaseMapping.Planar) || ((UVBaseMapping)UVBase.floatValue == UVBaseMapping.Triplanar))
{
m_MaterialEditor.ShaderProperty(TexWorldScale, Styles.texWorldScaleText);
}
m_MaterialEditor.TextureScaleOffsetProperty(diffuseColorMap);
EditorGUILayout.Space();
GUILayout.Label(Styles.detailText, EditorStyles.boldLabel);
m_MaterialEditor.TexturePropertySingleLine(Styles.detailMaskText, detailMask);
m_MaterialEditor.TexturePropertySingleLine(Styles.detailMapNormalText, detailMap);
EditorGUI.indentLevel++;
// When Planar or Triplanar is enable the UVDetail use the same mode, so we disable the choice on UVDetail
if ((UVBaseMapping)UVBase.floatValue == UVBaseMapping.UV0)
{
m_MaterialEditor.ShaderProperty(UVDetail, Styles.UVDetailMappingText);
}
else if ((UVBaseMapping)UVBase.floatValue == UVBaseMapping.Planar)
{
GUILayout.Label(" " + Styles.UVDetailMappingText.text + ": Planar");
}
else if ((UVBaseMapping)UVBase.floatValue == UVBaseMapping.Triplanar)
{
GUILayout.Label(" " + Styles.UVDetailMappingText.text + ": Triplanar");
}
// Setup the UVSet for detail, if planar/triplanar is use for base, it will override the mapping of detail (See shader code)
float X, Y, Z, W;
X = ((UVDetailMapping)UVDetail.floatValue == UVDetailMapping.UV0) ? 1.0f : 0.0f;
Y = ((UVDetailMapping)UVDetail.floatValue == UVDetailMapping.UV1) ? 1.0f : 0.0f;
Z = ((UVDetailMapping)UVDetail.floatValue == UVDetailMapping.UV2) ? 1.0f : 0.0f;
W = ((UVDetailMapping)UVDetail.floatValue == UVDetailMapping.UV3) ? 1.0f : 0.0f;
UVDetailsMappingMask.colorValue = new Color(X, Y, Z, W);
m_MaterialEditor.TextureScaleOffsetProperty(detailMap);
m_MaterialEditor.ShaderProperty(detailAlbedoScale, Styles.detailAlbedoScaleText);
m_MaterialEditor.ShaderProperty(detailNormalScale, Styles.detailNormalScaleText);
m_MaterialEditor.ShaderProperty(detailSmoothnessScale, Styles.detailSmoothnessScaleText);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
GUILayout.Label(Styles.lightingText, EditorStyles.boldLabel);
m_MaterialEditor.ShaderProperty(emissiveColorMode, Styles.emissiveColorModeText);
if (!useEmissiveMask)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, emissiveColor);
}
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
// The parent Base.ShaderPropertiesGUI will call DoEmissionArea
}
protected override bool ShouldEmissionBeEnabled(Material mat)
{
return mat.GetFloat(kEmissiveIntensity) > 0.0f;
}
protected override void SetupMaterialKeywordsAndPassInternal(Material material)
{
SetupMaterialKeywordsAndPass(material);
}
// All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if code change
static public void SetupMaterialKeywordsAndPass(Material material)
{
SetupBaseHairKeywords(material);
// Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation
// (MaterialProperty value might come from renderer material property block)
SetKeyword(material, "_MAPPING_PLANAR", ((UVBaseMapping)material.GetFloat(kUVBase)) == UVBaseMapping.Planar);
SetKeyword(material, "_MAPPING_TRIPLANAR", ((UVBaseMapping)material.GetFloat(kUVBase)) == UVBaseMapping.Triplanar);
SetKeyword(material, "_NORMALMAP_TANGENT_SPACE", ((NormalMapSpace)material.GetFloat(kNormalMapSpace)) == NormalMapSpace.TangentSpace);
SetKeyword(material, "_EMISSIVE_COLOR", ((EmissiveColorMode)material.GetFloat(kEmissiveColorMode)) == EmissiveColorMode.UseEmissiveColor);
SetKeyword(material, "_NORMALMAP", material.GetTexture(kNormalMap) || material.GetTexture(kDetailMap)); // With details map, we always use a normal map and Unity provide a default (0, 0, 1) normal map for ir
SetKeyword(material, "_MASKMAP", material.GetTexture(kMaskMap));
SetKeyword(material, "_SPECULAROCCLUSIONMAP", material.GetTexture(kSpecularOcclusionMap));
SetKeyword(material, "_EMISSIVE_COLOR_MAP", material.GetTexture(kEmissiveColorMap));
SetKeyword(material, "_TANGENTMAP", material.GetTexture(kTangentMap));
SetKeyword(material, "_ANISOTROPYMAP", material.GetTexture(kAnisotropyMap));
SetKeyword(material, "_DETAIL_MAP", material.GetTexture(kDetailMap));
bool needUV2 = (UVDetailMapping)material.GetFloat(kUVDetail) == UVDetailMapping.UV2 && (UVBaseMapping)material.GetFloat(kUVBase) == UVBaseMapping.UV0;
bool needUV3 = (UVDetailMapping)material.GetFloat(kUVDetail) == UVDetailMapping.UV3 && (UVBaseMapping)material.GetFloat(kUVBase) == UVBaseMapping.UV0;
if (needUV3)
{
material.DisableKeyword("_REQUIRE_UV2");
material.EnableKeyword("_REQUIRE_UV3");
}
else if (needUV2)
{
material.EnableKeyword("_REQUIRE_UV2");
material.DisableKeyword("_REQUIRE_UV3");
}
else
{
material.DisableKeyword("_REQUIRE_UV2");
material.DisableKeyword("_REQUIRE_UV3");
}
}
}
} // namespace UnityEditor
| |
namespace Abp.NServiceBus.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class AbpZero_Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AbpAuditLogs",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
ServiceName = c.String(maxLength: 256),
MethodName = c.String(maxLength: 256),
Parameters = c.String(maxLength: 1024),
ExecutionTime = c.DateTime(nullable: false),
ExecutionDuration = c.Int(nullable: false),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Exception = c.String(maxLength: 2000),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.RoleId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsStatic = c.Boolean(nullable: false),
IsDefault = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUsers",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
AuthenticationSource = c.String(maxLength: 64),
Name = c.String(nullable: false, maxLength: 32),
Surname = c.String(nullable: false, maxLength: 32),
UserName = c.String(nullable: false, maxLength: 32),
Password = c.String(nullable: false, maxLength: 128),
EmailAddress = c.String(nullable: false, maxLength: 256),
IsEmailConfirmed = c.Boolean(nullable: false),
EmailConfirmationCode = c.String(maxLength: 128),
PasswordResetCode = c.String(maxLength: 128),
LastLoginTime = c.DateTime(),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpTenants",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenancyName = c.String(nullable: false, maxLength: 64),
Name = c.String(nullable: false, maxLength: 128),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
}
public override void Down()
{
DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles");
DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers");
DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" });
DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" });
DropIndex("dbo.AbpSettings", new[] { "UserId" });
DropIndex("dbo.AbpSettings", new[] { "TenantId" });
DropIndex("dbo.AbpUserRoles", new[] { "UserId" });
DropIndex("dbo.AbpUserLogins", new[] { "UserId" });
DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" });
DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" });
DropIndex("dbo.AbpUsers", new[] { "TenantId" });
DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" });
DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" });
DropIndex("dbo.AbpRoles", new[] { "TenantId" });
DropIndex("dbo.AbpPermissions", new[] { "UserId" });
DropIndex("dbo.AbpPermissions", new[] { "RoleId" });
DropTable("dbo.AbpTenants",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpSettings");
DropTable("dbo.AbpUserRoles");
DropTable("dbo.AbpUserLogins");
DropTable("dbo.AbpUsers",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpPermissions");
DropTable("dbo.AbpAuditLogs",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
}
}
}
| |
using System;
/// <summary>
/// Equals(System.Object)
/// </summary>
public class GuidEquals2
{
#region Private Fields
private const int c_GUID_BYTE_ARRAY_SIZE = 16;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Equals with self instance");
try
{
Guid guid = Guid.Empty;
if (!guid.Equals((object)guid))
{
TestLibrary.TestFramework.LogError("001.1", "Calling Equals with self instance returns false");
retVal = false;
}
// double check
if (!guid.Equals((object)guid))
{
TestLibrary.TestFramework.LogError("001.2", "Calling Equals with self instance returns false");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid = new Guid(bytes);
if (!guid.Equals((object)guid))
{
TestLibrary.TestFramework.LogError("001.3", "Calling Equals with self instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
// double check
if (!guid.Equals((object)guid))
{
TestLibrary.TestFramework.LogError("001.4", "Calling Equals with self instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Equals with equal instance");
try
{
Guid guid1 = Guid.Empty;
Guid guid2 = new Guid("00000000-0000-0000-0000-000000000000");
if (!guid1.Equals((object)guid2))
{
TestLibrary.TestFramework.LogError("002.1", "Calling Equals with equal instance returns false");
retVal = false;
}
// double check
if (!guid1.Equals((object)guid2))
{
TestLibrary.TestFramework.LogError("002.2", "Calling Equals with equal instance returns false");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid1 = new Guid(bytes);
guid2 = new Guid(bytes);
if (!guid1.Equals((object)guid2))
{
TestLibrary.TestFramework.LogError("002.3", "Calling Equals with equal instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2);
retVal = false;
}
// double check
if (!guid1.Equals((object)guid2))
{
TestLibrary.TestFramework.LogError("002.4", "Calling Equals with equal instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Equals with not equal instance");
try
{
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000000001"), false, "003.1") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000000100"), false, "003.2") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000010000"), false, "003.3") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000001000000"), false, "003.4") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000100000000"), false, "003.5") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-010000000000"), false, "003.6") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0001-000000000000"), false, "003.7") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0100-000000000000"), false, "003.8") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0001-0000-000000000000"), false, "003.9") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0100-0000-000000000000"), false, "003.10") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0001-0000-0000-000000000000"), false, "003.11") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0100-0000-0000-000000000000"), false, "003.12") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000001-0000-0000-0000-000000000000"), false, "003.13") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000100-0000-0000-0000-000000000000"), false, "003.14") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00010000-0000-0000-0000-000000000000"), false, "003.15") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("01000000-0000-0000-0000-000000000000"), false, "003.16") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call Equals with null reference");
try
{
Guid guid = Guid.Empty;
if (guid.Equals(null))
{
TestLibrary.TestFramework.LogError("004.1", "Calling Equals with null reference returns true");
retVal = false;
}
// double check
if (guid.Equals(null))
{
TestLibrary.TestFramework.LogError("004.2", "Calling Equals with null reference returns true");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid = new Guid(bytes);
if (guid.Equals(null))
{
TestLibrary.TestFramework.LogError("004.3", "Calling Equals with null reference returns true");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
// double check
if (guid.Equals(null))
{
TestLibrary.TestFramework.LogError("004.4", "Calling Equals with null reference returns true");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Call Equals with not a Guid instance");
try
{
Guid guid = Guid.Empty;
Object obj = new Object();
if (guid.Equals(obj))
{
TestLibrary.TestFramework.LogError("005.1", "Calling Equals with not a Guid instance returns true");
retVal = false;
}
// double check
if (guid.Equals(obj))
{
TestLibrary.TestFramework.LogError("005.2", "Calling Equals with not a Guid instance returns true");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid = new Guid(bytes);
if (guid.Equals(obj))
{
TestLibrary.TestFramework.LogError("005.3", "Calling Equals with not a Guid instance returns true");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
// double check
if (guid.Equals(obj))
{
TestLibrary.TestFramework.LogError("005.4", "Calling Equals with not a Guid instance returns true");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
GuidEquals2 test = new GuidEquals2();
TestLibrary.TestFramework.BeginTestCase("GuidEquals2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerificationHelper(Guid guid1, object guid2, bool expected, string errorNo)
{
bool retVal = true;
bool actual = guid1.Equals(guid2);
if (actual != expected)
{
TestLibrary.TestFramework.LogError(errorNo, "Calling Equals returns wrong result");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2 + ", actual = " + actual + ", expected = " + expected);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
using Xunit;
namespace Avalonia.Interactivity.UnitTests
{
public class InteractiveTests
{
[Fact]
public void Direct_Event_Should_Go_Straight_To_Source()
{
var ev = new RoutedEvent("test", RoutingStrategies.Direct, typeof(RoutedEventArgs), typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) => invoked.Add(((TestInteractive)s).Name);
var target = CreateTree(ev, handler, RoutingStrategies.Direct);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "2b" }, invoked);
}
[Fact]
public void Direct_Event_Should_Have_Route_Set_To_Direct()
{
var ev = new RoutedEvent("test", RoutingStrategies.Direct, typeof(RoutedEventArgs), typeof(TestInteractive));
bool called = false;
EventHandler<RoutedEventArgs> handler = (s, e) =>
{
Assert.Equal(RoutingStrategies.Direct, e.Route);
called = true;
};
var target = CreateTree(ev, handler, RoutingStrategies.Direct);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.True(called);
}
[Fact]
public void Bubbling_Event_Should_Bubble_Up()
{
var ev = new RoutedEvent("test", RoutingStrategies.Bubble, typeof(RoutedEventArgs), typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) => invoked.Add(((TestInteractive)s).Name);
var target = CreateTree(ev, handler, RoutingStrategies.Bubble | RoutingStrategies.Tunnel);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "2b", "1" }, invoked);
}
[Fact]
public void Tunneling_Event_Should_Tunnel()
{
var ev = new RoutedEvent("test", RoutingStrategies.Tunnel, typeof(RoutedEventArgs), typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) => invoked.Add(((TestInteractive)s).Name);
var target = CreateTree(ev, handler, RoutingStrategies.Bubble | RoutingStrategies.Tunnel);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "1", "2b" }, invoked);
}
[Fact]
public void Tunneling_Bubbling_Event_Should_Tunnel_Then_Bubble_Up()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) => invoked.Add(((TestInteractive)s).Name);
var target = CreateTree(ev, handler, RoutingStrategies.Bubble | RoutingStrategies.Tunnel);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "1", "2b", "2b", "1" }, invoked);
}
[Fact]
public void Events_Should_Have_Route_Set()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var invoked = new List<RoutingStrategies>();
EventHandler<RoutedEventArgs> handler = (s, e) => invoked.Add(e.Route);
var target = CreateTree(ev, handler, RoutingStrategies.Bubble | RoutingStrategies.Tunnel);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[]
{
RoutingStrategies.Tunnel,
RoutingStrategies.Tunnel,
RoutingStrategies.Bubble,
RoutingStrategies.Bubble,
},
invoked);
}
[Fact]
public void Handled_Bubbled_Event_Should_Not_Propogate_Further()
{
var ev = new RoutedEvent("test", RoutingStrategies.Bubble, typeof(RoutedEventArgs), typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) =>
{
var t = (TestInteractive)s;
invoked.Add(t.Name);
e.Handled = t.Name == "2b";
};
var target = CreateTree(ev, handler, RoutingStrategies.Bubble);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "2b" }, invoked);
}
[Fact]
public void Handled_Tunnelled_Event_Should_Not_Propogate_Further()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) =>
{
var t = (TestInteractive)s;
invoked.Add(t.Name);
e.Handled = t.Name == "2b";
};
var target = CreateTree(ev, handler, RoutingStrategies.Bubble | RoutingStrategies.Tunnel);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "1", "2b" }, invoked);
}
[Fact]
public void Direct_Subscription_Should_Not_Catch_Tunneling_Or_Bubbling()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var count = 0;
EventHandler<RoutedEventArgs> handler = (s, e) =>
{
++count;
};
var target = CreateTree(ev, handler, RoutingStrategies.Direct);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(0, count);
}
[Fact]
public void Bubbling_Subscription_Should_Not_Catch_Tunneling()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var count = 0;
EventHandler<RoutedEventArgs> handler = (s, e) =>
{
Assert.Equal(RoutingStrategies.Bubble, e.Route);
++count;
};
var target = CreateTree(ev, handler, RoutingStrategies.Bubble);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(2, count);
}
[Fact]
public void Tunneling_Subscription_Should_Not_Catch_Bubbling()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var count = 0;
EventHandler<RoutedEventArgs> handler = (s, e) =>
{
Assert.Equal(RoutingStrategies.Tunnel, e.Route);
++count;
};
var target = CreateTree(ev, handler, RoutingStrategies.Tunnel);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(2, count);
}
[Fact]
public void Event_Should_Should_Keep_Propogating_To_HandedEventsToo_Handlers()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) =>
{
invoked.Add(((TestInteractive)s).Name);
e.Handled = true;
};
var target = CreateTree(ev, handler, RoutingStrategies.Bubble | RoutingStrategies.Tunnel, true);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "1", "2b", "2b", "1" }, invoked);
}
[Fact]
public void Direct_Class_Handlers_Should_Be_Called()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Direct,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) => invoked.Add(((TestInteractive)s).Name);
var target = CreateTree(ev, null, 0);
ev.AddClassHandler(typeof(TestInteractive), handler, RoutingStrategies.Direct);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "2b" }, invoked);
}
[Fact]
public void Tunneling_Class_Handlers_Should_Be_Called()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) => invoked.Add(((TestInteractive)s).Name);
var target = CreateTree(ev, null, 0);
ev.AddClassHandler(typeof(TestInteractive), handler, RoutingStrategies.Tunnel);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "1", "2b" }, invoked);
}
[Fact]
public void Bubbling_Class_Handlers_Should_Be_Called()
{
var ev = new RoutedEvent(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(RoutedEventArgs),
typeof(TestInteractive));
var invoked = new List<string>();
EventHandler<RoutedEventArgs> handler = (s, e) => invoked.Add(((TestInteractive)s).Name);
var target = CreateTree(ev, null, 0);
ev.AddClassHandler(typeof(TestInteractive), handler, RoutingStrategies.Bubble);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.Equal(new[] { "2b", "1" }, invoked);
}
[Fact]
public void Typed_Class_Handlers_Should_Be_Called()
{
var ev = new RoutedEvent<RoutedEventArgs>(
"test",
RoutingStrategies.Bubble | RoutingStrategies.Tunnel,
typeof(TestInteractive));
var target = CreateTree(ev, null, 0);
ev.AddClassHandler<TestInteractive>(x => x.ClassHandler, RoutingStrategies.Bubble);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
Assert.True(target.ClassHandlerInvoked);
Assert.True(target.GetVisualParent<TestInteractive>().ClassHandlerInvoked);
}
[Fact]
public void GetObservable_Should_Listen_To_Event()
{
var ev = new RoutedEvent<RoutedEventArgs>("test", RoutingStrategies.Direct, typeof(TestInteractive));
var target = new TestInteractive();
var called = 0;
var subscription = target.GetObservable(ev).Subscribe(_ => ++called);
var args = new RoutedEventArgs(ev, target);
target.RaiseEvent(args);
subscription.Dispose();
target.RaiseEvent(args);
Assert.Equal(1, called);
}
private TestInteractive CreateTree(
RoutedEvent ev,
EventHandler<RoutedEventArgs> handler,
RoutingStrategies handlerRoutes,
bool handledEventsToo = false)
{
TestInteractive target;
var tree = new TestInteractive
{
Name = "1",
Children = new[]
{
new TestInteractive
{
Name = "2a",
},
(target = new TestInteractive
{
Name = "2b",
Children = new[]
{
new TestInteractive
{
Name = "3",
},
},
}),
}
};
if (handler != null)
{
foreach (var i in tree.GetSelfAndVisualDescendants().Cast<Interactive>())
{
i.AddHandler(ev, handler, handlerRoutes, handledEventsToo);
}
}
return target;
}
private class TestInteractive : Interactive
{
public bool ClassHandlerInvoked { get; private set; }
public string Name { get; set; }
public IEnumerable<IVisual> Children
{
get
{
return ((IVisual)this).VisualChildren.AsEnumerable();
}
set
{
VisualChildren.AddRange(value.Cast<Visual>());
}
}
public void ClassHandler(RoutedEventArgs e)
{
ClassHandlerInvoked = true;
}
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using Adaptive.SimpleBinaryEncoding;
namespace Adaptive.SimpleBinaryEncoding.PerfTests.Bench.SBE.FIX
{
public class NewOrder
{
public const ushort TemplateId = (ushort)68;
public const byte TemplateVersion = (byte)0;
public const ushort BlockLength = (ushort)156;
public const string SematicType = "D";
private readonly NewOrder _parentMessage;
private DirectBuffer _buffer;
private int _offset;
private int _limit;
private int _actingBlockLength;
private int _actingVersion;
public int Offset { get { return _offset; } }
public NewOrder()
{
_parentMessage = this;
}
public void WrapForEncode(DirectBuffer buffer, int offset)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = BlockLength;
_actingVersion = TemplateVersion;
Limit = offset + _actingBlockLength;
}
public void WrapForDecode(DirectBuffer buffer, int offset,
int actingBlockLength, int actingVersion)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = actingBlockLength;
_actingVersion = actingVersion;
Limit = offset + _actingBlockLength;
}
public int Size
{
get
{
return _limit - _offset;
}
}
public int Limit
{
get
{
return _limit;
}
set
{
_buffer.CheckLimit(_limit);
_limit = value;
}
}
public const int AccountSchemaId = 1;
public static string AccountMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte AccountNullValue = (byte)0;
public const byte AccountMinValue = (byte)32;
public const byte AccountMaxValue = (byte)126;
public const int AccountLength = 12;
public byte GetAccount(int index)
{
if (index < 0 || index >= 12)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 0 + (index * 1));
}
public void SetAccount(int index, byte value)
{
if (index < 0 || index >= 12)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 0 + (index * 1), value);
}
public const string AccountCharacterEncoding = "UTF-8";
public int GetAccount(byte[] dst, int dstOffset)
{
const int length = 12;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 0, dst, dstOffset, length);
return length;
}
public void SetAccount(byte[] src, int srcOffset)
{
const int length = 12;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 0, src, srcOffset, length);
}
public const int ClOrdIDSchemaId = 11;
public static string ClOrdIDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte ClOrdIDNullValue = (byte)0;
public const byte ClOrdIDMinValue = (byte)32;
public const byte ClOrdIDMaxValue = (byte)126;
public const int ClOrdIDLength = 20;
public byte GetClOrdID(int index)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 12 + (index * 1));
}
public void SetClOrdID(int index, byte value)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 12 + (index * 1), value);
}
public const string ClOrdIDCharacterEncoding = "UTF-8";
public int GetClOrdID(byte[] dst, int dstOffset)
{
const int length = 20;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 12, dst, dstOffset, length);
return length;
}
public void SetClOrdID(byte[] src, int srcOffset)
{
const int length = 20;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 12, src, srcOffset, length);
}
public const int HandInstSchemaId = 21;
public static string HandInstMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public HandInst HandInst
{
get
{
return (HandInst)_buffer.CharGet(_offset + 32);
}
set
{
_buffer.CharPut(_offset + 32, (byte)value);
}
}
public const int CustOrderHandlingInstSchemaId = 1031;
public static string CustOrderHandlingInstMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public CustOrderHandlingInst CustOrderHandlingInst
{
get
{
return (CustOrderHandlingInst)_buffer.CharGet(_offset + 33);
}
set
{
_buffer.CharPut(_offset + 33, (byte)value);
}
}
public const int OrderQtySchemaId = 38;
public static string OrderQtyMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Qty";
}
return "";
}
private readonly IntQty32 _orderQty = new IntQty32();
public IntQty32 OrderQty
{
get
{
_orderQty.Wrap(_buffer, _offset + 34, _actingVersion);
return _orderQty;
}
}
public const int OrdTypeSchemaId = 40;
public static string OrdTypeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public OrdType OrdType
{
get
{
return (OrdType)_buffer.CharGet(_offset + 38);
}
set
{
_buffer.CharPut(_offset + 38, (byte)value);
}
}
public const int PriceSchemaId = 44;
public static string PriceMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Price";
}
return "";
}
private readonly OptionalPrice _price = new OptionalPrice();
public OptionalPrice Price
{
get
{
_price.Wrap(_buffer, _offset + 39, _actingVersion);
return _price;
}
}
public const int SideSchemaId = 54;
public static string SideMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public Side Side
{
get
{
return (Side)_buffer.CharGet(_offset + 48);
}
set
{
_buffer.CharPut(_offset + 48, (byte)value);
}
}
public const int SymbolSchemaId = 55;
public static string SymbolMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte SymbolNullValue = (byte)0;
public const byte SymbolMinValue = (byte)32;
public const byte SymbolMaxValue = (byte)126;
public const int SymbolLength = 6;
public byte GetSymbol(int index)
{
if (index < 0 || index >= 6)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 49 + (index * 1));
}
public void SetSymbol(int index, byte value)
{
if (index < 0 || index >= 6)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 49 + (index * 1), value);
}
public const string SymbolCharacterEncoding = "UTF-8";
public int GetSymbol(byte[] dst, int dstOffset)
{
const int length = 6;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 49, dst, dstOffset, length);
return length;
}
public void SetSymbol(byte[] src, int srcOffset)
{
const int length = 6;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 49, src, srcOffset, length);
}
public const int TimeInForceSchemaId = 59;
public static string TimeInForceMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public TimeInForce TimeInForce
{
get
{
return (TimeInForce)_buffer.CharGet(_offset + 55);
}
set
{
_buffer.CharPut(_offset + 55, (byte)value);
}
}
public const int TransactTimeSchemaId = 60;
public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "UTCTimestamp";
}
return "";
}
public const ulong TransactTimeNullValue = 0x8000000000000000UL;
public const ulong TransactTimeMinValue = 0x0UL;
public const ulong TransactTimeMaxValue = 0x7fffffffffffffffUL;
public ulong TransactTime
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 56);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 56, value);
}
}
public const int ManualOrderIndicatorSchemaId = 1028;
public static string ManualOrderIndicatorMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public BooleanType ManualOrderIndicator
{
get
{
return (BooleanType)_buffer.Uint8Get(_offset + 64);
}
set
{
_buffer.Uint8Put(_offset + 64, (byte)value);
}
}
public const int AllocAccountSchemaId = 79;
public static string AllocAccountMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte AllocAccountNullValue = (byte)0;
public const byte AllocAccountMinValue = (byte)32;
public const byte AllocAccountMaxValue = (byte)126;
public const int AllocAccountLength = 10;
public byte GetAllocAccount(int index)
{
if (index < 0 || index >= 10)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 65 + (index * 1));
}
public void SetAllocAccount(int index, byte value)
{
if (index < 0 || index >= 10)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 65 + (index * 1), value);
}
public const string AllocAccountCharacterEncoding = "UTF-8";
public int GetAllocAccount(byte[] dst, int dstOffset)
{
const int length = 10;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 65, dst, dstOffset, length);
return length;
}
public void SetAllocAccount(byte[] src, int srcOffset)
{
const int length = 10;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 65, src, srcOffset, length);
}
public const int StopPxSchemaId = 99;
public static string StopPxMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Price";
}
return "";
}
private readonly OptionalPrice _stopPx = new OptionalPrice();
public OptionalPrice StopPx
{
get
{
_stopPx.Wrap(_buffer, _offset + 75, _actingVersion);
return _stopPx;
}
}
public const int SecurityDescSchemaId = 107;
public static string SecurityDescMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte SecurityDescNullValue = (byte)0;
public const byte SecurityDescMinValue = (byte)32;
public const byte SecurityDescMaxValue = (byte)126;
public const int SecurityDescLength = 20;
public byte GetSecurityDesc(int index)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 84 + (index * 1));
}
public void SetSecurityDesc(int index, byte value)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 84 + (index * 1), value);
}
public const string SecurityDescCharacterEncoding = "UTF-8";
public int GetSecurityDesc(byte[] dst, int dstOffset)
{
const int length = 20;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 84, dst, dstOffset, length);
return length;
}
public void SetSecurityDesc(byte[] src, int srcOffset)
{
const int length = 20;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 84, src, srcOffset, length);
}
public const int MinQtySchemaId = 110;
public static string MinQtyMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Qty";
}
return "";
}
private readonly IntQty32 _minQty = new IntQty32();
public IntQty32 MinQty
{
get
{
_minQty.Wrap(_buffer, _offset + 104, _actingVersion);
return _minQty;
}
}
public const int SecurityTypeSchemaId = 167;
public static string SecurityTypeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte SecurityTypeNullValue = (byte)0;
public const byte SecurityTypeMinValue = (byte)32;
public const byte SecurityTypeMaxValue = (byte)126;
public const int SecurityTypeLength = 3;
public byte GetSecurityType(int index)
{
if (index < 0 || index >= 3)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 108 + (index * 1));
}
public void SetSecurityType(int index, byte value)
{
if (index < 0 || index >= 3)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 108 + (index * 1), value);
}
public const string SecurityTypeCharacterEncoding = "UTF-8";
public int GetSecurityType(byte[] dst, int dstOffset)
{
const int length = 3;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 108, dst, dstOffset, length);
return length;
}
public void SetSecurityType(byte[] src, int srcOffset)
{
const int length = 3;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 108, src, srcOffset, length);
}
public const int CustomerOrFirmSchemaId = 204;
public static string CustomerOrFirmMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public CustomerOrFirm CustomerOrFirm
{
get
{
return (CustomerOrFirm)_buffer.Uint8Get(_offset + 111);
}
set
{
_buffer.Uint8Put(_offset + 111, (byte)value);
}
}
public const int MaxShowSchemaId = 210;
public static string MaxShowMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Qty";
}
return "";
}
private readonly IntQty32 _maxShow = new IntQty32();
public IntQty32 MaxShow
{
get
{
_maxShow.Wrap(_buffer, _offset + 112, _actingVersion);
return _maxShow;
}
}
public const int ExpireDateSchemaId = 432;
public static string ExpireDateMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ushort ExpireDateNullValue = (ushort)65535;
public const ushort ExpireDateMinValue = (ushort)0;
public const ushort ExpireDateMaxValue = (ushort)65534;
public ushort ExpireDate
{
get
{
return _buffer.Uint16GetLittleEndian(_offset + 116);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 116, value);
}
}
public const int SelfMatchPreventionIDSchemaId = 7928;
public static string SelfMatchPreventionIDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte SelfMatchPreventionIDNullValue = (byte)0;
public const byte SelfMatchPreventionIDMinValue = (byte)32;
public const byte SelfMatchPreventionIDMaxValue = (byte)126;
public const int SelfMatchPreventionIDLength = 12;
public byte GetSelfMatchPreventionID(int index)
{
if (index < 0 || index >= 12)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 118 + (index * 1));
}
public void SetSelfMatchPreventionID(int index, byte value)
{
if (index < 0 || index >= 12)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 118 + (index * 1), value);
}
public const string SelfMatchPreventionIDCharacterEncoding = "UTF-8";
public int GetSelfMatchPreventionID(byte[] dst, int dstOffset)
{
const int length = 12;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 118, dst, dstOffset, length);
return length;
}
public void SetSelfMatchPreventionID(byte[] src, int srcOffset)
{
const int length = 12;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 118, src, srcOffset, length);
}
public const int CtiCodeSchemaId = 9702;
public static string CtiCodeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public CtiCode CtiCode
{
get
{
return (CtiCode)_buffer.CharGet(_offset + 130);
}
set
{
_buffer.CharPut(_offset + 130, (byte)value);
}
}
public const int GiveUpFirmSchemaId = 9707;
public static string GiveUpFirmMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte GiveUpFirmNullValue = (byte)0;
public const byte GiveUpFirmMinValue = (byte)32;
public const byte GiveUpFirmMaxValue = (byte)126;
public const int GiveUpFirmLength = 3;
public byte GetGiveUpFirm(int index)
{
if (index < 0 || index >= 3)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 131 + (index * 1));
}
public void SetGiveUpFirm(int index, byte value)
{
if (index < 0 || index >= 3)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 131 + (index * 1), value);
}
public const string GiveUpFirmCharacterEncoding = "UTF-8";
public int GetGiveUpFirm(byte[] dst, int dstOffset)
{
const int length = 3;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 131, dst, dstOffset, length);
return length;
}
public void SetGiveUpFirm(byte[] src, int srcOffset)
{
const int length = 3;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 131, src, srcOffset, length);
}
public const int CmtaGiveupCDSchemaId = 9708;
public static string CmtaGiveupCDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte CmtaGiveupCDNullValue = (byte)0;
public const byte CmtaGiveupCDMinValue = (byte)32;
public const byte CmtaGiveupCDMaxValue = (byte)126;
public const int CmtaGiveupCDLength = 2;
public byte GetCmtaGiveupCD(int index)
{
if (index < 0 || index >= 2)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 134 + (index * 1));
}
public void SetCmtaGiveupCD(int index, byte value)
{
if (index < 0 || index >= 2)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 134 + (index * 1), value);
}
public const string CmtaGiveupCDCharacterEncoding = "UTF-8";
public int GetCmtaGiveupCD(byte[] dst, int dstOffset)
{
const int length = 2;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 134, dst, dstOffset, length);
return length;
}
public void SetCmtaGiveupCD(byte[] src, int srcOffset)
{
const int length = 2;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 134, src, srcOffset, length);
}
public const int CorrelationClOrdIDSchemaId = 9717;
public static string CorrelationClOrdIDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "String";
}
return "";
}
public const byte CorrelationClOrdIDNullValue = (byte)0;
public const byte CorrelationClOrdIDMinValue = (byte)32;
public const byte CorrelationClOrdIDMaxValue = (byte)126;
public const int CorrelationClOrdIDLength = 20;
public byte GetCorrelationClOrdID(int index)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
return _buffer.CharGet(_offset + 136 + (index * 1));
}
public void SetCorrelationClOrdID(int index, byte value)
{
if (index < 0 || index >= 20)
{
throw new IndexOutOfRangeException("index out of range: index=" + index);
}
_buffer.CharPut(_offset + 136 + (index * 1), value);
}
public const string CorrelationClOrdIDCharacterEncoding = "UTF-8";
public int GetCorrelationClOrdID(byte[] dst, int dstOffset)
{
const int length = 20;
if (dstOffset < 0 || dstOffset > (dst.Length - length))
{
throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset);
}
_buffer.GetBytes(_offset + 136, dst, dstOffset, length);
return length;
}
public void SetCorrelationClOrdID(byte[] src, int srcOffset)
{
const int length = 20;
if (srcOffset < 0 || srcOffset > (src.Length - length))
{
throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset);
}
_buffer.SetBytes(_offset + 136, src, srcOffset, length);
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// GroupByQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using IEnumerator = System.Collections.IEnumerator;
namespace System.Linq.Parallel
{
/// <summary>
/// The operator type for GroupBy statements. This operator groups the input based on
/// a key-selection routine, yielding one-to-many values of key-to-elements. The
/// implementation is very much like the hash join operator, in which we first build
/// a big hashtable of the input; then we just iterate over each unique key in the
/// hashtable, yielding it plus all of the elements with the same key.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TGroupKey"></typeparam>
/// <typeparam name="TElement"></typeparam>
internal sealed class GroupByQueryOperator<TSource, TGroupKey, TElement> :
UnaryQueryOperator<TSource, IGrouping<TGroupKey, TElement>>
{
private readonly Func<TSource, TGroupKey> _keySelector; // Key selection function.
private readonly Func<TSource, TElement> _elementSelector; // Optional element selection function.
private readonly IEqualityComparer<TGroupKey> _keyComparer; // An optional key comparison object.
//---------------------------------------------------------------------------------------
// Initializes a new group by operator.
//
// Arguments:
// child - the child operator or data source from which to pull data
// keySelector - a delegate representing the key selector function
// elementSelector - a delegate representing the element selector function
// keyComparer - an optional key comparison routine
//
// Assumptions:
// keySelector must be non null.
// elementSelector must be non null.
//
internal GroupByQueryOperator(IEnumerable<TSource> child,
Func<TSource, TGroupKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TGroupKey> keyComparer)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
Debug.Assert(keySelector != null, "need a selector function");
Debug.Assert(elementSelector != null ||
typeof(TSource) == typeof(TElement), "need an element function if TSource!=TElement");
_keySelector = keySelector;
_elementSelector = elementSelector;
_keyComparer = keyComparer;
SetOrdinalIndexState(OrdinalIndexState.Shuffled);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
bool preferStriping, QuerySettings settings)
{
// Hash-repartition the source stream
if (Child.OutputOrdered)
{
WrapPartitionedStreamHelperOrdered<TKey>(
ExchangeUtilities.HashRepartitionOrdered<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
else
{
WrapPartitionedStreamHelper<TKey, int>(
ExchangeUtilities.HashRepartition<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelper<TIgnoreKey, TKey>(
PartitionedStream<Pair<TSource, TGroupKey>, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Debug.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keyComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keyComparer, _elementSelector, cancellationToken);
}
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelperOrdered<TKey>(
PartitionedStream<Pair<TSource, TGroupKey>, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
IComparer<TKey> orderComparer = hashStream.KeyComparer;
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Debug.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keySelector, _keyComparer, orderComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keySelector, _elementSelector, _keyComparer, orderComparer,
cancellationToken);
}
}
recipient.Receive(outputStream);
}
//-----------------------------------------------------------------------------------
// Override of the query operator base class's Open method.
//
internal override QueryResults<IGrouping<TGroupKey, TElement>> Open(QuerySettings settings, bool preferStriping)
{
// We just open our child operator. Do not propagate the preferStriping value, but instead explicitly
// set it to false. Regardless of whether the parent prefers striping or range partitioning, the output
// will be hash-partitioned.
QueryResults<TSource> childResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childResults, this, settings, false);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<IGrouping<TGroupKey, TElement>> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TSource> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
if (_elementSelector == null)
{
Debug.Assert(typeof(TElement) == typeof(TSource));
return (IEnumerable<IGrouping<TGroupKey, TElement>>)wrappedChild.GroupBy(_keySelector, _keyComparer);
}
else
{
return wrappedChild.GroupBy(_keySelector, _elementSelector, _keyComparer);
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for grouping elements and yielding the key-value sets.
//
// Assumptions:
// Just like the Join operator, this won't work properly at all if the analysis engine
// didn't choose to hash partition. We will simply not yield correct groupings.
//
internal abstract class GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> _source; // The data source to enumerate.
protected readonly IEqualityComparer<TGroupKey> _keyComparer; // A key comparer.
protected readonly CancellationToken _cancellationToken;
private Mutables _mutables; // All of the mutable state.
class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected GroupByQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
IEqualityComparer<TGroupKey> keyComparer, CancellationToken cancellationToken)
{
Debug.Assert(source != null);
_source = source;
_keyComparer = keyComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext(ref IGrouping<TGroupKey, TElement> currentElement, ref TOrderKey currentKey)
{
Debug.Assert(_source != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
Debug.Assert(mutables._hashLookup != null);
mutables._hashLookupIndex = -1;
}
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
currentElement = new GroupByGrouping<TGroupKey, TElement>(
mutables._hashLookup[mutables._hashLookupIndex]);
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with the identity
// function.
//
internal sealed class GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByIdentityQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
IEqualityComparer<TGroupKey> keyComparer, CancellationToken cancellationToken)
: base(source, keyComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceKeyUnused = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TSource> currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TSource>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add(sourceElement.First);
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByElementSelectorQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
IEqualityComparer<TGroupKey> keyComparer, Func<TSource, TElement> elementSelector, CancellationToken cancellationToken) :
base(source, keyComparer, cancellationToken)
{
Debug.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceKeyUnused = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TElement> currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TElement>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add(_elementSelector(sourceElement.First));
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// Ordered version of the GroupBy operator.
//
internal abstract class OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> _source; // The data source to enumerate.
private readonly Func<TSource, TGroupKey> _keySelector; // The key selection routine.
protected readonly IEqualityComparer<TGroupKey> _keyComparer; // The key comparison routine.
protected readonly IComparer<TOrderKey> _orderComparer; // The comparison routine for order keys.
protected readonly CancellationToken _cancellationToken;
private Mutables _mutables; // All the mutable state.
class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, GroupKeyData> _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected OrderedGroupByQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(keySelector != null);
_source = source;
_keySelector = keySelector;
_keyComparer = keyComparer;
_orderComparer = orderComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext(ref IGrouping<TGroupKey, TElement> currentElement, ref TOrderKey currentKey)
{
Debug.Assert(_source != null);
Debug.Assert(_keySelector != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
Debug.Assert(mutables._hashLookup != null);
mutables._hashLookupIndex = -1;
}
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
GroupKeyData value = mutables._hashLookup[mutables._hashLookupIndex].Value;
currentElement = value._grouping;
currentKey = value._orderKey;
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
//-----------------------------------------------------------------------------------
// A data structure that holds information about elements with a particular key.
//
// This information includes two parts:
// - An order key for the grouping.
// - The grouping itself. The grouping consists of elements and the grouping key.
//
protected class GroupKeyData
{
internal TOrderKey _orderKey;
internal OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> _grouping;
internal GroupKeyData(TOrderKey orderKey, TGroupKey hashKey, IComparer<TOrderKey> orderComparer)
{
_orderKey = orderKey;
_grouping = new OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement>(hashKey, orderComparer);
}
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with the identity
// function.
//
internal sealed class OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByIdentityQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
: base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceOrderKey = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
currentValue._grouping.Add(sourceElement.First, sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByElementSelectorQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken) :
base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
Debug.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceOrderKey = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue._grouping.Add(_elementSelector(sourceElement.First), sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// This little type implements the IGrouping<K,T> interface, and exposes a single
// key-to-many-values mapping.
//
internal class GroupByGrouping<TGroupKey, TElement> : IGrouping<TGroupKey, TElement>
{
private KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> _keyValues; // A key value pair.
//---------------------------------------------------------------------------------------
// Constructs a new grouping out of the key value pair.
//
internal GroupByGrouping(KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> keyValues)
{
Debug.Assert(keyValues.Value != null);
_keyValues = keyValues;
}
//---------------------------------------------------------------------------------------
// The key this mapping represents.
//
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _keyValues.Key.Value;
}
}
//---------------------------------------------------------------------------------------
// Access to value enumerators.
//
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Debug.Assert(_keyValues.Value != null);
return _keyValues.Value.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
}
/// <summary>
/// An ordered version of the grouping data structure. Represents an ordered group of elements that
/// have the same grouping key.
/// </summary>
internal class OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> : IGrouping<TGroupKey, TElement>
{
private TGroupKey _groupKey; // The group key for this grouping
private GrowingArray<TElement> _values; // Values in this group
private GrowingArray<TOrderKey> _orderKeys; // Order keys that correspond to the values
private IComparer<TOrderKey> _orderComparer; // Comparer for order keys
private KeyAndValuesComparer _wrappedComparer; // Comparer that wraps the _orderComparer used for sorting key/value pairs
/// <summary>
/// Constructs a new grouping
/// </summary>
internal OrderedGroupByGrouping(
TGroupKey groupKey,
IComparer<TOrderKey> orderComparer)
{
_groupKey = groupKey;
_values = new GrowingArray<TElement>();
_orderKeys = new GrowingArray<TOrderKey>();
_orderComparer = orderComparer;
_wrappedComparer = new KeyAndValuesComparer(_orderComparer);
}
/// <summary>
/// The key this grouping represents.
/// </summary>
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _groupKey;
}
}
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Debug.Assert(_values != null);
int valueCount = _values.Count;
TElement[] valueArray = _values.InternalArray;
Debug.Assert(valueArray.Length >= valueCount); // valueArray.Length may be larger than valueCount
for (int i = 0; i < valueCount; i++)
{
yield return valueArray[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
/// <summary>
/// Add an element
/// </summary>
internal void Add(TElement value, TOrderKey orderKey)
{
Debug.Assert(_values != null);
Debug.Assert(_orderKeys != null);
_values.Add(value);
_orderKeys.Add(orderKey);
}
/// <summary>
/// No more elements will be added, so we can sort the group now.
/// </summary>
internal void DoneAdding()
{
Debug.Assert(_values != null);
Debug.Assert(_orderKeys != null);
// Create a map of key-value pair.
// We can't use a dictionary since the keys are not necessarily unique
List<KeyValuePair<TOrderKey, TElement>> sortedValues = new List<KeyValuePair<TOrderKey, TElement>>();
for (int i = 0; i < _orderKeys.InternalArray.Length; i++)
{
sortedValues.Add(new KeyValuePair<TOrderKey, TElement>(_orderKeys.InternalArray[i], _values.InternalArray[i]));
}
// Sort the values by using the _orderComparer wrapped in a Tuple comparer
sortedValues.Sort(0, _values.Count, _wrappedComparer);
// Un-pack the values from the list back into the 2 separate arrays
for (int i = 0; i < _values.InternalArray.Length; i++)
{
_orderKeys.InternalArray[i] = sortedValues[i].Key;
_values.InternalArray[i] = sortedValues[i].Value;
}
#if DEBUG
_orderKeys = null; // Any future calls to Add() or DoneAdding() will fail
#endif
}
private class KeyAndValuesComparer : IComparer<KeyValuePair<TOrderKey, TElement>>
{
private IComparer<TOrderKey> myComparer;
public KeyAndValuesComparer(IComparer<TOrderKey> comparer)
{
myComparer = comparer;
}
public int Compare(KeyValuePair<TOrderKey, TElement> x, KeyValuePair<TOrderKey, TElement> y)
{
return myComparer.Compare(x.Key, y.Key);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Windows;
using System.Collections.Generic;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PushSDK;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.JSON;
using System.Runtime.Serialization;
using System.Threading;
using Newtonsoft.Json.Linq;
using PushSDK.Classes;
using Newtonsoft.Json;
namespace WPCordovaClassLib.Cordova.Commands
{
public class PushNotification : BaseCommand
{
private String appid;
private String authenticatedServiceName = null;
private NotificationService service = null;
volatile private bool deviceReady = false;
private string registerCallbackId = null;
// returns null value if it fails.
private string getCallbackId(string options)
{
string[] optStings = null;
try
{
optStings = JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), CurrentCommandCallbackId);
}
if (optStings == null)
return CurrentCommandCallbackId;
//callback id is the last item
return optStings[optStings.Length - 1];
}
//Phonegap runs all plugins methods on a separate threads, make sure onDeviceReady goes first
void waitDeviceReady()
{
while (!deviceReady)
Thread.Sleep(10);
}
public void onDeviceReady(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
PushOptions pushOptions = JSON.JsonHelper.Deserialize<PushOptions>(args[0]);
this.appid = pushOptions.AppID;
authenticatedServiceName = pushOptions.ServiceName;
service = NotificationService.GetCurrent(appid, authenticatedServiceName, null);
service.OnPushTokenReceived += OnPushTokenReceived;
service.OnPushTokenFailed += OnPushTokenFailed;
service.OnPushAccepted += ExecutePushNotificationCallback;
deviceReady = true;
}
private void OnPushTokenReceived(object sender, string token)
{
if(registerCallbackId != null)
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, token), registerCallbackId);
}
private void OnPushTokenFailed(object sender, string error)
{
if (registerCallbackId != null)
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, error), registerCallbackId);
}
public void registerDevice(string options)
{
string callbackId = getCallbackId(options);
waitDeviceReady();
service.SubscribeToPushService(authenticatedServiceName);
if (string.IsNullOrEmpty(service.PushToken))
{
registerCallbackId = callbackId;
PluginResult plugResult = new PluginResult(PluginResult.Status.NO_RESULT);
plugResult.KeepCallback = true;
DispatchCommandResult(plugResult, callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, service.PushToken), callbackId);
}
}
public void unregisterDevice(string options)
{
string callbackId = getCallbackId(options);
PluginResult plugResult = new PluginResult(PluginResult.Status.NO_RESULT);
plugResult.KeepCallback = true;
DispatchCommandResult(plugResult);
waitDeviceReady();
service.UnsubscribeFromPushes(
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result));
},
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, result));
});
}
public void getTags(string options)
{
string callbackId = getCallbackId(options);
PluginResult plugResult = new PluginResult(PluginResult.Status.NO_RESULT);
plugResult.KeepCallback = true;
DispatchCommandResult(plugResult);
waitDeviceReady();
service.GetTags(
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
},
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, result), callbackId);
});
}
public void getPushwooshHWID(string options)
{
waitDeviceReady();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, service.DeviceUniqueID));
}
public void getPushToken(string options)
{
waitDeviceReady();
if (service != null && !string.IsNullOrEmpty(service.PushToken))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, service.PushToken));
}
}
public void setTags(string options)
{
string callbackId = getCallbackId(options);
PluginResult plugResult = new PluginResult(PluginResult.Status.NO_RESULT);
plugResult.KeepCallback = true;
DispatchCommandResult(plugResult);
waitDeviceReady();
string[] opts = JSON.JsonHelper.Deserialize<string[]>(options);
JObject jsonObject = JObject.Parse(opts[0]);
List<KeyValuePair<string, object>> tags = new List<KeyValuePair<string, object>>();
foreach (var element in jsonObject)
{
tags.Add(new KeyValuePair<string,object>(element.Key, element.Value));
}
service.SendTag(tags,
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
},
(obj, args) =>
{
string result = JsonConvert.SerializeObject(args);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, result), callbackId);
}
);
}
public void startLocationTracking(string options)
{
waitDeviceReady();
service.StartGeoLocation();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "GeoZone service is started"));
}
public void stopLocationTracking(string options)
{
waitDeviceReady();
service.StopGeoLocation();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "GeoZone service is stopped"));
}
void ExecutePushNotificationCallback(object sender, ToastPush push)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
PhoneApplicationFrame frame;
PhoneApplicationPage page;
CordovaView cView;
if (TryCast(Application.Current.RootVisual, out frame) &&
TryCast(frame.Content, out page) &&
TryCast(page.FindName("CordovaView"), out cView))
{
cView.Browser.Dispatcher.BeginInvoke(() =>
{
try
{
string pushPayload = JsonConvert.SerializeObject(push);
cView.Browser.InvokeScript("execScript", "cordova.require(\"com.pushwoosh.plugins.pushwoosh.PushNotification\").notificationCallback(" + pushPayload + ")");
}
catch (Exception ex)
{
Debug.WriteLine("ERROR: Exception in InvokeScriptCallback :: " + ex.Message);
}
});
}
});
}
static bool TryCast<T>(object obj, out T result) where T : class
{
result = obj as T;
return result != null;
}
[DataContract]
public class PushOptions
{
[DataMember(Name = "appid", IsRequired = true)]
public string AppID { get; set; }
[DataMember(Name = "serviceName", IsRequired = false)]
public string ServiceName { get; set; }
}
}
}
| |
// 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.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata
{
partial class MetadataReader
{
internal const string ClrPrefix = "<CLR>";
internal static readonly byte[] WinRTPrefix = new[] {
(byte)'<',
(byte)'W',
(byte)'i',
(byte)'n',
(byte)'R',
(byte)'T',
(byte)'>'
};
#region Projection Tables
// Maps names of projected types to projection information for each type.
// Both arrays are of the same length and sorted by the type name.
private static string[] s_projectedTypeNames;
private static ProjectionInfo[] s_projectionInfos;
private struct ProjectionInfo
{
public readonly string WinRTNamespace;
public readonly StringHandle.VirtualIndex ClrNamespace;
public readonly StringHandle.VirtualIndex ClrName;
public readonly AssemblyReferenceHandle.VirtualIndex AssemblyRef;
public readonly TypeDefTreatment Treatment;
public readonly bool IsIDisposable;
public ProjectionInfo(
string winRtNamespace,
StringHandle.VirtualIndex clrNamespace,
StringHandle.VirtualIndex clrName,
AssemblyReferenceHandle.VirtualIndex clrAssembly,
TypeDefTreatment treatment = TypeDefTreatment.RedirectedToClrType,
bool isIDisposable = false)
{
this.WinRTNamespace = winRtNamespace;
this.ClrNamespace = clrNamespace;
this.ClrName = clrName;
this.AssemblyRef = clrAssembly;
this.Treatment = treatment;
this.IsIDisposable = isIDisposable;
}
}
private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef)
{
InitializeProjectedTypes();
StringHandle name = TypeDefTable.GetName(typeDef);
int index = StringStream.BinarySearchRaw(s_projectedTypeNames, name);
if (index < 0)
{
return TypeDefTreatment.None;
}
StringHandle namespaceName = TypeDefTable.GetNamespace(typeDef);
if (StringStream.EqualsRaw(namespaceName, StringStream.GetVirtualValue(s_projectionInfos[index].ClrNamespace)))
{
return s_projectionInfos[index].Treatment;
}
// TODO: we can avoid this comparison if info.DotNetNamespace == info.WinRtNamespace
if (StringStream.EqualsRaw(namespaceName, s_projectionInfos[index].WinRTNamespace))
{
return s_projectionInfos[index].Treatment | TypeDefTreatment.MarkInternalFlag;
}
return TypeDefTreatment.None;
}
private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable)
{
InitializeProjectedTypes();
int index = StringStream.BinarySearchRaw(s_projectedTypeNames, TypeRefTable.GetName(typeRef));
if (index >= 0 && StringStream.EqualsRaw(TypeRefTable.GetNamespace(typeRef), s_projectionInfos[index].WinRTNamespace))
{
isIDisposable = s_projectionInfos[index].IsIDisposable;
return index;
}
isIDisposable = false;
return -1;
}
internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return AssemblyReferenceHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].AssemblyRef);
}
internal static StringHandle GetProjectedName(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrName);
}
internal static StringHandle GetProjectedNamespace(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrNamespace);
}
private static void InitializeProjectedTypes()
{
if (s_projectedTypeNames == null || s_projectionInfos == null)
{
var systemRuntimeWindowsRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime;
var systemRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime;
var systemObjectModel = AssemblyReferenceHandle.VirtualIndex.System_ObjectModel;
var systemRuntimeWindowsUiXaml = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml;
var systemRuntimeInterop = AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime;
var systemNumericsVectors = AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors;
// sorted by name
var keys = new string[50];
var values = new ProjectionInfo[50];
int k = 0, v = 0;
// WARNING: Keys must be sorted by name and must only contain ASCII characters. WinRTNamespace must also be ASCII only.
keys[k++] = "AttributeTargets"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeTargets, systemRuntime);
keys[k++] = "AttributeUsageAttribute"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeUsageAttribute, systemRuntime, treatment: TypeDefTreatment.RedirectedToClrAttribute);
keys[k++] = "Color"; values[v++] = new ProjectionInfo("Windows.UI", StringHandle.VirtualIndex.Windows_UI, StringHandle.VirtualIndex.Color, systemRuntimeWindowsRuntime);
keys[k++] = "CornerRadius"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.CornerRadius, systemRuntimeWindowsUiXaml);
keys[k++] = "DateTime"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.DateTimeOffset, systemRuntime);
keys[k++] = "Duration"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Duration, systemRuntimeWindowsUiXaml);
keys[k++] = "DurationType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.DurationType, systemRuntimeWindowsUiXaml);
keys[k++] = "EventHandler`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.EventHandler1, systemRuntime);
keys[k++] = "EventRegistrationToken"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, StringHandle.VirtualIndex.EventRegistrationToken, systemRuntimeInterop);
keys[k++] = "GeneratorPosition"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Controls.Primitives", StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives, StringHandle.VirtualIndex.GeneratorPosition, systemRuntimeWindowsUiXaml);
keys[k++] = "GridLength"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridLength, systemRuntimeWindowsUiXaml);
keys[k++] = "GridUnitType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridUnitType, systemRuntimeWindowsUiXaml);
keys[k++] = "HResult"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Exception, systemRuntime);
keys[k++] = "IBindableIterable"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IEnumerable, systemRuntime);
keys[k++] = "IBindableVector"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IList, systemRuntime);
keys[k++] = "IClosable"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.IDisposable, systemRuntime, isIDisposable: true);
keys[k++] = "ICommand"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Input", StringHandle.VirtualIndex.System_Windows_Input, StringHandle.VirtualIndex.ICommand, systemObjectModel);
keys[k++] = "IIterable`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IEnumerable1, systemRuntime);
keys[k++] = "IKeyValuePair`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.KeyValuePair2, systemRuntime);
keys[k++] = "IMapView`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyDictionary2, systemRuntime);
keys[k++] = "IMap`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IDictionary2, systemRuntime);
keys[k++] = "INotifyCollectionChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.INotifyCollectionChanged, systemObjectModel);
keys[k++] = "INotifyPropertyChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.INotifyPropertyChanged, systemObjectModel);
keys[k++] = "IReference`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Nullable1, systemRuntime);
keys[k++] = "IVectorView`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyList1, systemRuntime);
keys[k++] = "IVector`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IList1, systemRuntime);
keys[k++] = "KeyTime"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.KeyTime, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media", StringHandle.VirtualIndex.Windows_UI_Xaml_Media, StringHandle.VirtualIndex.Matrix, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix3D"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Media3D", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D, StringHandle.VirtualIndex.Matrix3D, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix3x2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix3x2, systemNumericsVectors);
keys[k++] = "Matrix4x4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix4x4, systemNumericsVectors);
keys[k++] = "NotifyCollectionChangedAction"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedAction, systemObjectModel);
keys[k++] = "NotifyCollectionChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs, systemObjectModel);
keys[k++] = "NotifyCollectionChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler, systemObjectModel);
keys[k++] = "Plane"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Plane, systemNumericsVectors);
keys[k++] = "Point"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Point, systemRuntimeWindowsRuntime);
keys[k++] = "PropertyChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventArgs, systemObjectModel);
keys[k++] = "PropertyChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventHandler, systemObjectModel);
keys[k++] = "Quaternion"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Quaternion, systemNumericsVectors);
keys[k++] = "Rect"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Rect, systemRuntimeWindowsRuntime);
keys[k++] = "RepeatBehavior"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehavior, systemRuntimeWindowsUiXaml);
keys[k++] = "RepeatBehaviorType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehaviorType, systemRuntimeWindowsUiXaml);
keys[k++] = "Size"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Size, systemRuntimeWindowsRuntime);
keys[k++] = "Thickness"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Thickness, systemRuntimeWindowsUiXaml);
keys[k++] = "TimeSpan"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.TimeSpan, systemRuntime);
keys[k++] = "TypeName"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Type, systemRuntime);
keys[k++] = "Uri"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Uri, systemRuntime);
keys[k++] = "Vector2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector2, systemNumericsVectors);
keys[k++] = "Vector3"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector3, systemNumericsVectors);
keys[k++] = "Vector4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector4, systemNumericsVectors);
Debug.Assert(k == keys.Length && v == keys.Length && k == v);
AssertSorted(keys);
s_projectedTypeNames = keys;
s_projectionInfos = values;
}
}
[Conditional("DEBUG")]
private static void AssertSorted(string[] keys)
{
for (int i = 0; i < keys.Length - 1; i++)
{
Debug.Assert(String.CompareOrdinal(keys[i], keys[i + 1]) < 0);
}
}
// test only
internal static string[] GetProjectedTypeNames()
{
InitializeProjectedTypes();
return s_projectedTypeNames;
}
#endregion
private static uint TreatmentAndRowId(byte treatment, int rowId)
{
return ((uint)treatment << TokenTypeIds.RowIdBitCount) | (uint)rowId;
}
#region TypeDef
[MethodImpl(MethodImplOptions.NoInlining)]
internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
TypeDefTreatment treatment;
TypeAttributes flags = TypeDefTable.GetFlags(handle);
EntityHandle extends = TypeDefTable.GetExtends(handle);
if ((flags & TypeAttributes.WindowsRuntime) != 0)
{
if (_metadataKind == MetadataKind.WindowsMetadata)
{
treatment = GetWellKnownTypeDefinitionTreatment(handle);
if (treatment != TypeDefTreatment.None)
{
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
// Is this an attribute?
if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends))
{
treatment = TypeDefTreatment.NormalAttribute;
}
else
{
treatment = TypeDefTreatment.NormalNonAttribute;
}
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends))
{
// WinMDExp emits two versions of RuntimeClasses and Enums:
//
// public class Foo {} // the WinRT reference class
// internal class <CLR>Foo {} // the implementation class that we want WinRT consumers to ignore
//
// The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into:
//
// internal class <WinRT>Foo {} // the WinRT reference class that we want CLR consumers to ignore
// public class Foo {} // the implementation class
//
// We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime
// De-mangling the CLR name is done below.
// tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version
// not marked with tdSpecialName. These enums should *not* be mangled and flipped to private.
// We don't implement this flag since the WinMDs producted by the older WinMDExp are not used in the wild.
treatment = TypeDefTreatment.PrefixWinRTName;
}
else
{
treatment = TypeDefTreatment.None;
}
// Scan through Custom Attributes on type, looking for interesting bits. We only
// need to do this for RuntimeClasses
if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute))
{
if ((flags & TypeAttributes.Interface) == 0
&& HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute"))
{
treatment |= TypeDefTreatment.MarkAbstractFlag;
}
}
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle))
{
// <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified
// by the adapter.
treatment = TypeDefTreatment.UnmangleWinRTName;
}
else
{
treatment = TypeDefTreatment.None;
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
private bool IsClrImplementationType(TypeDefinitionHandle typeDef)
{
var attrs = TypeDefTable.GetFlags(typeDef);
if ((attrs & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName)
{
return false;
}
return StringStream.StartsWithRaw(TypeDefTable.GetName(typeDef), ClrPrefix);
}
#endregion
#region TypeRef
internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
bool isIDisposable;
int projectionIndex = GetProjectionIndexForTypeReference(handle, out isIDisposable);
if (projectionIndex >= 0)
{
return TreatmentAndRowId((byte)TypeRefTreatment.UseProjectionInfo, projectionIndex);
}
else
{
return TreatmentAndRowId((byte)GetSpecialTypeRefTreatment(handle), handle.RowId);
}
}
private TypeRefTreatment GetSpecialTypeRefTreatment(TypeReferenceHandle handle)
{
if (StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System"))
{
StringHandle name = TypeRefTable.GetName(handle);
if (StringStream.EqualsRaw(name, "MulticastDelegate"))
{
return TypeRefTreatment.SystemDelegate;
}
if (StringStream.EqualsRaw(name, "Attribute"))
{
return TypeRefTreatment.SystemAttribute;
}
}
return TypeRefTreatment.None;
}
private bool IsSystemAttribute(TypeReferenceHandle handle)
{
return StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") &&
StringStream.EqualsRaw(TypeRefTable.GetName(handle), "Attribute");
}
private bool IsSystemEnum(TypeReferenceHandle handle)
{
return StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") &&
StringStream.EqualsRaw(TypeRefTable.GetName(handle), "Enum");
}
private bool NeedsWinRTPrefix(TypeAttributes flags, EntityHandle extends)
{
if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.Interface)) != TypeAttributes.Public)
{
return false;
}
if (extends.Kind != HandleKind.TypeReference)
{
return false;
}
// Check if the type is a delegate, struct, or attribute
TypeReferenceHandle extendsRefHandle = (TypeReferenceHandle)extends;
if (StringStream.EqualsRaw(TypeRefTable.GetNamespace(extendsRefHandle), "System"))
{
StringHandle nameHandle = TypeRefTable.GetName(extendsRefHandle);
if (StringStream.EqualsRaw(nameHandle, "MulticastDelegate")
|| StringStream.EqualsRaw(nameHandle, "ValueType")
|| StringStream.EqualsRaw(nameHandle, "Attribute"))
{
return false;
}
}
return true;
}
#endregion
#region MethodDef
private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef)
{
MethodDefTreatment treatment = MethodDefTreatment.Implementation;
TypeDefinitionHandle parentTypeDef = GetDeclaringType(methodDef);
TypeAttributes parentFlags = TypeDefTable.GetFlags(parentTypeDef);
if ((parentFlags & TypeAttributes.WindowsRuntime) != 0)
{
if (IsClrImplementationType(parentTypeDef))
{
treatment = MethodDefTreatment.Implementation;
}
else if (parentFlags.IsNested())
{
treatment = MethodDefTreatment.Implementation;
}
else if ((parentFlags & TypeAttributes.Interface) != 0)
{
treatment = MethodDefTreatment.InterfaceMethod;
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && (parentFlags & TypeAttributes.Public) == 0)
{
treatment = MethodDefTreatment.Implementation;
}
else
{
treatment = MethodDefTreatment.Other;
var parentBaseType = TypeDefTable.GetExtends(parentTypeDef);
if (parentBaseType.Kind == HandleKind.TypeReference)
{
switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)parentBaseType))
{
case TypeRefTreatment.SystemAttribute:
treatment = MethodDefTreatment.AttributeMethod;
break;
case TypeRefTreatment.SystemDelegate:
treatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag;
break;
}
}
}
}
if (treatment == MethodDefTreatment.Other)
{
// we want to hide the method if it implements
// only redirected interfaces
// We also want to check if the methodImpl is IClosable.Close,
// so we can change the name
bool seenRedirectedInterfaces = false;
bool seenNonRedirectedInterfaces = false;
bool isIClosableClose = false;
foreach (var methodImplHandle in new MethodImplementationHandleCollection(this, parentTypeDef))
{
MethodImplementation methodImpl = GetMethodImplementation(methodImplHandle);
if (methodImpl.MethodBody == methodDef)
{
EntityHandle declaration = methodImpl.MethodDeclaration;
// See if this MethodImpl implements a redirected interface
// In WinMD, MethodImpl will always use MemberRef and TypeRefs to refer to redirected interfaces,
// even if they are in the same module.
if (declaration.Kind == HandleKind.MemberReference &&
ImplementsRedirectedInterface((MemberReferenceHandle)declaration, out isIClosableClose))
{
seenRedirectedInterfaces = true;
if (isIClosableClose)
{
// This method implements IClosable.Close
// Let's rename to IDisposable later
// Once we know this implements IClosable.Close, we are done
// looking
break;
}
}
else
{
// Now we know this implements a non-redirected interface
// But we need to keep looking, just in case we got a methodimpl that
// implements the IClosable.Close method and needs to be renamed
seenNonRedirectedInterfaces = true;
}
}
}
if (isIClosableClose)
{
treatment = MethodDefTreatment.DisposeMethod;
}
else if (seenRedirectedInterfaces && !seenNonRedirectedInterfaces)
{
// Only hide if all the interfaces implemented are redirected
treatment = MethodDefTreatment.HiddenInterfaceImplementation;
}
}
// If treatment is other, then this is a non-managed WinRT runtime class definition
// Find out about various bits that we apply via attributes and name parsing
if (treatment == MethodDefTreatment.Other)
{
treatment |= GetMethodTreatmentFromCustomAttributes(methodDef);
}
return TreatmentAndRowId((byte)treatment, methodDef.RowId);
}
private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodDefinitionHandle methodDef)
{
MethodDefTreatment treatment = 0;
foreach (var caHandle in GetCustomAttributes(methodDef))
{
StringHandle namespaceHandle, nameHandle;
if (!GetAttributeTypeNameRaw(caHandle, out namespaceHandle, out nameHandle))
{
continue;
}
Debug.Assert(!namespaceHandle.IsVirtual && !nameHandle.IsVirtual);
if (StringStream.EqualsRaw(namespaceHandle, "Windows.UI.Xaml"))
{
if (StringStream.EqualsRaw(nameHandle, "TreatAsPublicMethodAttribute"))
{
treatment |= MethodDefTreatment.MarkPublicFlag;
}
if (StringStream.EqualsRaw(nameHandle, "TreatAsAbstractMethodAttribute"))
{
treatment |= MethodDefTreatment.MarkAbstractFlag;
}
}
}
return treatment;
}
#endregion
#region FieldDef
/// <summary>
/// The backing field of a WinRT enumeration type is not public although the backing fields
/// of managed enumerations are. To allow managed languages to directly access this field,
/// it is made public by the metadata adapter.
/// </summary>
private uint CalculateFieldDefTreatmentAndRowId(FieldDefinitionHandle handle)
{
var flags = FieldTable.GetFlags(handle);
FieldDefTreatment treatment = FieldDefTreatment.None;
if ((flags & FieldAttributes.RTSpecialName) != 0 && StringStream.EqualsRaw(FieldTable.GetName(handle), "value__"))
{
TypeDefinitionHandle typeDef = GetDeclaringType(handle);
EntityHandle baseTypeHandle = TypeDefTable.GetExtends(typeDef);
if (baseTypeHandle.Kind == HandleKind.TypeReference)
{
var typeRef = (TypeReferenceHandle)baseTypeHandle;
if (StringStream.EqualsRaw(TypeRefTable.GetName(typeRef), "Enum") &&
StringStream.EqualsRaw(TypeRefTable.GetNamespace(typeRef), "System"))
{
treatment = FieldDefTreatment.EnumValue;
}
}
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
#endregion
#region MemberRef
private uint CalculateMemberRefTreatmentAndRowId(MemberReferenceHandle handle)
{
MemberRefTreatment treatment;
// We need to rename the MemberRef for IClosable.Close as well
// so that the MethodImpl for the Dispose method can be correctly shown
// as IDisposable.Dispose instead of IDisposable.Close
bool isIDisposable;
if (ImplementsRedirectedInterface(handle, out isIDisposable) && isIDisposable)
{
treatment = MemberRefTreatment.Dispose;
}
else
{
treatment = MemberRefTreatment.None;
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
/// <summary>
/// We want to know if a given method implements a redirected interface.
/// For example, if we are given the method RemoveAt on a class "A"
/// which implements the IVector interface (which is redirected
/// to IList in .NET) then this method would return true. The most
/// likely reason why we would want to know this is that we wish to hide
/// (mark private) all methods which implement methods on a redirected
/// interface.
/// </summary>
/// <param name="memberRef">The declaration token for the method</param>
/// <param name="isIDisposable">
/// Returns true if the redirected interface is <see cref="IDisposable"/>.
/// </param>
/// <returns>True if the method implements a method on a redirected interface.
/// False otherwise.</returns>
private bool ImplementsRedirectedInterface(MemberReferenceHandle memberRef, out bool isIDisposable)
{
isIDisposable = false;
EntityHandle parent = MemberRefTable.GetClass(memberRef);
TypeReferenceHandle typeRef;
if (parent.Kind == HandleKind.TypeReference)
{
typeRef = (TypeReferenceHandle)parent;
}
else if (parent.Kind == HandleKind.TypeSpecification)
{
BlobHandle blob = TypeSpecTable.GetSignature((TypeSpecificationHandle)parent);
BlobReader sig = BlobStream.GetBlobReader(blob);
if (sig.Length < 2 ||
sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_GENERICINST ||
sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_CLASS)
{
return false;
}
EntityHandle token = sig.ReadTypeHandle();
if (token.Kind != HandleKind.TypeReference)
{
return false;
}
typeRef = (TypeReferenceHandle)token;
}
else
{
return false;
}
return GetProjectionIndexForTypeReference(typeRef, out isIDisposable) >= 0;
}
#endregion
#region AssemblyRef
private int FindMscorlibAssemblyRefNoProjection()
{
for (int i = 1; i <= AssemblyRefTable.NumberOfNonVirtualRows; i++)
{
if (StringStream.EqualsRaw(AssemblyRefTable.GetName(i), "mscorlib"))
{
return i;
}
}
throw new BadImageFormatException(SR.WinMDMissingMscorlibRef);
}
#endregion
#region CustomAttribute
internal CustomAttributeValueTreatment CalculateCustomAttributeValueTreatment(CustomAttributeHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
var parent = CustomAttributeTable.GetParent(handle);
// Check for Windows.Foundation.Metadata.AttributeUsageAttribute.
// WinMD rules:
// - The attribute is only applicable on TypeDefs.
// - Constructor must be a MemberRef with TypeRef.
if (!IsWindowsAttributeUsageAttribute(parent, handle))
{
return CustomAttributeValueTreatment.None;
}
var targetTypeDef = (TypeDefinitionHandle)parent;
if (StringStream.EqualsRaw(TypeDefTable.GetNamespace(targetTypeDef), "Windows.Foundation.Metadata"))
{
if (StringStream.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "VersionAttribute"))
{
return CustomAttributeValueTreatment.AttributeUsageVersionAttribute;
}
if (StringStream.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "DeprecatedAttribute"))
{
return CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute;
}
}
bool allowMultiple = HasAttribute(targetTypeDef, "Windows.Foundation.Metadata", "AllowMultipleAttribute");
return allowMultiple ? CustomAttributeValueTreatment.AttributeUsageAllowMultiple : CustomAttributeValueTreatment.AttributeUsageAllowSingle;
}
private bool IsWindowsAttributeUsageAttribute(EntityHandle targetType, CustomAttributeHandle attributeHandle)
{
// Check for Windows.Foundation.Metadata.AttributeUsageAttribute.
// WinMD rules:
// - The attribute is only applicable on TypeDefs.
// - Constructor must be a MemberRef with TypeRef.
if (targetType.Kind != HandleKind.TypeDefinition)
{
return false;
}
var attributeCtor = CustomAttributeTable.GetConstructor(attributeHandle);
if (attributeCtor.Kind != HandleKind.MemberReference)
{
return false;
}
var attributeType = MemberRefTable.GetClass((MemberReferenceHandle)attributeCtor);
if (attributeType.Kind != HandleKind.TypeReference)
{
return false;
}
var attributeTypeRef = (TypeReferenceHandle)attributeType;
return StringStream.EqualsRaw(TypeRefTable.GetName(attributeTypeRef), "AttributeUsageAttribute") &&
StringStream.EqualsRaw(TypeRefTable.GetNamespace(attributeTypeRef), "Windows.Foundation.Metadata");
}
private bool HasAttribute(EntityHandle token, string asciiNamespaceName, string asciiTypeName)
{
foreach (var caHandle in GetCustomAttributes(token))
{
StringHandle namespaceName, typeName;
if (GetAttributeTypeNameRaw(caHandle, out namespaceName, out typeName) &&
StringStream.EqualsRaw(typeName, asciiTypeName) &&
StringStream.EqualsRaw(namespaceName, asciiNamespaceName))
{
return true;
}
}
return false;
}
private bool GetAttributeTypeNameRaw(CustomAttributeHandle caHandle, out StringHandle namespaceName, out StringHandle typeName)
{
namespaceName = typeName = default(StringHandle);
EntityHandle typeDefOrRef = GetAttributeTypeRaw(caHandle);
if (typeDefOrRef.IsNil)
{
return false;
}
if (typeDefOrRef.Kind == HandleKind.TypeReference)
{
TypeReferenceHandle typeRef = (TypeReferenceHandle)typeDefOrRef;
var resolutionScope = TypeRefTable.GetResolutionScope(typeRef);
if (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference)
{
// we don't need to handle nested types
return false;
}
// other resolution scopes don't affect full name
typeName = TypeRefTable.GetName(typeRef);
namespaceName = TypeRefTable.GetNamespace(typeRef);
}
else if (typeDefOrRef.Kind == HandleKind.TypeDefinition)
{
TypeDefinitionHandle typeDef = (TypeDefinitionHandle)typeDefOrRef;
if (TypeDefTable.GetFlags(typeDef).IsNested())
{
// we don't need to handle nested types
return false;
}
typeName = TypeDefTable.GetName(typeDef);
namespaceName = TypeDefTable.GetNamespace(typeDef);
}
else
{
// invalid metadata
return false;
}
return true;
}
/// <summary>
/// Returns the type definition or reference handle of the attribute type.
/// </summary>
/// <returns><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/> or nil token if the metadata is invalid and the type can't be determined.</returns>
private EntityHandle GetAttributeTypeRaw(CustomAttributeHandle handle)
{
var ctor = CustomAttributeTable.GetConstructor(handle);
if (ctor.Kind == HandleKind.MethodDefinition)
{
return GetDeclaringType((MethodDefinitionHandle)ctor);
}
if (ctor.Kind == HandleKind.MemberReference)
{
// In general the parent can be MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec.
// For attributes only TypeDef and TypeRef are applicable.
EntityHandle typeDefOrRef = MemberRefTable.GetClass((MemberReferenceHandle)ctor);
HandleKind handleType = typeDefOrRef.Kind;
if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition)
{
return typeDefOrRef;
}
}
return default(EntityHandle);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs
{
/// <summary>
/// Packets for SmbTransaction Request
/// </summary>
public abstract class SmbTransactionRequestPacket : SmbSingleRequestPacket
{
#region Fields
/// <summary>
/// the SMB_Parameters
/// </summary>
protected SMB_COM_TRANSACTION_Request_SMB_Parameters smbParameters;
/// <summary>
/// the SMB_Data
/// </summary>
protected SMB_COM_TRANSACTION_Request_SMB_Data smbData;
/// <summary>
/// Specify whether the packet is sent out with following secondary packets.
/// </summary>
internal bool isDivided;
private const int padLength = 1;
#endregion
#region Properties
/// <summary>
/// get or set the Smb_Parameters:SMB_COM_TRANSACTION_Request_SMB_Parameters
/// </summary>
public virtual SMB_COM_TRANSACTION_Request_SMB_Parameters SmbParameters
{
get
{
return this.smbParameters;
}
set
{
this.smbParameters = value;
}
}
/// <summary>
/// get or set the Smb_Data:SMB_COM_TRANSACTION_Request_SMB_Data
/// </summary>
public SMB_COM_TRANSACTION_Request_SMB_Data SmbData
{
get
{
return this.smbData;
}
set
{
this.smbData = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
protected SmbTransactionRequestPacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
protected SmbTransactionRequestPacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
protected SmbTransactionRequestPacket(SmbTransactionRequestPacket packet)
: base(packet)
{
this.InitDefaultValue();
this.smbParameters.WordCount = packet.SmbParameters.WordCount;
this.smbParameters.TotalParameterCount = packet.SmbParameters.TotalParameterCount;
this.smbParameters.TotalDataCount = packet.SmbParameters.TotalDataCount;
this.smbParameters.MaxParameterCount = packet.SmbParameters.MaxParameterCount;
this.smbParameters.MaxDataCount = packet.SmbParameters.MaxDataCount;
this.smbParameters.MaxSetupCount = packet.SmbParameters.MaxSetupCount;
this.smbParameters.Reserved1 = packet.SmbParameters.Reserved1;
this.smbParameters.Flags = packet.SmbParameters.Flags;
this.smbParameters.Timeout = packet.SmbParameters.Timeout;
this.smbParameters.Reserved2 = packet.SmbParameters.Reserved2;
this.smbParameters.ParameterCount = packet.SmbParameters.ParameterCount;
this.smbParameters.ParameterOffset = packet.SmbParameters.ParameterOffset;
this.smbParameters.DataCount = packet.SmbParameters.DataCount;
this.smbParameters.DataOffset = packet.SmbParameters.DataOffset;
this.smbParameters.SetupCount = packet.SmbParameters.SetupCount;
this.smbParameters.Reserved3 = packet.SmbParameters.Reserved3;
if (packet.smbParameters.Setup != null)
{
this.smbParameters.Setup = new ushort[packet.smbParameters.Setup.Length];
Array.Copy(packet.smbParameters.Setup, this.smbParameters.Setup, packet.smbParameters.Setup.Length);
}
else
{
this.smbParameters.Setup = new ushort[0];
}
this.smbData.ByteCount = packet.SmbData.ByteCount;
this.smbData.Name = packet.SmbData.Name;
if (packet.smbData.Pad1 != null)
{
this.smbData.Pad1 = new byte[packet.smbData.Pad1.Length];
Array.Copy(packet.smbData.Pad1, this.smbData.Pad1, packet.smbData.Pad1.Length);
}
else
{
this.smbData.Pad1 = new byte[0];
}
if (packet.smbData.Trans_Parameters != null)
{
this.smbData.Trans_Parameters = new byte[packet.smbData.Trans_Parameters.Length];
Array.Copy(packet.smbData.Trans_Parameters,
this.smbData.Trans_Parameters, packet.smbData.Trans_Parameters.Length);
}
else
{
this.smbData.Trans_Parameters = new byte[0];
}
if (packet.smbData.Pad2 != null)
{
this.smbData.Pad2 = new byte[packet.smbData.Pad2.Length];
Array.Copy(packet.smbData.Pad2, this.smbData.Pad2, packet.smbData.Pad2.Length);
}
else
{
this.smbData.Pad2 = new byte[0];
}
if (packet.smbData.Trans_Data != null)
{
this.smbData.Trans_Data = new byte[packet.smbData.Trans_Data.Length];
Array.Copy(packet.smbData.Trans_Data, this.smbData.Trans_Data, packet.smbData.Trans_Data.Length);
}
else
{
this.smbData.Trans_Data = new byte[0];
}
}
#endregion
#region Methods
/// <summary>
/// to update fields about size and offset automatly.
/// </summary>
public void UpdateCountAndOffset()
{
if (!this.isDivided)
{
this.EncodeTransParameters();
this.EncodeTransData();
}
int byteCount = 0;
if (this.smbData.Name != null)
{
byteCount = (this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE ?
this.smbData.Name.Length + padLength : this.smbData.Name.Length;
}
if (this.smbData.Trans_Parameters != null)
{
this.smbParameters.ParameterCount = (ushort)smbData.Trans_Parameters.Length;
byteCount += this.smbData.Trans_Parameters.Length;
if (!this.isDivided)
{
this.smbParameters.TotalParameterCount = (ushort)smbData.Trans_Parameters.Length;
}
}
this.smbParameters.ParameterOffset = (ushort)(this.HeaderSize + this.smbParameters.WordCount * 2
+ SmbComTransactionPacket.SmbParametersWordCountLength + SmbComTransactionPacket.SmbDataByteCountLength
+ this.smbData.Name.Length);
// add the padding bytes, padding for Name.
if ((this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE)
{
this.smbParameters.ParameterOffset += padLength;
}
if (this.smbData.Pad1 != null)
{
this.smbParameters.ParameterOffset += (ushort)this.smbData.Pad1.Length;
byteCount += this.smbData.Pad1.Length;
}
if (this.smbData.Trans_Data != null)
{
this.smbParameters.DataCount = (ushort)this.smbData.Trans_Data.Length;
byteCount += this.smbData.Trans_Data.Length;
if (!this.isDivided)
{
this.smbParameters.TotalDataCount = (ushort)this.smbData.Trans_Data.Length;
}
}
this.smbParameters.DataOffset = (ushort)(this.smbParameters.ParameterOffset +
this.smbParameters.ParameterCount);
if (this.smbData.Pad2 != null)
{
this.smbParameters.DataOffset += (ushort)this.smbData.Pad2.Length;
byteCount += this.smbData.Pad2.Length;
}
this.smbData.ByteCount = (ushort)byteCount;
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this.</returns>
public override abstract StackPacket Clone();
/// <summary>
/// Encode the struct of SMB_COM_TRANSACTION_Request_SMB_Parameters into the struct of SmbParameters
/// Update Smb Parameters
/// </summary>
protected override void EncodeParameters()
{
this.smbParametersBlock = TypeMarshal.ToStruct<SmbParameters>(
CifsMessageUtils.ToBytes<SMB_COM_TRANSACTION_Request_SMB_Parameters>(this.smbParameters));
}
/// <summary>
/// Encode the struct of SMB_COM_TRANSACTION_Request_SMB_Data into the struct of SmbData
/// Update Smb Data
/// </summary>
protected override void EncodeData()
{
if (!isDivided)
{
this.EncodeTransParameters();
this.EncodeTransData();
}
int byteCount = 0;
if (this.smbData.Name != null)
{
byteCount = (this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE ?
this.smbData.Name.Length + padLength : this.smbData.Name.Length;
}
if (this.smbData.Pad1 != null)
{
byteCount += this.smbData.Pad1.Length;
}
if (this.smbData.Trans_Parameters != null)
{
byteCount += this.smbData.Trans_Parameters.Length;
}
if (this.smbData.Pad2 != null)
{
byteCount += this.smbData.Pad2.Length;
}
if (this.smbData.Trans_Data != null)
{
byteCount += this.smbData.Trans_Data.Length;
}
this.smbDataBlock.ByteCount = this.SmbData.ByteCount;
this.smbDataBlock.Bytes = new byte[byteCount];
using (MemoryStream memoryStream = new MemoryStream(this.smbDataBlock.Bytes))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
if ((this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE)
{
byte padding = 0;
channel.Write<byte>(padding);
}
if (this.SmbData.Name != null)
{
channel.WriteBytes(this.SmbData.Name);
}
if (this.SmbData.Pad1 != null)
{
channel.WriteBytes(this.SmbData.Pad1);
}
if (this.SmbData.Trans_Parameters != null)
{
channel.WriteBytes(this.SmbData.Trans_Parameters);
}
if (this.SmbData.Pad2 != null)
{
channel.WriteBytes(this.SmbData.Pad2);
}
if (this.SmbData.Trans_Data != null)
{
channel.WriteBytes(this.SmbData.Trans_Data);
}
channel.EndWriteGroup();
}
}
}
/// <summary>
/// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters.
/// </summary>
protected override void DecodeParameters()
{
this.smbParameters = TypeMarshal.ToStruct<SMB_COM_TRANSACTION_Request_SMB_Parameters>(
TypeMarshal.ToBytes(this.smbParametersBlock));
}
/// <summary>
/// to decode the smb data: from the general SmbDada to the concrete Smb Data.
/// </summary>
protected override void DecodeData()
{
this.smbData = new SMB_COM_TRANSACTION_Request_SMB_Data();
using (MemoryStream memoryStream = new MemoryStream(CifsMessageUtils.ToBytes<SmbData>(this.smbDataBlock)))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.smbData.ByteCount = channel.Read<ushort>();
bool isUnicode = (this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE;
if (isUnicode)
{
byte padLength = 1;
channel.ReadBytes(padLength);
List<ushort> array = new List<ushort>();
ushort letter;
do
{
letter = channel.Read<ushort>();
array.Add(letter);
}
while (letter != new ushort());
this.smbData.Name = CifsMessageUtils.ToBytesArray(array.ToArray());
}
else
{
List<byte> array = new List<byte>();
byte letter;
do
{
letter = channel.Read<byte>();
array.Add(letter);
}
while (letter != new byte());
this.smbData.Name = array.ToArray();
}
// the padding length of Pad1.
int pad1Length = this.smbParameters.ParameterOffset - this.HeaderSize
- this.smbParameters.WordCount * 2 - SmbComTransactionPacket.SmbParametersWordCountLength
- SmbComTransactionPacket.SmbDataByteCountLength - this.smbData.Name.Length;
// sub the padding bytes for Name.
if (isUnicode)
{
pad1Length -= 1;
}
// read Pad1 from channel.
if (pad1Length > 0)
{
this.smbData.Pad1 = channel.ReadBytes(pad1Length);
}
this.smbData.Trans_Parameters = channel.ReadBytes(this.smbParameters.ParameterCount);
if (this.smbParameters.DataOffset > 0)
{
this.smbData.Pad2 = channel.ReadBytes(this.smbParameters.DataOffset
- this.smbParameters.ParameterOffset - this.smbParameters.ParameterCount);
this.smbData.Trans_Data = channel.ReadBytes(this.smbParameters.DataCount);
}
else
{
this.smbData.Pad2 = new byte[0];
this.smbData.Trans_Data = new byte[0];
}
}
}
this.DecodeTransParameters();
this.DecodeTransData();
}
/// <summary>
/// Encode the struct of TransParameters into the byte array in SmbData.Trans_Parameters
/// </summary>
protected abstract void EncodeTransParameters();
/// <summary>
/// Encode the struct of TransData into the byte array in SmbData.Trans_Data
/// </summary>
protected abstract void EncodeTransData();
/// <summary>
/// to decode the Trans parameters: from the general TransParameters to the concrete Trans Parameters.
/// </summary>
protected abstract void DecodeTransParameters();
/// <summary>
/// to decode the Trans data: from the general TransDada to the concrete Trans Data.
/// </summary>
protected abstract void DecodeTransData();
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
this.smbData.Name = new byte[0];
this.smbData.Pad1 = new byte[0];
this.smbData.Pad2 = new byte[0];
this.smbData.Trans_Data = new byte[0];
this.smbData.Trans_Parameters = new byte[0];
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class SocketAsyncEventArgsTest
{
[Fact]
public void Usertoken_Roundtrips()
{
using (var args = new SocketAsyncEventArgs())
{
object o = new object();
Assert.Null(args.UserToken);
args.UserToken = o;
Assert.Same(o, args.UserToken);
}
}
[Fact]
public void SocketFlags_Roundtrips()
{
using (var args = new SocketAsyncEventArgs())
{
Assert.Equal(SocketFlags.None, args.SocketFlags);
args.SocketFlags = SocketFlags.Broadcast;
Assert.Equal(SocketFlags.Broadcast, args.SocketFlags);
}
}
[Fact]
public void SendPacketsSendSize_Roundtrips()
{
using (var args = new SocketAsyncEventArgs())
{
Assert.Equal(0, args.SendPacketsSendSize);
args.SendPacketsSendSize = 4;
Assert.Equal(4, args.SendPacketsSendSize);
}
}
[Fact]
public void SendPacketsFlags_Roundtrips()
{
using (var args = new SocketAsyncEventArgs())
{
Assert.Equal((TransmitFileOptions)0, args.SendPacketsFlags);
args.SendPacketsFlags = TransmitFileOptions.UseDefaultWorkerThread;
Assert.Equal(TransmitFileOptions.UseDefaultWorkerThread, args.SendPacketsFlags);
}
}
[Fact]
public void Dispose_MultipleCalls_Success()
{
using (var args = new SocketAsyncEventArgs())
{
args.Dispose();
}
}
[Fact]
public async Task Dispose_WhileInUse_DisposeDelayed()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
using (var receiveSaea = new SocketAsyncEventArgs())
{
var tcs = new TaskCompletionSource<bool>();
receiveSaea.SetBuffer(new byte[1], 0, 1);
receiveSaea.Completed += delegate { tcs.SetResult(true); };
Assert.True(client.ReceiveAsync(receiveSaea));
Assert.Throws<InvalidOperationException>(() => client.ReceiveAsync(receiveSaea)); // already in progress
receiveSaea.Dispose();
server.Send(new byte[1]);
await tcs.Task; // completes successfully even though it was disposed
Assert.Throws<ObjectDisposedException>(() => client.ReceiveAsync(receiveSaea));
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ExecutionContext_FlowsIfNotSuppressed(bool suppressed)
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
using (var receiveSaea = new SocketAsyncEventArgs())
{
if (suppressed)
{
ExecutionContext.SuppressFlow();
}
var local = new AsyncLocal<int>();
local.Value = 42;
int threadId = Environment.CurrentManagedThreadId;
var mres = new ManualResetEventSlim();
receiveSaea.SetBuffer(new byte[1], 0, 1);
receiveSaea.Completed += delegate
{
Assert.NotEqual(threadId, Environment.CurrentManagedThreadId);
Assert.Equal(suppressed ? 0 : 42, local.Value);
mres.Set();
};
Assert.True(client.ReceiveAsync(receiveSaea));
server.Send(new byte[1]);
mres.Wait();
}
}
}
[Fact]
public void SetBuffer_InvalidArgs_Throws()
{
using (var saea = new SocketAsyncEventArgs())
{
Assert.Throws<ArgumentOutOfRangeException>("offset", () => saea.SetBuffer(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => saea.SetBuffer(new byte[1], 2, 0));
Assert.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 0, 2));
Assert.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 1, 2));
}
}
[Fact]
public void SetBufferListWhenBufferSet_Throws()
{
using (var saea = new SocketAsyncEventArgs())
{
var bufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
byte[] buffer = new byte[1];
saea.SetBuffer(buffer, 0, 1);
Assert.Throws<ArgumentException>(() => saea.BufferList = bufferList);
Assert.Same(buffer, saea.Buffer);
Assert.Null(saea.BufferList);
saea.SetBuffer(null, 0, 0);
saea.BufferList = bufferList; // works fine when Buffer has been set back to null
}
}
[Fact]
public void SetBufferWhenBufferListSet_Throws()
{
using (var saea = new SocketAsyncEventArgs())
{
var bufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
saea.BufferList = bufferList;
Assert.Throws<ArgumentException>(() => saea.SetBuffer(new byte[1], 0, 1));
Assert.Same(bufferList, saea.BufferList);
Assert.Null(saea.Buffer);
saea.BufferList = null;
saea.SetBuffer(new byte[1], 0, 1); // works fine when BufferList has been set back to null
}
}
[Fact]
public void SetBufferListWhenBufferListSet_Succeeds()
{
using (var saea = new SocketAsyncEventArgs())
{
Assert.Null(saea.BufferList);
saea.BufferList = null;
Assert.Null(saea.BufferList);
var bufferList1 = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
saea.BufferList = bufferList1;
Assert.Same(bufferList1, saea.BufferList);
saea.BufferList = bufferList1;
Assert.Same(bufferList1, saea.BufferList);
var bufferList2 = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
saea.BufferList = bufferList2;
Assert.Same(bufferList2, saea.BufferList);
}
}
[Fact]
public void SetBufferWhenBufferSet_Succeeds()
{
using (var saea = new SocketAsyncEventArgs())
{
byte[] buffer1 = new byte[1];
saea.SetBuffer(buffer1, 0, buffer1.Length);
Assert.Same(buffer1, saea.Buffer);
saea.SetBuffer(buffer1, 0, buffer1.Length);
Assert.Same(buffer1, saea.Buffer);
byte[] buffer2 = new byte[1];
saea.SetBuffer(buffer2, 0, buffer1.Length);
Assert.Same(buffer2, saea.Buffer);
}
}
[Fact]
public async Task Completed_RegisterThenInvoked_UnregisterThenNotInvoked()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
using (var receiveSaea = new SocketAsyncEventArgs())
{
receiveSaea.SetBuffer(new byte[1], 0, 1);
TaskCompletionSource<bool> tcs1 = null, tcs2 = null;
EventHandler<SocketAsyncEventArgs> handler1 = (_, __) => tcs1.SetResult(true);
EventHandler<SocketAsyncEventArgs> handler2 = (_, __) => tcs2.SetResult(true);
receiveSaea.Completed += handler2;
receiveSaea.Completed += handler1;
tcs1 = new TaskCompletionSource<bool>();
tcs2 = new TaskCompletionSource<bool>();
Assert.True(client.ReceiveAsync(receiveSaea));
server.Send(new byte[1]);
await Task.WhenAll(tcs1.Task, tcs2.Task);
receiveSaea.Completed -= handler2;
tcs1 = new TaskCompletionSource<bool>();
tcs2 = new TaskCompletionSource<bool>();
Assert.True(client.ReceiveAsync(receiveSaea));
server.Send(new byte[1]);
await tcs1.Task;
Assert.False(tcs2.Task.IsCompleted);
}
}
}
[Fact]
public void CancelConnectAsync_InstanceConnect_CancelsInProgressConnect()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
using (var connectSaea = new SocketAsyncEventArgs())
{
var tcs = new TaskCompletionSource<SocketError>();
connectSaea.Completed += (s, e) => tcs.SetResult(e.SocketError);
connectSaea.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port);
Assert.True(client.ConnectAsync(connectSaea), $"ConnectAsync completed synchronously with SocketError == {connectSaea.SocketError}");
if (tcs.Task.IsCompleted)
{
Assert.NotEqual(SocketError.Success, tcs.Task.Result);
}
Socket.CancelConnectAsync(connectSaea);
Assert.False(client.Connected, "Expected Connected to be false");
}
}
}
[Fact]
public void CancelConnectAsync_StaticConnect_CancelsInProgressConnect()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
using (var connectSaea = new SocketAsyncEventArgs())
{
var tcs = new TaskCompletionSource<SocketError>();
connectSaea.Completed += (s, e) => tcs.SetResult(e.SocketError);
connectSaea.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port);
Assert.True(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, connectSaea), $"ConnectAsync completed synchronously with SocketError == {connectSaea.SocketError}");
if (tcs.Task.IsCompleted)
{
Assert.NotEqual(SocketError.Success, tcs.Task.Result);
}
Socket.CancelConnectAsync(connectSaea);
}
}
}
[Fact]
public async Task ReuseSocketAsyncEventArgs_SameInstance_MultipleSockets()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
TaskCompletionSource<bool> tcs = null;
var args = new SocketAsyncEventArgs();
args.SetBuffer(new byte[1024], 0, 1024);
args.Completed += (_,__) => tcs.SetResult(true);
for (int i = 1; i <= 10; i++)
{
tcs = new TaskCompletionSource<bool>();
args.Buffer[0] = (byte)i;
args.SetBuffer(0, 1);
if (server.SendAsync(args))
{
await tcs.Task;
}
args.Buffer[0] = 0;
tcs = new TaskCompletionSource<bool>();
if (client.ReceiveAsync(args))
{
await tcs.Task;
}
Assert.Equal(1, args.BytesTransferred);
Assert.Equal(i, args.Buffer[0]);
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task ReuseSocketAsyncEventArgs_MutateBufferList()
{
using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listen.Listen(1);
Task<Socket> acceptTask = listen.AcceptAsync();
await Task.WhenAll(
acceptTask,
client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
TaskCompletionSource<bool> tcs = null;
var sendBuffer = new byte[64];
var sendBufferList = new List<ArraySegment<byte>>();
sendBufferList.Add(new ArraySegment<byte>(sendBuffer, 0, 1));
var sendArgs = new SocketAsyncEventArgs();
sendArgs.BufferList = sendBufferList;
sendArgs.Completed += (_,__) => tcs.SetResult(true);
var recvBuffer = new byte[64];
var recvBufferList = new List<ArraySegment<byte>>();
recvBufferList.Add(new ArraySegment<byte>(recvBuffer, 0, 1));
var recvArgs = new SocketAsyncEventArgs();
recvArgs.BufferList = recvBufferList;
recvArgs.Completed += (_,__) => tcs.SetResult(true);
for (int i = 1; i <= 10; i++)
{
tcs = new TaskCompletionSource<bool>();
sendBuffer[0] = (byte)i;
if (server.SendAsync(sendArgs))
{
await tcs.Task;
}
recvBuffer[0] = 0;
tcs = new TaskCompletionSource<bool>();
if (client.ReceiveAsync(recvArgs))
{
await tcs.Task;
}
Assert.Equal(1, recvArgs.BytesTransferred);
Assert.Equal(i, recvBuffer[0]);
// Mutate the send/recv BufferLists
// This should not affect Send or Receive behavior, since the buffer list is cached
// at the time it is set.
sendBufferList[0] = new ArraySegment<byte>(sendBuffer, i, 1);
sendBufferList.Insert(0, new ArraySegment<byte>(sendBuffer, i * 2, 1));
recvBufferList[0] = new ArraySegment<byte>(recvBuffer, i, 1);
recvBufferList.Add(new ArraySegment<byte>(recvBuffer, i * 2, 1));
}
}
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using ASC.Mail.Net.TCP;
namespace ASC.Mail.Net.IMAP.Server
{
#region usings
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using AUTH;
#endregion
#region Event delegates
/// <summary>
/// Represents the method that will handle the AuthUser event for SMTP_Server.
/// </summary>
/// <param name="sender">The source of the event. </param>
/// <param name="e">A AuthUser_EventArgs that contains the event data.</param>
public delegate void AuthUserEventHandler(object sender, AuthUser_EventArgs e);
/// <summary>
///
/// </summary>
public delegate void FolderEventHandler(object sender, Mailbox_EventArgs e);
/// <summary>
///
/// </summary>
public delegate void FoldersEventHandler(object sender, IMAP_Folders e);
/// <summary>
///
/// </summary>
public delegate void MessagesEventHandler(object sender, IMAP_eArgs_GetMessagesInfo e);
/// <summary>
///
/// </summary>
public delegate void MessagesItemsEventHandler(object sender, IMAP_eArgs_MessageItems e);
public delegate byte[] FiletGetDelegate(IMAP_Session session);
public delegate void FiletSetDelegate(IMAP_Session session, byte[] buffer);
/// <summary>
///
/// </summary>
public delegate void MessageEventHandler(object sender, Message_EventArgs e);
/*
/// <summary>
///
/// </summary>
public delegate void SearchEventHandler(object sender,IMAP_eArgs_Search e);*/
/// <summary>
///
/// </summary>
public delegate void SharedRootFoldersEventHandler(object sender, SharedRootFolders_EventArgs e);
/// <summary>
///
/// </summary>
public delegate void GetFolderACLEventHandler(object sender, IMAP_GETACL_eArgs e);
/// <summary>
///
/// </summary>
public delegate void DeleteFolderACLEventHandler(object sender, IMAP_DELETEACL_eArgs e);
/// <summary>
///
/// </summary>
public delegate void SetFolderACLEventHandler(object sender, IMAP_SETACL_eArgs e);
/// <summary>
///
/// </summary>
public delegate void GetUserACLEventHandler(object sender, IMAP_GetUserACL_eArgs e);
/// <summary>
///
/// </summary>
public delegate void GetUserQuotaHandler(object sender, IMAP_eArgs_GetQuota e);
#endregion
/// <summary>
/// IMAP server componet.
/// </summary>
public class IMAP_Server : TCP_Server<IMAP_Session>
{
#region Events
/// <summary>
/// Occurs when connected user tryes to authenticate.
/// </summary>
public event AuthUserEventHandler AuthUser = null;
/// <summary>
/// Occurs when server requests to copy message to new location.
/// </summary>
public event MessageEventHandler CopyMessage = null;
/// <summary>
/// Occurs when server requests to create folder.
/// </summary>
public event FolderEventHandler CreateFolder = null;
/// <summary>
/// Occurs when server requests to delete folder.
/// </summary>
public event FolderEventHandler DeleteFolder = null;
/// <summary>
/// Occurs when IMAP server requests to delete folder ACL.
/// </summary>
public event DeleteFolderACLEventHandler DeleteFolderACL = null;
/// <summary>
/// Occurs when server requests to delete message.
/// </summary>
public event MessageEventHandler DeleteMessage = null;
/// <summary>
/// Occurs when IMAP server requests folder ACL.
/// </summary>
public event GetFolderACLEventHandler GetFolderACL = null;
/// <summary>
/// Occurs when server requests all available folders.
/// </summary>
public event FoldersEventHandler GetFolders = null;
/// <summary>
/// Occurs when server requests to get message items.
/// </summary>
public event MessagesItemsEventHandler GetMessageItems = null;
/// <summary>
/// Occurs when server requests to folder messages info.
/// </summary>
public event MessagesEventHandler GetMessagesInfo = null;
/// <summary>
/// Occurs when IMAP server requests shared root folders info.
/// </summary>
public event SharedRootFoldersEventHandler GetSharedRootFolders = null;
/// <summary>
/// Occurs when server requests subscribed folders.
/// </summary>
public event FoldersEventHandler GetSubscribedFolders = null;
/// <summary>
/// Occurs when IMAP server requests to get user ACL for specified folder.
/// </summary>
public event GetUserACLEventHandler GetUserACL = null;
/// <summary>
/// Occurs when IMAP server requests to get user quota.
/// </summary>
public event GetUserQuotaHandler GetUserQuota = null;
/// <summary>
/// Occurs when server requests to rename folder.
/// </summary>
public event FolderEventHandler RenameFolder = null;
/// <summary>
/// Occurs when IMAP session has finished and session log is available.
/// </summary>
public event LogEventHandler SessionLog = null;
/// <summary>
/// Occurs when IMAP server requests to set folder ACL.
/// </summary>
public event SetFolderACLEventHandler SetFolderACL = null;
/// <summary>
/// Occurs when server requests to store message.
/// </summary>
public event MessageEventHandler StoreMessage = null;
/*
/// <summary>
/// Occurs when server requests to search specified folder messages.
/// </summary>
public event SearchEventHandler Search = null;*/
/// <summary>
/// Occurs when server requests to store message flags.
/// </summary>
public event MessageEventHandler StoreMessageFlags = null;
/// <summary>
/// Occurs when server requests to subscribe folder.
/// </summary>
public event FolderEventHandler SubscribeFolder = null;
/// <summary>
/// Occurs when server requests to unsubscribe folder.
/// </summary>
public event FolderEventHandler UnSubscribeFolder = null;
/// <summary>
/// Occurs when new computer connected to IMAP server.
/// </summary>
public event ValidateIPHandler ValidateIPAddress = null;
internal delegate void FolderChangedHandler(string folderName, string username);
internal event FolderChangedHandler FolderChanged = null;
public void OnFolderChanged(string folderName, string username)
{
if (FolderChanged!=null)
{
FolderChanged(folderName, username);
}
}
#endregion
#region Members
private string m_GreetingText = "";
private int m_MaxConnectionsPerIP;
private int m_MaxMessageSize = 1000000;
private SaslAuthTypes m_SupportedAuth = SaslAuthTypes.All;
#endregion
#region Properties
/// <summary>
/// Gets or sets server supported authentication types.
/// </summary>
public SaslAuthTypes SupportedAuthentications
{
get { return m_SupportedAuth; }
set { m_SupportedAuth = value; }
}
/// <summary>
/// Gets or sets server greeting text.
/// </summary>
public string GreetingText
{
get { return m_GreetingText; }
set { m_GreetingText = value; }
}
/// <summary>
/// Gets or sets maximum allowed conncurent connections from 1 IP address. Value 0 means unlimited connections.
/// </summary>
public new int MaxConnectionsPerIP
{
get { return m_MaxConnectionsPerIP; }
set { m_MaxConnectionsPerIP = value; }
}
/// <summary>
/// Maximum message size.
/// </summary>
public int MaxMessageSize
{
get { return m_MaxMessageSize; }
set { m_MaxMessageSize = value; }
}
public int MaxBadCommands { get; set; }
#endregion
#region Constructor
#endregion
#region Overrides
protected override void OnMaxConnectionsPerIPExceeded(IMAP_Session session)
{
base.OnMaxConnectionsPerIPExceeded(session);
session.TcpStream.WriteLine("* NO Maximum connections from your IP address is exceeded, try again later !\r\n");
}
protected override void OnMaxConnectionsExceeded(IMAP_Session session)
{
session.TcpStream.WriteLine("* NO Maximum connections is exceeded");
}
/// <summary>
/// Initialize and start new session here. Session isn't added to session list automatically,
/// session must add itself to server session list by calling AddSession().
/// </summary>
/// <param name="socket">Connected client socket.</param>
/// <param name="bindInfo">BindInfo what accepted socket.</param>
//protected override void InitNewSession(Socket socket, IPBindInfo bindInfo)
//{
// // Check maximum conncurent connections from 1 IP.
// if (m_MaxConnectionsPerIP > 0)
// {
// lock (Sessions)
// {
// int nSessions = 0;
// foreach (SocketServerSession s in Sessions)
// {
// IPEndPoint ipEndpoint = s.RemoteEndPoint;
// if (ipEndpoint != null)
// {
// if (ipEndpoint.Address.Equals(((IPEndPoint) socket.RemoteEndPoint).Address))
// {
// nSessions++;
// }
// }
// // Maimum allowed exceeded
// if (nSessions >= m_MaxConnectionsPerIP)
// {
// socket.Send(
// Encoding.ASCII.GetBytes(
// "* NO Maximum connections from your IP address is exceeded, try again later !\r\n"));
// socket.Shutdown(SocketShutdown.Both);
// socket.Close();
// return;
// }
// }
// }
// }
// string sessionID = Guid.NewGuid().ToString();
// SocketEx socketEx = new SocketEx(socket);
// if (LogCommands)
// {
// socketEx.Logger = new SocketLogger(socket, SessionLog);
// socketEx.Logger.SessionID = sessionID;
// }
// IMAP_Session session = new IMAP_Session(sessionID, socketEx, bindInfo, this);
// FolderChanged += session.OnFolderChanged;
//}
#endregion
#region Internal methods
/// <summary>
/// Raises event ValidateIP event.
/// </summary>
/// <param name="localEndPoint">Server IP.</param>
/// <param name="remoteEndPoint">Connected client IP.</param>
/// <returns>Returns true if connection allowed.</returns>
internal bool OnValidate_IpAddress(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint)
{
ValidateIP_EventArgs oArg = new ValidateIP_EventArgs(localEndPoint, remoteEndPoint);
if (ValidateIPAddress != null)
{
ValidateIPAddress(this, oArg);
}
return oArg.Validated;
}
/// <summary>
/// Raises event AuthUser.
/// </summary>
/// <param name="session">Reference to current IMAP session.</param>
/// <param name="userName">User name.</param>
/// <param name="passwordData">Password compare data,it depends of authentication type.</param>
/// <param name="data">For md5 eg. md5 calculation hash.It depends of authentication type.</param>
/// <param name="authType">Authentication type.</param>
/// <returns>Returns true if user is authenticated ok.</returns>
internal AuthUser_EventArgs OnAuthUser(IMAP_Session session,
string userName,
string passwordData,
string data,
AuthType authType)
{
AuthUser_EventArgs oArgs = new AuthUser_EventArgs(session, userName, passwordData, data, authType);
if (AuthUser != null)
{
AuthUser(this, oArgs);
}
return oArgs;
}
/// <summary>
/// Raises event 'SubscribeMailbox'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="mailbox">Mailbox which to subscribe.</param>
/// <returns></returns>
internal string OnSubscribeMailbox(IMAP_Session session, string mailbox)
{
if (SubscribeFolder != null)
{
Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox);
SubscribeFolder(session, eArgs);
return eArgs.ErrorText;
}
return null;
}
/// <summary>
/// Raises event 'UnSubscribeMailbox'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="mailbox">Mailbox which to unsubscribe.</param>
/// <returns></returns>
internal string OnUnSubscribeMailbox(IMAP_Session session, string mailbox)
{
if (UnSubscribeFolder != null)
{
Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox);
UnSubscribeFolder(session, eArgs);
return eArgs.ErrorText;
}
return null;
}
/// <summary>
/// Raises event 'GetSubscribedMailboxes'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="referenceName">Mailbox reference.</param>
/// <param name="mailBox">Mailbox search pattern or mailbox.</param>
/// <returns></returns>
internal IMAP_Folders OnGetSubscribedMailboxes(IMAP_Session session,
string referenceName,
string mailBox)
{
IMAP_Folders retVal = new IMAP_Folders(session, referenceName, mailBox);
if (GetSubscribedFolders != null)
{
GetSubscribedFolders(session, retVal);
}
return retVal;
}
/// <summary>
/// Raises event 'GetMailboxes'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="referenceName">Mailbox reference.</param>
/// <param name="mailBox">Mailbox search pattern or mailbox.</param>
/// <returns></returns>
internal IMAP_Folders OnGetMailboxes(IMAP_Session session, string referenceName, string mailBox)
{
IMAP_Folders retVal = new IMAP_Folders(session, referenceName, mailBox);
if (GetFolders != null)
{
GetFolders(session, retVal);
}
return retVal;
}
/// <summary>
/// Raises event 'CreateMailbox'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="mailbox">Mailbox to create.</param>
/// <returns></returns>
internal string OnCreateMailbox(IMAP_Session session, string mailbox)
{
if (CreateFolder != null)
{
Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox);
CreateFolder(session, eArgs);
return eArgs.ErrorText;
}
return null;
}
/// <summary>
/// Raises event 'DeleteMailbox'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="mailbox">Mailbox which to delete.</param>
/// <returns></returns>
internal string OnDeleteMailbox(IMAP_Session session, string mailbox)
{
if (DeleteFolder != null)
{
Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox);
DeleteFolder(session, eArgs);
return eArgs.ErrorText;
}
return null;
}
/// <summary>
/// Raises event 'RenameMailbox'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="mailbox">Mailbox which to rename.</param>
/// <param name="newMailboxName">New mailbox name.</param>
/// <returns></returns>
internal string OnRenameMailbox(IMAP_Session session, string mailbox, string newMailboxName)
{
if (RenameFolder != null)
{
Mailbox_EventArgs eArgs = new Mailbox_EventArgs(mailbox, newMailboxName);
RenameFolder(session, eArgs);
return eArgs.ErrorText;
}
return null;
}
/// <summary>
/// Raises event 'GetMessagesInfo'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="folder">Folder which messages info to get.</param>
/// <returns></returns>
internal IMAP_eArgs_GetMessagesInfo OnGetMessagesInfo(IMAP_Session session, IMAP_SelectedFolder folder)
{
IMAP_eArgs_GetMessagesInfo eArgs = new IMAP_eArgs_GetMessagesInfo(session, folder);
if (GetMessagesInfo != null)
{
GetMessagesInfo(session, eArgs);
}
return eArgs;
}
/// <summary>
/// Raises event 'DeleteMessage'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="message">Message which to delete.</param>
/// <returns></returns>
internal string OnDeleteMessage(IMAP_Session session, IMAP_Message message)
{
Message_EventArgs eArgs =
new Message_EventArgs(Core.Decode_IMAP_UTF7_String(session.SelectedMailbox), message);
if (DeleteMessage != null)
{
DeleteMessage(session, eArgs);
}
return eArgs.ErrorText;
}
/// <summary>
/// Raises event 'CopyMessage'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="msg">Message which to copy.</param>
/// <param name="location">New message location.</param>
/// <returns></returns>
internal string OnCopyMessage(IMAP_Session session, IMAP_Message msg, string location)
{
Message_EventArgs eArgs =
new Message_EventArgs(Core.Decode_IMAP_UTF7_String(session.SelectedMailbox), msg, location);
if (CopyMessage != null)
{
CopyMessage(session, eArgs);
}
return eArgs.ErrorText;
}
/// <summary>
/// Raises event 'StoreMessage'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="folder">Folder where to store.</param>
/// <param name="msg">Message which to store.</param>
/// <param name="messageData">Message data which to store.</param>
/// <returns></returns>
internal string OnStoreMessage(IMAP_Session session,
string folder,
IMAP_Message msg,
byte[] messageData)
{
Message_EventArgs eArgs = new Message_EventArgs(folder, msg);
eArgs.MessageData = messageData;
if (StoreMessage != null)
{
StoreMessage(session, eArgs);
}
return eArgs.ErrorText;
}
/*
/// <summary>
/// Raises event 'Search'.
/// </summary>
/// <param name="session">IMAP session what calls this search.</param>
/// <param name="folder">Folder what messages to search.</param>
/// <param name="matcher">Matcher what must be used to check if message matches searching criterial.</param>
/// <returns></returns>
internal IMAP_eArgs_Search OnSearch(IMAP_Session session,string folder,IMAP_SearchMatcher matcher)
{
IMAP_eArgs_Search eArgs = new IMAP_eArgs_Search(session,folder,matcher);
if(this.Search != null){
this.Search(session,eArgs);
}
return eArgs;
}*/
/// <summary>
/// Raises event 'StoreMessageFlags'.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="msg">Message which flags to store.</param>
/// <returns></returns>
internal string OnStoreMessageFlags(IMAP_Session session, IMAP_Message msg)
{
Message_EventArgs eArgs =
new Message_EventArgs(Core.Decode_IMAP_UTF7_String(session.SelectedMailbox), msg);
if (StoreMessageFlags != null)
{
StoreMessageFlags(session, eArgs);
}
return eArgs.ErrorText;
}
internal SharedRootFolders_EventArgs OnGetSharedRootFolders(IMAP_Session session)
{
SharedRootFolders_EventArgs eArgs = new SharedRootFolders_EventArgs(session);
if (GetSharedRootFolders != null)
{
GetSharedRootFolders(session, eArgs);
}
return eArgs;
}
internal IMAP_GETACL_eArgs OnGetFolderACL(IMAP_Session session, string folderName)
{
IMAP_GETACL_eArgs eArgs = new IMAP_GETACL_eArgs(session, folderName);
if (GetFolderACL != null)
{
GetFolderACL(session, eArgs);
}
return eArgs;
}
internal IMAP_SETACL_eArgs OnSetFolderACL(IMAP_Session session,
string folderName,
string userName,
IMAP_Flags_SetType flagsSetType,
IMAP_ACL_Flags aclFlags)
{
IMAP_SETACL_eArgs eArgs = new IMAP_SETACL_eArgs(session,
folderName,
userName,
flagsSetType,
aclFlags);
if (SetFolderACL != null)
{
SetFolderACL(session, eArgs);
}
return eArgs;
}
internal IMAP_DELETEACL_eArgs OnDeleteFolderACL(IMAP_Session session,
string folderName,
string userName)
{
IMAP_DELETEACL_eArgs eArgs = new IMAP_DELETEACL_eArgs(session, folderName, userName);
if (DeleteFolderACL != null)
{
DeleteFolderACL(session, eArgs);
}
return eArgs;
}
internal IMAP_GetUserACL_eArgs OnGetUserACL(IMAP_Session session, string folderName, string userName)
{
IMAP_GetUserACL_eArgs eArgs = new IMAP_GetUserACL_eArgs(session, folderName, userName);
if (GetUserACL != null)
{
GetUserACL(session, eArgs);
}
return eArgs;
}
internal IMAP_eArgs_GetQuota OnGetUserQuota(IMAP_Session session)
{
IMAP_eArgs_GetQuota eArgs = new IMAP_eArgs_GetQuota(session);
if (GetUserQuota != null)
{
GetUserQuota(session, eArgs);
}
return eArgs;
}
#endregion
/// <summary>
/// Raises event GetMessageItems.
/// </summary>
/// <param name="session">Reference to IMAP session.</param>
/// <param name="messageInfo">Message info what message items to get.</param>
/// <param name="messageItems">Specifies message items what must be filled.</param>
/// <returns></returns>
protected internal IMAP_eArgs_MessageItems OnGetMessageItems(IMAP_Session session,
IMAP_Message messageInfo,
IMAP_MessageItems_enum messageItems)
{
IMAP_eArgs_MessageItems eArgs = new IMAP_eArgs_MessageItems(session, messageInfo, messageItems);
if (GetMessageItems != null)
{
GetMessageItems(session, eArgs);
}
return eArgs;
}
public event FiletSetDelegate SetFilterSet = null;
public event FiletGetDelegate GetFilterSet = null;
public byte[] GetFilter(IMAP_Session session)
{
if (GetFilterSet != null)
{
return GetFilterSet(session);
}
return null;
}
public void SetFilter(IMAP_Session session, byte[] filter)
{
if (SetFilterSet != null)
{
SetFilterSet(session, filter);
}
}
public void OnSysError(string text, Exception exception)
{
OnError(exception);
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.Linq;
using MindTouch.Deki.Data;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Logic {
public class GroupBL {
public static GroupBE GetGroupByName(string groupName) {
return DbUtils.CurrentSession.Groups_GetByNames(new List<string>() {groupName}).FirstOrDefault();
}
public static GroupBE GetGroupById(uint groupId) {
return DbUtils.CurrentSession.Groups_GetByIds(new List<uint>() {groupId}).FirstOrDefault();
}
public static IList<GroupBE> GetGroupsByQuery(DreamContext context, out uint totalCount, out uint queryCount) {
uint limit, offset;
SortDirection sortDir;
string sortFieldString;
Utils.GetOffsetAndCountFromRequest(context, 100, out limit, out offset, out sortDir, out sortFieldString);
// Attempt to read the sort field. If a parsing error occurs, default to undefined.
GroupsSortField sortField = GroupsSortField.UNDEFINED;
if (!String.IsNullOrEmpty(sortFieldString)) {
try { sortField = SysUtil.ChangeType<GroupsSortField>(sortFieldString); } catch { }
}
string groupnamefilter = context.GetParam("groupnamefilter", null);
uint? serviceid = context.GetParam<uint>("authprovider", 0);
if ((serviceid ?? 0) == 0) {
serviceid = null;
}
return DbUtils.CurrentSession.Groups_GetByQuery(groupnamefilter, serviceid, sortDir, sortField, offset, limit, out totalCount, out queryCount);
}
public static GroupBE PostGroupFromXml(XDoc groupDoc, GroupBE groupToProcess, string externalusername, string externalpassword ) {
GroupBE group = null;
string groupName = string.Empty;
ServiceBE groupService = null;
RoleBE groupRole = null;
UserBE[] groupMembers = null;
uint? groupId = null;
ParseGroupXml(groupDoc, out groupId, out groupName, out groupService, out groupRole, out groupMembers);
//Create new group
if (groupToProcess == null && (groupId == null || groupId == 0)) {
if (groupService == null)
groupService = ServiceBL.RetrieveLocalAuthService();
//External groups should be confirmed with the auth provider
if (groupService != null && !ServiceBL.IsLocalAuthService(groupService)) {
//username+password from request query params are used here
group = ExternalServiceSA.BuildGroupFromAuthService(groupService, groupToProcess, groupName, externalusername, externalpassword);
if (group == null) {
throw new DreamAbortException(DreamMessage.NotFound(string.Format(DekiResources.EXTERNAL_GROUP_NOT_FOUND, groupName)));
}
}
//Does this group already exist?
GroupBE tempGroup = GetGroupByName(groupName);
if (tempGroup != null) {
throw new DreamAbortException(DreamMessage.Conflict(string.Format(DekiResources.GROUP_EXISTS_WITH_SERVICE, groupName, tempGroup.ServiceId)));
}
ValidateGroupMemberList(groupService, groupMembers);
// Insert the group
GroupBE newGroup = new GroupBE();
newGroup.Name = groupName;
newGroup.RoleId = groupRole.ID;
newGroup.ServiceId = groupService.Id;
newGroup.CreatorUserId = DekiContext.Current.User.ID;
newGroup.TimeStamp = DateTime.UtcNow;
uint newGroupId = DbUtils.CurrentSession.Groups_Insert(newGroup);
if (newGroupId == 0) {
group = null;
} else {
DbUtils.CurrentSession.GroupMembers_UpdateUsersInGroup(newGroupId, groupMembers.Select(e => e.ID).ToList(), newGroup.TimeStamp);
// reload the group to ensure group members are set
group = GetGroupById(newGroupId);
}
}
//Edit existing group
else {
if (groupId != null)
groupToProcess = GetGroupById(groupId.Value);
if (groupToProcess == null) {
throw new DreamAbortException(DreamMessage.NotFound(string.Format(DekiResources.GROUP_ID_NOT_FOUND, groupId)));
}
group = groupToProcess;
//Change the role?
if( group.RoleId != groupRole.ID){
group.RoleId = groupRole.ID;
}
//Rename the group?
if (group.Name != groupName && !string.IsNullOrEmpty(groupName)) {
GroupBE tempGroup = GetGroupByName(groupName);
if (tempGroup != null) {
throw new DreamAbortException(DreamMessage.Conflict(string.Format(DekiResources.GROUP_EXISTS_WITH_SERVICE, groupName, tempGroup.ServiceId)));
}
if (!ServiceBL.IsLocalAuthService(group.ServiceId)) {
//TODO MaxM: allow renaming of external groups
throw new DreamAbortException(DreamMessage.NotImplemented(DekiResources.EXTERNAL_GROUP_RENAME_NOT_ALLOWED));
}
//Set the new name of the group.
group.Name = groupName;
}
DbUtils.CurrentSession.Groups_Update(group);
//TODO (MaxM): Update group list as well?
group = GetGroupById(group.Id);
}
if (group == null) {
throw new DreamAbortException(DreamMessage.InternalError(DekiResources.GROUP_CREATE_UPDATE_FAILED));
}
return group;
}
public static GroupBE SetGroupMembers(GroupBE group, XDoc userList) {
UserBE[] members = ProcessGroupMemberInput(group, userList);
DbUtils.CurrentSession.GroupMembers_UpdateUsersInGroup(group.Id, members.Select(e => e.ID).ToList(), DateTime.UtcNow);
// reload the group to ensure group members are set
return GetGroupById(group.Id);
}
private static IList<UserBE> GetMemberUsers(GroupBE group) {
IList<UserBE> memberUsers;
if (ArrayUtil.IsNullOrEmpty(group.UserIdsList)) {
memberUsers = new List<UserBE>();
} else {
memberUsers = DbUtils.CurrentSession.Users_GetByIds(group.UserIdsList);
}
return memberUsers;
}
public static GroupBE AddGroupMembers(GroupBE group, XDoc userList) {
UserBE[] newMembers = ProcessGroupMemberInput(group, userList);
if(ArrayUtil.IsNullOrEmpty(newMembers)) {
return group;
}
IList<UserBE> members = GetMemberUsers(group);
members.AddRange(newMembers);
DbUtils.CurrentSession.GroupMembers_UpdateUsersInGroup(group.Id, members.Select(e => e.ID).ToList(), DateTime.UtcNow);
return GetGroupById(group.Id);
}
public static GroupBE RemoveGroupMember(GroupBE group, UserBE user) {
List<UserBE> members = new List<UserBE>();
foreach(UserBE u in GetMemberUsers(group)) {
if(u.ID != user.ID) {
members.Add(u);
}
}
DbUtils.CurrentSession.GroupMembers_UpdateUsersInGroup(group.Id, members.Select(e => e.ID).ToList(), DateTime.UtcNow);
return GetGroupById(group.Id);
}
private static UserBE[] ProcessGroupMemberInput(GroupBE group, XDoc userList) {
if(!userList.HasName("users")) {
throw new DreamBadRequestException(DekiResources.EXPECTED_ROOT_NODE_USERS);
}
ServiceBE service = ServiceBL.GetServiceById(group.ServiceId);
if(service == null) {
throw new DreamInternalErrorException(string.Format("Could not find service with id '{0}' for group name '{1}'. ", group.ServiceId, group.Name));
}
//Changing members of an external group is not supported. You may modify members in the external provider instead.
if(!ServiceBL.IsLocalAuthService(service)) {
throw new DreamBadRequestException(DekiResources.GROUP_EXTERNAL_CHANGE_MEMBERS);
}
UserBE[] members = ReadUserListXml(userList);
ValidateGroupMemberList(service, members);
return members;
}
private static void ValidateGroupMemberList(ServiceBE groupService, UserBE[] potentialMembers) {
//Groups belonging to built-in auth service are allowed to contain users from remote services
if (!ServiceBL.IsLocalAuthService(groupService)) {
foreach (UserBE u in potentialMembers) {
if (u.ServiceId != groupService.Id)
throw new DreamBadRequestException(DekiResources.GROUP_MEMBERS_REQUIRE_SAME_AUTH);
}
}
}
#region XML Helpers
private static void ParseGroupXml(XDoc groupDoc, out uint? id, out string name, out ServiceBE authService, out RoleBE role, out UserBE[] userList) {
name = groupDoc["groupname"].AsText ?? groupDoc["name"].AsText;
string authserviceidstr = groupDoc["service.authentication/@id"].AsText;
string rolestr = groupDoc["permissions.group/role"].AsText;
authService = null;
role = null;
id = null;
if (!groupDoc["@id"].IsEmpty) {
uint id_temp;
if (!uint.TryParse(groupDoc["@id"].Contents, out id_temp))
throw new DreamBadRequestException(DekiResources.GROUP_ID_ATTR_INVALID);
id = id_temp;
}
if (!string.IsNullOrEmpty(authserviceidstr)) {
uint serviceid;
if (!uint.TryParse(authserviceidstr, out serviceid))
throw new DreamBadRequestException(DekiResources.SERVICE_AUTH_ID_ATTR_INVALID);
authService = ServiceBL.GetServiceById(serviceid);
if (authService == null)
throw new DreamBadRequestException(string.Format(DekiResources.SERVICE_DOES_NOT_EXIST, serviceid));
}
if (!string.IsNullOrEmpty(rolestr)) {
role = PermissionsBL.GetRoleByName(rolestr);
if (role == null)
throw new DreamBadRequestException(string.Format(DekiResources.ROLE_DOES_NOT_EXIST, rolestr));
} else {
role = PermissionsBL.RetrieveDefaultRoleForNewAccounts();
}
if (!groupDoc["users"].IsEmpty) {
userList = ReadUserListXml(groupDoc["users"]);
} else
userList = new UserBE[] { };
}
private static UserBE[] ReadUserListXml(XDoc usersList) {
UserBE[] ret = null;
List<uint> userIds = new List<uint>();
foreach (XDoc userXml in usersList["user/@id"]) {
uint? id = userXml.AsUInt;
if (id == null)
throw new DreamBadRequestException(DekiResources.USER_ID_ATTR_INVALID);
userIds.Add(id.Value);
}
if (userIds.Count > 0) {
Dictionary<uint, UserBE> userHash = DbUtils.CurrentSession.Users_GetByIds(userIds).AsHash(e => e.ID);
foreach (uint id in userIds) {
if (!userHash.ContainsKey(id))
throw new DreamBadRequestException(string.Format(DekiResources.COULD_NOT_FIND_USER, id));
}
ret = new List<UserBE>(userHash.Values).ToArray();
} else {
ret = new UserBE[] { };
}
return ret;
}
public static XDoc GetGroupXml(GroupBE group, string relation) {
XDoc groupXml = new XDoc(string.IsNullOrEmpty(relation) ? "group" : "group." + relation);
groupXml.Attr("id", group.Id);
groupXml.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString()));
groupXml.Start("groupname").Value(group.Name).End();
return groupXml;
}
public static XDoc GetGroupXmlVerbose(GroupBE group, string relation) {
XDoc groupXml = GetGroupXml(group, relation);
ServiceBE authService = ServiceBL.GetServiceById(group.ServiceId);
if (authService != null)
groupXml.Add(ServiceBL.GetServiceXml(authService, "authentication"));
groupXml.Start("users");
if (group.UserIdsList != null) {
groupXml.Attr("count", group.UserIdsList.Length);
}
groupXml.Attr("href", DekiContext.Current.ApiUri.At("groups", group.Id.ToString(), "users"));
groupXml.End();
//Permissions for the group
RoleBE role = PermissionsBL.GetRoleById(group.RoleId); ;
groupXml.Add(PermissionsBL.GetRoleXml(role, "group"));
return groupXml;
}
#endregion
}
}
| |
using System.Collections.Generic;
using UnityEngine;
using Cinemachine.Utility;
namespace Cinemachine
{
/// <summary>
/// Cinemachine ClearShot is a "manager camera" that owns and manages a set of
/// Virtual Camera gameObject children. When Live, the ClearShot will check the
/// children, and choose the one with the best quality shot and make it Live.
///
/// This can be a very powerful tool. If the child cameras have CinemachineCollider
/// extensions, they will analyze the scene for target obstructions, optimal target
/// distance, and other items, and report their assessment of shot quality back to
/// the ClearShot parent, who will then choose the best one. You can use this to set
/// up complex multi-camera coverage of a scene, and be assured that a clear shot of
/// the target will always be available.
///
/// If multiple child cameras have the same shot quality, the one with the highest
/// priority will be chosen.
///
/// You can also define custom blends between the ClearShot children.
/// </summary>
[DocumentationSorting(12, DocumentationSortingAttribute.Level.UserRef)]
[ExecuteInEditMode, DisallowMultipleComponent]
[AddComponentMenu("Cinemachine/CinemachineClearShot")]
public class CinemachineClearShot : CinemachineVirtualCameraBase
{
/// <summary>Default object for the camera children to look at (the aim target), if not specified in a child camera. May be empty.</summary>
[Tooltip("Default object for the camera children to look at (the aim target), if not specified in a child camera. May be empty if all children specify targets of their own.")]
[NoSaveDuringPlay]
public Transform m_LookAt = null;
/// <summary>Default object for the camera children wants to move with (the body target), if not specified in a child camera. May be empty.</summary>
[Tooltip("Default object for the camera children wants to move with (the body target), if not specified in a child camera. May be empty if all children specify targets of their own.")]
[NoSaveDuringPlay]
public Transform m_Follow = null;
/// <summary>When enabled, the current camera and blend will be indicated in the game window, for debugging</summary>
[Tooltip("When enabled, the current child camera and blend will be indicated in the game window, for debugging")]
[NoSaveDuringPlay]
public bool m_ShowDebugText = false;
/// <summary>Internal API for the editor. Do not use this filed.</summary>
[SerializeField, HideInInspector, NoSaveDuringPlay]
public CinemachineVirtualCameraBase[] m_ChildCameras = null;
/// <summary>Wait this many seconds before activating a new child camera</summary>
[Tooltip("Wait this many seconds before activating a new child camera")]
public float m_ActivateAfter;
/// <summary>An active camera must be active for at least this many seconds</summary>
[Tooltip("An active camera must be active for at least this many seconds")]
public float m_MinDuration;
/// <summary>If checked, camera choice will be randomized if multiple cameras are equally desirable. Otherwise, child list order will be used</summary>
[Tooltip("If checked, camera choice will be randomized if multiple cameras are equally desirable. Otherwise, child list order and child camera priority will be used.")]
public bool m_RandomizeChoice = false;
/// <summary>The blend which is used if you don't explicitly define a blend between two Virtual Cameras</summary>
[CinemachineBlendDefinitionProperty]
[Tooltip("The blend which is used if you don't explicitly define a blend between two Virtual Cameras")]
public CinemachineBlendDefinition m_DefaultBlend
= new CinemachineBlendDefinition(CinemachineBlendDefinition.Style.Cut, 0);
/// <summary>This is the asset which contains custom settings for specific blends</summary>
[HideInInspector]
public CinemachineBlenderSettings m_CustomBlends = null;
/// <summary>Gets a brief debug description of this virtual camera, for use when displayiong debug info</summary>
public override string Description
{
get
{
// Show the active camera and blend
ICinemachineCamera vcam = LiveChild;
if (mActiveBlend == null)
return (vcam != null) ? "[" + vcam.Name + "]" : "(none)";
return mActiveBlend.Description;
}
}
/// <summary>Get the current "best" child virtual camera, that would be chosen
/// if the ClearShot camera were active.</summary>
public ICinemachineCamera LiveChild { set; get; }
/// <summary>The CameraState of the currently live child</summary>
public override CameraState State { get { return m_State; } }
/// <summary>Return the live child.</summary>
public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } }
/// <summary>Check whether the vcam a live child of this camera.</summary>
/// <param name="vcam">The Virtual Camera to check</param>
/// <returns>True if the vcam is currently actively influencing the state of this vcam</returns>
public override bool IsLiveChild(ICinemachineCamera vcam)
{
return vcam == LiveChild
|| (mActiveBlend != null && (vcam == mActiveBlend.CamA || vcam == mActiveBlend.CamB));
}
/// <summary>Get the current LookAt target. Returns parent's LookAt if parent
/// is non-null and no specific LookAt defined for this camera</summary>
override public Transform LookAt
{
get { return ResolveLookAt(m_LookAt); }
set { m_LookAt = value; }
}
/// <summary>Get the current Follow target. Returns parent's Follow if parent
/// is non-null and no specific Follow defined for this camera</summary>
override public Transform Follow
{
get { return ResolveFollow(m_Follow); }
set { m_Follow = value; }
}
/// <summary>Remove a Pipeline stage hook callback.
/// Make sure it is removed from all the children.</summary>
/// <param name="d">The delegate to remove.</param>
public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d)
{
base.RemovePostPipelineStageHook(d);
UpdateListOfChildren();
foreach (var vcam in m_ChildCameras)
vcam.RemovePostPipelineStageHook(d);
}
/// <summary>Called by CinemachineCore at designated update time
/// so the vcam can position itself and track its targets. This implementation
/// updates all the children, chooses the best one, and implements any required blending.</summary>
/// <param name="worldUp">Default world Up, set by the CinemachineBrain</param>
/// <param name="deltaTime">Delta time for time-based effects (ignore if less than 0)</param>
public override void UpdateCameraState(Vector3 worldUp, float deltaTime)
{
//UnityEngine.Profiling.Profiler.BeginSample("CinemachineClearShot.UpdateCameraState");
if (!PreviousStateIsValid)
deltaTime = -1;
// Choose the best camera
UpdateListOfChildren();
ICinemachineCamera previousCam = LiveChild;
LiveChild = ChooseCurrentCamera(worldUp, deltaTime);
// Are we transitioning cameras?
if (previousCam != null && LiveChild != null && previousCam != LiveChild)
{
// Create a blend (will be null if a cut)
float duration = 0;
AnimationCurve curve = LookupBlendCurve(previousCam, LiveChild, out duration);
mActiveBlend = CreateBlend(
previousCam, LiveChild,
curve, duration, mActiveBlend, deltaTime);
// Notify incoming camera of transition
LiveChild.OnTransitionFromCamera(previousCam, worldUp, deltaTime);
// Generate Camera Activation event if live
CinemachineCore.Instance.GenerateCameraActivationEvent(LiveChild);
// If cutting, generate a camera cut event if live
if (mActiveBlend == null)
CinemachineCore.Instance.GenerateCameraCutEvent(LiveChild);
}
// Advance the current blend (if any)
if (mActiveBlend != null)
{
mActiveBlend.TimeInBlend += (deltaTime >= 0)
? deltaTime : mActiveBlend.Duration;
if (mActiveBlend.IsComplete)
mActiveBlend = null;
}
if (mActiveBlend != null)
{
mActiveBlend.UpdateCameraState(worldUp, deltaTime);
m_State = mActiveBlend.State;
}
else if (LiveChild != null)
m_State = LiveChild.State;
PreviousStateIsValid = true;
//UnityEngine.Profiling.Profiler.EndSample();
}
/// <summary>Makes sure the internal child cache is up to date</summary>
protected override void OnEnable()
{
base.OnEnable();
InvalidateListOfChildren();
mActiveBlend = null;
}
/// <summary>Makes sure the internal child cache is up to date</summary>
public void OnTransformChildrenChanged()
{
InvalidateListOfChildren();
}
#if UNITY_EDITOR
/// <summary>Displays the current active camera on the game screen, if requested</summary>
protected override void OnGUI()
{
base.OnGUI();
if (!m_ShowDebugText)
CinemachineGameWindowDebug.ReleaseScreenPos(this);
else
{
string text = Name + ": " + Description;
Rect r = CinemachineGameWindowDebug.GetScreenPos(this, text, GUI.skin.box);
GUI.Label(r, text, GUI.skin.box);
}
}
#endif
/// <summary>Is there a blend in progress?</summary>
public bool IsBlending { get { return mActiveBlend != null; } }
CameraState m_State = CameraState.Default;
/// <summary>The list of child cameras. These are just the immediate children in the hierarchy.</summary>
public CinemachineVirtualCameraBase[] ChildCameras
{
get { UpdateListOfChildren(); return m_ChildCameras; }
}
float mActivationTime = 0;
float mPendingActivationTime = 0;
ICinemachineCamera mPendingCamera;
private CinemachineBlend mActiveBlend = null;
void InvalidateListOfChildren()
{
m_ChildCameras = null;
m_RandomizedChilden = null;
LiveChild = null;
}
/// <summary>If RandomizeChoice is enabled, call this to re-randomize the children next frame.
/// This is useful if you want to freshen up the shot.</summary>
public void ResetRandomization()
{
m_RandomizedChilden = null;
mRandomizeNow = true;
}
void UpdateListOfChildren()
{
if (m_ChildCameras != null)
return;
List<CinemachineVirtualCameraBase> list = new List<CinemachineVirtualCameraBase>();
CinemachineVirtualCameraBase[] kids = GetComponentsInChildren<CinemachineVirtualCameraBase>(true);
foreach (CinemachineVirtualCameraBase k in kids)
if (k.transform.parent == transform)
list.Add(k);
m_ChildCameras = list.ToArray();
// Zap the cached current instructions
mActivationTime = mPendingActivationTime = 0;
mPendingCamera = null;
LiveChild = null;
mActiveBlend = null;
}
private bool mRandomizeNow = false;
private CinemachineVirtualCameraBase[] m_RandomizedChilden = null;
private ICinemachineCamera ChooseCurrentCamera(Vector3 worldUp, float deltaTime)
{
if (m_ChildCameras == null || m_ChildCameras.Length == 0)
{
mActivationTime = 0;
return null;
}
CinemachineVirtualCameraBase[] childCameras = m_ChildCameras;
if (!m_RandomizeChoice)
m_RandomizedChilden = null;
else if (m_ChildCameras.Length > 1)
{
if (m_RandomizedChilden == null)
m_RandomizedChilden = Randomize(m_ChildCameras);
childCameras = m_RandomizedChilden;
}
if (LiveChild != null && !LiveChild.VirtualCameraGameObject.activeSelf)
LiveChild = null;
ICinemachineCamera best = LiveChild;
for (int i = 0; i < childCameras.Length; ++i)
{
CinemachineVirtualCameraBase vcam = childCameras[i];
if (vcam != null && vcam.VirtualCameraGameObject.activeInHierarchy)
{
// Choose the first in the list that is better than the current
if (best == null
|| vcam.State.ShotQuality > best.State.ShotQuality
|| (vcam.State.ShotQuality == best.State.ShotQuality && vcam.Priority > best.Priority)
|| (m_RandomizeChoice && mRandomizeNow && (ICinemachineCamera)vcam != LiveChild
&& vcam.State.ShotQuality == best.State.ShotQuality
&& vcam.Priority == best.Priority))
{
best = vcam;
}
}
}
mRandomizeNow = false;
float now = Time.time;
if (mActivationTime != 0)
{
// Is it active now?
if (LiveChild == best)
{
// Yes, cancel any pending
mPendingActivationTime = 0;
mPendingCamera = null;
return best;
}
// Is it pending?
if (deltaTime >= 0)
{
if (mPendingActivationTime != 0 && mPendingCamera == best)
{
// Has it been pending long enough, and are we allowed to switch away
// from the active action?
if ((now - mPendingActivationTime) > m_ActivateAfter
&& (now - mActivationTime) > m_MinDuration)
{
// Yes, activate it now
m_RandomizedChilden = null; // reshuffle the children
mActivationTime = now;
mPendingActivationTime = 0;
mPendingCamera = null;
return best;
}
return LiveChild;
}
}
}
// Neither active nor pending.
mPendingActivationTime = 0; // cancel the pending, if any
mPendingCamera = null;
// Can we activate it now?
if (deltaTime >= 0 && mActivationTime > 0)
{
if (m_ActivateAfter > 0
|| (now - mActivationTime) < m_MinDuration)
{
// Too early - make it pending
mPendingCamera = best;
mPendingActivationTime = now;
return LiveChild;
}
}
// Activate now
m_RandomizedChilden = null; // reshuffle the children
mActivationTime = now;
return best;
}
struct Pair { public int a; public float b; }
CinemachineVirtualCameraBase[] Randomize(CinemachineVirtualCameraBase[] src)
{
List<Pair> pairs = new List<Pair>();
for (int i = 0; i < src.Length; ++i)
{
Pair p = new Pair(); p.a = i; p.b = Random.Range(0, 1000f);
pairs.Add(p);
}
pairs.Sort((p1, p2) => (int)p1.b - (int)p2.b);
CinemachineVirtualCameraBase[] dst = new CinemachineVirtualCameraBase[src.Length];
Pair[] result = pairs.ToArray();
for (int i = 0; i < src.Length; ++i)
dst[i] = src[result[i].a];
return dst;
}
private AnimationCurve LookupBlendCurve(
ICinemachineCamera fromKey, ICinemachineCamera toKey, out float duration)
{
// Get the blend curve that's most appropriate for these cameras
AnimationCurve blendCurve = m_DefaultBlend.BlendCurve;
if (m_CustomBlends != null)
{
string fromCameraName = (fromKey != null) ? fromKey.Name : string.Empty;
string toCameraName = (toKey != null) ? toKey.Name : string.Empty;
blendCurve = m_CustomBlends.GetBlendCurveForVirtualCameras(
fromCameraName, toCameraName, blendCurve);
}
var keys = blendCurve.keys;
duration = (keys == null || keys.Length == 0) ? 0 : keys[keys.Length-1].time;
return blendCurve;
}
private CinemachineBlend CreateBlend(
ICinemachineCamera camA, ICinemachineCamera camB,
AnimationCurve blendCurve, float duration,
CinemachineBlend activeBlend, float deltaTime)
{
if (blendCurve == null || duration <= 0 || (camA == null && camB == null))
return null;
if (camA == null || activeBlend != null)
{
// Blend from the current camera position
CameraState state = (activeBlend != null) ? activeBlend.State : State;
camA = new StaticPointVirtualCamera(state, (activeBlend != null) ? "Mid-blend" : "(none)");
}
return new CinemachineBlend(camA, camB, blendCurve, duration, 0);
}
/// <summary>Notification that this virtual camera is going live.
/// This implementation resets the child randomization.</summary>
/// <param name="fromCam">The camera being deactivated. May be null.</param>
/// <param name="worldUp">Default world Up, set by the CinemachineBrain</param>
/// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param>
public override void OnTransitionFromCamera(
ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime)
{
base.OnTransitionFromCamera(fromCam, worldUp, deltaTime);
if (m_RandomizeChoice && mActiveBlend == null)
{
m_RandomizedChilden = null;
LiveChild = null;
UpdateCameraState(worldUp, deltaTime);
}
}
}
}
| |
//
// System.Net.ResponseStream
//
// Author:
// Gonzalo Paniagua Javier ([email protected])
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.IO;
using System.Net.Sockets;
using System.Text;
using System;
using System.Runtime.InteropServices;
namespace HTTP.Net {
// FIXME: Does this buffer the response until Close?
// Update: we send a single packet for the first non-chunked Write
// What happens when we set content-length to X and write X-1 bytes then close?
// what if we don't set content-length at all?
internal class ResponseStream : Stream
{
HttpListenerResponse response;
bool ignore_errors;
bool disposed;
bool trailer_sent;
Stream stream;
internal ResponseStream (Stream stream, HttpListenerResponse response, bool ignore_errors)
{
this.response = response;
this.ignore_errors = ignore_errors;
this.stream = stream;
}
public override bool CanRead {
get { return false; }
}
public override bool CanSeek {
get { return false; }
}
public override bool CanWrite {
get { return true; }
}
public override long Length {
get { throw new NotSupportedException (); }
}
public override long Position {
get { throw new NotSupportedException (); }
set { throw new NotSupportedException (); }
}
public override void Close ()
{
if (disposed == false) {
disposed = true;
byte [] bytes = null;
MemoryStream ms = GetHeaders (true);
bool chunked = response.SendChunked;
if (ms != null) {
long start = ms.Position;
if (chunked && !trailer_sent) {
bytes = GetChunkSizeBytes (0, true);
ms.Position = ms.Length;
ms.Write (bytes, 0, bytes.Length);
}
InternalWrite (ms.GetBuffer (), (int) start, (int) (ms.Length - start));
trailer_sent = true;
} else if (chunked && !trailer_sent) {
bytes = GetChunkSizeBytes (0, true);
InternalWrite (bytes, 0, bytes.Length);
trailer_sent = true;
}
response.Close ();
}
}
MemoryStream GetHeaders (bool closing)
{
if (response.HeadersSent)
return null;
MemoryStream ms = new MemoryStream ();
response.SendHeaders (closing, ms);
return ms;
}
public override void Flush ()
{
}
static byte [] crlf = new byte [] { 13, 10 };
static byte [] GetChunkSizeBytes (int size, bool final)
{
string str = String.Format ("{0:x}\r\n{1}", size, final ? "\r\n" : "");
return Encoding.ASCII.GetBytes (str);
}
internal void InternalWrite (byte [] buffer, int offset, int count)
{
if (ignore_errors) {
try {
stream.Write (buffer, offset, count);
} catch { }
} else {
stream.Write (buffer, offset, count);
}
}
public override void Write (byte [] buffer, int offset, int count)
{
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
byte [] bytes = null;
MemoryStream ms = GetHeaders (false);
bool chunked = response.SendChunked;
if (ms != null) {
long start = ms.Position; // After the possible preamble for the encoding
ms.Position = ms.Length;
if (chunked) {
bytes = GetChunkSizeBytes (count, false);
ms.Write (bytes, 0, bytes.Length);
}
int new_count = Math.Min (count, 16384 - (int) ms.Position + (int) start);
ms.Write (buffer, offset, new_count);
count -= new_count;
offset += new_count;
InternalWrite (ms.GetBuffer (), (int) start, (int) (ms.Length - start));
ms.SetLength (0);
ms.Capacity = 0; // 'dispose' the buffer in ms.
} else if (chunked) {
bytes = GetChunkSizeBytes (count, false);
InternalWrite (bytes, 0, bytes.Length);
}
if (count > 0)
InternalWrite (buffer, offset, count);
if (chunked)
InternalWrite (crlf, 0, 2);
}
public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count,
AsyncCallback cback, object state)
{
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
byte [] bytes = null;
MemoryStream ms = GetHeaders (false);
bool chunked = response.SendChunked;
if (ms != null) {
long start = ms.Position;
ms.Position = ms.Length;
if (chunked) {
bytes = GetChunkSizeBytes (count, false);
ms.Write (bytes, 0, bytes.Length);
}
ms.Write (buffer, offset, count);
buffer = ms.GetBuffer ();
offset = (int) start;
count = (int) (ms.Position - start);
} else if (chunked) {
bytes = GetChunkSizeBytes (count, false);
InternalWrite (bytes, 0, bytes.Length);
}
return stream.BeginWrite (buffer, offset, count, cback, state);
}
public override void EndWrite (IAsyncResult ares)
{
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (ignore_errors) {
try {
stream.EndWrite (ares);
if (response.SendChunked)
stream.Write (crlf, 0, 2);
} catch { }
} else {
stream.EndWrite (ares);
if (response.SendChunked)
stream.Write (crlf, 0, 2);
}
}
public override int Read ([In,Out] byte[] buffer, int offset, int count)
{
throw new NotSupportedException ();
}
public override IAsyncResult BeginRead (byte [] buffer, int offset, int count,
AsyncCallback cback, object state)
{
throw new NotSupportedException ();
}
public override int EndRead (IAsyncResult ares)
{
throw new NotSupportedException ();
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ();
}
public override void SetLength (long value)
{
throw new NotSupportedException ();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml
{
internal abstract partial class AbstractMethodXmlBuilder
{
private const string ArgumentElementName = "Argument";
private const string ArrayElementName = "Array";
private const string ArrayElementAccessElementName = "ArrayElementAccess";
private const string ArrayTypeElementName = "ArrayType";
private const string AssignmentElementName = "Assignment";
private const string BaseReferenceElementName = "BaseReference";
private const string BinaryOperationElementName = "BinaryOperation";
private const string BlockElementName = "Block";
private const string BooleanElementName = "Boolean";
private const string BoundElementName = "Bound";
private const string CastElementName = "Cast";
private const string CharElementName = "Char";
private const string CommentElementName = "Comment";
private const string ExpressionElementName = "Expression";
private const string ExpressionStatementElementName = "ExpressionStatement";
private const string LiteralElementName = "Literal";
private const string LocalElementName = "Local";
private const string MethodCallElementName = "MethodCall";
private const string NameElementName = "Name";
private const string NameRefElementName = "NameRef";
private const string NewArrayElementName = "NewArray";
private const string NewClassElementName = "NewClass";
private const string NewDelegateElementName = "NewDelegate";
private const string NullElementName = "Null";
private const string NumberElementName = "Number";
private const string ParenthesesElementName = "Parentheses";
private const string QuoteElementName = "Quote";
private const string StringElementName = "String";
private const string ThisReferenceElementName = "ThisReference";
private const string TypeElementName = "Type";
private const string BinaryOperatorAttributeName = "binaryoperator";
private const string DirectCastAttributeName = "directcast";
private const string FullNameAttributeName = "fullname";
private const string ImplicitAttributeName = "implicit";
private const string LineAttributeName = "line";
private const string NameAttributeName = "name";
private const string RankAttributeName = "rank";
private const string TryCastAttributeName = "trycast";
private const string TypeAttributeName = "type";
private const string VariableKindAttributeName = "variablekind";
private static readonly char[] s_encodedChars = new[] { '<', '>', '&' };
private static readonly string[] s_encodings = new[] { "<", ">", "&" };
private readonly StringBuilder _builder;
protected readonly IMethodSymbol Symbol;
protected readonly SemanticModel SemanticModel;
protected readonly SourceText Text;
protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel)
{
_builder = new StringBuilder();
this.Symbol = symbol;
this.SemanticModel = semanticModel;
this.Text = semanticModel.SyntaxTree.GetText();
}
public override string ToString()
{
return _builder.ToString();
}
private void AppendEncoded(string text)
{
var length = text.Length;
var startIndex = 0;
int index;
for (index = 0; index < length; index++)
{
var encodingIndex = Array.IndexOf(s_encodedChars, text[index]);
if (encodingIndex >= 0)
{
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
_builder.Append(s_encodings[encodingIndex]);
startIndex = index + 1;
}
}
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
}
private void AppendOpenTag(string name, AttributeInfo[] attributes)
{
_builder.Append('<');
_builder.Append(name);
foreach (var attribute in attributes.Where(a => !a.IsEmpty))
{
_builder.Append(' ');
_builder.Append(attribute.Name);
_builder.Append("=\"");
AppendEncoded(attribute.Value);
_builder.Append('"');
}
_builder.Append('>');
}
private void AppendCloseTag(string name)
{
_builder.Append("</");
_builder.Append(name);
_builder.Append('>');
}
private void AppendLeafTag(string name)
{
_builder.Append('<');
_builder.Append(name);
_builder.Append("/>");
}
private static string GetBinaryOperatorKindText(BinaryOperatorKind kind)
{
switch (kind)
{
case BinaryOperatorKind.Plus:
return "plus";
case BinaryOperatorKind.BitwiseOr:
return "bitor";
case BinaryOperatorKind.BitwiseAnd:
return "bitand";
case BinaryOperatorKind.Concatenate:
return "concatenate";
case BinaryOperatorKind.AddDelegate:
return "adddelegate";
default:
throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString());
}
}
private static string GetVariableKindText(VariableKind kind)
{
switch (kind)
{
case VariableKind.Property:
return "property";
case VariableKind.Method:
return "method";
case VariableKind.Field:
return "field";
case VariableKind.Local:
return "local";
case VariableKind.Unknown:
return "unknown";
default:
throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString());
}
}
private IDisposable Tag(string name, params AttributeInfo[] attributes)
{
return new AutoTag(this, name, attributes);
}
private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind)
{
if (kind == BinaryOperatorKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind));
}
private AttributeInfo FullNameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(FullNameAttributeName, name);
}
private AttributeInfo ImplicitAttribute(bool? @implicit)
{
if (@implicit == null)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no");
}
private AttributeInfo LineNumberAttribute(int lineNumber)
{
return new AttributeInfo(LineAttributeName, lineNumber.ToString());
}
private AttributeInfo NameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(NameAttributeName, name);
}
private AttributeInfo RankAttribute(int rank)
{
return new AttributeInfo(RankAttributeName, rank.ToString());
}
private AttributeInfo SpecialCastKindAttribute(SpecialCastKind? specialCastKind = null)
{
switch (specialCastKind)
{
case SpecialCastKind.DirectCast:
return new AttributeInfo(DirectCastAttributeName, "yes");
case SpecialCastKind.TryCast:
return new AttributeInfo(TryCastAttributeName, "yes");
default:
return AttributeInfo.Empty;
}
}
private AttributeInfo TypeAttribute(string typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(TypeAttributeName, typeName);
}
private AttributeInfo VariableKindAttribute(VariableKind kind)
{
if (kind == VariableKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind));
}
protected IDisposable ArgumentTag()
{
return Tag(ArgumentElementName);
}
protected IDisposable ArrayElementAccessTag()
{
return Tag(ArrayElementAccessElementName);
}
protected IDisposable ArrayTag()
{
return Tag(ArrayElementName);
}
protected IDisposable ArrayTypeTag(int rank)
{
return Tag(ArrayTypeElementName, RankAttribute(rank));
}
protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None)
{
return Tag(AssignmentElementName, BinaryOperatorAttribute(kind));
}
protected void BaseReferenceTag()
{
AppendLeafTag(BaseReferenceElementName);
}
protected IDisposable BinaryOperationTag(BinaryOperatorKind kind)
{
return Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind));
}
protected IDisposable BlockTag()
{
return Tag(BlockElementName);
}
protected IDisposable BooleanTag()
{
return Tag(BooleanElementName);
}
protected IDisposable BoundTag()
{
return Tag(BoundElementName);
}
protected IDisposable CastTag(SpecialCastKind? specialCastKind = null)
{
return Tag(CastElementName, SpecialCastKindAttribute(specialCastKind));
}
protected IDisposable CharTag()
{
return Tag(CharElementName);
}
protected IDisposable CommentTag()
{
return Tag(CommentElementName);
}
protected IDisposable ExpressionTag()
{
return Tag(ExpressionElementName);
}
protected IDisposable ExpressionStatementTag(int lineNumber)
{
return Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber));
}
protected IDisposable LiteralTag()
{
return Tag(LiteralElementName);
}
protected IDisposable LocalTag(int lineNumber)
{
return Tag(LocalElementName, LineNumberAttribute(lineNumber));
}
protected IDisposable MethodCallTag()
{
return Tag(MethodCallElementName);
}
protected IDisposable NameTag()
{
return Tag(NameElementName);
}
protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null)
{
return Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName));
}
protected IDisposable NewArrayTag()
{
return Tag(NewArrayElementName);
}
protected IDisposable NewClassTag()
{
return Tag(NewClassElementName);
}
protected IDisposable NewDelegateTag(string name)
{
return Tag(NewDelegateElementName, NameAttribute(name));
}
protected void NullTag()
{
AppendLeafTag(NullElementName);
}
protected IDisposable NumberTag(string typeName = null)
{
return Tag(NumberElementName, TypeAttribute(typeName));
}
protected IDisposable ParenthesesTag()
{
return Tag(ParenthesesElementName);
}
protected IDisposable QuoteTag(int lineNumber)
{
return Tag(QuoteElementName, LineNumberAttribute(lineNumber));
}
protected IDisposable StringTag()
{
return Tag(StringElementName);
}
protected void ThisReferenceTag()
{
AppendLeafTag(ThisReferenceElementName);
}
protected IDisposable TypeTag(bool? @implicit = null)
{
return Tag(TypeElementName, ImplicitAttribute(@implicit));
}
protected void LineBreak()
{
_builder.AppendLine();
}
protected void EncodedText(string text)
{
AppendEncoded(text);
}
protected int GetMark()
{
return _builder.Length;
}
protected void Rewind(int mark)
{
_builder.Length = mark;
}
protected virtual VariableKind GetVariableKind(ISymbol symbol)
{
if (symbol == null)
{
return VariableKind.Unknown;
}
switch (symbol.Kind)
{
case SymbolKind.Event:
case SymbolKind.Field:
return VariableKind.Field;
case SymbolKind.Local:
case SymbolKind.Parameter:
return VariableKind.Local;
case SymbolKind.Method:
return VariableKind.Method;
case SymbolKind.Property:
return VariableKind.Property;
default:
throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString());
}
}
protected string GetTypeName(ITypeSymbol typeSymbol)
{
return MetadataNameHelpers.GetMetadataName(typeSymbol);
}
protected int GetLineNumber(SyntaxNode node)
{
return Text.Lines.IndexOf(node.SpanStart);
}
protected void GenerateUnknown(SyntaxNode node)
{
using (QuoteTag(GetLineNumber(node)))
{
EncodedText(node.ToString());
}
}
protected void GenerateName(string name)
{
using (NameTag())
{
EncodedText(name);
}
}
protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false)
{
if (type.TypeKind == TypeKind.Array)
{
var arrayType = (IArrayTypeSymbol)type;
using (var tag = ArrayTypeTag(arrayType.Rank))
{
GenerateType(arrayType.ElementType, @implicit, assemblyQualify);
}
}
else
{
using (TypeTag(@implicit))
{
var typeName = assemblyQualify
? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString()
: GetTypeName(type);
EncodedText(typeName);
}
}
}
protected void GenerateType(SpecialType specialType)
{
GenerateType(SemanticModel.Compilation.GetSpecialType(specialType));
}
protected void GenerateNullLiteral()
{
using (LiteralTag())
{
NullTag();
}
}
protected void GenerateNumber(object value, ITypeSymbol type)
{
using (NumberTag(GetTypeName(type)))
{
if (value is double)
{
// Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit
EncodedText(((double)value).ToString("G17", CultureInfo.InvariantCulture));
}
else if (value is float)
{
EncodedText(((float)value).ToString("R", CultureInfo.InvariantCulture));
}
else
{
EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture));
}
}
}
protected void GenerateNumber(object value, SpecialType specialType)
{
GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType));
}
protected void GenerateChar(char value)
{
using (CharTag())
{
EncodedText(value.ToString());
}
}
protected void GenerateString(string value)
{
using (StringTag())
{
EncodedText(value);
}
}
protected void GenerateBoolean(bool value)
{
using (BooleanTag())
{
EncodedText(value.ToString().ToLower());
}
}
protected void GenerateThisReference()
{
ThisReferenceTag();
}
protected void GenerateBaseReference()
{
BaseReferenceTag();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.Numerics;
#if KESTREL
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
#endif
namespace System.Net.Http.HPack
{
internal sealed class HPackDecoder
{
private enum State : byte
{
Ready,
HeaderFieldIndex,
HeaderNameIndex,
HeaderNameLength,
HeaderNameLengthContinue,
HeaderName,
HeaderValueLength,
HeaderValueLengthContinue,
HeaderValue,
DynamicTableSizeUpdate
}
public const int DefaultHeaderTableSize = 4096;
public const int DefaultStringOctetsSize = 4096;
public const int DefaultMaxHeadersLength = 64 * 1024;
// http://httpwg.org/specs/rfc7541.html#rfc.section.6.1
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 1 | Index (7+) |
// +---+---------------------------+
private const byte IndexedHeaderFieldMask = 0x80;
// http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.1
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 0 | 1 | Index (6+) |
// +---+---+-----------------------+
private const byte LiteralHeaderFieldWithIncrementalIndexingMask = 0xc0;
// http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.2
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 0 | 0 | 0 | 0 | Index (4+) |
// +---+---+-----------------------+
private const byte LiteralHeaderFieldWithoutIndexingMask = 0xf0;
// http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.3
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 0 | 0 | 0 | 1 | Index (4+) |
// +---+---+-----------------------+
private const byte LiteralHeaderFieldNeverIndexedMask = 0xf0;
// http://httpwg.org/specs/rfc7541.html#rfc.section.6.3
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 0 | 0 | 1 | Max size (5+) |
// +---+---------------------------+
private const byte DynamicTableSizeUpdateMask = 0xe0;
// http://httpwg.org/specs/rfc7541.html#rfc.section.5.2
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | H | String Length (7+) |
// +---+---------------------------+
private const byte HuffmanMask = 0x80;
private const int IndexedHeaderFieldPrefix = 7;
private const int LiteralHeaderFieldWithIncrementalIndexingPrefix = 6;
private const int LiteralHeaderFieldWithoutIndexingPrefix = 4;
private const int LiteralHeaderFieldNeverIndexedPrefix = 4;
private const int DynamicTableSizeUpdatePrefix = 5;
private const int StringLengthPrefix = 7;
private readonly int _maxDynamicTableSize;
private readonly int _maxHeadersLength;
private readonly DynamicTable _dynamicTable;
private IntegerDecoder _integerDecoder;
private byte[] _stringOctets;
private byte[] _headerNameOctets;
private byte[] _headerValueOctets;
private (int start, int length)? _headerNameRange;
private (int start, int length)? _headerValueRange;
private State _state = State.Ready;
private byte[]? _headerName;
private int _headerStaticIndex;
private int _stringIndex;
private int _stringLength;
private int _headerNameLength;
private int _headerValueLength;
private bool _index;
private bool _huffman;
private bool _headersObserved;
public HPackDecoder(int maxDynamicTableSize = DefaultHeaderTableSize, int maxHeadersLength = DefaultMaxHeadersLength)
: this(maxDynamicTableSize, maxHeadersLength, new DynamicTable(maxDynamicTableSize))
{
}
// For testing.
internal HPackDecoder(int maxDynamicTableSize, int maxHeadersLength, DynamicTable dynamicTable)
{
_maxDynamicTableSize = maxDynamicTableSize;
_maxHeadersLength = maxHeadersLength;
_dynamicTable = dynamicTable;
_stringOctets = new byte[DefaultStringOctetsSize];
_headerNameOctets = new byte[DefaultStringOctetsSize];
_headerValueOctets = new byte[DefaultStringOctetsSize];
}
public void Decode(in ReadOnlySequence<byte> data, bool endHeaders, IHttpHeadersHandler handler)
{
foreach (ReadOnlyMemory<byte> segment in data)
{
DecodeInternal(segment.Span, handler);
}
CheckIncompleteHeaderBlock(endHeaders);
}
public void Decode(ReadOnlySpan<byte> data, bool endHeaders, IHttpHeadersHandler handler)
{
DecodeInternal(data, handler);
CheckIncompleteHeaderBlock(endHeaders);
}
private void DecodeInternal(ReadOnlySpan<byte> data, IHttpHeadersHandler handler)
{
int currentIndex = 0;
do
{
switch (_state)
{
case State.Ready:
Parse(data, ref currentIndex, handler);
break;
case State.HeaderFieldIndex:
ParseHeaderFieldIndex(data, ref currentIndex, handler);
break;
case State.HeaderNameIndex:
ParseHeaderNameIndex(data, ref currentIndex, handler);
break;
case State.HeaderNameLength:
ParseHeaderNameLength(data, ref currentIndex, handler);
break;
case State.HeaderNameLengthContinue:
ParseHeaderNameLengthContinue(data, ref currentIndex, handler);
break;
case State.HeaderName:
ParseHeaderName(data, ref currentIndex, handler);
break;
case State.HeaderValueLength:
ParseHeaderValueLength(data, ref currentIndex, handler);
break;
case State.HeaderValueLengthContinue:
ParseHeaderValueLengthContinue(data, ref currentIndex, handler);
break;
case State.HeaderValue:
ParseHeaderValue(data, ref currentIndex, handler);
break;
case State.DynamicTableSizeUpdate:
ParseDynamicTableSizeUpdate(data, ref currentIndex);
break;
default:
// Can't happen
Debug.Fail("HPACK decoder reach an invalid state");
throw new NotImplementedException(_state.ToString());
}
}
// Parse methods each check the length. This check is to see whether there is still data available
// and to continue parsing.
while (currentIndex < data.Length);
// If a header range was set, but the value was not in the data, then copy the range
// to the name buffer. Must copy because because the data will be replaced and the range
// will no longer be valid.
if (_headerNameRange != null)
{
EnsureStringCapacity(ref _headerNameOctets);
_headerName = _headerNameOctets;
ReadOnlySpan<byte> headerBytes = data.Slice(_headerNameRange.GetValueOrDefault().start, _headerNameRange.GetValueOrDefault().length);
headerBytes.CopyTo(_headerName);
_headerNameLength = headerBytes.Length;
_headerNameRange = null;
}
}
private void ParseDynamicTableSizeUpdate(ReadOnlySpan<byte> data, ref int currentIndex)
{
if (TryDecodeInteger(data, ref currentIndex, out int intResult))
{
SetDynamicHeaderTableSize(intResult);
_state = State.Ready;
}
}
private void ParseHeaderValueLength(ReadOnlySpan<byte> data, ref int currentIndex, IHttpHeadersHandler handler)
{
if (currentIndex < data.Length)
{
byte b = data[currentIndex++];
_huffman = IsHuffmanEncoded(b);
if (_integerDecoder.BeginTryDecode((byte)(b & ~HuffmanMask), StringLengthPrefix, out int intResult))
{
OnStringLength(intResult, nextState: State.HeaderValue);
if (intResult == 0)
{
OnString(nextState: State.Ready);
ProcessHeaderValue(data, handler);
}
else
{
ParseHeaderValue(data, ref currentIndex, handler);
}
}
else
{
_state = State.HeaderValueLengthContinue;
ParseHeaderValueLengthContinue(data, ref currentIndex, handler);
}
}
}
private void ParseHeaderNameLengthContinue(ReadOnlySpan<byte> data, ref int currentIndex, IHttpHeadersHandler handler)
{
if (TryDecodeInteger(data, ref currentIndex, out int intResult))
{
// IntegerDecoder disallows overlong encodings, where an integer is encoded with more bytes than is strictly required.
// 0 should always be represented by a single byte, so we shouldn't need to check for it in the continuation case.
Debug.Assert(intResult != 0, "A header name length of 0 should never be encoded with a continuation byte.");
OnStringLength(intResult, nextState: State.HeaderName);
ParseHeaderName(data, ref currentIndex, handler);
}
}
private void ParseHeaderValueLengthContinue(ReadOnlySpan<byte> data, ref int currentIndex, IHttpHeadersHandler handler)
{
if (TryDecodeInteger(data, ref currentIndex, out int intResult))
{
// 0 should always be represented by a single byte, so we shouldn't need to check for it in the continuation case.
Debug.Assert(intResult != 0, "A header value length of 0 should never be encoded with a continuation byte.");
OnStringLength(intResult, nextState: State.HeaderValue);
ParseHeaderValue(data, ref currentIndex, handler);
}
}
private void ParseHeaderFieldIndex(ReadOnlySpan<byte> data, ref int currentIndex, IHttpHeadersHandler handler)
{
if (TryDecodeInteger(data, ref currentIndex, out int intResult))
{
OnIndexedHeaderField(intResult, handler);
}
}
private void ParseHeaderNameIndex(ReadOnlySpan<byte> data, ref int currentIndex, IHttpHeadersHandler handler)
{
if (TryDecodeInteger(data, ref currentIndex, out int intResult))
{
OnIndexedHeaderName(intResult);
ParseHeaderValueLength(data, ref currentIndex, handler);
}
}
private void ParseHeaderNameLength(ReadOnlySpan<byte> data, ref int currentIndex, IHttpHeadersHandler handler)
{
if (currentIndex < data.Length)
{
byte b = data[currentIndex++];
_huffman = IsHuffmanEncoded(b);
if (_integerDecoder.BeginTryDecode((byte)(b & ~HuffmanMask), StringLengthPrefix, out int intResult))
{
if (intResult == 0)
{
throw new HPackDecodingException(SR.Format(SR.net_http_invalid_header_name, ""));
}
OnStringLength(intResult, nextState: State.HeaderName);
ParseHeaderName(data, ref currentIndex, handler);
}
else
{
_state = State.HeaderNameLengthContinue;
ParseHeaderNameLengthContinue(data, ref currentIndex, handler);
}
}
}
private void Parse(ReadOnlySpan<byte> data, ref int currentIndex, IHttpHeadersHandler handler)
{
if (currentIndex < data.Length)
{
Debug.Assert(_state == State.Ready, "Should be ready to parse a new header.");
byte b = data[currentIndex++];
switch (BitOperations.LeadingZeroCount(b) - 24) // byte 'b' is extended to uint, so will have 24 extra 0s.
{
case 0: // Indexed Header Field
{
_headersObserved = true;
int val = b & ~IndexedHeaderFieldMask;
if (_integerDecoder.BeginTryDecode((byte)val, IndexedHeaderFieldPrefix, out int intResult))
{
OnIndexedHeaderField(intResult, handler);
}
else
{
_state = State.HeaderFieldIndex;
ParseHeaderFieldIndex(data, ref currentIndex, handler);
}
break;
}
case 1: // Literal Header Field with Incremental Indexing
ParseLiteralHeaderField(
data,
ref currentIndex,
b,
LiteralHeaderFieldWithIncrementalIndexingMask,
LiteralHeaderFieldWithIncrementalIndexingPrefix,
index: true,
handler);
break;
case 4:
default: // Literal Header Field without Indexing
ParseLiteralHeaderField(
data,
ref currentIndex,
b,
LiteralHeaderFieldWithoutIndexingMask,
LiteralHeaderFieldWithoutIndexingPrefix,
index: false,
handler);
break;
case 3: // Literal Header Field Never Indexed
ParseLiteralHeaderField(
data,
ref currentIndex,
b,
LiteralHeaderFieldNeverIndexedMask,
LiteralHeaderFieldNeverIndexedPrefix,
index: false,
handler);
break;
case 2: // Dynamic Table Size Update
{
// https://tools.ietf.org/html/rfc7541#section-4.2
// This dynamic table size
// update MUST occur at the beginning of the first header block
// following the change to the dynamic table size.
if (_headersObserved)
{
throw new HPackDecodingException(SR.net_http_hpack_late_dynamic_table_size_update);
}
if (_integerDecoder.BeginTryDecode((byte)(b & ~DynamicTableSizeUpdateMask), DynamicTableSizeUpdatePrefix, out int intResult))
{
SetDynamicHeaderTableSize(intResult);
}
else
{
_state = State.DynamicTableSizeUpdate;
ParseDynamicTableSizeUpdate(data, ref currentIndex);
}
break;
}
}
}
}
private void ParseLiteralHeaderField(ReadOnlySpan<byte> data, ref int currentIndex, byte b, byte mask, byte indexPrefix, bool index, IHttpHeadersHandler handler)
{
_headersObserved = true;
_index = index;
int val = b & ~mask;
if (val == 0)
{
_state = State.HeaderNameLength;
ParseHeaderNameLength(data, ref currentIndex, handler);
}
else
{
if (_integerDecoder.BeginTryDecode((byte)val, indexPrefix, out int intResult))
{
OnIndexedHeaderName(intResult);
ParseHeaderValueLength(data, ref currentIndex, handler);
}
else
{
_state = State.HeaderNameIndex;
ParseHeaderNameIndex(data, ref currentIndex, handler);
}
}
}
private void ParseHeaderName(ReadOnlySpan<byte> data, ref int currentIndex, IHttpHeadersHandler handler)
{
// Read remaining chars, up to the length of the current data
int count = Math.Min(_stringLength - _stringIndex, data.Length - currentIndex);
// Check whether the whole string is available in the data and no decompression required.
// If string is good then mark its range.
// NOTE: it may need to be copied to buffer later the if value is not current data.
if (count == _stringLength && !_huffman)
{
// Fast path. Store the range rather than copying.
_headerNameRange = (start: currentIndex, count);
currentIndex += count;
_state = State.HeaderValueLength;
}
else
{
// Copy string to temporary buffer.
// _stringOctets was already
data.Slice(currentIndex, count).CopyTo(_stringOctets.AsSpan(_stringIndex));
_stringIndex += count;
currentIndex += count;
if (_stringIndex == _stringLength)
{
OnString(nextState: State.HeaderValueLength);
ParseHeaderValueLength(data, ref currentIndex, handler);
}
}
}
private void ParseHeaderValue(ReadOnlySpan<byte> data, ref int currentIndex, IHttpHeadersHandler handler)
{
// Read remaining chars, up to the length of the current data
int count = Math.Min(_stringLength - _stringIndex, data.Length - currentIndex);
// Check whether the whole string is available in the data and no decompressed required.
// If string is good then mark its range.
if (count == _stringLength && !_huffman)
{
// Fast path. Store the range rather than copying.
_headerValueRange = (start: currentIndex, count);
currentIndex += count;
_state = State.Ready;
ProcessHeaderValue(data, handler);
}
else
{
// Copy string to temporary buffer.
data.Slice(currentIndex, count).CopyTo(_stringOctets.AsSpan(_stringIndex));
_stringIndex += count;
currentIndex += count;
if (_stringIndex == _stringLength)
{
OnString(nextState: State.Ready);
ProcessHeaderValue(data, handler);
}
}
}
private void CheckIncompleteHeaderBlock(bool endHeaders)
{
if (endHeaders)
{
if (_state != State.Ready)
{
throw new HPackDecodingException(SR.net_http_hpack_incomplete_header_block);
}
_headersObserved = false;
}
}
private void ProcessHeaderValue(ReadOnlySpan<byte> data, IHttpHeadersHandler handler)
{
ReadOnlySpan<byte> headerValueSpan = _headerValueRange == null
? _headerValueOctets.AsSpan(0, _headerValueLength)
: data.Slice(_headerValueRange.GetValueOrDefault().start, _headerValueRange.GetValueOrDefault().length);
if (_headerStaticIndex > 0)
{
handler.OnStaticIndexedHeader(_headerStaticIndex, headerValueSpan);
if (_index)
{
_dynamicTable.Insert(H2StaticTable.Get(_headerStaticIndex - 1).Name, headerValueSpan);
}
}
else
{
ReadOnlySpan<byte> headerNameSpan = _headerNameRange == null
? _headerName.AsSpan(0, _headerNameLength)
: data.Slice(_headerNameRange.GetValueOrDefault().start, _headerNameRange.GetValueOrDefault().length);
handler.OnHeader(headerNameSpan, headerValueSpan);
if (_index)
{
_dynamicTable.Insert(headerNameSpan, headerValueSpan);
}
}
_headerStaticIndex = 0;
_headerNameRange = null;
_headerValueRange = null;
}
public void CompleteDecode()
{
if (_state != State.Ready)
{
// Incomplete header block
throw new HPackDecodingException(SR.net_http_hpack_unexpected_end);
}
}
private void OnIndexedHeaderField(int index, IHttpHeadersHandler handler)
{
if (index <= H2StaticTable.Count)
{
handler.OnStaticIndexedHeader(index);
}
else
{
ref readonly HeaderField header = ref GetDynamicHeader(index);
handler.OnHeader(header.Name, header.Value);
}
_state = State.Ready;
}
private void OnIndexedHeaderName(int index)
{
if (index <= H2StaticTable.Count)
{
_headerStaticIndex = index;
}
else
{
_headerName = GetDynamicHeader(index).Name;
_headerNameLength = _headerName.Length;
}
_state = State.HeaderValueLength;
}
private void OnStringLength(int length, State nextState)
{
if (length > _stringOctets.Length)
{
if (length > _maxHeadersLength)
{
throw new HPackDecodingException(SR.Format(SR.net_http_headers_exceeded_length, _maxHeadersLength));
}
_stringOctets = new byte[Math.Max(length, _stringOctets.Length * 2)];
}
_stringLength = length;
_stringIndex = 0;
_state = nextState;
}
private void OnString(State nextState)
{
int Decode(ref byte[] dst)
{
if (_huffman)
{
return Huffman.Decode(new ReadOnlySpan<byte>(_stringOctets, 0, _stringLength), ref dst);
}
else
{
EnsureStringCapacity(ref dst);
Buffer.BlockCopy(_stringOctets, 0, dst, 0, _stringLength);
return _stringLength;
}
}
try
{
if (_state == State.HeaderName)
{
_headerNameLength = Decode(ref _headerNameOctets);
_headerName = _headerNameOctets;
}
else
{
_headerValueLength = Decode(ref _headerValueOctets);
}
}
catch (HuffmanDecodingException ex)
{
throw new HPackDecodingException(SR.net_http_hpack_huffman_decode_failed, ex);
}
_state = nextState;
}
private void EnsureStringCapacity(ref byte[] dst)
{
if (dst.Length < _stringLength)
{
dst = new byte[Math.Max(_stringLength, dst.Length * 2)];
}
}
private bool TryDecodeInteger(ReadOnlySpan<byte> data, ref int currentIndex, out int result)
{
for (; currentIndex < data.Length; currentIndex++)
{
if (_integerDecoder.TryDecode(data[currentIndex], out result))
{
currentIndex++;
return true;
}
}
result = default;
return false;
}
private static bool IsHuffmanEncoded(byte b)
{
return (b & HuffmanMask) != 0;
}
private ref readonly HeaderField GetDynamicHeader(int index)
{
try
{
return ref _dynamicTable[index - H2StaticTable.Count - 1];
}
catch (IndexOutOfRangeException)
{
// Header index out of range.
throw new HPackDecodingException(SR.Format(SR.net_http_hpack_invalid_index, index));
}
}
private void SetDynamicHeaderTableSize(int size)
{
if (size > _maxDynamicTableSize)
{
throw new HPackDecodingException(SR.Format(SR.net_http_hpack_large_table_size_update, size, _maxDynamicTableSize));
}
_dynamicTable.Resize(size);
}
}
}
| |
using System.Runtime.CompilerServices;
using UnityEngine;
using Votyra.Core.Models;
using Votyra.Core.Pooling;
namespace Votyra.Core.Utils
{
public static class ConversionUtils
{
public static Vector2f ToVector2f(this Vector2 vector) => new Vector2f(vector.x, vector.y);
public static Vector3f ToVector3f(this Vector3 vector) => new Vector3f(vector.x, vector.y, vector.z);
public static PooledArrayContainer<Vector3f> ToVector3f(this PooledArrayContainer<Vector3> planesUnity)
{
var unityArray = planesUnity.Array;
var container = PooledArrayContainer<Vector3f>.CreateDirty(unityArray.Length);
var votyraArray = container.Array;
for (var i = 0; i < unityArray.Length; i++)
{
votyraArray[i] = unityArray[i]
.ToVector3f();
}
return container;
}
public static Plane3f ToPlane3f(this Plane plane) => new Plane3f(plane.normal.ToVector3f(), plane.distance);
public static PooledArrayContainer<Plane3f> ToPlane3f(this PooledArrayContainer<Plane> planesUnity)
{
var unityArray = planesUnity.Array;
var container = PooledArrayContainer<Plane3f>.CreateDirty(unityArray.Length);
var votyraArray = container.Array;
for (var i = 0; i < unityArray.Length; i++)
{
votyraArray[i] = unityArray[i]
.ToPlane3f();
}
return container;
}
public static Vector2 ToVector2(this Vector2f vector) => new Vector2(vector.X, vector.Y);
public static Vector3 ToVector3(this Vector3f vector) => new Vector3(vector.X, vector.Y, vector.Z);
public static Bounds ToBounds(this Area3f bounds) => new Bounds(bounds.Center.ToVector3(), bounds.Size.ToVector3());
// public static UnityEngine.Vector3[] ToVector3Array(this List<Vector3f> vector)
// {
// return vector.Select(o => o.ToVector3()).ToArray();
// // return vector.GetInnerArray<Vector3f>().ToVector3();
// }
//
// public static List<UnityEngine.Vector3> ToVector3List(this List<Vector3f> vector)
// {
// return vector.Select(o => o.ToVector3()).ToList();
// // return vector.ConvertListOfMatchingStructs<Vector3f, UnityEngine.Vector3>(ToVector3);
// }
// public static Plane3f[] ToPlane3f(this UnityEngine.Plane[] vector)
// {
// return Array.ConvertAll(vector, item => item.ToPlane3f());
//
// // var union = new UnionPlane();
// // union.Unity = vector;
// // var res = union.Votyra;
// // if (res.Length != vector.Length)
// // {
// // throw new InvalidOperationException("ToPlane3f conversion failed!");
// // }
// // return res;
// }
// public static UnityEngine.Vector3[] ToVector3(this Vector3f[] vector)
// {
// return Array.ConvertAll(vector, item => item.ToVector3());
//
//
// // var union = new UnionVector3();
// // union.Votyra = vector;
// // var res = union.Unity;
// // if (res.Length != vector.Length)
// // {
// // throw new InvalidOperationException("ToVector3 conversion failed!");
// // }
// // return res;
// // //return vector.Select(o => o.ToVector3()).ToArray();
// }
// public static Vector3f[] ToVector3f(this UnityEngine.Vector3[] vector)
// {
// return Array.ConvertAll(vector, item => item.ToVector3f());
//
// // var union = new UnionVector3();
// // union.Unity = vector;
// // var res = union.Votyra;
// // if (res.Length != vector.Length)
// // {
// // throw new InvalidOperationException("ToVector3f conversion failed!");
// // }
// // return res;
// // //return vector.Select(o => o.ToVector3()).ToArray();
// }
// public static UnityEngine.Vector2[] ToVector2(this Vector2f[] vector)
// {
// return Array.ConvertAll(vector, item => item.ToVector2());
//
// // var union = new UnionVector2();
// // union.Votyra = vector;
// // var res = union.Unity;
// // if (res.Length != vector.Length)
// // {
// // throw new InvalidOperationException("ToVector2 conversion failed!");
// // }
// // return res;
// // //return vector.Select(o => o.ToVector2()).ToArray();
// }
// public static UnityEngine.Vector2[] ToVector2Array(this List<Vector2f> vector)
// {
// return vector.Select(o => o.ToVector2()).ToArray();
// // return vector.GetInnerArray<Vector2f>().ToVector2();
// }
//
// public static List<UnityEngine.Vector2> ToVector2List(this List<Vector2f> vector)
// {
// return vector.Select(o => o.ToVector2()).ToList();
// // return vector.ConvertListOfMatchingStructs<Vector2f, UnityEngine.Vector2>(ToVector2);
// }
public static Matrix4x4f ToMatrix4x4f(this Matrix4x4 mat) => new Matrix4x4f(mat.m00, mat.m01, mat.m02, mat.m03, mat.m10, mat.m11, mat.m12, mat.m13, mat.m20, mat.m21, mat.m22, mat.m23, mat.m30, mat.m31, mat.m32, mat.m33);
public static Matrix4x4 ToMatrix4x4(this Matrix4x4f mat)
{
var mat2 = new Matrix4x4();
mat2.m00 = mat.m00;
mat2.m10 = mat.m10;
mat2.m20 = mat.m20;
mat2.m30 = mat.m30;
mat2.m01 = mat.m01;
mat2.m11 = mat.m11;
mat2.m21 = mat.m21;
mat2.m31 = mat.m31;
mat2.m02 = mat.m02;
mat2.m12 = mat.m12;
mat2.m22 = mat.m22;
mat2.m32 = mat.m32;
mat2.m03 = mat.m03;
mat2.m13 = mat.m13;
mat2.m23 = mat.m23;
mat2.m33 = mat.m33;
return mat2;
}
// private static T[] GetInnerArray<T>(this List<T> source)
// {
// source.TrimExcess();
// var itemsGet = ListInternals<T>.ItemsGet;
// var res = itemsGet(source);
// if (res.Length != source.Count)
// {
// throw new InvalidOperationException($"GetInnerArray<{typeof(T).Name}> conversion failed!");
// }
// return res;
// }
//
// private static List<TResult> ConvertListOfMatchingStructs<TSource, TResult>(this List<TSource> source, Func<TSource[], TResult[]> convert)
// {
// var target = new List<TResult>();
// var targetItemsSet = ListInternals<TResult>.ItemsSet;
// var sourceItemsGet = ListInternals<TSource>.ItemsGet;
// var targetSizeSet = ListInternals<TResult>.SizeSet;
//
// var sourceItemsValue = sourceItemsGet(source);
// var targetItems = convert(sourceItemsValue);
//
// targetItemsSet(target, targetItems);
// // targetItemsSet.SetValue(target, targetItems, BindingFlags.SetField, new ArrayKeepBinder<TSource, TResult>(), null);
// targetSizeSet(target, source.Count);
// return target;
// }
//
// [StructLayout(LayoutKind.Explicit)]
// private struct UnionVector3
// {
// [FieldOffset(0)] public UnityEngine.Vector3[] Unity;
// [FieldOffset(0)] public Vector3f[] Votyra;
// }
//
// [StructLayout(LayoutKind.Explicit)]
// private struct UnionVector2
// {
// [FieldOffset(0)] public UnityEngine.Vector2[] Unity;
// [FieldOffset(0)] public Vector2f[] Votyra;
// }
//
// [StructLayout(LayoutKind.Explicit)]
// private struct UnionPlane
// {
// [FieldOffset(0)] public UnityEngine.Plane[] Unity;
// [FieldOffset(0)] public Plane3f[] Votyra;
// }
// private static class ListInternals<T>
// {
// public static readonly Func<List<T>, T[]> ItemsGet;
// public static readonly Action<List<T>, T[]> ItemsSet;
// public static readonly Func<List<T>, int> SizeGet;
// public static readonly Action<List<T>, int> SizeSet;
//
// static ListInternals()
// {
// var itemsField = typeof(List<T>).GetField("_items", BindingFlags.Instance | BindingFlags.NonPublic);
// ItemsGet = CreateGetFieldDelegate<List<T>, T[]>(itemsField);
// ItemsSet = CreateSetFieldDelegate<List<T>, T[]>(itemsField);
//
// var sizeField = typeof(List<T>).GetField("_size", BindingFlags.Instance | BindingFlags.NonPublic);
// SizeGet = CreateGetFieldDelegate<List<T>, int>(sizeField);
// SizeSet = CreateSetFieldDelegate<List<T>, int>(sizeField);
// }
//
// private static Func<TOwner, TValue> CreateGetFieldDelegate<TOwner, TValue>(FieldInfo fieldInfo)
// {
// ParameterExpression ownerParameter = Expression.Parameter(typeof(TOwner));
//
// var fieldExpression = Expression.Field(
// Expression.Convert(ownerParameter, typeof(TOwner)), fieldInfo);
//
// return Expression.Lambda<Func<TOwner, TValue>>(
// Expression.Convert(fieldExpression, typeof(TValue)),
// ownerParameter).Compile();
// }
//
// private static Action<TOwner, TValue> CreateSetFieldDelegate<TOwner, TValue>(FieldInfo fieldInfo)
// {
// ParameterExpression ownerParameter = Expression.Parameter(typeof(TOwner));
// ParameterExpression fieldParameter = Expression.Parameter(typeof(TValue));
//
// var fieldExpression = Expression.Field(
// Expression.Convert(ownerParameter, typeof(TOwner)), fieldInfo);
//
// return Expression.Lambda<Action<TOwner, TValue>>(
// Expression.Assign(fieldExpression,
// Expression.Convert(fieldParameter, fieldInfo.FieldType)),
// ownerParameter, fieldParameter).Compile();
// }
// }
//
// private class ArrayKeepBinder<TSource, TResult> : Binder
// {
// public override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture)
// {
// return Type.DefaultBinder.BindToField(bindingAttr, match, value, culture);
// }
//
// public override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state)
// {
// return Type.DefaultBinder.BindToMethod(bindingAttr, match, ref args, modifiers, culture, names, out state);
// }
//
// public override object ChangeType(object value, Type type, CultureInfo culture)
// {
// if (value.GetType() == typeof(TSource[]) && type == typeof(TResult[]))
// {
// return value;
// }
// throw new NotImplementedException();
// }
//
// public override void ReorderArgumentArray(ref object[] args, object state)
// {
// Type.DefaultBinder.ReorderArgumentArray(ref args, state);
// }
//
// public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
// {
// return Type.DefaultBinder.SelectMethod(bindingAttr, match, types, modifiers);
// }
//
// public override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers)
// {
// return Type.DefaultBinder.SelectProperty(bindingAttr, match, returnType, indexes, modifiers);
// }
// }
}
}
| |
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Analytics
{
public class AnalyticsManager
{
#region Declarations
ServiceAccountCredential credential;
public Google.Apis.Analytics.v3.AnalyticsService analyticsService;
bool IsInitialized = false;
public List<Google.Apis.Analytics.v3.Data.Profile> Profiles {get; set;}
public Google.Apis.Analytics.v3.Data.Profile DefaultProfile { set; get; }
public List<Google.Apis.Analytics.v3.Data.Account> Accounts { get; set; }
public Google.Apis.Analytics.v3.Data.Account DefaultAccount { set; get; }
public List<Google.Apis.Analytics.v3.Data.CustomDimension> CustomDimensions { set; get; }
public List<Google.Apis.Analytics.v3.Data.CustomMetric> CustomMetrics { set; get; }
public bool InitFailed { get; set; }
public Exception FailureException { get; set; }
private string ApplicationName = "Default";
/// <summary>
/// Lets you enforce per-user quotas when calling the API from a server-side application, based on IP.
///
/// Ignored if QuotaUser is set
/// </summary>
public string UserIp { get; set; }
/// <summary>
/// Lets you enforce per-user quotas from a server-side application even in cases when the user's IP address is unknown.
///
/// You can choose any arbitrary string that uniquely identifies a user, but it is limited to 40 characters.
/// </summary>
public string QuotaUser { get; set; }
#endregion
#region Constructor & Initialization
public AnalyticsManager()
{
}
public AnalyticsManager(string certificateKeyPath, string apiEmail)
{
InitializeService(certificateKeyPath, apiEmail);
}
public AnalyticsManager(string certificateKeyPath, string apiEmail, string applicationName)
{
this.ApplicationName = applicationName;
InitializeService(certificateKeyPath, apiEmail);
}
public void InitializeService(string certificateKeyPath, string apiEmail)
{
if (!IsInitialized)
{
var certificate = new X509Certificate2(certificateKeyPath, "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
string x = certificate.IssuerName.Name;
credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(apiEmail)
{
Scopes = new[] { Google.Apis.Analytics.v3.AnalyticsService.Scope.Analytics, Google.Apis.Analytics.v3.AnalyticsService.Scope.AnalyticsEdit, Google.Apis.Analytics.v3.AnalyticsService.Scope.AnalyticsManageUsers, Google.Apis.Analytics.v3.AnalyticsService.Scope.AnalyticsProvision }
}.FromCertificate(certificate));
analyticsService = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
IsInitialized = true;
}
}
public void InitializeService(string certificateKeyPath, string apiEmail, Google.Apis.Analytics.v3.AnalyticsService.Scope scope)
{
try
{
if (!IsInitialized)
{
var certificate = new X509Certificate2(certificateKeyPath, "notasecret", X509KeyStorageFlags.Exportable);
credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(apiEmail)
{
Scopes = new[] { scope.ToString() }
}.FromCertificate(certificate));
}
analyticsService = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Jareeda"
});
IsInitialized = true;
}
catch (Exception ex)
{
InitFailed = true;
FailureException = ex;
}
}
#endregion
#region Management Resource Methods
#region Analytics Profiles
public void LoadAnalyticsProfiles()
{
Google.Apis.Analytics.v3.ManagementResource.ProfilesResource.ListRequest request = analyticsService.Management.Profiles.List("~all", "~all");
Google.Apis.Analytics.v3.Data.Profiles profiles = request.Execute();
if (Profiles == null)
Profiles = new List<Google.Apis.Analytics.v3.Data.Profile>();
if (profiles.Items.Count == 0)
throw new Exception("No profiles found in Analytics Account, you must have an active profile to access.");
foreach (Google.Apis.Analytics.v3.Data.Profile p in profiles.Items)
{
Profiles.Add(p);
}
}
public bool HasProfile()
{
return DefaultProfile != null;
}
public void SetDefaultAnalyticProfile(string profileId)
{
var profile = (from p in Profiles where p.WebPropertyId == profileId select p).FirstOrDefault();
if (profile != null)
{
DefaultProfile = profile;
}
else
{
StringBuilder validProfiles = new StringBuilder();
Profiles.ForEach(delegate(Google.Apis.Analytics.v3.Data.Profile p)
{
validProfiles.AppendLine(p.Name + " - " + p.WebsiteUrl + " - " + p.WebPropertyId);
});
throw new Exception("The profile specified was not found in the profile list. Valid profile ids are: \r\n\r\n" + validProfiles.ToString() + "\r\n\r\nIf the profile you are attempting to load is not in this list, you must give access to the API account in Google Analytics.");
}
}
#endregion
#region Analytics Accounts
public void LoadAnalyticsAccounts()
{
Google.Apis.Analytics.v3.ManagementResource.AccountsResource.ListRequest request = analyticsService.Management.Accounts.List();
Google.Apis.Analytics.v3.Data.Accounts accounts = request.Execute();
if (Accounts == null)
Accounts = new List<Google.Apis.Analytics.v3.Data.Account>();
foreach (Google.Apis.Analytics.v3.Data.Account p in accounts.Items)
{
Accounts.Add(p);
}
}
public bool HasAccount()
{
return DefaultAccount != null;
}
public void SetDefaultAnalyticAccount(string accountId)
{
var account = (from p in Accounts where p.Id == accountId select p).FirstOrDefault();
if (account != null)
DefaultAccount = account;
}
#endregion
#region Custom Dimensions & Metrics
#region Custom Dimensions
public Management.Data.CustomDimension CreateCustomDimension(string name)
{
return CreateCustomDimension(name, true);
}
public Management.Data.CustomDimension CreateCustomDimension(string name,bool isActive)
{
Google.Apis.Analytics.v3.Data.CustomDimension dimension = new Google.Apis.Analytics.v3.Data.CustomDimension() { Active = isActive, AccountId = DefaultAccount.Id, Name = name, Scope = "HIT", WebPropertyId = DefaultProfile.WebPropertyId };
Google.Apis.Analytics.v3.ManagementResource.CustomDimensionsResource.InsertRequest request = analyticsService.Management.CustomDimensions.Insert(dimension, DefaultAccount.Id, DefaultProfile.WebPropertyId);
try
{
dimension = request.Execute();
CustomDimensions.Add(dimension);
Management.Data.CustomDimension d = new Management.Data.CustomDimension() { Id = dimension.Id, Index = dimension.Index, Name = dimension.Name };
return d;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
public Management.Data.CustomDimension GetCustomDimensionById(string id)
{
Google.Apis.Analytics.v3.ManagementResource.CustomDimensionsResource.GetRequest request = analyticsService.Management.CustomDimensions.Get(DefaultAccount.Id, DefaultProfile.WebPropertyId, id);
try
{
var dimension = request.Execute();
Management.Data.CustomDimension d = new Management.Data.CustomDimension() { Id = dimension.Id, Index = dimension.Index, Name = dimension.Name };
return d;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
public void GetCustomDimensions()
{
Google.Apis.Analytics.v3.ManagementResource.CustomDimensionsResource.ListRequest request = analyticsService.Management.CustomDimensions.List(DefaultAccount.Id, DefaultProfile.WebPropertyId);
try
{
var dimensions = request.Execute();
if (CustomDimensions == null)
CustomDimensions = new List<Google.Apis.Analytics.v3.Data.CustomDimension>();
foreach(var item in dimensions.Items)
{
CustomDimensions.Add(item);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public Management.Data.CustomDimension GetCustomDimensionByName(string name)
{
try
{
if (CustomDimensions == null)
GetCustomDimensions();
var dimension = (from x in CustomDimensions where x.Name == name select x).FirstOrDefault();
if (dimension != null)
{
Management.Data.CustomDimension d = new Management.Data.CustomDimension() { Id = dimension.Id, Index = dimension.Index, Name = dimension.Name };
return d;
}
else
return null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
#endregion
#region Custom Metrics
public Management.Data.CustomMetric CreateCustomMetric(string name)
{
return CreateCustomMetric(name, true);
}
public Management.Data.CustomMetric CreateCustomMetric(string name, bool isActive)
{
Google.Apis.Analytics.v3.Data.CustomMetric dimension = new Google.Apis.Analytics.v3.Data.CustomMetric() { Active = isActive, AccountId = DefaultAccount.Id, Name = name, Scope = "HIT", WebPropertyId = DefaultProfile.WebPropertyId };
Google.Apis.Analytics.v3.ManagementResource.CustomMetricsResource.InsertRequest request = analyticsService.Management.CustomMetrics.Insert(dimension, DefaultAccount.Id, DefaultProfile.WebPropertyId);
try
{
dimension = request.Execute();
CustomMetrics.Add(dimension);
Management.Data.CustomMetric d = new Management.Data.CustomMetric() { Id = dimension.Id, Index = dimension.Index, Name = dimension.Name };
return d;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
public Management.Data.CustomMetric GetCustomMetricById(string id)
{
Google.Apis.Analytics.v3.ManagementResource.CustomMetricsResource.GetRequest request = analyticsService.Management.CustomMetrics.Get(DefaultAccount.Id, DefaultProfile.WebPropertyId, id);
try
{
var dimension = request.Execute();
Management.Data.CustomMetric d = new Management.Data.CustomMetric() { Id = dimension.Id, Index = dimension.Index, Name = dimension.Name };
return d;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
public void GetCustomMetrics()
{
Google.Apis.Analytics.v3.ManagementResource.CustomMetricsResource.ListRequest request = analyticsService.Management.CustomMetrics.List(DefaultAccount.Id, DefaultProfile.WebPropertyId);
try
{
var dimensions = request.Execute();
if (CustomMetrics == null)
CustomMetrics = new List<Google.Apis.Analytics.v3.Data.CustomMetric>();
foreach (var item in dimensions.Items)
{
CustomMetrics.Add(item);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public Management.Data.CustomMetric GetCustomMetricByName(string name)
{
try
{
if (CustomMetrics == null)
GetCustomMetrics();
var dimension = (from x in CustomMetrics where x.Name == name select x).FirstOrDefault();
if (dimension != null)
{
Management.Data.CustomMetric d = new Management.Data.CustomMetric() { Id = dimension.Id, Index = dimension.Index, Name = dimension.Name };
return d;
}
else
return null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
#endregion
#endregion
#endregion
#region Data Resource Methods
#region GetGaData
public Google.Apis.Analytics.v3.Data.GaData GetGaData(string profileid, DateTime startDate, DateTime endDate, string metrics)
{
return GetGaData(profileid, startDate, endDate, metrics, "");
}
public Google.Apis.Analytics.v3.Data.GaData GetGaData(string profileid, DateTime startDate, DateTime endDate, string metrics, string sort)
{
return GetGaData(profileid, startDate, endDate, metrics, "", "", sort);
}
public Google.Apis.Analytics.v3.Data.GaData GetGaData(string profileid, DateTime startDate, DateTime endDate, string metrics, string dimensions, string filters, string sort)
{
return GetGaData(profileid, startDate, endDate, metrics, dimensions, filters, null, sort, "");
}
public Google.Apis.Analytics.v3.Data.GaData GetGaData(string profileid, DateTime startDate, DateTime endDate, string metrics, string dimensions, string filters, Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.SamplingLevelEnum? samplingLevel, string sort, string fields)
{
return GetGaData(profileid, startDate, endDate, metrics, dimensions, filters, null, null, samplingLevel, "", sort, null, fields);
}
public Google.Apis.Analytics.v3.Data.GaData GetGaData(string profileid, DateTime startDate, DateTime endDate, string metrics, string dimensions, string filters, int? maxResults, Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.OutputEnum? output, Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.SamplingLevelEnum? samplingLevel, string segment, string sort, int? startIndex, string fields)
{
Google.Apis.Analytics.v3.Data.GaData data = null;
try
{
Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest request = analyticsService.Data.Ga.Get(profileid, startDate.ToString("yyyy-MM-dd"), endDate.ToString("yyyy-MM-dd"), metrics);
if (!string.IsNullOrEmpty(dimensions))
request.Dimensions = dimensions;
if (!string.IsNullOrEmpty(filters))
request.Filters = filters;
if (maxResults.HasValue)
request.MaxResults = maxResults;
if(output.HasValue)
request.Output = output;
if(samplingLevel.HasValue)
request.SamplingLevel = samplingLevel;
if(!string.IsNullOrEmpty(segment))
request.Segment = segment;
if(startIndex.HasValue)
request.StartIndex = startIndex;
if(!string.IsNullOrEmpty(sort))
request.Sort = sort;
if(!string.IsNullOrEmpty(fields))
request.Fields = fields;
if (!string.IsNullOrEmpty(this.UserIp))
request.UserIp = this.UserIp;
if (!string.IsNullOrEmpty(this.QuotaUser))
request.QuotaUser = this.QuotaUser;
data = request.Execute();
}
catch (Exception ex)
{
InitFailed = true;
FailureException = ex;
}
return data;
}
#endregion
#region GetDataTable
public System.Data.DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList)
{
return GetGaDataTable(startDate, endDate, metricsList, null, null, null, null, null, null, null,false, null, null);
}
public System.Data.DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList, List<Data.DataItem> sortList,bool ascending)
{
return GetGaDataTable(startDate, endDate, metricsList, null, null, null, null, null, null, sortList,ascending, null, null);
}
public System.Data.DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList, List<Data.DataItem> dimensionsList, List<Data.DataItem> filtersList, List<Data.DataItem> sortList,bool ascending)
{
return GetGaDataTable(startDate, endDate, metricsList, dimensionsList, filtersList, null, null, null, null, sortList,ascending, null, null);
}
public System.Data.DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList, List<Data.DataItem> dimensionsList, List<Data.DataItem> filtersList, Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.SamplingLevelEnum? samplingLevel, List<Data.DataItem> sortList,bool ascending, List<Data.DataItem> fields)
{
return GetGaDataTable(startDate, endDate, metricsList, dimensionsList, filtersList, null, null, samplingLevel, null, sortList,ascending, null, fields);
}
public System.Data.DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList, List<Data.DataItem> dimensionsList, List<Data.DataItem> filtersList, int? maxResults, Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.OutputEnum? output, Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.SamplingLevelEnum? samplingLevel, List<Data.DataItem> segmentList, List<Data.DataItem> sortList,bool ascending, int? startIndex, List<Data.DataItem> fieldsList)
{
if (DefaultProfile == null)
throw new Exception("Please set a default profile first using SetDefaultAnalyticProfile method");
string sort = "";
if(ascending)
sort = Data.DataItem.GetString(sortList);
else
sort = Data.DataItem.GetString(sortList, "-");
Google.Apis.Analytics.v3.Data.GaData gaData = GetGaData("ga:" + DefaultProfile.Id, startDate, endDate, Data.DataItem.GetString(metricsList), Data.DataItem.GetString(dimensionsList), Data.DataItem.GetStringFilter(filtersList), maxResults, output, samplingLevel, Data.DataItem.GetString(segmentList), sort, startIndex, Data.DataItem.GetString(fieldsList));
System.Data.DataTable table = BuildTableColumns(metricsList, dimensionsList);
if(gaData != null)
table = BuildTableRows(gaData, table);
return table;
}
#endregion
private System.Data.DataTable BuildTableColumns(List<Data.DataItem> metricsList, List<Data.DataItem> dimensionsList)
{
System.Data.DataTable table = new System.Data.DataTable();
if (dimensionsList != null)
{
foreach (Data.DataItem item in dimensionsList)
{
System.Data.DataColumn column = new System.Data.DataColumn(item.Name, item.Type);
column.Caption = item.WebViewName;
table.Columns.Add(column);
}
}
foreach (Data.DataItem item in metricsList)
{
System.Data.DataColumn column = new System.Data.DataColumn(item.Name, item.Type);
column.Caption = item.WebViewName;
table.Columns.Add(column);
}
return table;
}
private System.Data.DataTable BuildTableRows(Google.Apis.Analytics.v3.Data.GaData gaData, System.Data.DataTable table)
{
if (gaData.Rows == null) return table;
foreach (var ls in gaData.Rows)
{
System.Data.DataRow row = table.NewRow();
for(int i = 0; i < ls.Count(); i++)
{
if (table.Columns[i].DataType == typeof(DateTime))
{
row[i] = DateTime.ParseExact(ls[i], "yyyyMMdd", CultureInfo.InvariantCulture);
}
else
{
row[i] = ls[i];
}
}
table.Rows.Add(row);
}
return table;
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Security.PrivateCA.V1Beta1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCertificateAuthorityServiceClientTest
{
[xunit::FactAttribute]
public void CreateCertificateRequestObject()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateCertificateRequest request = new CreateCertificateRequest
{
ParentAsCertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
CertificateId = "certificate_id007930d5",
Certificate = new Certificate(),
RequestId = "request_id362c8df6",
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.CreateCertificate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateCertificateRequestObjectAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateCertificateRequest request = new CreateCertificateRequest
{
ParentAsCertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
CertificateId = "certificate_id007930d5",
Certificate = new Certificate(),
RequestId = "request_id362c8df6",
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.CreateCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.CreateCertificateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateCertificate()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateCertificateRequest request = new CreateCertificateRequest
{
ParentAsCertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
CertificateId = "certificate_id007930d5",
Certificate = new Certificate(),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.CreateCertificate(request.Parent, request.Certificate, request.CertificateId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateCertificateAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateCertificateRequest request = new CreateCertificateRequest
{
ParentAsCertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
CertificateId = "certificate_id007930d5",
Certificate = new Certificate(),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.CreateCertificateAsync(request.Parent, request.Certificate, request.CertificateId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.CreateCertificateAsync(request.Parent, request.Certificate, request.CertificateId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateCertificateResourceNames()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateCertificateRequest request = new CreateCertificateRequest
{
ParentAsCertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
CertificateId = "certificate_id007930d5",
Certificate = new Certificate(),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.CreateCertificate(request.ParentAsCertificateAuthorityName, request.Certificate, request.CertificateId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateCertificateResourceNamesAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateCertificateRequest request = new CreateCertificateRequest
{
ParentAsCertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
CertificateId = "certificate_id007930d5",
Certificate = new Certificate(),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.CreateCertificateAsync(request.ParentAsCertificateAuthorityName, request.Certificate, request.CertificateId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.CreateCertificateAsync(request.ParentAsCertificateAuthorityName, request.Certificate, request.CertificateId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCertificateRequestObject()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRequest request = new GetCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.GetCertificate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCertificateRequestObjectAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRequest request = new GetCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.GetCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.GetCertificateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCertificate()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRequest request = new GetCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.GetCertificate(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCertificateAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRequest request = new GetCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.GetCertificateAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.GetCertificateAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCertificateResourceNames()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRequest request = new GetCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.GetCertificate(request.CertificateName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCertificateResourceNamesAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRequest request = new GetCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.GetCertificateAsync(request.CertificateName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.GetCertificateAsync(request.CertificateName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void RevokeCertificateRequestObject()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
RevokeCertificateRequest request = new RevokeCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
Reason = RevocationReason.Superseded,
RequestId = "request_id362c8df6",
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.RevokeCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.RevokeCertificate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RevokeCertificateRequestObjectAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
RevokeCertificateRequest request = new RevokeCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
Reason = RevocationReason.Superseded,
RequestId = "request_id362c8df6",
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.RevokeCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.RevokeCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.RevokeCertificateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void RevokeCertificate()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
RevokeCertificateRequest request = new RevokeCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.RevokeCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.RevokeCertificate(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RevokeCertificateAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
RevokeCertificateRequest request = new RevokeCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.RevokeCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.RevokeCertificateAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.RevokeCertificateAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void RevokeCertificateResourceNames()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
RevokeCertificateRequest request = new RevokeCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.RevokeCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.RevokeCertificate(request.CertificateName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RevokeCertificateResourceNamesAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
RevokeCertificateRequest request = new RevokeCertificateRequest
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.RevokeCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.RevokeCertificateAsync(request.CertificateName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.RevokeCertificateAsync(request.CertificateName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateCertificateRequestObject()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateCertificateRequest request = new UpdateCertificateRequest
{
Certificate = new Certificate(),
UpdateMask = new wkt::FieldMask(),
RequestId = "request_id362c8df6",
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.UpdateCertificate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateCertificateRequestObjectAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateCertificateRequest request = new UpdateCertificateRequest
{
Certificate = new Certificate(),
UpdateMask = new wkt::FieldMask(),
RequestId = "request_id362c8df6",
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.UpdateCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.UpdateCertificateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateCertificate()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateCertificateRequest request = new UpdateCertificateRequest
{
Certificate = new Certificate(),
UpdateMask = new wkt::FieldMask(),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate response = client.UpdateCertificate(request.Certificate, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateCertificateAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateCertificateRequest request = new UpdateCertificateRequest
{
Certificate = new Certificate(),
UpdateMask = new wkt::FieldMask(),
};
Certificate expectedResponse = new Certificate
{
CertificateName = CertificateName.FromProjectLocationCertificateAuthorityCertificate("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE]"),
PemCsr = "pem_csr6e61aeb4",
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
RevocationDetails = new Certificate.Types.RevocationDetails(),
PemCertificate = "pem_certificate5c1b61ff",
CertificateDescription = new CertificateDescription(),
PemCertificateChain =
{
"pem_certificate_chain1eff25c5",
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Certificate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
Certificate responseCallSettings = await client.UpdateCertificateAsync(request.Certificate, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Certificate responseCancellationToken = await client.UpdateCertificateAsync(request.Certificate, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void FetchCertificateAuthorityCsrRequestObject()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
FetchCertificateAuthorityCsrRequest request = new FetchCertificateAuthorityCsrRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
FetchCertificateAuthorityCsrResponse expectedResponse = new FetchCertificateAuthorityCsrResponse
{
PemCsr = "pem_csr6e61aeb4",
};
mockGrpcClient.Setup(x => x.FetchCertificateAuthorityCsr(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
FetchCertificateAuthorityCsrResponse response = client.FetchCertificateAuthorityCsr(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task FetchCertificateAuthorityCsrRequestObjectAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
FetchCertificateAuthorityCsrRequest request = new FetchCertificateAuthorityCsrRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
FetchCertificateAuthorityCsrResponse expectedResponse = new FetchCertificateAuthorityCsrResponse
{
PemCsr = "pem_csr6e61aeb4",
};
mockGrpcClient.Setup(x => x.FetchCertificateAuthorityCsrAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FetchCertificateAuthorityCsrResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
FetchCertificateAuthorityCsrResponse responseCallSettings = await client.FetchCertificateAuthorityCsrAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FetchCertificateAuthorityCsrResponse responseCancellationToken = await client.FetchCertificateAuthorityCsrAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void FetchCertificateAuthorityCsr()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
FetchCertificateAuthorityCsrRequest request = new FetchCertificateAuthorityCsrRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
FetchCertificateAuthorityCsrResponse expectedResponse = new FetchCertificateAuthorityCsrResponse
{
PemCsr = "pem_csr6e61aeb4",
};
mockGrpcClient.Setup(x => x.FetchCertificateAuthorityCsr(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
FetchCertificateAuthorityCsrResponse response = client.FetchCertificateAuthorityCsr(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task FetchCertificateAuthorityCsrAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
FetchCertificateAuthorityCsrRequest request = new FetchCertificateAuthorityCsrRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
FetchCertificateAuthorityCsrResponse expectedResponse = new FetchCertificateAuthorityCsrResponse
{
PemCsr = "pem_csr6e61aeb4",
};
mockGrpcClient.Setup(x => x.FetchCertificateAuthorityCsrAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FetchCertificateAuthorityCsrResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
FetchCertificateAuthorityCsrResponse responseCallSettings = await client.FetchCertificateAuthorityCsrAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FetchCertificateAuthorityCsrResponse responseCancellationToken = await client.FetchCertificateAuthorityCsrAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void FetchCertificateAuthorityCsrResourceNames()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
FetchCertificateAuthorityCsrRequest request = new FetchCertificateAuthorityCsrRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
FetchCertificateAuthorityCsrResponse expectedResponse = new FetchCertificateAuthorityCsrResponse
{
PemCsr = "pem_csr6e61aeb4",
};
mockGrpcClient.Setup(x => x.FetchCertificateAuthorityCsr(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
FetchCertificateAuthorityCsrResponse response = client.FetchCertificateAuthorityCsr(request.CertificateAuthorityName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task FetchCertificateAuthorityCsrResourceNamesAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
FetchCertificateAuthorityCsrRequest request = new FetchCertificateAuthorityCsrRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
FetchCertificateAuthorityCsrResponse expectedResponse = new FetchCertificateAuthorityCsrResponse
{
PemCsr = "pem_csr6e61aeb4",
};
mockGrpcClient.Setup(x => x.FetchCertificateAuthorityCsrAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FetchCertificateAuthorityCsrResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
FetchCertificateAuthorityCsrResponse responseCallSettings = await client.FetchCertificateAuthorityCsrAsync(request.CertificateAuthorityName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
FetchCertificateAuthorityCsrResponse responseCancellationToken = await client.FetchCertificateAuthorityCsrAsync(request.CertificateAuthorityName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCertificateAuthorityRequestObject()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateAuthorityRequest request = new GetCertificateAuthorityRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
CertificateAuthority expectedResponse = new CertificateAuthority
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
Type = CertificateAuthority.Types.Type.Unspecified,
Tier = CertificateAuthority.Types.Tier.Enterprise,
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
KeySpec = new CertificateAuthority.Types.KeyVersionSpec(),
CertificatePolicy = new CertificateAuthority.Types.CertificateAuthorityPolicy(),
IssuingOptions = new CertificateAuthority.Types.IssuingOptions(),
PemCaCertificates =
{
"pem_ca_certificatese5e19b71",
},
State = CertificateAuthority.Types.State.PendingActivation,
CaCertificateDescriptions =
{
new CertificateDescription(),
},
GcsBucket = "gcs_bucket69bbfa63",
AccessUrls = new CertificateAuthority.Types.AccessUrls(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
SubordinateConfig = new SubordinateConfig(),
};
mockGrpcClient.Setup(x => x.GetCertificateAuthority(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateAuthority response = client.GetCertificateAuthority(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCertificateAuthorityRequestObjectAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateAuthorityRequest request = new GetCertificateAuthorityRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
CertificateAuthority expectedResponse = new CertificateAuthority
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
Type = CertificateAuthority.Types.Type.Unspecified,
Tier = CertificateAuthority.Types.Tier.Enterprise,
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
KeySpec = new CertificateAuthority.Types.KeyVersionSpec(),
CertificatePolicy = new CertificateAuthority.Types.CertificateAuthorityPolicy(),
IssuingOptions = new CertificateAuthority.Types.IssuingOptions(),
PemCaCertificates =
{
"pem_ca_certificatese5e19b71",
},
State = CertificateAuthority.Types.State.PendingActivation,
CaCertificateDescriptions =
{
new CertificateDescription(),
},
GcsBucket = "gcs_bucket69bbfa63",
AccessUrls = new CertificateAuthority.Types.AccessUrls(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
SubordinateConfig = new SubordinateConfig(),
};
mockGrpcClient.Setup(x => x.GetCertificateAuthorityAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CertificateAuthority>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateAuthority responseCallSettings = await client.GetCertificateAuthorityAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CertificateAuthority responseCancellationToken = await client.GetCertificateAuthorityAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCertificateAuthority()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateAuthorityRequest request = new GetCertificateAuthorityRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
CertificateAuthority expectedResponse = new CertificateAuthority
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
Type = CertificateAuthority.Types.Type.Unspecified,
Tier = CertificateAuthority.Types.Tier.Enterprise,
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
KeySpec = new CertificateAuthority.Types.KeyVersionSpec(),
CertificatePolicy = new CertificateAuthority.Types.CertificateAuthorityPolicy(),
IssuingOptions = new CertificateAuthority.Types.IssuingOptions(),
PemCaCertificates =
{
"pem_ca_certificatese5e19b71",
},
State = CertificateAuthority.Types.State.PendingActivation,
CaCertificateDescriptions =
{
new CertificateDescription(),
},
GcsBucket = "gcs_bucket69bbfa63",
AccessUrls = new CertificateAuthority.Types.AccessUrls(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
SubordinateConfig = new SubordinateConfig(),
};
mockGrpcClient.Setup(x => x.GetCertificateAuthority(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateAuthority response = client.GetCertificateAuthority(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCertificateAuthorityAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateAuthorityRequest request = new GetCertificateAuthorityRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
CertificateAuthority expectedResponse = new CertificateAuthority
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
Type = CertificateAuthority.Types.Type.Unspecified,
Tier = CertificateAuthority.Types.Tier.Enterprise,
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
KeySpec = new CertificateAuthority.Types.KeyVersionSpec(),
CertificatePolicy = new CertificateAuthority.Types.CertificateAuthorityPolicy(),
IssuingOptions = new CertificateAuthority.Types.IssuingOptions(),
PemCaCertificates =
{
"pem_ca_certificatese5e19b71",
},
State = CertificateAuthority.Types.State.PendingActivation,
CaCertificateDescriptions =
{
new CertificateDescription(),
},
GcsBucket = "gcs_bucket69bbfa63",
AccessUrls = new CertificateAuthority.Types.AccessUrls(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
SubordinateConfig = new SubordinateConfig(),
};
mockGrpcClient.Setup(x => x.GetCertificateAuthorityAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CertificateAuthority>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateAuthority responseCallSettings = await client.GetCertificateAuthorityAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CertificateAuthority responseCancellationToken = await client.GetCertificateAuthorityAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCertificateAuthorityResourceNames()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateAuthorityRequest request = new GetCertificateAuthorityRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
CertificateAuthority expectedResponse = new CertificateAuthority
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
Type = CertificateAuthority.Types.Type.Unspecified,
Tier = CertificateAuthority.Types.Tier.Enterprise,
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
KeySpec = new CertificateAuthority.Types.KeyVersionSpec(),
CertificatePolicy = new CertificateAuthority.Types.CertificateAuthorityPolicy(),
IssuingOptions = new CertificateAuthority.Types.IssuingOptions(),
PemCaCertificates =
{
"pem_ca_certificatese5e19b71",
},
State = CertificateAuthority.Types.State.PendingActivation,
CaCertificateDescriptions =
{
new CertificateDescription(),
},
GcsBucket = "gcs_bucket69bbfa63",
AccessUrls = new CertificateAuthority.Types.AccessUrls(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
SubordinateConfig = new SubordinateConfig(),
};
mockGrpcClient.Setup(x => x.GetCertificateAuthority(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateAuthority response = client.GetCertificateAuthority(request.CertificateAuthorityName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCertificateAuthorityResourceNamesAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateAuthorityRequest request = new GetCertificateAuthorityRequest
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
};
CertificateAuthority expectedResponse = new CertificateAuthority
{
CertificateAuthorityName = CertificateAuthorityName.FromProjectLocationCertificateAuthority("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]"),
Type = CertificateAuthority.Types.Type.Unspecified,
Tier = CertificateAuthority.Types.Tier.Enterprise,
Config = new CertificateConfig(),
Lifetime = new wkt::Duration(),
KeySpec = new CertificateAuthority.Types.KeyVersionSpec(),
CertificatePolicy = new CertificateAuthority.Types.CertificateAuthorityPolicy(),
IssuingOptions = new CertificateAuthority.Types.IssuingOptions(),
PemCaCertificates =
{
"pem_ca_certificatese5e19b71",
},
State = CertificateAuthority.Types.State.PendingActivation,
CaCertificateDescriptions =
{
new CertificateDescription(),
},
GcsBucket = "gcs_bucket69bbfa63",
AccessUrls = new CertificateAuthority.Types.AccessUrls(),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
SubordinateConfig = new SubordinateConfig(),
};
mockGrpcClient.Setup(x => x.GetCertificateAuthorityAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CertificateAuthority>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateAuthority responseCallSettings = await client.GetCertificateAuthorityAsync(request.CertificateAuthorityName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CertificateAuthority responseCancellationToken = await client.GetCertificateAuthorityAsync(request.CertificateAuthorityName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCertificateRevocationListRequestObject()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRevocationListRequest request = new GetCertificateRevocationListRequest
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
};
CertificateRevocationList expectedResponse = new CertificateRevocationList
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
SequenceNumber = 785044825799214282L,
RevokedCertificates =
{
new CertificateRevocationList.Types.RevokedCertificate(),
},
PemCrl = "pem_crle4a1db0f",
AccessUrl = "access_url8b12f83f",
State = CertificateRevocationList.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificateRevocationList(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateRevocationList response = client.GetCertificateRevocationList(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCertificateRevocationListRequestObjectAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRevocationListRequest request = new GetCertificateRevocationListRequest
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
};
CertificateRevocationList expectedResponse = new CertificateRevocationList
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
SequenceNumber = 785044825799214282L,
RevokedCertificates =
{
new CertificateRevocationList.Types.RevokedCertificate(),
},
PemCrl = "pem_crle4a1db0f",
AccessUrl = "access_url8b12f83f",
State = CertificateRevocationList.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificateRevocationListAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CertificateRevocationList>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateRevocationList responseCallSettings = await client.GetCertificateRevocationListAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CertificateRevocationList responseCancellationToken = await client.GetCertificateRevocationListAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCertificateRevocationList()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRevocationListRequest request = new GetCertificateRevocationListRequest
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
};
CertificateRevocationList expectedResponse = new CertificateRevocationList
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
SequenceNumber = 785044825799214282L,
RevokedCertificates =
{
new CertificateRevocationList.Types.RevokedCertificate(),
},
PemCrl = "pem_crle4a1db0f",
AccessUrl = "access_url8b12f83f",
State = CertificateRevocationList.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificateRevocationList(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateRevocationList response = client.GetCertificateRevocationList(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCertificateRevocationListAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRevocationListRequest request = new GetCertificateRevocationListRequest
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
};
CertificateRevocationList expectedResponse = new CertificateRevocationList
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
SequenceNumber = 785044825799214282L,
RevokedCertificates =
{
new CertificateRevocationList.Types.RevokedCertificate(),
},
PemCrl = "pem_crle4a1db0f",
AccessUrl = "access_url8b12f83f",
State = CertificateRevocationList.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificateRevocationListAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CertificateRevocationList>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateRevocationList responseCallSettings = await client.GetCertificateRevocationListAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CertificateRevocationList responseCancellationToken = await client.GetCertificateRevocationListAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCertificateRevocationListResourceNames()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRevocationListRequest request = new GetCertificateRevocationListRequest
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
};
CertificateRevocationList expectedResponse = new CertificateRevocationList
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
SequenceNumber = 785044825799214282L,
RevokedCertificates =
{
new CertificateRevocationList.Types.RevokedCertificate(),
},
PemCrl = "pem_crle4a1db0f",
AccessUrl = "access_url8b12f83f",
State = CertificateRevocationList.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificateRevocationList(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateRevocationList response = client.GetCertificateRevocationList(request.CertificateRevocationListName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCertificateRevocationListResourceNamesAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCertificateRevocationListRequest request = new GetCertificateRevocationListRequest
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
};
CertificateRevocationList expectedResponse = new CertificateRevocationList
{
CertificateRevocationListName = CertificateRevocationListName.FromProjectLocationCertificateAuthorityCertificateRevocationList("[PROJECT]", "[LOCATION]", "[CERTIFICATE_AUTHORITY]", "[CERTIFICATE_REVOCATION_LIST]"),
SequenceNumber = 785044825799214282L,
RevokedCertificates =
{
new CertificateRevocationList.Types.RevokedCertificate(),
},
PemCrl = "pem_crle4a1db0f",
AccessUrl = "access_url8b12f83f",
State = CertificateRevocationList.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetCertificateRevocationListAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CertificateRevocationList>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
CertificateRevocationList responseCallSettings = await client.GetCertificateRevocationListAsync(request.CertificateRevocationListName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CertificateRevocationList responseCancellationToken = await client.GetCertificateRevocationListAsync(request.CertificateRevocationListName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetReusableConfigRequestObject()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetReusableConfigRequest request = new GetReusableConfigRequest
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
};
ReusableConfig expectedResponse = new ReusableConfig
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
Values = new ReusableConfigValues(),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetReusableConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
ReusableConfig response = client.GetReusableConfig(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetReusableConfigRequestObjectAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetReusableConfigRequest request = new GetReusableConfigRequest
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
};
ReusableConfig expectedResponse = new ReusableConfig
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
Values = new ReusableConfigValues(),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetReusableConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReusableConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
ReusableConfig responseCallSettings = await client.GetReusableConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReusableConfig responseCancellationToken = await client.GetReusableConfigAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetReusableConfig()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetReusableConfigRequest request = new GetReusableConfigRequest
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
};
ReusableConfig expectedResponse = new ReusableConfig
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
Values = new ReusableConfigValues(),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetReusableConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
ReusableConfig response = client.GetReusableConfig(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetReusableConfigAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetReusableConfigRequest request = new GetReusableConfigRequest
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
};
ReusableConfig expectedResponse = new ReusableConfig
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
Values = new ReusableConfigValues(),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetReusableConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReusableConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
ReusableConfig responseCallSettings = await client.GetReusableConfigAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReusableConfig responseCancellationToken = await client.GetReusableConfigAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetReusableConfigResourceNames()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetReusableConfigRequest request = new GetReusableConfigRequest
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
};
ReusableConfig expectedResponse = new ReusableConfig
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
Values = new ReusableConfigValues(),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetReusableConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
ReusableConfig response = client.GetReusableConfig(request.ReusableConfigName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetReusableConfigResourceNamesAsync()
{
moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient> mockGrpcClient = new moq::Mock<CertificateAuthorityService.CertificateAuthorityServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetReusableConfigRequest request = new GetReusableConfigRequest
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
};
ReusableConfig expectedResponse = new ReusableConfig
{
ReusableConfigName = ReusableConfigName.FromProjectLocationReusableConfig("[PROJECT]", "[LOCATION]", "[REUSABLE_CONFIG]"),
Values = new ReusableConfigValues(),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetReusableConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReusableConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CertificateAuthorityServiceClient client = new CertificateAuthorityServiceClientImpl(mockGrpcClient.Object, null);
ReusableConfig responseCallSettings = await client.GetReusableConfigAsync(request.ReusableConfigName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReusableConfig responseCancellationToken = await client.GetReusableConfigAsync(request.ReusableConfigName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
using CodeFixGroupKey = Tuple<DiagnosticData, CodeActionPriority>;
[Export(typeof(ISuggestedActionsSourceProvider))]
[VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)]
[VisualStudio.Utilities.Name("Roslyn Code Fix")]
[VisualStudio.Utilities.Order]
internal class SuggestedActionsSourceProvider : ISuggestedActionsSourceProvider
{
private static readonly Guid s_CSharpSourceGuid = new Guid("b967fea8-e2c3-4984-87d4-71a38f49e16a");
private static readonly Guid s_visualBasicSourceGuid = new Guid("4de30e93-3e0c-40c2-a4ba-1124da4539f6");
private const int InvalidSolutionVersion = -1;
private readonly ICodeRefactoringService _codeRefactoringService;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ICodeFixService _codeFixService;
private readonly ICodeActionEditHandlerService _editHandler;
private readonly IAsynchronousOperationListener _listener;
private readonly IWaitIndicator _waitIndicator;
[ImportingConstructor]
public SuggestedActionsSourceProvider(
ICodeRefactoringService codeRefactoringService,
IDiagnosticAnalyzerService diagnosticService,
ICodeFixService codeFixService,
ICodeActionEditHandlerService editHandler,
IWaitIndicator waitIndicator,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
_codeRefactoringService = codeRefactoringService;
_diagnosticService = diagnosticService;
_codeFixService = codeFixService;
_editHandler = editHandler;
_waitIndicator = waitIndicator;
_listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.LightBulb);
}
public ISuggestedActionsSource CreateSuggestedActionsSource(ITextView textView, ITextBuffer textBuffer)
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(textBuffer);
return new Source(this, textView, textBuffer);
}
private class Source : ForegroundThreadAffinitizedObject, ISuggestedActionsSource
{
// state that will be only reset when source is disposed.
private SuggestedActionsSourceProvider _owner;
private ITextView _textView;
private ITextBuffer _subjectBuffer;
private WorkspaceRegistration _registration;
// mutable state
private Workspace _workspace;
private int _lastSolutionVersionReported;
public Source(SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer)
{
_owner = owner;
_textView = textView;
_textView.Closed += OnTextViewClosed;
_subjectBuffer = textBuffer;
_registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer());
_lastSolutionVersionReported = InvalidSolutionVersion;
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated += OnDiagnosticsUpdated;
if (_registration.Workspace != null)
{
_workspace = _registration.Workspace;
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
_registration.WorkspaceChanged += OnWorkspaceChanged;
}
public event EventHandler<EventArgs> SuggestedActionsChanged;
public bool TryGetTelemetryId(out Guid telemetryId)
{
telemetryId = default(Guid);
var workspace = _workspace;
if (workspace == null || _subjectBuffer == null)
{
return false;
}
var documentId = workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer());
if (documentId == null)
{
return false;
}
var project = workspace.CurrentSolution.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
switch (project.Language)
{
case LanguageNames.CSharp:
telemetryId = s_CSharpSourceGuid;
return true;
case LanguageNames.VisualBasic:
telemetryId = s_visualBasicSourceGuid;
return true;
default:
return false;
}
}
public IEnumerable<SuggestedActionSet> GetSuggestedActions(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken)
{
AssertIsForeground();
using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActions, cancellationToken))
{
var documentAndSnapshot = GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).WaitAndGetResult(cancellationToken);
if (!documentAndSnapshot.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return null;
}
var document = documentAndSnapshot.Value.Item1;
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
var fixes = GetCodeFixes(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken);
var refactorings = GetRefactorings(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken);
var result = fixes == null ? refactorings : refactorings == null
? fixes : fixes.Concat(refactorings);
if (result == null)
{
return null;
}
var allActionSets = result.ToList();
allActionSets = InlineActionSetsIfDesirable(allActionSets);
return allActionSets;
}
}
private List<SuggestedActionSet> InlineActionSetsIfDesirable(List<SuggestedActionSet> allActionSets)
{
// If we only have a single set of items, and that set only has three max suggestion
// offered. Then we can consider inlining any nested actions into the top level list.
// (but we only do this if the parent of the nested actions isn't invokable itself).
if (allActionSets.Sum(a => a.Actions.Count()) > 3)
{
return allActionSets;
}
return allActionSets.Select(InlineActions).ToList();
}
private bool IsInlineable(ISuggestedAction action)
{
var suggestedAction = action as SuggestedAction;
return suggestedAction != null &&
!suggestedAction.CodeAction.IsInvokable &&
suggestedAction.CodeAction.HasCodeActions;
}
private SuggestedActionSet InlineActions(SuggestedActionSet actionSet)
{
if (!actionSet.Actions.Any(IsInlineable))
{
return actionSet;
}
var newActions = new List<ISuggestedAction>();
foreach (var action in actionSet.Actions)
{
if (IsInlineable(action))
{
// Looks like something we can inline.
var childActionSets = ((SuggestedAction)action).GetActionSets();
if (childActionSets.Length != 1)
{
return actionSet;
}
newActions.AddRange(childActionSets[0].Actions);
continue;
}
newActions.Add(action);
}
return new SuggestedActionSet(newActions, actionSet.Title, actionSet.Priority, actionSet.ApplicableToSpan);
}
private IEnumerable<SuggestedActionSet> GetCodeFixes(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (_owner._codeFixService != null &&
supportsFeatureService.SupportsCodeFixes(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix))
{
// We only include suppressions if lightbulb is asking for everything.
// If the light bulb is only asking for code fixes, then we don't include suppressions.
var includeSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any);
var fixes = Task.Run(
async () =>
{
var stream = await _owner._codeFixService.GetFixesAsync(
document, range.Span.ToTextSpan(), includeSuppressionFixes, cancellationToken).ConfigureAwait(false);
return stream.ToList();
},
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredFixes = FilterOnUIThread(fixes, workspace);
return OrganizeFixes(workspace, filteredFixes, hasSuppressionFixes: includeSuppressionFixes);
}
return null;
}
private List<CodeFixCollection> FilterOnUIThread(List<CodeFixCollection> collections, Workspace workspace)
{
this.AssertIsForeground();
return collections.Select(c => FilterOnUIThread(c, workspace)).WhereNotNull().ToList();
}
private CodeFixCollection FilterOnUIThread(
CodeFixCollection collection,
Workspace workspace)
{
this.AssertIsForeground();
var applicableFixes = collection.Fixes.Where(f => IsApplicable(f.Action, workspace)).ToList();
return applicableFixes.Count == 0
? null
: applicableFixes.Count == collection.Fixes.Length
? collection
: new CodeFixCollection(collection.Provider, collection.TextSpan, applicableFixes,
collection.FixAllState,
collection.SupportedScopes, collection.FirstDiagnostic);
}
private bool IsApplicable(CodeAction action, Workspace workspace)
{
if (!action.PerformFinalApplicabilityCheck)
{
// If we don't even need to perform the final applicability check,
// then the code actoin is applicable.
return true;
}
// Otherwise, defer to the action to make the decision.
this.AssertIsForeground();
return action.IsApplicable(workspace);
}
private List<CodeRefactoring> FilterOnUIThread(List<CodeRefactoring> refactorings, Workspace workspace)
{
return refactorings.Select(r => FilterOnUIThread(r, workspace)).WhereNotNull().ToList();
}
private CodeRefactoring FilterOnUIThread(CodeRefactoring refactoring, Workspace workspace)
{
var actions = refactoring.Actions.Where(a => IsApplicable(a, workspace)).ToList();
return actions.Count == 0
? null
: actions.Count == refactoring.Actions.Count
? refactoring
: new CodeRefactoring(refactoring.Provider, actions);
}
/// <summary>
/// Arrange fixes into groups based on the issue (diagnostic being fixed) and prioritize these groups.
/// </summary>
private IEnumerable<SuggestedActionSet> OrganizeFixes(Workspace workspace, IEnumerable<CodeFixCollection> fixCollections, bool hasSuppressionFixes)
{
var map = ImmutableDictionary.CreateBuilder<CodeFixGroupKey, IList<SuggestedAction>>();
var order = ImmutableArray.CreateBuilder<CodeFixGroupKey>();
// First group fixes by diagnostic and priority.
GroupFixes(workspace, fixCollections, map, order, hasSuppressionFixes);
// Then prioritize between the groups.
return PrioritizeFixGroups(map.ToImmutable(), order.ToImmutable());
}
/// <summary>
/// Groups fixes by the diagnostic being addressed by each fix.
/// </summary>
private void GroupFixes(
Workspace workspace,
IEnumerable<CodeFixCollection> fixCollections,
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
IList<CodeFixGroupKey> order,
bool hasSuppressionFixes)
{
foreach (var fixCollection in fixCollections)
{
var fixes = fixCollection.Fixes;
var fixCount = fixes.Length;
Func<CodeAction, SuggestedActionSet> getFixAllSuggestedActionSet =
codeAction => CodeFixSuggestedAction.GetFixAllSuggestedActionSet(
codeAction, fixCount, fixCollection.FixAllState,
fixCollection.SupportedScopes, fixCollection.FirstDiagnostic,
workspace, _subjectBuffer, _owner._editHandler,
_owner._waitIndicator, _owner._listener);
foreach (var fix in fixes)
{
// Suppression fixes are handled below.
if (!(fix.Action is SuppressionCodeAction))
{
SuggestedAction suggestedAction;
if (fix.Action.HasCodeActions)
{
var nestedActions = new List<SuggestedAction>();
foreach (var nestedAction in fix.Action.GetCodeActions())
{
nestedActions.Add(new CodeFixSuggestedAction(workspace, _subjectBuffer,
_owner._editHandler, _owner._waitIndicator, fix,
nestedAction, fixCollection.Provider, getFixAllSuggestedActionSet(nestedAction), _owner._listener));
}
var diag = fix.PrimaryDiagnostic;
var set = new SuggestedActionSet(nestedActions, SuggestedActionSetPriority.Medium, diag.Location.SourceSpan.ToSpan());
suggestedAction = new SuggestedAction(workspace, _subjectBuffer,
_owner._editHandler, _owner._waitIndicator, fix.Action,
fixCollection.Provider, _owner._listener, new[] { set });
}
else
{
suggestedAction = new CodeFixSuggestedAction(
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator, fix,
fix.Action, fixCollection.Provider, getFixAllSuggestedActionSet(fix.Action), _owner._listener);
}
AddFix(fix, suggestedAction, map, order);
}
}
if (hasSuppressionFixes)
{
// Add suppression fixes to the end of a given SuggestedActionSet so that they always show up last in a group.
foreach (var fix in fixes)
{
if (fix.Action is SuppressionCodeAction)
{
SuggestedAction suggestedAction;
if (fix.Action.HasCodeActions)
{
suggestedAction = new SuppressionSuggestedAction(
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator,
fix, fixCollection.Provider, getFixAllSuggestedActionSet, _owner._listener);
}
else
{
suggestedAction = new CodeFixSuggestedAction(
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator, fix,
fix.Action, fixCollection.Provider, getFixAllSuggestedActionSet(fix.Action), _owner._listener);
}
AddFix(fix, suggestedAction, map, order);
}
}
}
}
}
private static void AddFix(CodeFix fix, SuggestedAction suggestedAction, IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map, IList<CodeFixGroupKey> order)
{
var diag = fix.GetPrimaryDiagnosticData();
var groupKey = new CodeFixGroupKey(diag, fix.Action.Priority);
if (!map.ContainsKey(groupKey))
{
order.Add(groupKey);
map[groupKey] = ImmutableArray.CreateBuilder<SuggestedAction>();
}
map[groupKey].Add(suggestedAction);
}
/// <summary>
/// Return prioritized set of fix groups such that fix group for suppression always show up at the bottom of the list.
/// </summary>
/// <remarks>
/// Fix groups are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing fixes is set to <see cref="SuggestedActionSetPriority.Medium"/> by default.
/// The only exception is the case where a <see cref="SuggestedActionSet"/> only contains suppression fixes -
/// the priority of such <see cref="SuggestedActionSet"/>s is set to <see cref="SuggestedActionSetPriority.None"/> so that suppression fixes
/// always show up last after all other fixes (and refactorings) for the selected line of code.
/// </remarks>
private static IEnumerable<SuggestedActionSet> PrioritizeFixGroups(IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map, IList<CodeFixGroupKey> order)
{
var sets = ImmutableArray.CreateBuilder<SuggestedActionSet>();
foreach (var diag in order)
{
var actions = map[diag];
foreach (var group in actions.GroupBy(a => a.Priority))
{
var priority = GetSuggestedActionSetPriority(group.Key);
// diagnostic from things like build shouldn't reach here since we don't support LB for those diagnostics
Contract.Requires(diag.Item1.HasTextSpan);
sets.Add(new SuggestedActionSet(group, priority, diag.Item1.TextSpan.ToSpan()));
}
}
return sets.ToImmutable();
}
private static SuggestedActionSetPriority GetSuggestedActionSetPriority(CodeActionPriority key)
{
switch (key)
{
case CodeActionPriority.None: return SuggestedActionSetPriority.None;
case CodeActionPriority.Low: return SuggestedActionSetPriority.Low;
case CodeActionPriority.Medium: return SuggestedActionSetPriority.Medium;
case CodeActionPriority.High: return SuggestedActionSetPriority.High;
default:
throw new InvalidOperationException();
}
}
private IEnumerable<SuggestedActionSet> GetRefactorings(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (document.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
_owner._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
// Get the selection while on the UI thread.
var selection = TryGetCodeRefactoringSelection(_subjectBuffer, _textView, range);
if (!selection.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return null;
}
var refactorings = Task.Run(
async () =>
{
var stream = await _owner._codeRefactoringService.GetRefactoringsAsync(
document, selection.Value, cancellationToken).ConfigureAwait(false);
return stream.ToList();
},
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredRefactorings = FilterOnUIThread(refactorings, workspace);
return filteredRefactorings.Select(r => OrganizeRefactorings(workspace, r));
}
return null;
}
/// <summary>
/// Arrange refactorings into groups.
/// </summary>
/// <remarks>
/// Refactorings are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing refactorings is set to <see cref="SuggestedActionSetPriority.Low"/>
/// and should show up after fixes but before suppression fixes in the light bulb menu.
/// </remarks>
private SuggestedActionSet OrganizeRefactorings(Workspace workspace, CodeRefactoring refactoring)
{
var refactoringSuggestedActions = ImmutableArray.CreateBuilder<SuggestedAction>();
foreach (var a in refactoring.Actions)
{
refactoringSuggestedActions.Add(new CodeRefactoringSuggestedAction(
workspace, _subjectBuffer, _owner._editHandler, _owner._waitIndicator,
a, refactoring.Provider, _owner._listener));
}
return new SuggestedActionSet(refactoringSuggestedActions.ToImmutable(), SuggestedActionSetPriority.Low);
}
public async Task<bool> HasSuggestedActionsAsync(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken)
{
// Explicitly hold onto below fields in locals and use these locals throughout this code path to avoid crashes
// if these fields happen to be cleared by Dispose() below. This is required since this code path involves
// code that can run asynchronously from background thread.
var view = _textView;
var buffer = _subjectBuffer;
var provider = _owner;
if (view == null || buffer == null || provider == null)
{
return false;
}
using (var asyncToken = provider._listener.BeginAsyncOperation("HasSuggestedActionsAsync"))
{
var documentAndSnapshot = await GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).ConfigureAwait(false);
if (!documentAndSnapshot.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return false;
}
var document = documentAndSnapshot.Value.Item1;
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
return
await HasFixesAsync(
supportsFeatureService, requestedActionCategories, provider, document, range,
cancellationToken).ConfigureAwait(false) ||
await HasRefactoringsAsync(
supportsFeatureService, requestedActionCategories, provider, document, buffer, view, range,
cancellationToken).ConfigureAwait(false);
}
}
private async Task<bool> HasFixesAsync(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
SuggestedActionsSourceProvider provider,
Document document, SnapshotSpan range,
CancellationToken cancellationToken)
{
if (provider._codeFixService != null && supportsFeatureService.SupportsCodeFixes(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix))
{
// We only consider suppressions if lightbulb is asking for everything.
// If the light bulb is only asking for code fixes, then we don't consider suppressions.
var considerSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any);
var result = await Task.Run(
async () => await provider._codeFixService.GetFirstDiagnosticWithFixAsync(
document, range.Span.ToTextSpan(), considerSuppressionFixes, cancellationToken).ConfigureAwait(false),
cancellationToken).ConfigureAwait(false);
if (result.HasFix)
{
Logger.Log(FunctionId.SuggestedActions_HasSuggestedActionsAsync);
return true;
}
if (result.PartialResult)
{
// reset solution version number so that we can raise suggested action changed event
Volatile.Write(ref _lastSolutionVersionReported, InvalidSolutionVersion);
return false;
}
}
return false;
}
private async Task<bool> HasRefactoringsAsync(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
SuggestedActionsSourceProvider provider,
Document document,
ITextBuffer buffer,
ITextView view,
SnapshotSpan range,
CancellationToken cancellationToken)
{
if (document.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
provider._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
TextSpan? selection = null;
if (IsForeground())
{
// This operation needs to happen on UI thread because it needs to access textView.Selection.
selection = TryGetCodeRefactoringSelection(buffer, view, range);
}
else
{
await InvokeBelowInputPriority(() =>
{
// This operation needs to happen on UI thread because it needs to access textView.Selection.
selection = TryGetCodeRefactoringSelection(buffer, view, range);
}).ConfigureAwait(false);
}
if (!selection.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return false;
}
return await Task.Run(
async () => await provider._codeRefactoringService.HasRefactoringsAsync(
document, selection.Value, cancellationToken).ConfigureAwait(false),
cancellationToken).ConfigureAwait(false);
}
return false;
}
private static TextSpan? TryGetCodeRefactoringSelection(ITextBuffer buffer, ITextView view, SnapshotSpan range)
{
var selectedSpans = view.Selection.SelectedSpans
.SelectMany(ss => view.BufferGraph.MapDownToBuffer(ss, SpanTrackingMode.EdgeExclusive, buffer))
.Where(ss => !view.IsReadOnlyOnSurfaceBuffer(ss))
.ToList();
// We only support refactorings when there is a single selection in the document.
if (selectedSpans.Count != 1)
{
return null;
}
var translatedSpan = selectedSpans[0].TranslateTo(range.Snapshot, SpanTrackingMode.EdgeInclusive);
// We only support refactorings when selected span intersects with the span that the light bulb is asking for.
if (!translatedSpan.IntersectsWith(range))
{
return null;
}
return translatedSpan.Span.ToTextSpan();
}
private static async Task<ValueTuple<Document, ITextSnapshot>?> GetMatchingDocumentAndSnapshotAsync(ITextSnapshot givenSnapshot, CancellationToken cancellationToken)
{
var buffer = givenSnapshot.TextBuffer;
if (buffer == null)
{
return null;
}
var workspace = buffer.GetWorkspace();
if (workspace == null)
{
return null;
}
var documentId = workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer());
if (documentId == null)
{
return null;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
if (document == null)
{
return null;
}
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var snapshot = sourceText.FindCorrespondingEditorTextSnapshot();
if (snapshot == null || snapshot.Version.ReiteratedVersionNumber != givenSnapshot.Version.ReiteratedVersionNumber)
{
return null;
}
return ValueTuple.Create(document, snapshot);
}
private void OnTextViewClosed(object sender, EventArgs e)
{
Dispose();
}
private void OnWorkspaceChanged(object sender, EventArgs e)
{
// REVIEW: this event should give both old and new workspace as argument so that
// one doesn't need to hold onto workspace in field.
// remove existing event registration
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
}
// REVIEW: why one need to get new workspace from registration? why not just pass in the new workspace?
// add new event registration
_workspace = _registration.Workspace;
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
}
private void OnActiveContextChanged(object sender, DocumentEventArgs e)
{
// REVIEW: it would be nice for changed event to pass in both old and new document.
OnSuggestedActionsChanged(e.Document.Project.Solution.Workspace, e.Document.Id, e.Document.Project.Solution.WorkspaceVersion);
}
private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e)
{
// document removed case. no reason to raise event
if (e.Solution == null)
{
return;
}
OnSuggestedActionsChanged(e.Workspace, e.DocumentId, e.Solution.WorkspaceVersion);
}
private void OnSuggestedActionsChanged(Workspace currentWorkspace, DocumentId currentDocumentId, int solutionVersion, DiagnosticsUpdatedArgs args = null)
{
// Explicitly hold onto the _subjectBuffer field in a local and use this local in this function to avoid crashes
// if this field happens to be cleared by Dispose() below. This is required since this code path involves code
// that can run on background thread.
var buffer = _subjectBuffer;
if (buffer == null)
{
return;
}
var workspace = buffer.GetWorkspace();
// workspace is not ready, nothing to do.
if (workspace == null || workspace != currentWorkspace)
{
return;
}
if (currentDocumentId != workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer()) ||
solutionVersion == Volatile.Read(ref _lastSolutionVersionReported))
{
return;
}
this.SuggestedActionsChanged?.Invoke(this, EventArgs.Empty);
Volatile.Write(ref _lastSolutionVersionReported, solutionVersion);
}
public void Dispose()
{
if (_owner != null)
{
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated -= OnDiagnosticsUpdated;
_owner = null;
}
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
_workspace = null;
}
if (_registration != null)
{
_registration.WorkspaceChanged -= OnWorkspaceChanged;
_registration = null;
}
if (_textView != null)
{
_textView.Closed -= OnTextViewClosed;
_textView = null;
}
if (_subjectBuffer != null)
{
_subjectBuffer = null;
}
}
}
}
}
| |
using PhotoNet.Common;
using RawNet.Decoder.Decompressor;
using RawNet.Format.Tiff;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace RawNet.Decoder
{
class RAFDecoder : TIFFDecoder
{
//bool alt_layout;
uint relativeOffset;
public RAFDecoder(Stream file) : base(file, true)
{
//alt_layout = false;
// FUJI has pointers to IFD's at fixed byte offsets
// So if camera is FUJI, we cannot use ordinary TIFF parser
//get first 8 char and see if equal fuji
file.Position = 0;
var data = new byte[110];
file.Read(data, 0, 8);
string dataAsString = System.Text.Encoding.UTF8.GetString(data.Take(8).ToArray());
if (dataAsString != "FUJIFILM")
{
throw new RawDecoderException("Header is wrong");
}
//Fuji is indexer reverse endian
reader = new ImageBinaryReaderBigEndian(file);
reader.BaseStream.Position = 8;
//read next 8 byte
dataAsString = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(8).ToArray()).Trim();
//4 byte version
var version = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(4).ToArray());
//8 bytes unknow ??
var unknow = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(8).ToArray()).Trim();
//32 byte a string (camera model)
dataAsString = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(32).ToArray()).Trim();
//Directory
//4 bytes version
version = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(4).ToArray());
//20 bytes unkown ??
dataAsString = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(20).ToArray()).Trim();
//parse the ifd
uint first_ifd = reader.ReadUInt32();
relativeOffset = first_ifd + 12;
reader.ReadInt32();
//raw header
// RAW information IFD on older
uint third_ifd = reader.ReadUInt32();
reader.ReadUInt32();
uint secondIFD = reader.ReadUInt32();
uint count = reader.ReadUInt32();
try
{
Parse(secondIFD);
}
catch (Exception)
{
//old format
ifd = new IFD(Endianness.Big, 0);
//raw image
var entry = new Tag(TagType.FUJI_STRIPOFFSETS, TiffDataType.LONG, 1);
entry.data[0] = secondIFD;
ifd.tags.Add(entry.TagId, entry);
entry = new Tag(TagType.FUJI_STRIPBYTECOUNTS, TiffDataType.LONG, 1);
entry.data[0] = count;
ifd.tags.Add(entry.TagId, entry);
}
Parse(first_ifd + 12);
ParseFuji(third_ifd);
}
public override Thumbnail DecodeThumb()
{
//find the preview IFD (usually the first if any)
List<IFD> potential = ifd.GetIFDsWithTag(TagType.NEWSUBFILETYPE);
IFD thumbIFD = null;
if (potential?.Count != 0)
{
for (int i = 0; i < potential.Count; i++)
{
var subFile = potential[i].GetEntry(TagType.NEWSUBFILETYPE);
if (subFile.GetInt(0) == 1)
{
thumbIFD = potential[i];
break;
}
}
}
if (thumbIFD != null)
{
//there is a thumbnail
uint bps = thumbIFD.GetEntry(TagType.BITSPERSAMPLE).GetUInt(0);
Point2D dim = new Point2D(thumbIFD.GetEntry(TagType.IMAGEWIDTH).GetUInt(0), thumbIFD.GetEntry(TagType.IMAGELENGTH).GetUInt(0));
int compression = thumbIFD.GetEntry(TagType.COMPRESSION).GetShort(0);
// Now load the image
if (compression == 1)
{
// Uncompressed
uint cpp = thumbIFD.GetEntry(TagType.SAMPLESPERPIXEL).GetUInt(0);
if (cpp > 4)
throw new RawDecoderException("DNG Decoder: More than 4 samples per pixel is not supported.");
Tag offsets = thumbIFD.GetEntry(TagType.STRIPOFFSETS);
Tag counts = thumbIFD.GetEntry(TagType.STRIPBYTECOUNTS);
uint yPerSlice = thumbIFD.GetEntry(TagType.ROWSPERSTRIP).GetUInt(0);
reader.BaseStream.Position = offsets.GetInt(0) + offsets.parent_offset;
return new JPEGThumbnail(reader.ReadBytes(counts.GetInt(0)));
}
else if (compression == 6)
{
var offset = thumbIFD.GetEntry((TagType)0x0201);
var size = thumbIFD.GetEntry((TagType)0x0202);
if (size == null || offset == null) return null;
//get the makernote offset
List<IFD> exifs = ifd.GetIFDsWithTag((TagType)0x927C);
if (exifs == null || exifs.Count == 0) return null;
Tag makerNoteOffsetTag = exifs[0].GetEntryRecursive((TagType)0x927C);
if (makerNoteOffsetTag == null) return null;
reader.Position = offset.GetUInt(0) + 10 + makerNoteOffsetTag.dataOffset;
return new JPEGThumbnail(reader.ReadBytes(size.GetInt(0)));
}
else return null;
}
else
{
var previews = ifd.GetIFDsWithTag(TagType.JPEGINTERCHANGEFORMAT);
//no thumbnail
if (previews?.Count == 0) return null;
var preview = previews[0];
var thumb = preview.GetEntry(TagType.JPEGINTERCHANGEFORMAT);
var size = preview.GetEntry(TagType.JPEGINTERCHANGEFORMATLENGTH);
if (size == null || thumb == null) return null;
reader.Position = thumb.GetUInt(0) + thumb.parent_offset;
return new JPEGThumbnail(reader.ReadBytes(size.GetInt(0)));
}
}
/* Parse FUJI information */
/* It is a simpler form of Tiff IFD, so we add them as TiffEntries */
void ParseFuji(uint offset)
{
try
{
IFD tempIFD = new IFD(ifd.endian, ifd.Depth);
ImageBinaryReaderBigEndian bytes = new ImageBinaryReaderBigEndian(stream, offset);
uint entries = bytes.ReadUInt32();
if (entries > 255)
throw new RawDecoderException("Too many entries");
for (int i = 0; i < entries; i++)
{
UInt16 tag = bytes.ReadUInt16();
uint length = bytes.ReadUInt16();
Tag t;
// Set types of known tags
switch (tag)
{
case 0x100:
case 0x121:
case 0x2ff0:
t = new Tag((TagType)tag, TiffDataType.SHORT, length / 2);
for (int k = 0; k < t.dataCount; k++)
{
t.data[k] = bytes.ReadUInt16();
}
break;
case 0xc000:
// This entry seem to have swapped endianness:
t = new Tag((TagType)tag, TiffDataType.LONG, length / 4);
for (int k = 0; k < t.dataCount; k++)
{
t.data[k] = bytes.ReadUInt32();
}
break;
default:
t = new Tag((TagType)tag, TiffDataType.UNDEFINED, length);
for (int k = 0; k < t.dataCount; k++)
{
t.data[k] = bytes.ReadByte();
}
break;
}
tempIFD.tags.Add(t.TagId, t);
//bytes.ReadBytes((int)length);
}
ifd.subIFD.Add(tempIFD);
}
catch (IOException)
{
throw new RawDecoderException("IO error occurred during parsing. Skipping the rest");
}
}
public override void DecodeRaw()
{
List<IFD> data = ifd.GetIFDsWithTag(TagType.FUJI_STRIPOFFSETS);
if (data.Count <= 0)
throw new RawDecoderException("Fuji decoder: Unable to locate raw IFD");
IFD raw = data[0];
uint height = 0;
uint width = 0;
var dim = raw.GetEntry(TagType.FUJI_RAWIMAGEFULLHEIGHT);
if (dim != null)
{
height = dim.GetUInt(0);
width = raw.GetEntry(TagType.FUJI_RAWIMAGEFULLWIDTH).GetUInt(0);
}
else
{
Tag wtag = raw.GetEntryRecursive(TagType.IMAGEWIDTH);
if (wtag != null)
{
if (wtag.dataCount < 2)
throw new RawDecoderException("Fuji decoder: Size array too small");
height = wtag.GetUShort(0);
width = wtag.GetUShort(1);
}
}
Tag e = raw.GetEntryRecursive(TagType.FUJI_LAYOUT);
if (e != null)
{
if (e.dataCount < 2)
throw new RawDecoderException("Fuji decoder: Layout array too small");
byte[] layout = e.GetByteArray();
//alt_layout = !(layout[0] >> 7);
}
if (width <= 0 || height <= 0)
throw new RawDecoderException("RAF decoder: Unable to locate image size");
Tag offsets = raw.GetEntry(TagType.FUJI_STRIPOFFSETS);
Tag counts = raw.GetEntry(TagType.FUJI_STRIPBYTECOUNTS);
if (offsets.dataCount != 1 || counts.dataCount != 1)
throw new RawDecoderException("RAF Decoder: Multiple Strips found: " + offsets.dataCount + " " + counts.dataCount);
int off = offsets.GetInt(0);
int count = counts.GetInt(0);
ushort bps = 12;
var bpsTag = raw.GetEntryRecursive(TagType.FUJI_BITSPERSAMPLE) ?? raw.GetEntryRecursive(TagType.BITSPERSAMPLE);
if (bpsTag != null)
{
bps = bpsTag.GetUShort(0);
}
else
{
rawImage.errors.Add("BPS not found");
}
rawImage.fullSize.ColorDepth = bps;
// x-trans sensors report 14bpp, but data isn't packed so read as 16bpp
if (bps == 14) bps = 16;
// Some fuji SuperCCD cameras include a second raw image next to the first one
// that is identical but darker to the first. The two combined can produce
// a higher dynamic range image. Right now we're ignoring it.
//bool double_width = hints.ContainsKey("double_width_unpacked");
rawImage.fullSize.dim = new Point2D(width, height);
rawImage.Init(false);
ImageBinaryReader input = new ImageBinaryReader(stream, (uint)(off + raw.RelativeOffset));
Point2D pos = new Point2D(0, 0);
if (count * 8 / (width * height) < 10)
{
throw new RawDecoderException("Don't know how to decode compressed images");
}
else if (ifd.endian == Endianness.Big)
{
RawDecompressor.Decode16BitRawUnpacked(input, new Point2D(width, height), pos, rawImage);
}
else
{
// RawDecompressor.ReadUncompressedRaw(input, rawImage.raw.dim, pos, width * bps / 8, bps, BitOrder.Jpeg32, rawImage);
RawDecompressor.ReadUncompressedRaw(input, new Point2D(width, height), pos, width * bps / 8, bps, BitOrder.Plain, rawImage);
}
}
public override void DecodeMetadata()
{
//metadata
base.DecodeMetadata();
if (rawImage.metadata.Model == null) throw new RawDecoderException("RAF Meta Decoder: Model name not found");
if (rawImage.metadata.Make == null) throw new RawDecoderException("RAF Support: Make name not found");
SetMetadata(rawImage.metadata.Model);
//get cfa
var rawifd = ifd.GetIFDsWithTag(TagType.FUJI_LAYOUT);
if (rawifd != null)
{
var cfa = rawifd[0].GetEntry(TagType.FUJI_LAYOUT);
var t = rawifd[0].GetEntry((TagType)0x0131);
if (t != null)
{
//fuji cfa
rawImage.colorFilter = new ColorFilterArray(new Point2D(6, 6));
rawImage.errors.Add("No support for X-trans yet,colour will be wrong");
for (int i = 0; i < t.dataCount; i++)
{
rawImage.colorFilter.cfa[i] = (CFAColor)t.GetInt(i);
}
}
else if (cfa.GetInt(0) < 4)
{
//bayer cfa
rawImage.colorFilter.SetCFA(new Point2D(2, 2), (CFAColor)cfa.GetInt(0),
(CFAColor)cfa.GetInt(1), (CFAColor)cfa.GetInt(2), (CFAColor)cfa.GetInt(3));
}
else
{
//default to GRBG
rawImage.colorFilter.SetCFA(new Point2D(2, 2), CFAColor.Red, CFAColor.Green, CFAColor.Green, CFAColor.Blue);
}
//ConsoleContent.Value +=("CFA pattern is not found");
}
else
{
//rawImage.cfa.SetCFA(new Point2D(2, 2), (CFAColor)cfa.GetInt(0), (CFAColor)cfa.GetInt(1), (CFAColor)cfa.GetInt(2), (CFAColor)cfa.GetInt(3));
}
//read lens
rawImage.metadata.Lens = ifd.GetEntryRecursive((TagType)42036)?.DataAsString;
rawImage.whitePoint = (1 << rawImage.fullSize.ColorDepth) - 1;
Tag sep_black = ifd.GetEntryRecursive(TagType.FUJI_RGGBLEVELSBLACK);
if (sep_black.dataCount > 1) Debug.Assert(sep_black?.GetInt(0) == sep_black?.GetInt(1));
rawImage.black = sep_black?.GetInt(0) ?? 0;
/*if (sep_black?.dataCount >= 4)
{
for (int k = 0; k < 4; k++)
rawImage.blackLevelSeparate[k] = sep_black.GetInt(k);
}
*/
Tag wb = ifd.GetEntryRecursive(TagType.FUJI_WB_GRBLEVELS);
if (wb?.dataCount == 3)
{
rawImage.metadata.WbCoeffs = new WhiteBalance(wb.GetInt(1), wb.GetInt(0), wb.GetInt(2), rawImage.fullSize.ColorDepth);
}
else
{
wb = ifd.GetEntryRecursive(TagType.FUJIOLDWB);
if (wb?.dataCount == 8)
{
rawImage.metadata.WbCoeffs = new WhiteBalance(wb.GetInt(1), wb.GetInt(0), wb.GetInt(3), rawImage.fullSize.ColorDepth);
}
}
}
protected void SetMetadata(string model)
{
if (model.Contains("S2Pro"))
{
rawImage.fullSize.dim.height = 2144;
rawImage.fullSize.dim.width = 2880;
//flip = 6;
}
else if (model.Contains("X-Pro1"))
{
rawImage.fullSize.dim.width -= 168;
}
else if (model.Contains("FinePix X100"))
{
rawImage.fullSize.dim.width -= 144;
rawImage.fullSize.offset.width = 74;
}
else
{
//maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
//top_margin = (raw_height - height) >> 2 << 1;
//left_margin = (raw_width - width) >> 2 << 1;
// if (rawImage.raw.dim.Width == 2848 || rawImage.raw.dim.Width == 3664) filters = 0x16161616;
//if (rawImage.raw.dim.Width == 4032 || rawImage.raw.dim.Width == 4952 || rawImage.raw.dim.Width == 6032) rawImage.raw.offset.Width = 0;
if (rawImage.fullSize.dim.width == 3328)
{
rawImage.fullSize.offset.width = 34;
rawImage.fullSize.dim.width -= 66;
}
else if (rawImage.fullSize.dim.width == 4936)
rawImage.fullSize.offset.width = 4;
if (model.Contains("HS50EXR") || model.Contains("F900EXR"))
{
rawImage.fullSize.dim.width += 2;
rawImage.fullSize.offset.width = 0;
}
}
}
/*
private CamRGB[] colorM = { { "Fujifilm E550", 0, 0,
{ 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
{ "Fujifilm E900", 0, 0,
{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
{ "Fujifilm F5", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F6", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F77", 0, 0xfe9,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F7", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm F8", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm S100FS", 514, 0,
{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
{ "Fujifilm S1", 0, 0,
{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
{ "Fujifilm S20Pro", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm S20", 512, 0x3fff,
{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
{ "Fujifilm S2Pro", 128, 0,
{ 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } },
{ "Fujifilm S3Pro", 0, 0,
{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
{ "Fujifilm S5Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm S5000", 0, 0,
{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
{ "Fujifilm S5100", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5500", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5200", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S5600", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S6", 0, 0,
{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
{ "Fujifilm S7000", 0, 0,
{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
{ "Fujifilm S9000", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9500", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9100", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm S9600", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm SL1000", 0, 0,
{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
{ "Fujifilm IS-1", 0, 0,
{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
{ "Fujifilm IS Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm HS10 HS11", 0, 0xf68,
{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
{ "Fujifilm HS2", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS3", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS50EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm F900EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm X100S", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100T", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100", 0, 0,
{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
{ "Fujifilm X10", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X20", 0, 0,
{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
{ "Fujifilm X30", 0, 0,
{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
{ "Fujifilm X70", 0, 0,
{ 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } },
{ "Fujifilm X-Pro1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-Pro2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-A1", 0, 0,
{ 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } },
{ "Fujifilm X-A2", 0, 0,
{ 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } },
{ "Fujifilm X-E1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E2S", 0, 0,
{ 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } },
{ "Fujifilm X-E2", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-M1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-S1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-T1", 0, 0, // also X-T10
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm XF1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm XQ", 0, 0, // XQ1 and XQ2
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }};*/
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeX509ChainHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeX509ChainHandle() : base (default(bool)) { }
protected override void Dispose(bool disposing) { }
protected override bool ReleaseHandle() { throw null; }
}
}
namespace System.Security.Cryptography.X509Certificates
{
public sealed partial class CertificateRequest
{
public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.ECDsa key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { }
public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { }
public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.X509Certificates.PublicKey publicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { }
public CertificateRequest(string subjectName, System.Security.Cryptography.ECDsa key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { }
public CertificateRequest(string subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { }
public System.Collections.ObjectModel.Collection<System.Security.Cryptography.X509Certificates.X509Extension> CertificateExtensions { get { throw null; } }
public System.Security.Cryptography.HashAlgorithmName HashAlgorithm { get { throw null; } }
public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Create(System.Security.Cryptography.X509Certificates.X500DistinguishedName issuerName, System.Security.Cryptography.X509Certificates.X509SignatureGenerator generator, System.DateTimeOffset notBefore, System.DateTimeOffset notAfter, byte[] serialNumber) { throw null; }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Create(System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate, System.DateTimeOffset notBefore, System.DateTimeOffset notAfter, byte[] serialNumber) { throw null; }
public System.Security.Cryptography.X509Certificates.X509Certificate2 CreateSelfSigned(System.DateTimeOffset notBefore, System.DateTimeOffset notAfter) { throw null; }
public byte[] CreateSigningRequest() { throw null; }
public byte[] CreateSigningRequest(System.Security.Cryptography.X509Certificates.X509SignatureGenerator signatureGenerator) { throw null; }
}
public static partial class DSACertificateExtensions
{
public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.DSA privateKey) { throw null; }
public static System.Security.Cryptography.DSA GetDSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public static System.Security.Cryptography.DSA GetDSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
}
public static partial class ECDsaCertificateExtensions
{
public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.ECDsa privateKey) { throw null; }
public static System.Security.Cryptography.ECDsa GetECDsaPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public static System.Security.Cryptography.ECDsa GetECDsaPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
}
[System.FlagsAttribute]
public enum OpenFlags
{
ReadOnly = 0,
ReadWrite = 1,
MaxAllowed = 2,
OpenExistingOnly = 4,
IncludeArchived = 8,
}
public sealed partial class PublicKey
{
public PublicKey(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedData parameters, System.Security.Cryptography.AsnEncodedData keyValue) { }
public System.Security.Cryptography.AsnEncodedData EncodedKeyValue { get { throw null; } }
public System.Security.Cryptography.AsnEncodedData EncodedParameters { get { throw null; } }
public System.Security.Cryptography.AsymmetricAlgorithm Key { get { throw null; } }
public System.Security.Cryptography.Oid Oid { get { throw null; } }
}
public static partial class RSACertificateExtensions
{
public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.RSA privateKey) { throw null; }
public static System.Security.Cryptography.RSA GetRSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public static System.Security.Cryptography.RSA GetRSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
}
public enum StoreLocation
{
CurrentUser = 1,
LocalMachine = 2,
}
public enum StoreName
{
AddressBook = 1,
AuthRoot = 2,
CertificateAuthority = 3,
Disallowed = 4,
My = 5,
Root = 6,
TrustedPeople = 7,
TrustedPublisher = 8,
}
public sealed partial class SubjectAlternativeNameBuilder
{
public SubjectAlternativeNameBuilder() { }
public void AddDnsName(string dnsName) { }
public void AddEmailAddress(string emailAddress) { }
public void AddIpAddress(System.Net.IPAddress ipAddress) { }
public void AddUri(System.Uri uri) { }
public void AddUserPrincipalName(string upn) { }
public System.Security.Cryptography.X509Certificates.X509Extension Build(bool critical = false) { throw null; }
}
public sealed partial class X500DistinguishedName : System.Security.Cryptography.AsnEncodedData
{
public X500DistinguishedName(byte[] encodedDistinguishedName) { }
public X500DistinguishedName(System.Security.Cryptography.AsnEncodedData encodedDistinguishedName) { }
public X500DistinguishedName(System.Security.Cryptography.X509Certificates.X500DistinguishedName distinguishedName) { }
public X500DistinguishedName(string distinguishedName) { }
public X500DistinguishedName(string distinguishedName, System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { }
public string Name { get { throw null; } }
public string Decode(System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { throw null; }
public override string Format(bool multiLine) { throw null; }
}
[System.FlagsAttribute]
public enum X500DistinguishedNameFlags
{
None = 0,
Reversed = 1,
UseSemicolons = 16,
DoNotUsePlusSign = 32,
DoNotUseQuotes = 64,
UseCommas = 128,
UseNewLines = 256,
UseUTF8Encoding = 4096,
UseT61Encoding = 8192,
ForceUTF8Encoding = 16384,
}
public sealed partial class X509BasicConstraintsExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509BasicConstraintsExtension() { }
public X509BasicConstraintsExtension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical) { }
public X509BasicConstraintsExtension(System.Security.Cryptography.AsnEncodedData encodedBasicConstraints, bool critical) { }
public bool CertificateAuthority { get { throw null; } }
public bool HasPathLengthConstraint { get { throw null; } }
public int PathLengthConstraint { get { throw null; } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public partial class X509Certificate : System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
{
public X509Certificate() { }
public X509Certificate(byte[] data) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate(byte[] rawData, System.Security.SecureString password) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate(byte[] rawData, string password) { }
public X509Certificate(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate(System.IntPtr handle) { }
public X509Certificate(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public X509Certificate(System.Security.Cryptography.X509Certificates.X509Certificate cert) { }
public X509Certificate(string fileName) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate(string fileName, System.Security.SecureString password) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate(string fileName, string password) { }
public X509Certificate(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public System.IntPtr Handle { get { throw null; } }
public string Issuer { get { throw null; } }
public string Subject { get { throw null; } }
public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromCertFile(string filename) { throw null; }
public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromSignedFile(string filename) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public override bool Equals(object obj) { throw null; }
public virtual bool Equals(System.Security.Cryptography.X509Certificates.X509Certificate other) { throw null; }
public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; }
[System.CLSCompliantAttribute(false)]
public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, System.Security.SecureString password) { throw null; }
public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; }
protected static string FormatDate(System.DateTime date) { throw null; }
public virtual byte[] GetCertHash() { throw null; }
public virtual byte[] GetCertHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual string GetCertHashString() { throw null; }
public virtual string GetCertHashString(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual string GetEffectiveDateString() { throw null; }
public virtual string GetExpirationDateString() { throw null; }
public virtual string GetFormat() { throw null; }
public override int GetHashCode() { throw null; }
[System.ObsoleteAttribute("This method has been deprecated. Please use the Issuer property instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public virtual string GetIssuerName() { throw null; }
public virtual string GetKeyAlgorithm() { throw null; }
public virtual byte[] GetKeyAlgorithmParameters() { throw null; }
public virtual string GetKeyAlgorithmParametersString() { throw null; }
[System.ObsoleteAttribute("This method has been deprecated. Please use the Subject property instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public virtual string GetName() { throw null; }
public virtual byte[] GetPublicKey() { throw null; }
public virtual string GetPublicKeyString() { throw null; }
public virtual byte[] GetRawCertData() { throw null; }
public virtual string GetRawCertDataString() { throw null; }
public virtual byte[] GetSerialNumber() { throw null; }
public virtual string GetSerialNumberString() { throw null; }
public virtual void Import(byte[] rawData) { }
[System.CLSCompliantAttribute(false)]
public virtual void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public virtual void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public virtual void Import(string fileName) { }
[System.CLSCompliantAttribute(false)]
public virtual void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public virtual void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public virtual void Reset() { }
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public override string ToString() { throw null; }
public virtual string ToString(bool fVerbose) { throw null; }
public virtual bool TryGetCertHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Span<byte> destination, out int bytesWritten) { throw null; }
}
public partial class X509Certificate2 : System.Security.Cryptography.X509Certificates.X509Certificate
{
public X509Certificate2() { }
public X509Certificate2(byte[] rawData) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate2(byte[] rawData, System.Security.SecureString password) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate2(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate2(byte[] rawData, string password) { }
public X509Certificate2(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate2(System.IntPtr handle) { }
protected X509Certificate2(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public X509Certificate2(System.Security.Cryptography.X509Certificates.X509Certificate certificate) { }
public X509Certificate2(string fileName) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate2(string fileName, System.Security.SecureString password) { }
[System.CLSCompliantAttribute(false)]
public X509Certificate2(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate2(string fileName, string password) { }
public X509Certificate2(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public bool Archived { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions { get { throw null; } }
public string FriendlyName { get { throw null; } set { } }
public bool HasPrivateKey { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X500DistinguishedName IssuerName { get { throw null; } }
public System.DateTime NotAfter { get { throw null; } }
public System.DateTime NotBefore { get { throw null; } }
public System.Security.Cryptography.AsymmetricAlgorithm PrivateKey { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } }
public byte[] RawData { get { throw null; } }
public string SerialNumber { get { throw null; } }
public System.Security.Cryptography.Oid SignatureAlgorithm { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { throw null; } }
public string Thumbprint { get { throw null; } }
public int Version { get { throw null; } }
public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(byte[] rawData) { throw null; }
public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(string fileName) { throw null; }
public string GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType nameType, bool forIssuer) { throw null; }
public override void Import(byte[] rawData) { }
[System.CLSCompliantAttribute(false)]
public override void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public override void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public override void Import(string fileName) { }
[System.CLSCompliantAttribute(false)]
public override void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public override void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public override void Reset() { }
public override string ToString() { throw null; }
public override string ToString(bool verbose) { throw null; }
public bool Verify() { throw null; }
}
public partial class X509Certificate2Collection : System.Security.Cryptography.X509Certificates.X509CertificateCollection
{
public X509Certificate2Collection() { }
public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { }
public new System.Security.Cryptography.X509Certificates.X509Certificate2 this[int index] { get { throw null; } set { } }
public int Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { }
public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; }
public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Find(System.Security.Cryptography.X509Certificates.X509FindType findType, object findValue, bool validOnly) { throw null; }
public new System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator GetEnumerator() { throw null; }
public void Import(byte[] rawData) { }
public void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public void Import(string fileName) { }
public void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { }
}
public sealed partial class X509Certificate2Enumerator : System.Collections.IEnumerator
{
internal X509Certificate2Enumerator() { }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
bool System.Collections.IEnumerator.MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
public partial class X509CertificateCollection : System.Collections.CollectionBase
{
public X509CertificateCollection() { }
public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { }
public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { }
public System.Security.Cryptography.X509Certificates.X509Certificate this[int index] { get { throw null; } set { } }
public int Add(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; }
public void AddRange(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { }
public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; }
public void CopyTo(System.Security.Cryptography.X509Certificates.X509Certificate[] array, int index) { }
public new System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator GetEnumerator() { throw null; }
public override int GetHashCode() { throw null; }
public int IndexOf(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; }
public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate value) { }
protected override void OnValidate(object value) { }
public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate value) { }
public partial class X509CertificateEnumerator : System.Collections.IEnumerator
{
public X509CertificateEnumerator(System.Security.Cryptography.X509Certificates.X509CertificateCollection mappings) { }
public System.Security.Cryptography.X509Certificates.X509Certificate Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
bool System.Collections.IEnumerator.MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class X509Chain : System.IDisposable
{
public X509Chain() { }
public X509Chain(bool useMachineContext) { }
public X509Chain(System.IntPtr chainContext) { }
public System.IntPtr ChainContext { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509ChainElementCollection ChainElements { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509ChainPolicy ChainPolicy { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainStatus { get { throw null; } }
public Microsoft.Win32.SafeHandles.SafeX509ChainHandle SafeHandle { get { throw null; } }
public bool Build(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; }
public static System.Security.Cryptography.X509Certificates.X509Chain Create() { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public void Reset() { }
}
public partial class X509ChainElement
{
internal X509ChainElement() { }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainElementStatus { get { throw null; } }
public string Information { get { throw null; } }
}
public sealed partial class X509ChainElementCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal X509ChainElementCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509ChainElement this[int index] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Security.Cryptography.X509Certificates.X509ChainElement[] array, int index) { }
public System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public sealed partial class X509ChainElementEnumerator : System.Collections.IEnumerator
{
internal X509ChainElementEnumerator() { }
public System.Security.Cryptography.X509Certificates.X509ChainElement Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
public sealed partial class X509ChainPolicy
{
public X509ChainPolicy() { }
public System.Security.Cryptography.OidCollection ApplicationPolicy { get { throw null; } }
public System.Security.Cryptography.OidCollection CertificatePolicy { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection ExtraStore { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509RevocationFlag RevocationFlag { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get { throw null; } set { } }
public System.TimeSpan UrlRetrievalTimeout { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509VerificationFlags VerificationFlags { get { throw null; } set { } }
public System.DateTime VerificationTime { get { throw null; } set { } }
public void Reset() { }
}
public partial struct X509ChainStatus
{
private object _dummy;
private int _dummyPrimitive;
public System.Security.Cryptography.X509Certificates.X509ChainStatusFlags Status { get { throw null; } set { } }
public string StatusInformation { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum X509ChainStatusFlags
{
NoError = 0,
NotTimeValid = 1,
NotTimeNested = 2,
Revoked = 4,
NotSignatureValid = 8,
NotValidForUsage = 16,
UntrustedRoot = 32,
RevocationStatusUnknown = 64,
Cyclic = 128,
InvalidExtension = 256,
InvalidPolicyConstraints = 512,
InvalidBasicConstraints = 1024,
InvalidNameConstraints = 2048,
HasNotSupportedNameConstraint = 4096,
HasNotDefinedNameConstraint = 8192,
HasNotPermittedNameConstraint = 16384,
HasExcludedNameConstraint = 32768,
PartialChain = 65536,
CtlNotTimeValid = 131072,
CtlNotSignatureValid = 262144,
CtlNotValidForUsage = 524288,
HasWeakSignature = 1048576,
OfflineRevocation = 16777216,
NoIssuanceChainPolicy = 33554432,
ExplicitDistrust = 67108864,
HasNotSupportedCriticalExtension = 134217728,
}
public enum X509ContentType
{
Unknown = 0,
Cert = 1,
SerializedCert = 2,
Pfx = 3,
Pkcs12 = 3,
SerializedStore = 4,
Pkcs7 = 5,
Authenticode = 6,
}
public sealed partial class X509EnhancedKeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509EnhancedKeyUsageExtension() { }
public X509EnhancedKeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedEnhancedKeyUsages, bool critical) { }
public X509EnhancedKeyUsageExtension(System.Security.Cryptography.OidCollection enhancedKeyUsages, bool critical) { }
public System.Security.Cryptography.OidCollection EnhancedKeyUsages { get { throw null; } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public partial class X509Extension : System.Security.Cryptography.AsnEncodedData
{
protected X509Extension() { }
public X509Extension(System.Security.Cryptography.AsnEncodedData encodedExtension, bool critical) { }
public X509Extension(System.Security.Cryptography.Oid oid, byte[] rawData, bool critical) { }
public X509Extension(string oid, byte[] rawData, bool critical) { }
public bool Critical { get { throw null; } set { } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public sealed partial class X509ExtensionCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
public X509ExtensionCollection() { }
public int Count { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509Extension this[int index] { get { throw null; } }
public System.Security.Cryptography.X509Certificates.X509Extension this[string oid] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public int Add(System.Security.Cryptography.X509Certificates.X509Extension extension) { throw null; }
public void CopyTo(System.Security.Cryptography.X509Certificates.X509Extension[] array, int index) { }
public System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public sealed partial class X509ExtensionEnumerator : System.Collections.IEnumerator
{
internal X509ExtensionEnumerator() { }
public System.Security.Cryptography.X509Certificates.X509Extension Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public bool MoveNext() { throw null; }
public void Reset() { }
}
public enum X509FindType
{
FindByThumbprint = 0,
FindBySubjectName = 1,
FindBySubjectDistinguishedName = 2,
FindByIssuerName = 3,
FindByIssuerDistinguishedName = 4,
FindBySerialNumber = 5,
FindByTimeValid = 6,
FindByTimeNotYetValid = 7,
FindByTimeExpired = 8,
FindByTemplateName = 9,
FindByApplicationPolicy = 10,
FindByCertificatePolicy = 11,
FindByExtension = 12,
FindByKeyUsage = 13,
FindBySubjectKeyIdentifier = 14,
}
public enum X509IncludeOption
{
None = 0,
ExcludeRoot = 1,
EndCertOnly = 2,
WholeChain = 3,
}
[System.FlagsAttribute]
public enum X509KeyStorageFlags
{
DefaultKeySet = 0,
UserKeySet = 1,
MachineKeySet = 2,
Exportable = 4,
UserProtected = 8,
PersistKeySet = 16,
EphemeralKeySet = 32,
}
public sealed partial class X509KeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509KeyUsageExtension() { }
public X509KeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedKeyUsage, bool critical) { }
public X509KeyUsageExtension(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags keyUsages, bool critical) { }
public System.Security.Cryptography.X509Certificates.X509KeyUsageFlags KeyUsages { get { throw null; } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
[System.FlagsAttribute]
public enum X509KeyUsageFlags
{
None = 0,
EncipherOnly = 1,
CrlSign = 2,
KeyCertSign = 4,
KeyAgreement = 8,
DataEncipherment = 16,
KeyEncipherment = 32,
NonRepudiation = 64,
DigitalSignature = 128,
DecipherOnly = 32768,
}
public enum X509NameType
{
SimpleName = 0,
EmailName = 1,
UpnName = 2,
DnsName = 3,
DnsFromAlternativeName = 4,
UrlName = 5,
}
public enum X509RevocationFlag
{
EndCertificateOnly = 0,
EntireChain = 1,
ExcludeRoot = 2,
}
public enum X509RevocationMode
{
NoCheck = 0,
Online = 1,
Offline = 2,
}
public abstract partial class X509SignatureGenerator
{
protected X509SignatureGenerator() { }
public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } }
protected abstract System.Security.Cryptography.X509Certificates.PublicKey BuildPublicKey();
public static System.Security.Cryptography.X509Certificates.X509SignatureGenerator CreateForECDsa(System.Security.Cryptography.ECDsa key) { throw null; }
public static System.Security.Cryptography.X509Certificates.X509SignatureGenerator CreateForRSA(System.Security.Cryptography.RSA key, System.Security.Cryptography.RSASignaturePadding signaturePadding) { throw null; }
public abstract byte[] GetSignatureAlgorithmIdentifier(System.Security.Cryptography.HashAlgorithmName hashAlgorithm);
public abstract byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm);
}
public sealed partial class X509Store : System.IDisposable
{
public X509Store() { }
public X509Store(System.IntPtr storeHandle) { }
public X509Store(System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { }
public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName) { }
public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { }
public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags) { }
public X509Store(string storeName) { }
public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { }
public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags) { }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { throw null; } }
public bool IsOpen { get { throw null; } }
public System.Security.Cryptography.X509Certificates.StoreLocation Location { get { throw null; } }
public string Name { get { throw null; } }
public System.IntPtr StoreHandle { get { throw null; } }
public void Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
public void Close() { }
public void Dispose() { }
public void Open(System.Security.Cryptography.X509Certificates.OpenFlags flags) { }
public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
}
public sealed partial class X509SubjectKeyIdentifierExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509SubjectKeyIdentifierExtension() { }
public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier, bool critical) { }
public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.AsnEncodedData encodedSubjectKeyIdentifier, bool critical) { }
public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, bool critical) { }
public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) { }
public X509SubjectKeyIdentifierExtension(string subjectKeyIdentifier, bool critical) { }
public string SubjectKeyIdentifier { get { throw null; } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public enum X509SubjectKeyIdentifierHashAlgorithm
{
Sha1 = 0,
ShortSha1 = 1,
CapiSha1 = 2,
}
[System.FlagsAttribute]
public enum X509VerificationFlags
{
NoFlag = 0,
IgnoreNotTimeValid = 1,
IgnoreCtlNotTimeValid = 2,
IgnoreNotTimeNested = 4,
IgnoreInvalidBasicConstraints = 8,
AllowUnknownCertificateAuthority = 16,
IgnoreWrongUsage = 32,
IgnoreInvalidName = 64,
IgnoreInvalidPolicy = 128,
IgnoreEndRevocationUnknown = 256,
IgnoreCtlSignerRevocationUnknown = 512,
IgnoreCertificateAuthorityRevocationUnknown = 1024,
IgnoreRootRevocationUnknown = 2048,
AllFlags = 4095,
}
}
| |
namespace ControlzEx.Tests.Theming
{
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using ControlzEx.Tests.TestClasses;
using ControlzEx.Theming;
using NUnit.Framework;
[TestFixture]
public class ThemeManagerTest
{
private ThemeManager testThemeManager;
[SetUp]
public void SetUp()
{
this.testThemeManager = new ThemeManager();
this.testThemeManager.RegisterLibraryThemeProvider(TestLibraryThemeProvider.DefaultInstance);
}
[Test]
public void ChangeThemeForAppShouldThrowArgumentNullException()
{
Assert.That(() => this.testThemeManager.ChangeTheme((Application)null, this.testThemeManager.GetTheme("Light.Red")), Throws.ArgumentNullException.With.Message.Contains("app"));
Assert.That(() => this.testThemeManager.ChangeTheme(Application.Current, this.testThemeManager.GetTheme("UnknownTheme")), Throws.ArgumentNullException.With.Message.Contains("newTheme"));
}
[Test]
public void ChangeThemeForWindowShouldThrowArgumentNullException()
{
using (var window = new TestWindow())
{
Assert.Throws<ArgumentNullException>(() => this.testThemeManager.ChangeTheme((Window)null, this.testThemeManager.GetTheme("Light.Red")));
Assert.Throws<ArgumentNullException>(() => this.testThemeManager.ChangeTheme(Application.Current.MainWindow, this.testThemeManager.GetTheme("UnknownTheme")));
}
}
[Test]
public void CanAddThemeBeforeGetterIsCalled()
{
{
var source = new Uri("pack://application:,,,/ControlzEx.Tests;component/Themes/Themes/Dark.Cobalt.xaml");
var newTheme = new Theme(new LibraryTheme(source, null));
Assert.That(this.testThemeManager.AddTheme(newTheme), Is.Not.EqualTo(newTheme));
}
{
var resource = new ResourceDictionary
{
{
Theme.ThemeNameKey, "Runtime"
},
{
Theme.ThemeDisplayNameKey, "Runtime"
},
{
Theme.ThemePrimaryAccentColorKey, Colors.Blue
},
{
Theme.ThemeIsRuntimeGeneratedKey, true
}
};
var newTheme = new Theme(new LibraryTheme(resource, null));
Assert.That(this.testThemeManager.AddTheme(newTheme), Is.EqualTo(newTheme));
}
}
[Test]
public void NewThemeAddsNewBaseColorAndColorScheme()
{
var resource = new ResourceDictionary
{
{
Theme.ThemeNameKey, "Runtime"
},
{
Theme.ThemeDisplayNameKey, "Runtime"
},
{
Theme.ThemeBaseColorSchemeKey, "Foo"
},
{
Theme.ThemeColorSchemeKey, "Bar"
},
{
Theme.ThemePrimaryAccentColorKey, Colors.Blue
},
{
Theme.ThemeIsRuntimeGeneratedKey, true
}
};
var newTheme = new Theme(new LibraryTheme(resource, null));
Assert.That(this.testThemeManager.AddTheme(newTheme), Is.EqualTo(newTheme));
Assert.That(this.testThemeManager.BaseColors, Is.EqualTo(new[] { ThemeManager.BaseColorLight, ThemeManager.BaseColorDark, "Foo" }));
Assert.That(this.testThemeManager.ColorSchemes, Does.Contain("Bar"));
}
[Test]
public void ChangingAppThemeChangesWindowTheme()
{
using (var window = new TestWindow())
{
var expectedTheme = this.testThemeManager.GetTheme("Dark.Teal");
this.testThemeManager.ChangeTheme(Application.Current, expectedTheme);
Assert.That(this.testThemeManager.DetectTheme(Application.Current), Is.EqualTo(expectedTheme));
Assert.That(this.testThemeManager.DetectTheme(window), Is.EqualTo(expectedTheme));
}
}
[Test]
public void ChangeBaseColor()
{
this.testThemeManager.ChangeTheme(Application.Current, this.testThemeManager.Themes.First());
{
var currentTheme = this.testThemeManager.DetectTheme(Application.Current);
Assert.That(currentTheme, Is.Not.Null);
this.testThemeManager.ChangeThemeBaseColor(Application.Current, this.testThemeManager.GetInverseTheme(currentTheme).BaseColorScheme);
Assert.That(this.testThemeManager.DetectTheme(Application.Current).BaseColorScheme, Is.Not.EqualTo(currentTheme.BaseColorScheme));
Assert.That(this.testThemeManager.DetectTheme(Application.Current).ColorScheme, Is.EqualTo(currentTheme.ColorScheme));
}
{
using (var window = new TestWindow())
{
var currentTheme = this.testThemeManager.DetectTheme(window);
Assert.That(currentTheme, Is.Not.Null);
this.testThemeManager.ChangeThemeBaseColor(window, this.testThemeManager.GetInverseTheme(currentTheme).BaseColorScheme);
Assert.That(this.testThemeManager.DetectTheme(window).BaseColorScheme, Is.Not.EqualTo(currentTheme.BaseColorScheme));
Assert.That(this.testThemeManager.DetectTheme(window).ColorScheme, Is.EqualTo(currentTheme.ColorScheme));
}
}
{
var currentTheme = this.testThemeManager.DetectTheme(Application.Current);
Assert.That(currentTheme, Is.Not.Null);
var control = new Control();
this.testThemeManager.ChangeThemeBaseColor(control, control.Resources, currentTheme, this.testThemeManager.GetInverseTheme(currentTheme).BaseColorScheme);
Assert.That(this.testThemeManager.DetectTheme(control.Resources).BaseColorScheme, Is.Not.EqualTo(currentTheme.BaseColorScheme));
Assert.That(this.testThemeManager.DetectTheme(control.Resources).ColorScheme, Is.EqualTo(currentTheme.ColorScheme));
}
}
[Test]
public void ChangeColorScheme()
{
this.testThemeManager.ChangeTheme(Application.Current, this.testThemeManager.Themes.First());
{
var currentTheme = this.testThemeManager.DetectTheme(Application.Current);
Assert.That(currentTheme, Is.Not.Null);
this.testThemeManager.ChangeThemeColorScheme(Application.Current, "Yellow");
Assert.That(this.testThemeManager.DetectTheme(Application.Current).BaseColorScheme, Is.EqualTo(currentTheme.BaseColorScheme));
Assert.That(this.testThemeManager.DetectTheme(Application.Current).ColorScheme, Is.EqualTo("Yellow"));
}
{
using (var window = new TestWindow())
{
var currentTheme = this.testThemeManager.DetectTheme(window);
Assert.That(currentTheme, Is.Not.Null);
this.testThemeManager.ChangeThemeColorScheme(window, "Green");
Assert.That(this.testThemeManager.DetectTheme(window).BaseColorScheme, Is.EqualTo(currentTheme.BaseColorScheme));
Assert.That(this.testThemeManager.DetectTheme(window).ColorScheme, Is.EqualTo("Green"));
}
}
{
var currentTheme = this.testThemeManager.DetectTheme(Application.Current);
Assert.That(currentTheme, Is.Not.Null);
var control = new Control();
this.testThemeManager.ChangeThemeColorScheme(control, control.Resources, currentTheme, "Red");
Assert.That(this.testThemeManager.DetectTheme(control.Resources).BaseColorScheme, Is.EqualTo(currentTheme.BaseColorScheme));
Assert.That(this.testThemeManager.DetectTheme(control.Resources).ColorScheme, Is.EqualTo("Red"));
}
Assert.That(this.testThemeManager.DetectTheme(Application.Current).ColorScheme, Is.EqualTo("Yellow"));
}
[Test]
public void ChangeBaseColorAndColorScheme()
{
this.testThemeManager.ChangeTheme(Application.Current, this.testThemeManager.Themes.First());
{
var currentTheme = this.testThemeManager.DetectTheme(Application.Current);
Assert.That(currentTheme, Is.Not.Null);
this.testThemeManager.ChangeTheme(Application.Current, ThemeManager.BaseColorDark, "Yellow");
Assert.That(this.testThemeManager.DetectTheme(Application.Current).BaseColorScheme, Is.EqualTo(ThemeManager.BaseColorDark));
Assert.That(this.testThemeManager.DetectTheme(Application.Current).ColorScheme, Is.EqualTo("Yellow"));
}
{
using (var window = new TestWindow())
{
var currentTheme = this.testThemeManager.DetectTheme(window);
Assert.That(currentTheme, Is.Not.Null);
this.testThemeManager.ChangeTheme(window, ThemeManager.BaseColorLight, "Green");
Assert.That(this.testThemeManager.DetectTheme(window).BaseColorScheme, Is.EqualTo(ThemeManager.BaseColorLight));
Assert.That(this.testThemeManager.DetectTheme(window).ColorScheme, Is.EqualTo("Green"));
}
}
{
var currentTheme = this.testThemeManager.DetectTheme(Application.Current);
Assert.That(currentTheme, Is.Not.Null);
var control = new Control();
this.testThemeManager.ChangeTheme(control, control.Resources, currentTheme, ThemeManager.BaseColorDark, "Red");
Assert.That(this.testThemeManager.DetectTheme(control.Resources).BaseColorScheme, Is.EqualTo(ThemeManager.BaseColorDark));
Assert.That(this.testThemeManager.DetectTheme(control.Resources).ColorScheme, Is.EqualTo("Red"));
}
Assert.That(this.testThemeManager.DetectTheme(Application.Current).ColorScheme, Is.EqualTo("Yellow"));
}
[Test]
public void GetInverseThemeReturnsDarkTheme()
{
var theme = this.testThemeManager.GetInverseTheme(this.testThemeManager.GetTheme("Light.Blue"));
Assert.That(theme.Name, Is.EqualTo("Dark.Blue"));
}
[Test]
public void GetInverseThemeReturnsLightTheme()
{
var theme = this.testThemeManager.GetInverseTheme(this.testThemeManager.GetTheme("Dark.Blue"));
Assert.That(theme.Name, Is.EqualTo("Light.Blue"));
}
[Test]
public void GetInverseThemeReturnsNullForMissingTheme()
{
var resource = new ResourceDictionary
{
{
"Theme.Name", "Runtime"
},
{
"Theme.DisplayName", "Runtime"
},
{
Theme.ThemePrimaryAccentColorKey, Colors.Blue
},
{
Theme.ThemeIsRuntimeGeneratedKey, true
}
};
var theme = new Theme(new LibraryTheme(resource, null));
var inverseTheme = this.testThemeManager.GetInverseTheme(theme);
Assert.Null(inverseTheme);
}
[Test]
[TestCase(ThemeManager.BaseColorLightConst, ThemeManager.BaseColorDarkConst)]
[TestCase(ThemeManager.BaseColorDarkConst, ThemeManager.BaseColorLightConst)]
public void GetInverseThemeReturnsInverseThemeForRuntimeGeneratedTheme(string baseColor, string inverseBaseColor)
{
var resource = new ResourceDictionary
{
{
Theme.ThemeNameKey, "Runtime"
},
{
Theme.ThemeDisplayNameKey, "Runtime"
},
{
Theme.ThemeBaseColorSchemeKey, baseColor
},
{
Theme.ThemePrimaryAccentColorKey, Colors.Blue
},
{
Theme.ThemeIsRuntimeGeneratedKey, true
}
};
var theme = new Theme(new LibraryTheme(resource, null));
var inverseTheme = this.testThemeManager.GetInverseTheme(theme);
Assert.AreEqual(inverseTheme.BaseColorScheme, inverseBaseColor);
}
[Test]
public void GetThemeIsCaseInsensitive()
{
var theme = this.testThemeManager.GetTheme("Dark.Blue");
Assert.NotNull(theme);
Assert.That(theme.GetAllResources().First().Source.ToString(), Is.EqualTo("pack://application:,,,/ControlzEx.Tests;component/Themes/Themes/Dark.Blue.xaml").IgnoreCase);
}
[Test]
public void GetThemeWithUriIsCaseInsensitive()
{
var dic = new ResourceDictionary
{
Source = new Uri("pack://application:,,,/ControlzEx.Tests;component/Themes/Themes/daRK.Blue.xaml")
};
var theme = this.testThemeManager.GetTheme(dic);
Assert.NotNull(theme);
Assert.That(theme.Name, Is.EqualTo("Dark.Blue"));
}
[Test]
public void GetThemeWithEmptyThemeManager()
{
var themeManager = new ThemeManager();
var theme = themeManager.GetTheme("Test");
Assert.That(theme, Is.Null);
}
[Test]
public void HighContrastScenarios()
{
var themeManager = new ThemeManager();
{
var resource = new ResourceDictionary
{
{
Theme.ThemeNameKey, "Theme 1"
},
{
Theme.ThemeDisplayNameKey, "Theme 1"
},
{
Theme.ThemeBaseColorSchemeKey, ThemeManager.BaseColorDark
},
{
Theme.ThemeColorSchemeKey, "Bar"
},
{
Theme.ThemePrimaryAccentColorKey, Colors.Blue
},
{
Theme.ThemeIsHighContrastKey, false
}
};
var newTheme = new Theme(new LibraryTheme(resource, null));
themeManager.AddTheme(newTheme);
}
{
var resource = new ResourceDictionary
{
{
Theme.ThemeNameKey, "Theme 2"
},
{
Theme.ThemeDisplayNameKey, "Theme 2"
},
{
Theme.ThemeBaseColorSchemeKey, ThemeManager.BaseColorLight
},
{
Theme.ThemeColorSchemeKey, "Bar"
},
{
Theme.ThemePrimaryAccentColorKey, Colors.Blue
},
{
Theme.ThemeIsHighContrastKey, false
}
};
var newTheme = new Theme(new LibraryTheme(resource, null));
themeManager.AddTheme(newTheme);
}
{
var resource = new ResourceDictionary
{
{
Theme.ThemeNameKey, "Theme 1"
},
{
Theme.ThemeDisplayNameKey, "Theme 1"
},
{
Theme.ThemeBaseColorSchemeKey, ThemeManager.BaseColorDark
},
{
Theme.ThemeColorSchemeKey, "Bar"
},
{
Theme.ThemePrimaryAccentColorKey, Colors.Blue
},
{
Theme.ThemeIsHighContrastKey, true
}
};
var newTheme = new Theme(new LibraryTheme(resource, null));
themeManager.AddTheme(newTheme);
}
{
var resource = new ResourceDictionary
{
{
Theme.ThemeNameKey, "Theme 2"
},
{
Theme.ThemeDisplayNameKey, "Theme 2"
},
{
Theme.ThemeBaseColorSchemeKey, ThemeManager.BaseColorLight
},
{
Theme.ThemeColorSchemeKey, "Bar"
},
{
Theme.ThemePrimaryAccentColorKey, Colors.Blue
},
{
Theme.ThemeIsHighContrastKey, true
}
};
var newTheme = new Theme(new LibraryTheme(resource, null));
themeManager.AddTheme(newTheme);
}
{
var theme = themeManager.GetTheme(ThemeManager.BaseColorDark, "Bar");
Assert.That(theme, Is.Not.Null);
Assert.That(theme.IsHighContrast, Is.False);
}
{
var theme = themeManager.GetTheme(ThemeManager.BaseColorDark, "Bar", true);
Assert.That(theme, Is.Not.Null);
Assert.That(theme.IsHighContrast, Is.True);
var inverseTheme = themeManager.GetInverseTheme(theme);
Assert.That(inverseTheme, Is.Not.Null);
Assert.That(inverseTheme, Is.Not.EqualTo(theme));
Assert.That(inverseTheme.IsHighContrast, Is.True);
}
{
var frameworkElement = new FrameworkElement();
var theme = themeManager.GetTheme(ThemeManager.BaseColorDark, "Bar", true);
var changeTheme = themeManager.ChangeTheme(frameworkElement, theme!);
Assert.That(changeTheme, Is.EqualTo(theme));
var changeThemeBaseColor = themeManager.ChangeThemeBaseColor(frameworkElement, ThemeManager.BaseColorLight);
Assert.That(changeThemeBaseColor, Is.Not.Null);
Assert.That(changeThemeBaseColor, Is.Not.EqualTo(changeTheme));
Assert.That(changeThemeBaseColor.IsHighContrast, Is.True);
}
}
[Test]
public void GetThemes()
{
var expectedThemes = new[]
{
"Amber (Dark)",
"Amber (Light)",
"Blue (Dark)",
"Blue (Light)",
"Brown (Dark)",
"Brown (Light)",
"Cobalt (Dark)",
"Cobalt (Light)",
"Crimson (Dark)",
"Crimson (Light)",
"Cyan (Dark)",
"Cyan (Light)",
"Emerald (Dark)",
"Emerald (Light)",
"Green (Dark)",
"Green (Light)",
"Indigo (Dark)",
"Indigo (Light)",
"Lime (Dark)",
"Lime (Light)",
"Magenta (Dark)",
"Magenta (Light)",
"Mauve (Dark)",
"Mauve (Light)",
"Olive (Dark)",
"Olive (Light)",
"Orange (Dark)",
"Orange (Light)",
"Pink (Dark)",
"Pink (Light)",
"Purple (Dark)",
"Purple (Light)",
"Red (Dark)",
"Red (Light)",
"Sienna (Dark)",
"Sienna (Light)",
"Steel (Dark)",
"Steel (Light)",
"Taupe (Dark)",
"Taupe (Light)",
"Teal (Dark)",
"Teal (Light)",
"Violet (Dark)",
"Violet (Light)",
"Yellow (Dark)",
"Yellow (Light)"
};
Assert.That(CollectionViewSource.GetDefaultView(this.testThemeManager.Themes).Cast<Theme>().Select(x => x.DisplayName).ToList(), Is.EqualTo(expectedThemes));
}
[Test]
public void GetBaseColors()
{
this.testThemeManager.ClearThemes();
Assert.That(this.testThemeManager.BaseColors, Is.Not.Empty);
}
[Test]
public void GetColorSchemes()
{
this.testThemeManager.ClearThemes();
Assert.That(this.testThemeManager.ColorSchemes, Is.Not.Empty);
}
[Test]
public void CreateDynamicThemeWithColor()
{
var applicationTheme = this.testThemeManager.DetectTheme(Application.Current);
this.testThemeManager.ChangeTheme(Application.Current, RuntimeThemeGenerator.Current.GenerateRuntimeTheme(ThemeManager.BaseColorLight, Colors.Red));
var detected = this.testThemeManager.DetectTheme(Application.Current);
Assert.NotNull(detected);
Assert.That(detected.Name, Is.EqualTo("Light.Runtime_#FFFF0000"));
this.testThemeManager.ChangeTheme(Application.Current, RuntimeThemeGenerator.Current.GenerateRuntimeTheme(ThemeManager.BaseColorDark, Colors.Green));
detected = this.testThemeManager.DetectTheme(Application.Current);
Assert.NotNull(detected);
Assert.That(detected.Name, Is.EqualTo("Dark.Runtime_#FF008000"));
this.testThemeManager.ChangeTheme(Application.Current, applicationTheme);
}
[Test]
public void CreateDynamicAccentWithColorAndChangeBaseColorScheme()
{
var darkRedTheme = this.testThemeManager.AddTheme(RuntimeThemeGenerator.Current.GenerateRuntimeTheme(ThemeManager.BaseColorDark, Colors.Red));
var lightRedTheme = this.testThemeManager.AddTheme(RuntimeThemeGenerator.Current.GenerateRuntimeTheme(ThemeManager.BaseColorLight, Colors.Red));
this.testThemeManager.ChangeTheme(Application.Current, lightRedTheme);
var detected = this.testThemeManager.DetectTheme(Application.Current);
Assert.NotNull(detected);
Assert.That(detected.ColorScheme, Is.EqualTo(Colors.Red.ToString()));
{
var newTheme = this.testThemeManager.ChangeThemeBaseColor(Application.Current, ThemeManager.BaseColorDark);
Assert.That(newTheme, Is.EqualTo(darkRedTheme));
}
{
var newTheme = this.testThemeManager.ChangeThemeBaseColor(Application.Current, ThemeManager.BaseColorLight);
Assert.That(newTheme, Is.EqualTo(lightRedTheme));
}
}
[Test]
[TestCase("pack://application:,,,/ControlzEx.Tests;component/Themes/themes/dark.blue.xaml", "Dark", "#FF2B579A", "#FF086F9E")]
[TestCase("pack://application:,,,/ControlzEx.Tests;component/Themes/themes/dark.green.xaml", "Dark", "#FF60A917", "#FF477D11")]
[TestCase("pack://application:,,,/ControlzEx.Tests;component/Themes/themes/Light.blue.xaml", "Light", "#FF2B579A", "#FF086F9E")]
[TestCase("pack://application:,,,/ControlzEx.Tests;component/Themes/themes/Light.green.xaml", "Light", "#FF60A917", "#FF477D11")]
public void CompareGeneratedAppStyleWithShipped(string source, string baseColor, string color, string highlightColor)
{
var dic = new ResourceDictionary
{
Source = new Uri(source)
};
var newTheme = RuntimeThemeGenerator.Current.GenerateRuntimeTheme(baseColor, (Color)ColorConverter.ConvertFromString(color));
var ignoredKeyValues = new[]
{
Theme.ThemeNameKey,
Theme.ThemeDisplayNameKey,
Theme.ThemeColorSchemeKey,
Theme.ThemeInstanceKey,
Theme.ThemeIsRuntimeGeneratedKey,
LibraryTheme.LibraryThemeInstanceKey,
"ControlzEx.Colors.HighlightColor", // Ignored because it's hand crafted
"ControlzEx.Brushes.HighlightBrush", // Ignored because it's hand crafted,
"Theme.RuntimeThemeColorValues"
};
CompareResourceDictionaries(dic, newTheme.GetAllResources().First(), ignoredKeyValues);
CompareResourceDictionaries(newTheme.GetAllResources().First(), dic, ignoredKeyValues);
}
private static void CompareResourceDictionaries(ResourceDictionary first, ResourceDictionary second, params string[] ignoredKeyValues)
{
foreach (var key in first.Keys)
{
if (ignoredKeyValues.Contains(key) == false)
{
if (second.Contains(key) == false)
{
throw new Exception($"Key \"{key}\" is missing from {second.Source}.");
}
Assert.That(second[key].ToString(), Is.EqualTo(first[key].ToString()), $"Values for {key} should be equal.");
}
}
}
}
}
| |
//
// 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.
//
namespace NLog.UnitTests.Config
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NLog.Config;
using NLog.Filters;
using Xunit;
public class RuleConfigurationTests : NLogTestBase
{
[Fact]
public void NoRulesTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
</rules>
</nlog>");
Assert.Equal(0, c.LoggingRules.Count);
}
[Fact]
public void SimpleRuleTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal("*", rule.LoggerNamePattern);
Assert.Equal(FilterResult.Neutral, rule.DefaultFilterResult);
Assert.Equal(4, rule.Levels.Count);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
Assert.Contains(LogLevel.Error, rule.Levels);
Assert.Contains(LogLevel.Fatal, rule.Levels);
Assert.Equal(1, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.False(rule.Final);
Assert.Equal(0, rule.Filters.Count);
}
[Fact]
public void SingleLevelTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Single(rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
}
[Fact]
public void MinMaxLevelTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' maxLevel='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Levels.Count);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
}
[Fact]
public void NoLevelsTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(6, rule.Levels.Count);
Assert.Contains(LogLevel.Trace, rule.Levels);
Assert.Contains(LogLevel.Debug, rule.Levels);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
Assert.Contains(LogLevel.Error, rule.Levels);
Assert.Contains(LogLevel.Fatal, rule.Levels);
}
[Fact]
public void ExplicitLevelsTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' levels='Trace,Info,Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Levels.Count);
Assert.Contains(LogLevel.Trace, rule.Levels);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
}
[Fact]
public void MultipleTargetsTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.Same(c.FindTargetByName("d2"), rule.Targets[1]);
Assert.Same(c.FindTargetByName("d3"), rule.Targets[2]);
}
[Fact]
public void MultipleRulesSameTargetTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
<target name='d3' type='Debug' layout='${message}' />
<target name='d4' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
<logger name='*' level='Warn' writeTo='d2' />
<logger name='*' level='Warn' writeTo='d3' />
</rules>
</nlog>");
LogFactory factory = new LogFactory(c);
var loggerConfig = factory.GetConfigurationForLogger("AAA", c);
var targets = loggerConfig.GetTargetsForLevel(LogLevel.Warn);
Assert.Equal("d1", targets.Target.Name);
Assert.Equal("d2", targets.NextInChain.Target.Name);
Assert.Equal("d3", targets.NextInChain.NextInChain.Target.Name);
Assert.Null(targets.NextInChain.NextInChain.NextInChain);
LogManager.Configuration = c;
var logger = LogManager.GetLogger("BBB");
logger.Warn("test1234");
AssertDebugLastMessage("d1", "test1234");
AssertDebugLastMessage("d2", "test1234");
AssertDebugLastMessage("d3", "test1234");
AssertDebugLastMessage("d4", string.Empty);
}
[Fact]
public void ChildRulesTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<logger name='Foo*' writeTo='d4' />
<logger name='Bar*' writeTo='d4' />
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.ChildRules.Count);
Assert.Equal("Foo*", rule.ChildRules[0].LoggerNamePattern);
Assert.Equal("Bar*", rule.ChildRules[1].LoggerNamePattern);
}
[Fact]
public void FiltersTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<filters>
<when condition=""starts-with(message, 'x')"" action='Ignore' />
<when condition=""starts-with(message, 'z')"" action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Filters.Count);
var conditionBasedFilter = rule.Filters[0] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'x')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
conditionBasedFilter = rule.Filters[1] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'z')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
}
[Fact]
public void FiltersTest_ignoreFinal()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters>
<when condition=""starts-with(message, 'x')"" action='IgnoreFinal' />
</filters>
</logger>
<logger name='*' level='Warn' writeTo='d2'>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
}
[Fact]
public void FiltersTest_logFinal()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters>
<when condition=""starts-with(message, 'x')"" action='LogFinal' />
</filters>
</logger>
<logger name='*' level='Warn' writeTo='d2'>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "x-mass");
AssertDebugLastMessage("d2", "test 1");
}
[Fact]
public void FiltersTest_ignore()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters>
<when condition=""starts-with(message, 'x')"" action='Ignore' />
</filters>
</logger>
<logger name='*' level='Warn' writeTo='d2'>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "x-mass");
}
[Fact]
public void FiltersTest_defaultFilterAction()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters defaultAction='Ignore'>
<when condition=""starts-with(message, 't')"" action='Log' />
</filters>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "test 1");
}
[Fact]
public void FiltersTest_defaultFilterAction_noRules()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters defaultAction='Ignore'>
</filters>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "");
}
[Fact]
public void LoggingRule_Final_SuppressesOnlyMatchingLevels()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='a' level='Debug' final='true' />
<logger name='*' minlevel='Debug' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = c;
Logger a = LogManager.GetLogger("a");
Assert.False(a.IsDebugEnabled);
Assert.True(a.IsInfoEnabled);
a.Info("testInfo");
a.Debug("suppressedDebug");
AssertDebugLastMessage("d1", "testInfo");
Logger b = LogManager.GetLogger("b");
b.Debug("testDebug");
AssertDebugLastMessage("d1", "testDebug");
}
[Fact]
public void UnusedTargetsShouldBeLoggedToInternalLogger()
{
string tempFileName = Path.GetTempFileName();
try
{
var config = XmlLoggingConfiguration.CreateFromXmlString("<nlog internalLogFile='" + tempFileName + @"' internalLogLevel='Warn'>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
<target name='d5' type='Debug' />
</targets>
<rules>
<logger name='*' level='Debug' writeTo='d1' />
<logger name='*' level='Debug' writeTo='d1,d2,d3' />
</rules>
</nlog>");
var logFactory = new LogFactory();
logFactory.Configuration = config;
AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d4", Encoding.UTF8);
AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d5", Encoding.UTF8);
}
finally
{
NLog.Common.InternalLogger.Reset();
if (File.Exists(tempFileName))
{
File.Delete(tempFileName);
}
}
}
[Fact]
public void UnusedTargetsShouldBeLoggedToInternalLogger_PermitWrapped()
{
string tempFileName = Path.GetTempFileName();
try
{
var config = XmlLoggingConfiguration.CreateFromXmlString("<nlog internalLogFile='" + tempFileName + @"' internalLogLevel='Warn'>
<extensions>
<add assembly='NLog.UnitTests'/>
</extensions>
<targets async='true'>
<target name='d1' type='Debug' />
<target name='d2' type='MockWrapper'>
<target name='d3' type='Debug' />
</target>
<target name='d4' type='Debug' />
<target name='d5' type='Debug' />
</targets>
<rules>
<logger name='*' level='Debug' writeTo='d1' />
<logger name='*' level='Debug' writeTo='d1,d2,d4' />
</rules>
</nlog>");
var logFactory = new LogFactory();
logFactory.Configuration = config;
AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d2", Encoding.UTF8);
AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d3", Encoding.UTF8);
AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d4", Encoding.UTF8);
AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d5", Encoding.UTF8);
}
finally
{
NLog.Common.InternalLogger.Reset();
if (File.Exists(tempFileName))
{
File.Delete(tempFileName);
}
}
}
[Fact]
public void LoggingRule_LevelOff_NotSetAsActualLogLevel()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='l1' type='Debug' layout='${message}' />
<target name='l2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='a' level='Off' appendTo='l1' />
<logger name='a' minlevel='Debug' appendTo='l2' />
</rules>
</nlog>");
LogManager.Configuration = c;
LogManager.GetLogger("a");
Assert.Equal(2, c.LoggingRules.Count);
Assert.False(c.LoggingRules[0].IsLoggingEnabledForLevel(LogLevel.Off), "Log level Off should always return false.");
// The two functions below should not throw an exception.
c.LoggingRules[0].EnableLoggingForLevel(LogLevel.Debug);
c.LoggingRules[0].DisableLoggingForLevel(LogLevel.Debug);
}
[Theory]
[InlineData("Off")]
[InlineData("")]
[InlineData((string)null)]
[InlineData("Trace")]
[InlineData("Debug")]
[InlineData("Info")]
[InlineData("Warn")]
[InlineData("Error")]
[InlineData(" error")]
[InlineData("Fatal")]
[InlineData("Wrong")]
public void LoggingRule_LevelLayout_ParseLevel(string levelVariable)
{
var config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>"
+ (levelVariable != null ? $"<variable name='var_level' value='{levelVariable}'/>" : "") +
@"<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='${var:var_level}' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = config;
Logger logger = LogManager.GetLogger(nameof(LoggingRule_LevelLayout_ParseLevel));
LogLevel expectedLogLevel = (NLog.Internal.StringHelpers.IsNullOrWhiteSpace(levelVariable) || levelVariable == "Wrong") ? LogLevel.Off : LogLevel.FromString(levelVariable.Trim());
AssertLogLevelEnabled(logger, expectedLogLevel);
// Verify that runtime override also works
LogManager.Configuration.Variables["var_level"] = LogLevel.Fatal.ToString();
LogManager.ReconfigExistingLoggers();
AssertLogLevelEnabled(logger, LogLevel.Fatal);
}
[Theory]
[MemberData(nameof(LoggingRule_LevelsLayout_ParseLevel_TestCases))]
public void LoggingRule_LevelsLayout_ParseLevel(string levelsVariable, LogLevel[] expectedLevels)
{
var config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>"
+ (!string.IsNullOrEmpty(levelsVariable) ? $"<variable name='var_levels' value='{levelsVariable}'/>" : "") +
@"<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' levels='${var:var_levels}' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = config;
var logger = LogManager.GetLogger(nameof(LoggingRule_LevelsLayout_ParseLevel));
AssertLogLevelEnabled(logger, expectedLevels);
// Verify that runtime override also works
LogManager.Configuration.Variables["var_levels"] = LogLevel.Fatal.ToString();
LogManager.ReconfigExistingLoggers();
AssertLogLevelEnabled(logger, LogLevel.Fatal);
}
public static IEnumerable<object[]> LoggingRule_LevelsLayout_ParseLevel_TestCases()
{
yield return new object[] { "Off", new[] { LogLevel.Off } };
yield return new object[] { "Off, Trace", new[] { LogLevel.Off, LogLevel.Trace } };
yield return new object[] { " ", new[] { LogLevel.Off } };
yield return new object[] { " , Debug", new[] { LogLevel.Off, LogLevel.Debug } };
yield return new object[] { "", new[] { LogLevel.Off } };
yield return new object[] { ",Info", new[] { LogLevel.Off, LogLevel.Info } };
yield return new object[] { "Error, Error", new[] { LogLevel.Error, LogLevel.Error } };
yield return new object[] { " error", new[] { LogLevel.Error } };
yield return new object[] { " error, Warn", new[] { LogLevel.Error, LogLevel.Warn } };
yield return new object[] { "Wrong", new[] { LogLevel.Off } };
yield return new object[] { "Wrong, Fatal", new[] { LogLevel.Off, LogLevel.Fatal } };
}
[Theory]
[MemberData(nameof(LoggingRule_MinMaxLayout_ParseLevel_TestCases2))]
public void LoggingRule_MinMaxLayout_ParseLevel(string minLevel, string maxLevel, LogLevel[] expectedLevels)
{
var config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>"
+ (!string.IsNullOrEmpty(minLevel) ? $"<variable name='var_minlevel' value='{minLevel}'/>" : "")
+ (!string.IsNullOrEmpty(maxLevel) ? $"<variable name='var_maxlevel' value='{maxLevel}'/>" : "") +
@"<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='${var:var_minlevel}' maxlevel='${var:var_maxlevel}' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = config;
var logger = LogManager.GetLogger(nameof(LoggingRule_MinMaxLayout_ParseLevel));
AssertLogLevelEnabled(logger, expectedLevels);
// Verify that runtime override also works
LogManager.Configuration.Variables["var_minlevel"] = LogLevel.Fatal.ToString();
LogManager.Configuration.Variables["var_maxlevel"] = LogLevel.Fatal.ToString();
LogManager.ReconfigExistingLoggers();
AssertLogLevelEnabled(logger, LogLevel.Fatal);
}
public static IEnumerable<object[]> LoggingRule_MinMaxLayout_ParseLevel_TestCases2()
{
yield return new object[] { "Off", "", new LogLevel[] { } };
yield return new object[] { "Off", "Fatal", new LogLevel[] { } };
yield return new object[] { "Error", "Debug", new LogLevel[] { } };
yield return new object[] { " ", "", new LogLevel[] { } };
yield return new object[] { " ", "Fatal", new LogLevel[] { } };
yield return new object[] { "", "", new LogLevel[] { } };
yield return new object[] { "", "Off", new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "", "Fatal", new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "", "Debug", new[] { LogLevel.Trace, LogLevel.Debug } };
yield return new object[] { "", "Trace", new[] { LogLevel.Trace } };
yield return new object[] { "", " error", new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error } };
yield return new object[] { "", "Wrong", new LogLevel[] { } };
yield return new object[] { "Wrong", "", new LogLevel[] { } };
yield return new object[] { "Wrong", "Fatal", new LogLevel[] { } };
yield return new object[] { " error", "Debug", new LogLevel[] { } };
yield return new object[] { " error", "Fatal", new[] { LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { " error", "", new[] { LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "Error", "", new[] { LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "Fatal", "", new[] { LogLevel.Fatal } };
yield return new object[] { "Off", "", new LogLevel[] { } };
yield return new object[] { "Trace", " ", new LogLevel[] { } };
yield return new object[] { "Trace", "", new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "Trace", "Debug", new[] { LogLevel.Trace, LogLevel.Debug } };
yield return new object[] { "Trace", "Trace", new[] { LogLevel.Trace, LogLevel.Trace } };
}
private static void AssertLogLevelEnabled(ILoggerBase logger, LogLevel expectedLogLevel)
{
AssertLogLevelEnabled(logger, new[] {expectedLogLevel });
}
private static void AssertLogLevelEnabled(ILoggerBase logger, LogLevel[] expectedLogLevels)
{
for (int i = LogLevel.MinLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
var logLevel = LogLevel.FromOrdinal(i);
if (expectedLogLevels.Contains(logLevel))
Assert.True(logger.IsEnabled(logLevel),$"{logLevel} expected as true");
else
Assert.False(logger.IsEnabled(logLevel),$"{logLevel} expected as false");
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache.Store
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Impl;
using NUnit.Framework;
/// <summary>
/// Tests cache store functionality.
/// </summary>
public class CacheStoreTest
{
/** */
private const string BinaryStoreCacheName = "binary_store";
/** */
private const string ObjectStoreCacheName = "object_store";
/** */
private const string CustomStoreCacheName = "custom_store";
/** */
private const string TemplateStoreCacheName = "template_store*";
/// <summary>
/// Fixture set up.
/// </summary>
[TestFixtureSetUp]
public virtual void BeforeTests()
{
var cfg = new IgniteConfiguration
{
GridName = GridName,
JvmClasspath = TestUtils.CreateTestClasspath(),
JvmOptions = TestUtils.TestJavaOptions(),
SpringConfigUrl = "config\\native-client-test-cache-store.xml",
BinaryConfiguration = new BinaryConfiguration(typeof (Key), typeof (Value))
};
Ignition.Start(cfg);
}
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureTearDown]
public void AfterTests()
{
Ignition.StopAll(true);
}
/// <summary>
/// Test tear down.
/// </summary>
[TearDown]
public void AfterTest()
{
CacheTestStore.Reset();
var cache = GetCache();
cache.Clear();
Assert.IsTrue(cache.IsEmpty(),
"Cache is not empty: " +
string.Join(", ", cache.Select(x => string.Format("[{0}:{1}]", x.Key, x.Value))));
TestUtils.AssertHandleRegistryHasItems(300, 3, Ignition.GetIgnite(GridName));
}
/// <summary>
/// Tests that simple cache loading works and exceptions are propagated properly.
/// </summary>
[Test]
public void TestLoadCache()
{
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LoadCache(new CacheEntryFilter(), 100, 10);
Assert.AreEqual(5, cache.GetSize());
for (int i = 105; i < 110; i++)
Assert.AreEqual("val_" + i, cache.Get(i));
// Test invalid filter
Assert.Throws<BinaryObjectException>(() => cache.LoadCache(new InvalidCacheEntryFilter(), 100, 10));
// Test exception in filter
Assert.Throws<CacheStoreException>(() => cache.LoadCache(new ExceptionalEntryFilter(), 100, 10));
// Test exception in store
CacheTestStore.ThrowError = true;
CheckCustomStoreError(Assert.Throws<CacheStoreException>(() =>
cache.LoadCache(new CacheEntryFilter(), 100, 10)).InnerException);
}
/// <summary>
/// Tests cache loading in local mode.
/// </summary>
[Test]
public void TestLocalLoadCache()
{
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCache(new CacheEntryFilter(), 100, 10);
Assert.AreEqual(5, cache.GetSize());
for (int i = 105; i < 110; i++)
Assert.AreEqual("val_" + i, cache.Get(i));
}
/// <summary>
/// Tests that object metadata propagates properly during cache loading.
/// </summary>
[Test]
public void TestLoadCacheMetadata()
{
CacheTestStore.LoadObjects = true;
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCache(null, 0, 3);
Assert.AreEqual(3, cache.GetSize());
var meta = cache.WithKeepBinary<Key, IBinaryObject>().Get(new Key(0)).GetBinaryType();
Assert.NotNull(meta);
Assert.AreEqual("Value", meta.TypeName);
}
/// <summary>
/// Tests asynchronous cache load.
/// </summary>
[Test]
public void TestLoadCacheAsync()
{
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCacheAsync(new CacheEntryFilter(), 100, 10).Wait();
Assert.AreEqual(5, cache.GetSizeAsync().Result);
for (int i = 105; i < 110; i++)
{
Assert.AreEqual("val_" + i, cache.GetAsync(i).Result);
}
// Test errors
CacheTestStore.ThrowError = true;
CheckCustomStoreError(
Assert.Throws<AggregateException>(
() => cache.LocalLoadCacheAsync(new CacheEntryFilter(), 100, 10).Wait())
.InnerException);
}
/// <summary>
/// Tests write-through and read-through behavior.
/// </summary>
[Test]
public void TestPutLoad()
{
var cache = GetCache();
cache.Put(1, "val");
IDictionary map = GetStoreMap();
Assert.AreEqual(1, map.Count);
cache.LocalEvict(new[] { 1 });
Assert.AreEqual(0, cache.GetSize());
Assert.AreEqual("val", cache.Get(1));
Assert.AreEqual(1, cache.GetSize());
}
[Test]
public void TestExceptions()
{
var cache = GetCache();
cache.Put(1, "val");
CacheTestStore.ThrowError = true;
CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Put(-2, "fail")).InnerException);
cache.LocalEvict(new[] {1});
CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Get(1)).InnerException);
CacheTestStore.ThrowError = false;
cache.Remove(1);
}
[Test]
[Ignore("IGNITE-4657")]
public void TestExceptionsNoRemove()
{
var cache = GetCache();
cache.Put(1, "val");
CacheTestStore.ThrowError = true;
CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Put(-2, "fail")).InnerException);
cache.LocalEvict(new[] {1});
CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Get(1)).InnerException);
}
/// <summary>
/// Tests write-through and read-through behavior with binarizable values.
/// </summary>
[Test]
public void TestPutLoadBinarizable()
{
var cache = GetBinaryStoreCache<int, Value>();
cache.Put(1, new Value(1));
IDictionary map = GetStoreMap();
Assert.AreEqual(1, map.Count);
IBinaryObject v = (IBinaryObject)map[1];
Assert.AreEqual(1, v.GetField<int>("_idx"));
cache.LocalEvict(new[] { 1 });
Assert.AreEqual(0, cache.GetSize());
Assert.AreEqual(1, cache.Get(1).Index);
Assert.AreEqual(1, cache.GetSize());
}
/// <summary>
/// Tests write-through and read-through behavior with storeKeepBinary=false.
/// </summary>
[Test]
public void TestPutLoadObjects()
{
var cache = GetObjectStoreCache<int, Value>();
cache.Put(1, new Value(1));
IDictionary map = GetStoreMap();
Assert.AreEqual(1, map.Count);
Value v = (Value)map[1];
Assert.AreEqual(1, v.Index);
cache.LocalEvict(new[] { 1 });
Assert.AreEqual(0, cache.GetSize());
Assert.AreEqual(1, cache.Get(1).Index);
Assert.AreEqual(1, cache.GetSize());
}
/// <summary>
/// Tests cache store LoadAll functionality.
/// </summary>
[Test]
public void TestPutLoadAll()
{
var putMap = new Dictionary<int, string>();
for (int i = 0; i < 10; i++)
putMap.Add(i, "val_" + i);
var cache = GetCache();
cache.PutAll(putMap);
IDictionary map = GetStoreMap();
Assert.AreEqual(10, map.Count);
for (int i = 0; i < 10; i++)
Assert.AreEqual("val_" + i, map[i]);
cache.Clear();
Assert.AreEqual(0, cache.GetSize());
ICollection<int> keys = new List<int>();
for (int i = 0; i < 10; i++)
keys.Add(i);
IDictionary<int, string> loaded = cache.GetAll(keys);
Assert.AreEqual(10, loaded.Count);
for (int i = 0; i < 10; i++)
Assert.AreEqual("val_" + i, loaded[i]);
Assert.AreEqual(10, cache.GetSize());
}
/// <summary>
/// Tests cache store removal.
/// </summary>
[Test]
public void TestRemove()
{
var cache = GetCache();
for (int i = 0; i < 10; i++)
cache.Put(i, "val_" + i);
IDictionary map = GetStoreMap();
Assert.AreEqual(10, map.Count);
for (int i = 0; i < 5; i++)
cache.Remove(i);
Assert.AreEqual(5, map.Count);
for (int i = 5; i < 10; i++)
Assert.AreEqual("val_" + i, map[i]);
}
/// <summary>
/// Tests cache store removal.
/// </summary>
[Test]
public void TestRemoveAll()
{
var cache = GetCache();
for (int i = 0; i < 10; i++)
cache.Put(i, "val_" + i);
IDictionary map = GetStoreMap();
Assert.AreEqual(10, map.Count);
cache.RemoveAll(new List<int> { 0, 1, 2, 3, 4 });
Assert.AreEqual(5, map.Count);
for (int i = 5; i < 10; i++)
Assert.AreEqual("val_" + i, map[i]);
}
/// <summary>
/// Tests cache store with transactions.
/// </summary>
[Test]
public void TestTx()
{
var cache = GetCache();
using (var tx = cache.Ignite.GetTransactions().TxStart())
{
tx.AddMeta("meta", 100);
cache.Put(1, "val");
tx.Commit();
}
IDictionary map = GetStoreMap();
Assert.AreEqual(1, map.Count);
Assert.AreEqual("val", map[1]);
}
/// <summary>
/// Tests multithreaded cache loading.
/// </summary>
[Test]
public void TestLoadCacheMultithreaded()
{
CacheTestStore.LoadMultithreaded = true;
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCache(null, 0, null);
Assert.AreEqual(1000, cache.GetSize());
for (int i = 0; i < 1000; i++)
Assert.AreEqual("val_" + i, cache.Get(i));
}
/// <summary>
/// Tests that cache store property values are propagated from Spring XML.
/// </summary>
[Test]
public void TestCustomStoreProperties()
{
var cache = GetCustomStoreCache();
Assert.IsNotNull(cache);
Assert.AreEqual(42, CacheTestStore.intProperty);
Assert.AreEqual("String value", CacheTestStore.stringProperty);
}
/// <summary>
/// Tests cache store with dynamically started cache.
/// </summary>
[Test]
public void TestDynamicStoreStart()
{
var grid = Ignition.GetIgnite(GridName);
var reg = ((Ignite) grid).HandleRegistry;
var handleCount = reg.Count;
var cache = GetTemplateStoreCache();
Assert.IsNotNull(cache);
cache.Put(1, cache.Name);
Assert.AreEqual(cache.Name, CacheTestStore.Map[1]);
Assert.AreEqual(handleCount + 1, reg.Count);
grid.DestroyCache(cache.Name);
Assert.AreEqual(handleCount, reg.Count);
}
/// <summary>
/// Tests the load all.
/// </summary>
[Test]
public void TestLoadAll([Values(true, false)] bool isAsync)
{
var cache = GetCache();
var loadAll = isAsync
? (Action<IEnumerable<int>, bool>) ((x, y) => { cache.LoadAllAsync(x, y).Wait(); })
: cache.LoadAll;
Assert.AreEqual(0, cache.GetSize());
loadAll(Enumerable.Range(105, 5), false);
Assert.AreEqual(5, cache.GetSize());
for (int i = 105; i < 110; i++)
Assert.AreEqual("val_" + i, cache[i]);
// Test overwrite
cache[105] = "42";
cache.LocalEvict(new[] { 105 });
loadAll(new[] {105}, false);
Assert.AreEqual("42", cache[105]);
loadAll(new[] {105, 106}, true);
Assert.AreEqual("val_105", cache[105]);
Assert.AreEqual("val_106", cache[106]);
}
/// <summary>
/// Tests the argument passing to LoadCache method.
/// </summary>
[Test]
public void TestArgumentPassing()
{
var cache = GetBinaryStoreCache<object, object>();
Action<object> checkValue = o =>
{
cache.Clear();
Assert.AreEqual(0, cache.GetSize());
cache.LoadCache(null, null, 1, o);
Assert.AreEqual(o, cache[1]);
};
// Null.
cache.LoadCache(null, null);
Assert.AreEqual(0, cache.GetSize());
// Empty args array.
cache.LoadCache(null);
Assert.AreEqual(0, cache.GetSize());
// Simple types.
checkValue(1);
checkValue(new[] {1, 2, 3});
checkValue("1");
checkValue(new[] {"1", "2"});
checkValue(Guid.NewGuid());
checkValue(new[] {Guid.NewGuid(), Guid.NewGuid()});
checkValue(DateTime.Now);
checkValue(new[] {DateTime.Now, DateTime.UtcNow});
// Collections.
checkValue(new ArrayList {1, "2", 3.3});
checkValue(new List<int> {1, 2});
checkValue(new Dictionary<int, string> {{1, "foo"}});
}
/// <summary>
/// Get's grid name for this test.
/// </summary>
/// <value>Grid name.</value>
protected virtual string GridName
{
get { return null; }
}
/// <summary>
/// Gets the store map.
/// </summary>
private static IDictionary GetStoreMap()
{
return CacheTestStore.Map;
}
/// <summary>
/// Gets the cache.
/// </summary>
private ICache<int, string> GetCache()
{
return GetBinaryStoreCache<int, string>();
}
/// <summary>
/// Gets the binary store cache.
/// </summary>
private ICache<TK, TV> GetBinaryStoreCache<TK, TV>()
{
return Ignition.GetIgnite(GridName).GetCache<TK, TV>(BinaryStoreCacheName);
}
/// <summary>
/// Gets the object store cache.
/// </summary>
private ICache<TK, TV> GetObjectStoreCache<TK, TV>()
{
return Ignition.GetIgnite(GridName).GetCache<TK, TV>(ObjectStoreCacheName);
}
/// <summary>
/// Gets the custom store cache.
/// </summary>
private ICache<int, string> GetCustomStoreCache()
{
return Ignition.GetIgnite(GridName).GetCache<int, string>(CustomStoreCacheName);
}
/// <summary>
/// Gets the template store cache.
/// </summary>
private ICache<int, string> GetTemplateStoreCache()
{
var cacheName = TemplateStoreCacheName.Replace("*", Guid.NewGuid().ToString());
return Ignition.GetIgnite(GridName).GetOrCreateCache<int, string>(cacheName);
}
/// <summary>
/// Checks the custom store error.
/// </summary>
private static void CheckCustomStoreError(Exception err)
{
var customErr = err as CacheTestStore.CustomStoreException ??
err.InnerException as CacheTestStore.CustomStoreException;
Assert.IsNotNull(customErr);
Assert.AreEqual(customErr.Message, customErr.Details);
}
}
/// <summary>
/// Cache key.
/// </summary>
internal class Key
{
/** */
private readonly int _idx;
/// <summary>
/// Initializes a new instance of the <see cref="Key"/> class.
/// </summary>
public Key(int idx)
{
_idx = idx;
}
/** <inheritdoc /> */
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
return false;
return ((Key)obj)._idx == _idx;
}
/** <inheritdoc /> */
public override int GetHashCode()
{
return _idx;
}
}
/// <summary>
/// Cache value.
/// </summary>
internal class Value
{
/** */
private readonly int _idx;
/// <summary>
/// Initializes a new instance of the <see cref="Value"/> class.
/// </summary>
public Value(int idx)
{
_idx = idx;
}
/// <summary>
/// Gets the index.
/// </summary>
public int Index
{
get { return _idx; }
}
}
/// <summary>
/// Cache entry predicate.
/// </summary>
[Serializable]
public class CacheEntryFilter : ICacheEntryFilter<int, string>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, string> entry)
{
return entry.Key >= 105;
}
}
/// <summary>
/// Cache entry predicate that throws an exception.
/// </summary>
[Serializable]
public class ExceptionalEntryFilter : ICacheEntryFilter<int, string>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, string> entry)
{
throw new Exception("Expected exception in ExceptionalEntryFilter");
}
}
/// <summary>
/// Filter that can't be serialized.
/// </summary>
public class InvalidCacheEntryFilter : CacheEntryFilter
{
// No-op.
}
}
| |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
/// This is the main GVR audio class that communicates with the native code implementation of
/// the audio system. Native functions of the system can only be called through this class to
/// preserve the internal system functionality. Public function calls are *not* thread-safe.
public static class GvrAudio {
/// Audio system rendering quality.
public enum Quality {
Stereo = 0, ///< Stereo-only rendering
Low = 1, ///< Low quality binaural rendering (first-order HRTF)
High = 2 ///< High quality binaural rendering (third-order HRTF)
}
/// Native audio spatializer effect data.
public enum SpatializerData {
Id = 0, /// ID.
Type = 1, /// Spatializer type.
NumChannels = 2, /// Number of input channels.
ChannelSet = 3, /// Soundfield channel set.
Gain = 4, /// Gain.
DistanceAttenuation = 5, /// Computed distance attenuation.
MinDistance = 6, /// Minimum distance for distance-based attenuation.
ZeroOutput = 7, /// Should zero out the output buffer?
}
/// Native audio spatializer type.
public enum SpatializerType {
Source = 0, /// 3D sound object.
Soundfield = 1 /// First-order ambisonic soundfield.
}
/// System sampling rate.
public static int SampleRate {
get { return sampleRate; }
}
private static int sampleRate = -1;
/// System number of output channels.
public static int NumChannels {
get { return numChannels; }
}
private static int numChannels = -1;
/// System number of frames per buffer.
public static int FramesPerBuffer {
get { return framesPerBuffer; }
}
private static int framesPerBuffer = -1;
/// Initializes the audio system with the current audio configuration.
/// @note This should only be called from the main Unity thread.
public static void Initialize (GvrAudioListener listener, Quality quality) {
if (!initialized) {
// Initialize the audio system.
AudioConfiguration config = AudioSettings.GetConfiguration();
sampleRate = config.sampleRate;
numChannels = (int)config.speakerMode;
framesPerBuffer = config.dspBufferSize;
if (numChannels != (int)AudioSpeakerMode.Stereo) {
Debug.LogError("Only 'Stereo' speaker mode is supported by GVR Audio.");
return;
}
Initialize(quality, sampleRate, numChannels, framesPerBuffer);
listenerTransform = listener.transform;
initialized = true;
} else if (listener.transform != listenerTransform) {
Debug.LogError("Only one GvrAudioListener component is allowed in the scene.");
GvrAudioListener.Destroy(listener);
}
}
/// Shuts down the audio system.
/// @note This should only be called from the main Unity thread.
public static void Shutdown (GvrAudioListener listener) {
if (initialized && listener.transform == listenerTransform) {
initialized = false;
Shutdown();
sampleRate = -1;
numChannels = -1;
framesPerBuffer = -1;
listenerTransform = null;
}
}
/// Updates the audio listener.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioListener (float globalGainDb, LayerMask occlusionMask) {
if (initialized) {
occlusionMaskValue = occlusionMask.value;
SetListenerGain(ConvertAmplitudeFromDb(globalGainDb));
}
}
/// Creates a new first-order ambisonic soundfield with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioSoundfield () {
int soundfieldId = -1;
if (initialized) {
soundfieldId = CreateSoundfield(numFoaChannels);
}
return soundfieldId;
}
/// Updates the |soundfield| with given |id| and its properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioSoundfield (int id, GvrAudioSoundfield soundfield) {
if (initialized) {
SetSourceBypassRoomEffects(id, soundfield.bypassRoomEffects);
}
}
/// Creates a new audio source with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioSource (bool hrtfEnabled) {
int sourceId = -1;
if (initialized) {
sourceId = CreateSoundObject(hrtfEnabled);
}
return sourceId;
}
/// Destroys the audio source with given |id|.
/// @note This should only be called from the main Unity thread.
public static void DestroyAudioSource (int id) {
if (initialized) {
DestroySource(id);
}
}
/// Updates the audio |source| with given |id| and its properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioSource (int id, GvrAudioSource source, float currentOcclusion) {
if (initialized) {
SetSourceBypassRoomEffects(id, source.bypassRoomEffects);
SetSourceDirectivity(id, source.directivityAlpha, source.directivitySharpness);
SetSourceListenerDirectivity(id, source.listenerDirectivityAlpha,
source.listenerDirectivitySharpness);
SetSourceOcclusionIntensity(id, currentOcclusion);
}
}
/// Updates the room effects of the environment with given |room| properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioRoom(GvrAudioRoom room, bool roomEnabled) {
// Update the enabled rooms list.
if (roomEnabled) {
if (!enabledRooms.Contains(room)) {
enabledRooms.Add(room);
}
} else {
enabledRooms.Remove(room);
}
// Update the current room effects to be applied.
if(initialized) {
if (enabledRooms.Count > 0) {
GvrAudioRoom currentRoom = enabledRooms[enabledRooms.Count - 1];
RoomProperties roomProperties = GetRoomProperties(currentRoom);
// Pass the room properties into a pointer.
IntPtr roomPropertiesPtr = Marshal.AllocHGlobal(Marshal.SizeOf(roomProperties));
Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, false);
SetRoomProperties(roomPropertiesPtr);
Marshal.FreeHGlobal(roomPropertiesPtr);
} else {
// Set the room properties to null, which will effectively disable the room effects.
SetRoomProperties(IntPtr.Zero);
}
}
}
/// Computes the occlusion intensity of a given |source| using point source detection.
/// @note This should only be called from the main Unity thread.
public static float ComputeOcclusion (Transform sourceTransform) {
float occlusion = 0.0f;
if (initialized) {
Vector3 listenerPosition = listenerTransform.position;
Vector3 sourceFromListener = sourceTransform.position - listenerPosition;
RaycastHit[] hits = Physics.RaycastAll(listenerPosition, sourceFromListener,
sourceFromListener.magnitude, occlusionMaskValue);
foreach (RaycastHit hit in hits) {
if (hit.transform != listenerTransform && hit.transform != sourceTransform) {
occlusion += 1.0f;
}
}
}
return occlusion;
}
/// Converts given |db| value to its amplitude equivalent where 'dB = 20 * log10(amplitude)'.
public static float ConvertAmplitudeFromDb (float db) {
return Mathf.Pow(10.0f, 0.05f * db);
}
/// Generates a set of points to draw a 2D polar pattern.
public static Vector2[] Generate2dPolarPattern (float alpha, float order, int resolution) {
Vector2[] points = new Vector2[resolution];
float interval = 2.0f * Mathf.PI / resolution;
for (int i = 0; i < resolution; ++i) {
float theta = i * interval;
// Magnitude |r| for |theta| in radians.
float r = Mathf.Pow(Mathf.Abs((1 - alpha) + alpha * Mathf.Cos(theta)), order);
points[i] = new Vector2(r * Mathf.Sin(theta), r * Mathf.Cos(theta));
}
return points;
}
/// Returns whether the listener is currently inside the given |room| boundaries.
public static bool IsListenerInsideRoom(GvrAudioRoom room) {
bool isInside = false;
if(initialized) {
Vector3 relativePosition = listenerTransform.position - room.transform.position;
Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation);
bounds.size = Vector3.Scale(room.transform.lossyScale, room.size);
isInside = bounds.Contains(rotationInverse * relativePosition);
}
return isInside;
}
/// Listener directivity GUI color.
public static readonly Color listenerDirectivityColor = 0.65f * Color.magenta;
/// Source directivity GUI color.
public static readonly Color sourceDirectivityColor = 0.65f * Color.blue;
/// Minimum distance threshold between |minDistance| and |maxDistance|.
public const float distanceEpsilon = 0.01f;
/// Max distance limit that can be set for volume rolloff.
public const float maxDistanceLimit = 1000000.0f;
/// Min distance limit that can be set for volume rolloff.
public const float minDistanceLimit = 990099.0f;
/// Maximum allowed gain value in decibels.
public const float maxGainDb = 24.0f;
/// Minimum allowed gain value in decibels.
public const float minGainDb = -24.0f;
/// Maximum allowed reverb brightness modifier value.
public const float maxReverbBrightness = 1.0f;
/// Minimum allowed reverb brightness modifier value.
public const float minReverbBrightness = -1.0f;
/// Maximum allowed reverb time modifier value.
public const float maxReverbTime = 3.0f;
/// Maximum allowed reflectivity multiplier of a room surface material.
public const float maxReflectivity = 2.0f;
/// Source occlusion detection rate in seconds.
public const float occlusionDetectionInterval = 0.2f;
// Number of first-order ambisonic input channels.
public const int numFoaChannels = 4;
[StructLayout(LayoutKind.Sequential)]
private struct RoomProperties {
// Center position of the room in world space.
public float positionX;
public float positionY;
public float positionZ;
// Rotation (quaternion) of the room in world space.
public float rotationX;
public float rotationY;
public float rotationZ;
public float rotationW;
// Size of the shoebox room in world space.
public float dimensionsX;
public float dimensionsY;
public float dimensionsZ;
// Material name of each surface of the shoebox room.
public GvrAudioRoom.SurfaceMaterial materialLeft;
public GvrAudioRoom.SurfaceMaterial materialRight;
public GvrAudioRoom.SurfaceMaterial materialBottom;
public GvrAudioRoom.SurfaceMaterial materialTop;
public GvrAudioRoom.SurfaceMaterial materialFront;
public GvrAudioRoom.SurfaceMaterial materialBack;
// User defined uniform scaling factor for reflectivity. This parameter has no effect when set
// to 1.0f.
public float reflectionScalar;
// User defined reverb tail gain multiplier. This parameter has no effect when set to 0.0f.
public float reverbGain;
// Parameter which allows the reverberation time across all frequency bands to be increased or
// decreased. This parameter has no effect when set to 1.0f.
public float reverbTime;
// Parameter which allows the ratio of high frequncy reverb components to low frequency reverb
// components to be adjusted. This parameter has no effect when set to 0.0f.
public float reverbBrightness;
};
// Converts given |position| and |rotation| from Unity space to audio space.
private static void ConvertAudioTransformFromUnity (ref Vector3 position,
ref Quaternion rotation) {
pose.SetRightHanded(Matrix4x4.TRS(position, rotation, Vector3.one));
position = pose.Position;
rotation = pose.Orientation;
}
// Returns room properties of the given |room|.
private static RoomProperties GetRoomProperties(GvrAudioRoom room) {
RoomProperties roomProperties;
Vector3 position = room.transform.position;
Quaternion rotation = room.transform.rotation;
Vector3 scale = Vector3.Scale(room.transform.lossyScale, room.size);
ConvertAudioTransformFromUnity(ref position, ref rotation);
roomProperties.positionX = position.x;
roomProperties.positionY = position.y;
roomProperties.positionZ = position.z;
roomProperties.rotationX = rotation.x;
roomProperties.rotationY = rotation.y;
roomProperties.rotationZ = rotation.z;
roomProperties.rotationW = rotation.w;
roomProperties.dimensionsX = scale.x;
roomProperties.dimensionsY = scale.y;
roomProperties.dimensionsZ = scale.z;
roomProperties.materialLeft = room.leftWall;
roomProperties.materialRight = room.rightWall;
roomProperties.materialBottom = room.floor;
roomProperties.materialTop = room.ceiling;
roomProperties.materialFront = room.frontWall;
roomProperties.materialBack = room.backWall;
roomProperties.reverbGain = ConvertAmplitudeFromDb(room.reverbGainDb);
roomProperties.reverbTime = room.reverbTime;
roomProperties.reverbBrightness = room.reverbBrightness;
roomProperties.reflectionScalar = room.reflectivity;
return roomProperties;
}
// Boundaries instance to be used in room detection logic.
private static Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
// Container to store the currently active rooms in the scene.
private static List<GvrAudioRoom> enabledRooms = new List<GvrAudioRoom>();
// Denotes whether the system is initialized properly.
private static bool initialized = false;
// Listener transform.
private static Transform listenerTransform = null;
// Occlusion layer mask.
private static int occlusionMaskValue = -1;
// 3D pose instance to be used in transform space conversion.
private static MutablePose3D pose = new MutablePose3D();
#if UNITY_IOS
private const string pluginName = "__Internal";
#else
private const string pluginName = "audioplugingvrunity";
#endif
// Listener handlers.
[DllImport(pluginName)]
private static extern void SetListenerGain (float gain);
// Soundfield handlers.
[DllImport(pluginName)]
private static extern int CreateSoundfield (int numChannels);
// Source handlers.
[DllImport(pluginName)]
private static extern int CreateSoundObject (bool enableHrtf);
[DllImport(pluginName)]
private static extern void DestroySource (int sourceId);
[DllImport(pluginName)]
private static extern void SetSourceBypassRoomEffects (int sourceId, bool bypassRoomEffects);
[DllImport(pluginName)]
private static extern void SetSourceDirectivity (int sourceId, float alpha, float order);
[DllImport(pluginName)]
private static extern void SetSourceListenerDirectivity (int sourceId, float alpha, float order);
[DllImport(pluginName)]
private static extern void SetSourceOcclusionIntensity (int sourceId, float intensity);
// Room handlers.
[DllImport(pluginName)]
private static extern void SetRoomProperties (IntPtr roomProperties);
// System handlers.
[DllImport(pluginName)]
private static extern void Initialize (Quality quality, int sampleRate, int numChannels,
int framesPerBuffer);
[DllImport(pluginName)]
private static extern void Shutdown ();
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Runtime.CompilerServices
{
#region ConditionalWeakTable
public sealed class ConditionalWeakTable<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
where TKey : class
where TValue : class
{
#region Constructors
public ConditionalWeakTable()
{
_container = new Container(this);
_lock = new Lock();
}
#endregion
#region Public Members
//--------------------------------------------------------------------------------------------
// key: key of the value to find. Cannot be null.
// value: if the key is found, contains the value associated with the key upon method return.
// if the key is not found, contains default(TValue).
//
// Method returns "true" if key was found, "false" otherwise.
//
// Note: The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue
// may at its discretion, return "false" and set "value" to the default (as if the key was not present.)
//--------------------------------------------------------------------------------------------
public bool TryGetValue(TKey key, out TValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _container.TryGetValueWorker(key, out value);
}
//--------------------------------------------------------------------------------------------
// key: key to add. May not be null.
// value: value to associate with key.
//
// If the key is already entered into the dictionary, this method throws an exception.
//
// Note: The key may get garbage collected during the Add() operation. If so, Add()
// has the right to consider any prior entries successfully removed and add a new entry without
// throwing an exception.
//--------------------------------------------------------------------------------------------
public void Add(TKey key, TValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
using (LockHolder.Hold(_lock))
{
object otherValue;
int entryIndex = _container.FindEntry(key, out otherValue);
if (entryIndex != -1)
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key));
}
CreateEntry(key, value);
}
}
//--------------------------------------------------------------------------------------------
// key: key to add or update. May not be null.
// value: value to associate with key.
//
// If the key is already entered into the dictionary, this method will update the value associated with key.
//--------------------------------------------------------------------------------------------
public void AddOrUpdate(TKey key, TValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
using (LockHolder.Hold(_lock))
{
object otherValue;
int entryIndex = _container.FindEntry(key, out otherValue);
// if we found a key we should just update, if no we should create a new entry.
if (entryIndex != -1)
{
_container.UpdateValue(entryIndex, value);
}
else
{
CreateEntry(key, value);
}
}
}
//--------------------------------------------------------------------------------------------
// key: key to remove. May not be null.
//
// Returns true if the key is found and removed. Returns false if the key was not in the dictionary.
//
// Note: The key may get garbage collected during the Remove() operation. If so,
// Remove() will not fail or throw, however, the return value can be either true or false
// depending on who wins the race.
//--------------------------------------------------------------------------------------------
public bool Remove(TKey key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
using (LockHolder.Hold(_lock))
{
return _container.Remove(key);
}
}
//--------------------------------------------------------------------------------------------
// Clear all the key/value pairs
//--------------------------------------------------------------------------------------------
public void Clear()
{
using (LockHolder.Hold(_lock))
{
// To clear, we would prefer to simply drop the existing container
// and replace it with an empty one, as that's overall more efficient.
// However, if there are any active enumerators, we don't want to do
// that as it will end up removing all of the existing entries and
// allowing new items to be added at the same indices when the container
// is filled and replaced, and one of the guarantees we try to make with
// enumeration is that new items added after enumeration starts won't be
// included in the enumeration. As such, if there are active enumerators,
// we simply use the container's removal functionality to remove all of the
// keys; then when the table is resized, if there are still active enumerators,
// these empty slots will be maintained.
if (_activeEnumeratorRefCount > 0)
{
_container.RemoveAllKeys();
}
else
{
_container = new Container(this);
}
}
}
//--------------------------------------------------------------------------------------------
// key: key of the value to find. Cannot be null.
// createValueCallback: callback that creates value for key. Cannot be null.
//
// Atomically tests if key exists in table. If so, returns corresponding value. If not,
// invokes createValueCallback() passing it the key. The returned value is bound to the key in the table
// and returned as the result of GetValue().
//
// If multiple threads race to initialize the same key, the table may invoke createValueCallback
// multiple times with the same key. Exactly one of these calls will "win the race" and the returned
// value of that call will be the one added to the table and returned by all the racing GetValue() calls.
//
// This rule permits the table to invoke createValueCallback outside the internal table lock
// to prevent deadlocks.
//--------------------------------------------------------------------------------------------
public TValue GetValue(TKey key, CreateValueCallback createValueCallback)
{
// Our call to TryGetValue() validates key so no need for us to.
//
// if (key == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
// }
if (createValueCallback == null)
{
throw new ArgumentNullException(nameof(createValueCallback));
}
TValue existingValue;
if (TryGetValue(key, out existingValue))
{
return existingValue;
}
return GetValueLocked(key, createValueCallback);
}
private TValue GetValueLocked(TKey key, CreateValueCallback createValueCallback)
{
// If we got here, the key was not in the table. Invoke the callback (outside the lock)
// to generate the new value for the key.
TValue newValue = createValueCallback(key);
using (LockHolder.Hold(_lock))
{
// Now that we've taken the lock, must recheck in case we lost a race to add the key.
TValue existingValue;
if (_container.TryGetValueWorker(key, out existingValue))
{
return existingValue;
}
else
{
// Verified in-lock that we won the race to add the key. Add it now.
CreateEntry(key, newValue);
return newValue;
}
}
}
//--------------------------------------------------------------------------------------------
// key: key of the value to find. Cannot be null.
//
// Helper method to call GetValue without passing a creation delegate. Uses Activator.CreateInstance
// to create new instances as needed. If TValue does not have a default constructor, this will
// throw.
//--------------------------------------------------------------------------------------------
public TValue GetOrCreateValue(TKey key)
{
return GetValue(key, k => Activator.CreateInstance<TValue>());
}
public delegate TValue CreateValueCallback(TKey key);
//--------------------------------------------------------------------------------------------
// Gets an enumerator for the table. The returned enumerator will not extend the lifetime of
// any object pairs in the table, other than the one that's Current. It will not return entries
// that have already been collected, nor will it return entries added after the enumerator was
// retrieved. It may not return all entries that were present when the enumerat was retrieved,
// however, such as not returning entries that were collected or removed after the enumerator
// was retrieved but before they were enumerated.
//--------------------------------------------------------------------------------------------
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
using (LockHolder.Hold(_lock))
{
Container c = _container;
return c == null || c.FirstFreeEntry == 0 ?
((IEnumerable<KeyValuePair<TKey, TValue>>)Array.Empty<KeyValuePair<TKey, TValue>>()).GetEnumerator() :
new Enumerator(this);
}
}
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<KeyValuePair<TKey, TValue>>)this).GetEnumerator();
/// <summary>Provides an enumerator for the table.</summary>
private sealed class Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
// The enumerator would ideally hold a reference to the Container and the end index within that
// container. However, the safety of the CWT depends on the only reference to the Container being
// from the CWT itself; the Container then employs a two-phase finalization scheme, where the first
// phase nulls out that parent CWT's reference, guaranteeing that the second time it's finalized there
// can be no other existing references to it in use that would allow for concurrent usage of the
// native handles with finalization. We would break that if we allowed this Enumerator to hold a
// reference to the Container. Instead, the Enumerator holds a reference to the CWT rather than to
// the Container, and it maintains the CWT._activeEnumeratorRefCount field to track whether there
// are outstanding enumerators that have yet to be disposed/finalized. If there aren't any, the CWT
// behaves as it normally does. If there are, certain operations are affected, in particular resizes.
// Normally when the CWT is resized, it enumerates the contents of the table looking for indices that
// contain entries which have been collected or removed, and it frees those up, effectively moving
// down all subsequent entries in the container (not in the existing container, but in a replacement).
// This, however, would cause the enumerator's understanding of indices to break. So, as long as
// there is any outstanding enumerator, no compaction is performed.
private ConditionalWeakTable<TKey, TValue> _table; // parent table, set to null when disposed
private readonly int _maxIndexInclusive; // last index in the container that should be enumerated
private int _currentIndex = -1; // the current index into the container
private KeyValuePair<TKey, TValue> _current; // the current entry set by MoveNext and returned from Current
public Enumerator(ConditionalWeakTable<TKey, TValue> table)
{
Debug.Assert(table != null, "Must provide a valid table");
Debug.Assert(table._lock.IsAcquired, "Must hold the _lock lock to construct the enumerator");
Debug.Assert(table._container != null, "Should not be used on a finalized table");
Debug.Assert(table._container.FirstFreeEntry > 0, "Should have returned an empty enumerator instead");
// Store a reference to the parent table and increase its active enumerator count.
_table = table;
Debug.Assert(table._activeEnumeratorRefCount >= 0, "Should never have a negative ref count before incrementing");
table._activeEnumeratorRefCount++;
// Store the max index to be enumerated.
_maxIndexInclusive = table._container.FirstFreeEntry - 1;
_currentIndex = -1;
}
~Enumerator() { Dispose(); }
public void Dispose()
{
// Use an interlocked operation to ensure that only one thread can get access to
// the _table for disposal and thus only decrement the ref count once.
ConditionalWeakTable<TKey, TValue> table = Interlocked.Exchange(ref _table, null);
if (table != null)
{
// Ensure we don't keep the last current alive unnecessarily
_current = default(KeyValuePair<TKey, TValue>);
// Decrement the ref count that was incremented when constructed
using (LockHolder.Hold(table._lock))
{
table._activeEnumeratorRefCount--;
Debug.Assert(table._activeEnumeratorRefCount >= 0, "Should never have a negative ref count after decrementing");
}
// Finalization is purely to decrement the ref count. We can suppress it now.
GC.SuppressFinalize(this);
}
}
public bool MoveNext()
{
// Start by getting the current table. If it's already been disposed, it will be null.
ConditionalWeakTable<TKey, TValue> table = _table;
if (table != null)
{
// Once have the table, we need to lock to synchronize with other operations on
// the table, like adding.
using (LockHolder.Hold(table._lock))
{
// From the table, we have to get the current container. This could have changed
// since we grabbed the enumerator, but the index-to-pair mapping should not have
// due to there being at least one active enumerator. If the table (or rather its
// container at the time) has already been finalized, this will be null.
Container c = table._container;
if (c != null)
{
// We have the container. Find the next entry to return, if there is one.
// We need to loop as we may try to get an entry that's already been removed
// or collected, in which case we try again.
while (_currentIndex < _maxIndexInclusive)
{
_currentIndex++;
TKey key;
TValue value;
if (c.TryGetEntry(_currentIndex, out key, out value))
{
_current = new KeyValuePair<TKey, TValue>(key, value);
return true;
}
}
}
}
}
// Nothing more to enumerate.
return false;
}
public KeyValuePair<TKey, TValue> Current
{
get
{
if (_currentIndex < 0)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _current;
}
}
object IEnumerator.Current => Current;
public void Reset() { }
}
#endregion
#region internal members
//--------------------------------------------------------------------------------------------
// Find a key that equals (value equality) with the given key - don't use in perf critical path
// Note that it calls out to Object.Equals which may calls the override version of Equals
// and that may take locks and leads to deadlock
// Currently it is only used by WinRT event code and you should only use this function
// if you know for sure that either you won't run into dead locks or you need to live with the
// possiblity
//--------------------------------------------------------------------------------------------
internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value)
{
using (LockHolder.Hold(_lock))
{
return _container.FindEquivalentKeyUnsafe(key, out value);
}
}
//--------------------------------------------------------------------------------------------
// Returns a collection of keys - don't use in perf critical path
//--------------------------------------------------------------------------------------------
internal ICollection<TKey> Keys
{
get
{
using (LockHolder.Hold(_lock))
{
return _container.Keys;
}
}
}
//--------------------------------------------------------------------------------------------
// Returns a collection of values - don't use in perf critical path
//--------------------------------------------------------------------------------------------
internal ICollection<TValue> Values
{
get
{
using (LockHolder.Hold(_lock))
{
return _container.Values;
}
}
}
#endregion
#region Private Members
//----------------------------------------------------------------------------------------
// Worker for adding a new key/value pair.
// Will resize the container if it is full
//
// Preconditions:
// Must hold _lock.
// Key already validated as non-null and not already in table.
//----------------------------------------------------------------------------------------
private void CreateEntry(TKey key, TValue value)
{
Debug.Assert(_lock.IsAcquired);
Container c = _container;
if (!c.HasCapacity)
{
c = _container = c.Resize();
}
c.CreateEntryNoResize(key, value);
}
private static bool IsPowerOfTwo(int value)
{
return (value > 0) && ((value & (value - 1)) == 0);
}
#endregion
#region Private Data Members
//--------------------------------------------------------------------------------------------
// Entry can be in one of four states:
//
// - Unused (stored with an index _firstFreeEntry and above)
// depHnd.IsAllocated == false
// hashCode == <dontcare>
// next == <dontcare>)
//
// - Used with live key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry)
// depHnd.IsAllocated == true, depHnd.GetPrimary() != null
// hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue
// next links to next Entry in bucket.
//
// - Used with dead key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry)
// depHnd.IsAllocated == true, depHnd.GetPrimary() == null
// hashCode == <notcare>
// next links to next Entry in bucket.
//
// - Has been removed from the table (by a call to Remove)
// depHnd.IsAllocated == true, depHnd.GetPrimary() == <notcare>
// hashCode == -1
// next links to next Entry in bucket.
//
// The only difference between "used with live key" and "used with dead key" is that
// depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key"
// happens asynchronously as a result of normal garbage collection. The dictionary itself
// receives no notification when this happens.
//
// When the dictionary grows the _entries table, it scours it for expired keys and does not
// add those to the new container.
//--------------------------------------------------------------------------------------------
private struct Entry
{
public DependentHandle depHnd; // Holds key and value using a weak reference for the key and a strong reference
// for the value that is traversed only if the key is reachable without going through the value.
public int hashCode; // Cached copy of key's hashcode
public int next; // Index of next entry, -1 if last
}
//
// Container holds the actual data for the table. A given instance of Container always has the same capacity. When we need
// more capacity, we create a new Container, copy the old one into the new one, and discard the old one. This helps enable lock-free
// reads from the table, as readers never need to deal with motion of entries due to rehashing.
//
private sealed class Container
{
internal Container(ConditionalWeakTable<TKey, TValue> parent)
{
Debug.Assert(parent != null);
Debug.Assert(IsPowerOfTwo(InitialCapacity));
int size = InitialCapacity;
_buckets = new int[size];
for (int i = 0; i < _buckets.Length; i++)
{
_buckets[i] = -1;
}
_entries = new Entry[size];
// Only store the parent after all of the allocations have happened successfully.
// Otherwise, as part of growing or clearing the container, we could end up allocating
// a new Container that fails (OOMs) part way through construction but that gets finalized
// and ends up clearing out some other container present in the associated CWT.
_parent = parent;
}
private Container(ConditionalWeakTable<TKey, TValue> parent, int[] buckets, Entry[] entries, int firstFreeEntry)
{
Debug.Assert(parent != null);
_parent = parent;
_buckets = buckets;
_entries = entries;
_firstFreeEntry = firstFreeEntry;
}
internal bool HasCapacity
{
get
{
return _firstFreeEntry < _entries.Length;
}
}
internal int FirstFreeEntry => _firstFreeEntry;
//----------------------------------------------------------------------------------------
// Worker for adding a new key/value pair.
// Preconditions:
// Container must NOT be full
//----------------------------------------------------------------------------------------
internal void CreateEntryNoResize(TKey key, TValue value)
{
Debug.Assert(HasCapacity);
VerifyIntegrity();
_invalid = true;
int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
int newEntry = _firstFreeEntry++;
_entries[newEntry].hashCode = hashCode;
_entries[newEntry].depHnd = new DependentHandle(key, value);
int bucket = hashCode & (_buckets.Length - 1);
_entries[newEntry].next = _buckets[bucket];
// This write must be volatile, as we may be racing with concurrent readers. If they see
// the new entry, they must also see all of the writes earlier in this method.
Volatile.Write(ref _buckets[bucket], newEntry);
_invalid = false;
}
//----------------------------------------------------------------------------------------
// Worker for finding a key/value pair
//
// Preconditions:
// Must hold _lock.
// Key already validated as non-null
//----------------------------------------------------------------------------------------
internal bool TryGetValueWorker(TKey key, out TValue value)
{
object secondary;
int entryIndex = FindEntry(key, out secondary);
value = Unsafe.As<TValue>(secondary);
return (entryIndex != -1);
}
//----------------------------------------------------------------------------------------
// Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.")
//
// Preconditions:
// Must hold _lock, or be prepared to retry the search while holding _lock.
// Key already validated as non-null.
//----------------------------------------------------------------------------------------
internal int FindEntry(TKey key, out object value)
{
int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
int bucket = hashCode & (_buckets.Length - 1);
for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
{
if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out value) == key)
{
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
return entriesIndex;
}
}
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
value = null;
return -1;
}
//----------------------------------------------------------------------------------------
// Gets the entry at the specified entry index.
//----------------------------------------------------------------------------------------
internal bool TryGetEntry(int index, out TKey key, out TValue value)
{
if (index < _entries.Length)
{
object oValue;
object oKey = _entries[index].depHnd.GetPrimaryAndSecondary(out oValue);
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
if (oKey != null)
{
key = Unsafe.As<TKey>(oKey);
value = Unsafe.As<TValue>(oValue);
return true;
}
}
key = default(TKey);
value = default(TValue);
return false;
}
//----------------------------------------------------------------------------------------
// Removes all of the keys in the table.
//----------------------------------------------------------------------------------------
internal void RemoveAllKeys()
{
for (int i = 0; i < _firstFreeEntry; i++)
{
RemoveIndex(i);
}
}
//----------------------------------------------------------------------------------------
// Removes the specified key from the table, if it exists.
//----------------------------------------------------------------------------------------
internal bool Remove(TKey key)
{
VerifyIntegrity();
object value;
int entryIndex = FindEntry(key, out value);
if (entryIndex != -1)
{
RemoveIndex(entryIndex);
return true;
}
return false;
}
private void RemoveIndex(int entryIndex)
{
Debug.Assert(entryIndex >= 0 && entryIndex < _firstFreeEntry);
ref Entry entry = ref _entries[entryIndex];
//
// We do not free the handle here, as we may be racing with readers who already saw the hash code.
// Instead, we simply overwrite the entry's hash code, so subsequent reads will ignore it.
// The handle will be free'd in Container's finalizer, after the table is resized or discarded.
//
Volatile.Write(ref entry.hashCode, -1);
// Also, clear the key to allow GC to collect objects pointed to by the entry
entry.depHnd.SetPrimary(null);
}
internal void UpdateValue(int entryIndex, TValue newValue)
{
Debug.Assert(entryIndex != -1);
VerifyIntegrity();
_invalid = true;
_entries[entryIndex].depHnd.SetSecondary(newValue);
_invalid = false;
}
//----------------------------------------------------------------------------------------
// This does two things: resize and scrub expired keys off bucket lists.
//
// Precondition:
// Must hold _lock.
//
// Postcondition:
// _firstEntry is less than _entries.Length on exit, that is, the table has at least one free entry.
//----------------------------------------------------------------------------------------
internal Container Resize()
{
Debug.Assert(!HasCapacity);
bool hasExpiredEntries = false;
int newSize = _buckets.Length;
if (_parent == null || _parent._activeEnumeratorRefCount == 0)
{
// If any expired or removed keys exist, we won't resize.
// If there any active enumerators, though, we don't want
// to compact and thus have no expired entries.
for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
{
ref Entry entry = ref _entries[entriesIndex];
if (entry.hashCode == -1)
{
// the entry was removed
hasExpiredEntries = true;
break;
}
if (entry.depHnd.IsAllocated && entry.depHnd.GetPrimary() == null)
{
// the entry has expired
hasExpiredEntries = true;
break;
}
}
}
if (!hasExpiredEntries)
{
// Not necessary to check for overflow here, the attempt to allocate new arrays will throw
newSize = _buckets.Length * 2;
}
return Resize(newSize);
}
internal Container Resize(int newSize)
{
Debug.Assert(newSize >= _buckets.Length);
Debug.Assert(IsPowerOfTwo(newSize));
// Reallocate both buckets and entries and rebuild the bucket and entries from scratch.
// This serves both to scrub entries with expired keys and to put the new entries in the proper bucket.
int[] newBuckets = new int[newSize];
for (int bucketIndex = 0; bucketIndex < newBuckets.Length; bucketIndex++)
{
newBuckets[bucketIndex] = -1;
}
Entry[] newEntries = new Entry[newSize];
int newEntriesIndex = 0;
bool activeEnumerators = _parent != null && _parent._activeEnumeratorRefCount > 0;
// Migrate existing entries to the new table.
if (activeEnumerators)
{
// There's at least one active enumerator, which means we don't want to
// remove any expired/removed entries, in order to not affect existing
// entries indices. Copy over the entries while rebuilding the buckets list,
// as the buckets are dependent on the buckets list length, which is changing.
for (; newEntriesIndex < _entries.Length; newEntriesIndex++)
{
ref Entry oldEntry = ref _entries[newEntriesIndex];
ref Entry newEntry = ref newEntries[newEntriesIndex];
int hashCode = oldEntry.hashCode;
newEntry.hashCode = hashCode;
newEntry.depHnd = oldEntry.depHnd;
int bucket = hashCode & (newBuckets.Length - 1);
newEntry.next = newBuckets[bucket];
newBuckets[bucket] = newEntriesIndex;
}
}
else
{
// There are no active enumerators, which means we want to compact by
// removing expired/removed entries.
for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
{
ref Entry oldEntry = ref _entries[entriesIndex];
int hashCode = oldEntry.hashCode;
DependentHandle depHnd = oldEntry.depHnd;
if (hashCode != -1 && depHnd.IsAllocated)
{
if (depHnd.GetPrimary() != null)
{
ref Entry newEntry = ref newEntries[newEntriesIndex];
// Entry is used and has not expired. Link it into the appropriate bucket list.
newEntry.hashCode = hashCode;
newEntry.depHnd = depHnd;
int bucket = hashCode & (newBuckets.Length - 1);
newEntry.next = newBuckets[bucket];
newBuckets[bucket] = newEntriesIndex;
newEntriesIndex++;
}
else
{
// Pretend the item was removed, so that this container's finalizer
// will clean up this dependent handle.
Volatile.Write(ref oldEntry.hashCode, -1);
}
}
}
}
// Create the new container. We want to transfer the responsibility of freeing the handles from
// the old container to the new container, and also ensure that the new container isn't finalized
// while the old container may still be in use. As such, we store a reference from the old container
// to the new one, which will keep the new container alive as long as the old one is.
var newContainer = new Container(_parent, newBuckets, newEntries, newEntriesIndex);
if (activeEnumerators)
{
// If there are active enumerators, both the old container and the new container may be storing
// the same entries with -1 hash codes, which the finalizer will clean up even if the container
// is not the active container for the table. To prevent that, we want to stop the old container
// from being finalized, as it no longer has any responsibility for any cleanup.
GC.SuppressFinalize(this);
}
_oldKeepAlive = newContainer; // once this is set, the old container's finalizer will not free transferred dependent handles
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
return newContainer;
}
internal ICollection<TKey> Keys
{
get
{
LowLevelListWithIList<TKey> list = new LowLevelListWithIList<TKey>();
for (int bucket = 0; bucket < _buckets.Length; ++bucket)
{
for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
{
TKey thisKey = Unsafe.As<TKey>(_entries[entriesIndex].depHnd.GetPrimary());
if (thisKey != null)
{
list.Add(thisKey);
}
}
}
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
return list;
}
}
internal ICollection<TValue> Values
{
get
{
LowLevelListWithIList<TValue> list = new LowLevelListWithIList<TValue>();
for (int bucket = 0; bucket < _buckets.Length; ++bucket)
{
for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
{
Object primary = null;
Object secondary = null;
primary = _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out secondary);
// Now that we've secured a strong reference to the secondary, must check the primary again
// to ensure it didn't expire (otherwise, we open a race where TryGetValue misreports an
// expired key as a live key with a null value.)
if (primary != null)
{
list.Add(Unsafe.As<TValue>(secondary));
}
}
}
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
return list;
}
}
internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value)
{
for (int bucket = 0; bucket < _buckets.Length; ++bucket)
{
for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
{
if (_entries[entriesIndex].hashCode == -1)
{
continue; // removed entry whose handle is awaiting condemnation by the finalizer.
}
object thisKey, thisValue;
thisKey = _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisValue);
if (Object.Equals(thisKey, key))
{
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
value = Unsafe.As<TValue>(thisValue);
return Unsafe.As<TKey>(thisKey);
}
}
}
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
value = default(TValue);
return null;
}
//----------------------------------------------------------------------------------------
// Precondition:
// Must hold _lock.
//----------------------------------------------------------------------------------------
private void VerifyIntegrity()
{
if (_invalid)
{
throw new InvalidOperationException(SR.CollectionCorrupted);
}
}
//----------------------------------------------------------------------------------------
// Finalizer.
//----------------------------------------------------------------------------------------
~Container()
{
// We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD,
// don't bother.
//
// (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.)
if (Environment.HasShutdownStarted)
{
return;
}
//We also skip doing anything if the container is invalid, including if someone
// the container object was allocated but its associated table never set.
if (_invalid || _parent == null)
{
return;
}
// It's possible that the ConditionalWeakTable could have been resurrected, in which case code could
// be accessing this Container as it's being finalized. We don't support usage after finalization,
// but we also don't want to potentially corrupt state by allowing dependency handles to be used as
// or after they've been freed. To avoid that, if it's at all possible that another thread has a
// reference to this container via the CWT, we remove such a reference and then re-register for
// finalization: the next time around, we can be sure that no references remain to this and we can
// clean up the dependency handles without fear of corruption.
if (!_finalized)
{
_finalized = true;
using (LockHolder.Hold(_parent._lock))
{
if (_parent._container == this)
{
_parent._container = null;
}
}
GC.ReRegisterForFinalize(this); // next time it's finalized, we'll be sure there are no remaining refs
return;
}
Entry[] entries = _entries;
_invalid = true;
_entries = null;
_buckets = null;
if (entries != null)
{
for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++)
{
// We need to free handles in two cases:
// - If this container still owns the dependency handle (meaning ownership hasn't been transferred
// to another container that replaced this one), then it should be freed.
// - If this container had the entry removed, then even if in general ownership was transferred to
// another container, removed entries are not, therefore this container must free them.
if (_oldKeepAlive == null || entries[entriesIndex].hashCode == -1)
{
entries[entriesIndex].depHnd.Free();
}
}
}
}
private readonly ConditionalWeakTable<TKey, TValue> _parent; // the ConditionalWeakTable with which this container is associated
private int[] _buckets; // _buckets[hashcode & (_buckets.Length - 1)] contains index of the first entry in bucket (-1 if empty)
private Entry[] _entries; // the table entries containing the stored dependency handles
private int _firstFreeEntry; // _firstFreeEntry < _entries.Length => table has capacity, entries grow from the bottom of the table.
private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock.
private bool _finalized; // set to true when initially finalized
private volatile object _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd
}
private volatile Container _container;
private readonly Lock _lock; // This lock protects all mutation of data in the table. Readers do not take this lock.
private int _activeEnumeratorRefCount; // The number of outstanding enumerators on the table
private const int InitialCapacity = 8; // Must be a power of two
#endregion
}
#endregion
#region DependentHandle
//=========================================================================================
// This struct collects all operations on native DependentHandles. The DependentHandle
// merely wraps an IntPtr so this struct serves mainly as a "managed typedef."
//
// DependentHandles exist in one of two states:
//
// IsAllocated == false
// No actual handle is allocated underneath. Illegal to call GetPrimary
// or GetPrimaryAndSecondary(). Ok to call Free().
//
// Initializing a DependentHandle using the nullary ctor creates a DependentHandle
// that's in the !IsAllocated state.
// (! Right now, we get this guarantee for free because (IntPtr)0 == NULL unmanaged handle.
// ! If that assertion ever becomes false, we'll have to add an _isAllocated field
// ! to compensate.)
//
//
// IsAllocated == true
// There's a handle allocated underneath. You must call Free() on this eventually
// or you cause a native handle table leak.
//
// This struct intentionally does no self-synchronization. It's up to the caller to
// to use DependentHandles in a thread-safe way.
//=========================================================================================
internal struct DependentHandle
{
#region Constructors
public DependentHandle(Object primary, Object secondary)
{
_handle = RuntimeImports.RhHandleAllocDependent(primary, secondary);
}
#endregion
#region Public Members
public bool IsAllocated
{
get
{
return _handle != (IntPtr)0;
}
}
// Getting the secondary object is more expensive than getting the first so
// we provide a separate primary-only accessor for those times we only want the
// primary.
public Object GetPrimary()
{
return RuntimeImports.RhHandleGet(_handle);
}
public object GetPrimaryAndSecondary(out object secondary)
{
return RuntimeImports.RhHandleGetDependent(_handle, out secondary);
}
public void SetPrimary(object primary)
{
RuntimeImports.RhHandleSet(_handle, primary);
}
public void SetSecondary(object secondary)
{
RuntimeImports.RhHandleSetDependentSecondary(_handle, secondary);
}
//----------------------------------------------------------------------
// Forces dependentHandle back to non-allocated state (if not already there)
// and frees the handle if needed.
//----------------------------------------------------------------------
public void Free()
{
if (_handle != (IntPtr)0)
{
IntPtr handle = _handle;
_handle = (IntPtr)0;
RuntimeImports.RhHandleFree(handle);
}
}
#endregion
#region Private Data Member
private IntPtr _handle;
#endregion
} // struct DependentHandle
#endregion
}
| |
using GitTfs.Commands;
using GitTfs.Core;
using GitTfs.Core.TfsInterop;
using GitTfs.Util;
using StructureMap;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace GitTfs.VsFake
{
public class MockBranchObject : IBranchObject
{
public string Path { get; set; }
public string ParentPath { get; set; }
public bool IsRoot { get; set; }
}
public class TfsHelper : ITfsHelper
{
#region misc/null
private readonly IContainer _container;
private readonly Script _script;
private readonly FakeVersionControlServer _versionControlServer;
public TfsHelper(IContainer container, Script script)
{
_container = container;
_script = script;
_versionControlServer = new FakeVersionControlServer(_script);
}
public string TfsClientLibraryVersion { get { return "(FAKE)"; } }
public string Url { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public void EnsureAuthenticated() { }
public void SetPathResolver() { }
public bool CanShowCheckinDialog { get { return false; } }
public int ShowCheckinDialog(IWorkspace workspace, IPendingChange[] pendingChanges, IEnumerable<IWorkItemCheckedInfo> checkedInfos, string checkinComment)
{
throw new NotImplementedException();
}
public IIdentity GetIdentity(string username)
{
if (username == "vtccds_cp")
return new FakeIdentity { DisplayName = username, MailAddress = "b8d46dada4dd62d2ab98a2bda7310285c42e46f6qvabajY2" };
return new NullIdentity();
}
#endregion
#region read changesets
public ITfsChangeset GetLatestChangeset(IGitTfsRemote remote)
{
return _script.Changesets.LastOrDefault().Try(x => BuildTfsChangeset(x, remote));
}
public int GetLatestChangesetId(IGitTfsRemote remote)
{
return _script.Changesets.LastOrDefault().Id;
}
public IEnumerable<ITfsChangeset> GetChangesets(string path, int startVersion, IGitTfsRemote remote, int lastVersion = -1, bool byLots = false)
{
if (!_script.Changesets.Any(c => c.IsBranchChangeset) && _script.Changesets.Any(c => c.IsMergeChangeset))
return _script.Changesets.Where(x => x.Id >= startVersion).Select(x => BuildTfsChangeset(x, remote));
var branchPath = path + "/";
return _script.Changesets
.Where(x => x.Id >= startVersion && x.Changes.Any(c => c.RepositoryPath.IndexOf(branchPath, StringComparison.CurrentCultureIgnoreCase) == 0 || branchPath.IndexOf(c.RepositoryPath, StringComparison.CurrentCultureIgnoreCase) == 0))
.Select(x => BuildTfsChangeset(x, remote));
}
public int FindMergeChangesetParent(string path, int firstChangeset, GitTfsRemote remote)
{
var firstChangesetOfBranch = _script.Changesets.FirstOrDefault(c => c.IsMergeChangeset && c.MergeChangesetDatas.MergeIntoBranch == path && c.MergeChangesetDatas.BeforeMergeChangesetId < firstChangeset);
if (firstChangesetOfBranch != null)
return firstChangesetOfBranch.MergeChangesetDatas.BeforeMergeChangesetId;
return -1;
}
private ITfsChangeset BuildTfsChangeset(ScriptedChangeset changeset, IGitTfsRemote remote)
{
var tfsChangeset = _container.With<ITfsHelper>(this).With<IChangeset>(new Changeset(_versionControlServer, changeset)).GetInstance<TfsChangeset>();
tfsChangeset.Summary = new TfsChangesetInfo { ChangesetId = changeset.Id, Remote = remote };
return tfsChangeset;
}
private class Changeset : IChangeset
{
private readonly IVersionControlServer _versionControlServer;
private readonly ScriptedChangeset _changeset;
public Changeset(IVersionControlServer versionControlServer, ScriptedChangeset changeset)
{
_versionControlServer = versionControlServer;
_changeset = changeset;
}
public IChange[] Changes
{
get { return _changeset.Changes.Select(x => new Change(_versionControlServer, _changeset, x)).ToArray(); }
}
public string Committer
{
get { return _changeset.Committer ?? "todo"; }
}
public DateTime CreationDate
{
get { return _changeset.CheckinDate; }
}
public string Comment
{
get { return _changeset.Comment.Replace("\n", "\r\n"); }
}
public int ChangesetId
{
get { return _changeset.Id; }
}
public IVersionControlServer VersionControlServer
{
get { throw new NotImplementedException(); }
}
public void Get(ITfsWorkspace workspace, IEnumerable<IChange> changes, Action<Exception> ignorableErrorHandler)
{
workspace.Get(ChangesetId, changes);
}
}
private class Change : IChange, IItem
{
private readonly IVersionControlServer _versionControlServer;
private readonly ScriptedChangeset _changeset;
private readonly ScriptedChange _change;
public Change(IVersionControlServer versionControlServer, ScriptedChangeset changeset, ScriptedChange change)
{
_versionControlServer = versionControlServer;
_changeset = changeset;
_change = change;
}
TfsChangeType IChange.ChangeType
{
get { return _change.ChangeType; }
}
IItem IChange.Item
{
get { return this; }
}
IVersionControlServer IItem.VersionControlServer
{
get { return _versionControlServer; }
}
int IItem.ChangesetId
{
get { return _changeset.Id; }
}
string IItem.ServerItem
{
get { return _change.RepositoryPath; }
}
int IItem.DeletionId
{
get { return 0; }
}
TfsItemType IItem.ItemType
{
get { return _change.ItemType; }
}
int IItem.ItemId
{
get { return _change.ItemId.Value; }
}
long IItem.ContentLength
{
get
{
using (var temp = ((IItem)this).DownloadFile())
return new FileInfo(temp).Length;
}
}
TemporaryFile IItem.DownloadFile()
{
var temp = new TemporaryFile();
using (var stream = File.Create(temp))
using (var writer = new BinaryWriter(stream))
writer.Write(_change.Content);
return temp;
}
}
#endregion
#region workspaces
public void WithWorkspace(string localDirectory, IGitTfsRemote remote, IEnumerable<Tuple<string, string>> mappings, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action)
{
Trace.WriteLine("Setting up a TFS workspace at " + localDirectory);
var fakeWorkspace = new FakeWorkspace(localDirectory, remote.TfsRepositoryPath);
var workspace = _container.With("localDirectory").EqualTo(localDirectory)
.With("remote").EqualTo(remote)
.With("contextVersion").EqualTo(versionToFetch)
.With("workspace").EqualTo(fakeWorkspace)
.With("tfsHelper").EqualTo(this)
.GetInstance<TfsWorkspace>();
action(workspace);
}
public void WithWorkspace(string directory, IGitTfsRemote remote, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action)
{
Trace.WriteLine("Setting up a TFS workspace at " + directory);
var fakeWorkspace = new FakeWorkspace(directory, remote.TfsRepositoryPath);
var workspace = _container.With("localDirectory").EqualTo(directory)
.With("remote").EqualTo(remote)
.With("contextVersion").EqualTo(versionToFetch)
.With("workspace").EqualTo(fakeWorkspace)
.With("tfsHelper").EqualTo(this)
.GetInstance<TfsWorkspace>();
action(workspace);
}
private class FakeWorkspace : IWorkspace
{
private readonly string _directory;
private readonly string _repositoryRoot;
public FakeWorkspace(string directory, string repositoryRoot)
{
_directory = directory;
_repositoryRoot = repositoryRoot;
}
public void GetSpecificVersion(int changesetId, IEnumerable<IItem> items, bool noParallel)
{
throw new NotImplementedException();
}
public void GetSpecificVersion(IChangeset changeset, bool noParallel)
{
GetSpecificVersion(changeset.ChangesetId, changeset.Changes, noParallel);
}
public void GetSpecificVersion(int changeset, IEnumerable<IChange> changes, bool noParallel)
{
var repositoryRoot = _repositoryRoot.ToLower();
if (!repositoryRoot.EndsWith("/")) repositoryRoot += "/";
foreach (var change in changes)
{
if (change.Item.ItemType == TfsItemType.File)
{
var outPath = Path.Combine(_directory, change.Item.ServerItem.ToLower().Replace(repositoryRoot, ""));
var outDir = Path.GetDirectoryName(outPath);
if (!Directory.Exists(outDir)) Directory.CreateDirectory(outDir);
using (var download = change.Item.DownloadFile())
File.WriteAllText(outPath, File.ReadAllText(download.Path));
}
}
}
#region unimplemented
public void Merge(string sourceTfsPath, string tfsRepositoryPath)
{
throw new NotImplementedException();
}
public IPendingChange[] GetPendingChanges()
{
throw new NotImplementedException();
}
public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes, string comment, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges)
{
throw new NotImplementedException();
}
public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes, string comment, string authors, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges)
{
throw new NotImplementedException();
}
public void Shelve(IShelveset shelveset, IPendingChange[] changes, TfsShelvingOptions options)
{
throw new NotImplementedException();
}
public int Checkin(IPendingChange[] changes, string comment, string author, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges, TfsPolicyOverrideInfo policyOverrideInfo, bool overrideGatedCheckIn)
{
throw new NotImplementedException();
}
public int PendAdd(string path)
{
throw new NotImplementedException();
}
public int PendEdit(string path)
{
throw new NotImplementedException();
}
public int PendDelete(string path)
{
throw new NotImplementedException();
}
public int PendRename(string pathFrom, string pathTo)
{
throw new NotImplementedException();
}
public void ForceGetFile(string path, int changeset)
{
throw new NotImplementedException();
}
public void GetSpecificVersion(int changeset)
{
throw new NotImplementedException();
}
public string GetLocalItemForServerItem(string serverItem)
{
throw new NotImplementedException();
}
public string GetServerItemForLocalItem(string localItem)
{
throw new NotImplementedException();
}
public string OwnerName
{
get { throw new NotImplementedException(); }
}
#endregion
}
public void CleanupWorkspaces(string workingDirectory)
{
}
public bool IsExistingInTfs(string path)
{
var exists = false;
foreach (var changeset in _script.Changesets)
{
foreach (var change in changeset.Changes)
{
if (change.RepositoryPath == path)
{
exists = !change.ChangeType.IncludesOneOf(TfsChangeType.Delete);
}
}
}
return exists;
}
public bool CanGetBranchInformation { get { return true; } }
public IChangeset GetChangeset(int changesetId)
{
return new Changeset(_versionControlServer, _script.Changesets.First(c => c.Id == changesetId));
}
public IList<RootBranch> GetRootChangesetForBranch(string tfsPathBranchToCreate, int lastChangesetIdToCheck = -1, string tfsPathParentBranch = null)
{
var branchChangesets = _script.Changesets.Where(c => c.IsBranchChangeset);
var firstBranchChangeset = branchChangesets.FirstOrDefault(c => c.BranchChangesetDatas.BranchPath == tfsPathBranchToCreate);
var rootBranches = new List<RootBranch>();
if (firstBranchChangeset != null)
{
do
{
var rootBranch = new RootBranch(
firstBranchChangeset.BranchChangesetDatas.RootChangesetId,
firstBranchChangeset.Id,
firstBranchChangeset.BranchChangesetDatas.BranchPath
);
rootBranch.IsRenamedBranch = DeletedBranchesPathes.Contains(rootBranch.TfsBranchPath);
rootBranches.Add(rootBranch);
firstBranchChangeset = branchChangesets.FirstOrDefault(c => c.BranchChangesetDatas.BranchPath == firstBranchChangeset.BranchChangesetDatas.ParentBranch);
} while (firstBranchChangeset != null);
rootBranches.Reverse();
return rootBranches;
}
rootBranches.Add(new RootBranch(-1, tfsPathBranchToCreate));
return rootBranches;
}
private List<string> _deletedBranchesPathes;
private List<string> DeletedBranchesPathes
{
get
{
return _deletedBranchesPathes ?? (_deletedBranchesPathes = _script.Changesets.Where(c => c.IsBranchChangeset &&
c.Changes.Any(ch => ch.ChangeType == TfsChangeType.Delete && ch.RepositoryPath == c.BranchChangesetDatas.ParentBranch))
.Select(b => b.BranchChangesetDatas.ParentBranch).ToList());
}
}
public IEnumerable<IBranchObject> GetBranches(bool getDeletedBranches = false)
{
var renamings = _script.Changesets.Where(
c => c.IsBranchChangeset &&
DeletedBranchesPathes.Any(b => b == c.BranchChangesetDatas.BranchPath)).ToList();
var branches = new List<IBranchObject>();
branches.AddRange(_script.RootBranches.Select(b => new MockBranchObject { IsRoot = true, Path = b.BranchPath, ParentPath = null }));
branches.AddRange(_script.Changesets.Where(c => c.IsBranchChangeset).Select(c => new MockBranchObject
{
IsRoot = false,
Path = c.BranchChangesetDatas.BranchPath,
ParentPath = GetRealRootBranch(renamings, c.BranchChangesetDatas.ParentBranch)
}));
if (!getDeletedBranches)
branches.RemoveAll(b => DeletedBranchesPathes.Contains(b.Path));
return branches;
}
private string GetRealRootBranch(List<ScriptedChangeset> deletedBranches, string branchPath)
{
var realRoot = branchPath;
while (true)
{
var parent = deletedBranches.FirstOrDefault(b => b.BranchChangesetDatas.BranchPath == realRoot);
if (parent == null)
return realRoot;
realRoot = parent.BranchChangesetDatas.ParentBranch;
}
}
#endregion
#region unimplemented
public IShelveset CreateShelveset(IWorkspace workspace, string shelvesetName)
{
throw new NotImplementedException();
}
public IEnumerable<IWorkItemCheckinInfo> GetWorkItemInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction)
{
throw new NotImplementedException();
}
public IEnumerable<IWorkItemCheckedInfo> GetWorkItemCheckedInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction)
{
throw new NotImplementedException();
}
public ICheckinNote CreateCheckinNote(Dictionary<string, string> checkinNotes)
{
throw new NotImplementedException();
}
public ITfsChangeset GetChangeset(int changesetId, IGitTfsRemote remote)
{
throw new NotImplementedException();
}
public bool HasShelveset(string shelvesetName)
{
throw new NotImplementedException();
}
public ITfsChangeset GetShelvesetData(IGitTfsRemote remote, string shelvesetOwner, string shelvesetName)
{
throw new NotImplementedException();
}
public int ListShelvesets(ShelveList shelveList, IGitTfsRemote remote)
{
throw new NotImplementedException();
}
public IEnumerable<string> GetAllTfsRootBranchesOrderedByCreation()
{
return new List<string>();
}
public IEnumerable<TfsLabel> GetLabels(string tfsPathBranch, string nameFilter = null)
{
throw new NotImplementedException();
}
public void CreateBranch(string sourcePath, string targetPath, int changesetId, string comment = null)
{
throw new NotImplementedException();
}
public void CreateTfsRootBranch(string projectName, string mainBranch, string gitRepositoryPath, bool createTeamProjectFolder)
{
throw new NotImplementedException();
}
public int QueueGatedCheckinBuild(Uri value, string buildDefinitionName, string shelvesetName, string checkInTicket)
{
throw new NotImplementedException();
}
public void DeleteShelveset(IWorkspace workspace, string shelvesetName)
{
throw new NotImplementedException();
}
#endregion
private class FakeVersionControlServer : IVersionControlServer
{
private readonly Script _script;
public FakeVersionControlServer(Script script)
{
_script = script;
}
public IItem GetItem(int itemId, int changesetNumber)
{
var match = _script.Changesets.AsEnumerable().Reverse()
.SkipWhile(cs => cs.Id > changesetNumber)
.Select(cs => new { Changeset = cs, Change = cs.Changes.SingleOrDefault(change => change.ItemId == itemId) })
.First(x => x.Change != null);
return new Change(this, match.Changeset, match.Change);
}
public IItem GetItem(string itemPath, int changesetNumber)
{
throw new NotImplementedException();
}
public IItem[] GetItems(string itemPath, int changesetNumber, TfsRecursionType recursionType)
{
throw new NotImplementedException();
}
public IEnumerable<IChangeset> QueryHistory(string path, int version, int deletionId, TfsRecursionType recursion, string user, int versionFrom, int versionTo, int maxCount, bool includeChanges, bool slotMode, bool includeDownloadInfo)
{
throw new NotImplementedException();
}
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.ADF.CATIDs;
using System.Runtime.InteropServices;
namespace PanZoom
{
[ClassInterface(ClassInterfaceType.None)]
[Guid("F75471BC-4904-43ef-875F-D0B3958FA181")]
public class FullExtent : ICommand
{
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
//
// TODO: Add any COM registration code here
//
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
//
// TODO: Add any COM unregistration code here
//
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Unregister(regKey);
}
#endregion
#endregion
[DllImport("gdi32.dll")]
static extern bool DeleteObject(IntPtr hObject);
private bool m_enabled;
private System.Drawing.Bitmap m_bitmap;
private IntPtr m_hBitmap;
private IHookHelper m_pHookHelper;
public FullExtent()
{
string[] res = GetType().Assembly.GetManifestResourceNames();
if(res.GetLength(0) > 0)
{
m_bitmap = new System.Drawing.Bitmap(GetType().Assembly.GetManifestResourceStream(GetType(), "FullExtent.bmp"));
if(m_bitmap != null)
{
m_bitmap.MakeTransparent(m_bitmap.GetPixel(1,1));
m_hBitmap = m_bitmap.GetHbitmap();
}
}
m_pHookHelper = new HookHelperClass ();
}
~FullExtent()
{
if(m_hBitmap.ToInt32() != 0)
DeleteObject(m_hBitmap);
}
#region ICommand Members
public void OnClick()
{
//Get IActiveView interface
IActiveView pActiveView = (IActiveView) m_pHookHelper.FocusMap;
//Set the extent to the full extent
pActiveView.Extent = pActiveView.FullExtent;
//Refresh the active view
pActiveView.Refresh();
}
public string Message
{
get
{
return "Zooms the Display to Full Extent of the Data";
}
}
public int Bitmap
{
get
{
return m_hBitmap.ToInt32();
}
}
public void OnCreate(object hook)
{
m_pHookHelper.Hook = hook;
m_enabled = true;
}
public string Caption
{
get
{
return "Full Extent";
}
}
public string Tooltip
{
get
{
return "Zoom Display to Full Data Extent";
}
}
public int HelpContextID
{
get
{
// TODO: Add FullExtent.HelpContextID getter implementation
return 0;
}
}
public string Name
{
get
{
return "Sample_Pan/Zoom_Full Extent";
}
}
public bool Checked
{
get
{
return false;
}
}
public bool Enabled
{
get
{
return m_enabled;
}
}
public string HelpFile
{
get
{
// TODO: Add FullExtent.HelpFile getter implementation
return null;
}
}
public string Category
{
get
{
return "Sample_Pan/Zoom";
}
}
#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.
/******************************************************************************
* 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 AddSubtractDouble()
{
var test = new AlternatingBinaryOpTest__AddSubtractDouble();
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 AlternatingBinaryOpTest__AddSubtractDouble
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int Op2ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private AlternatingBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static AlternatingBinaryOpTest__AddSubtractDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
}
public AlternatingBinaryOpTest__AddSubtractDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
_dataTable = new AlternatingBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Sse3.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse3.AddSubtract(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse3.AddSubtract(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse3.AddSubtract(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse3).GetMethod(nameof(Sse3.AddSubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse3).GetMethod(nameof(Sse3.AddSubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse3).GetMethod(nameof(Sse3.AddSubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse3.AddSubtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse3.AddSubtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse3.AddSubtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse3.AddSubtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new AlternatingBinaryOpTest__AddSubtractDouble();
var result = Sse3.AddSubtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse3.AddSubtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
for (var i = 0; i < RetElementCount; i += 2)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(left[i] - right[i]))
{
Succeeded = false;
break;
}
if (BitConverter.DoubleToInt64Bits(result[i + 1]) != BitConverter.DoubleToInt64Bits(left[i + 1] + right[i + 1]))
{
Succeeded = false;
break;
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse3)}.{nameof(Sse3.AddSubtract)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Http
{
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyCreate")]
public static extern SafeCurlHandle EasyCreate();
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyDestroy")]
private static extern void EasyDestroy(IntPtr handle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionString", CharSet = CharSet.Ansi)]
public static extern CURLcode EasySetOptionString(SafeCurlHandle curl, CURLoption option, string value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionLong")]
public static extern CURLcode EasySetOptionLong(SafeCurlHandle curl, CURLoption option, long value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")]
public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, IntPtr value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")]
public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, SafeHandle value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetErrorString")]
public static extern IntPtr EasyGetErrorString(int code);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoPointer")]
public static extern CURLcode EasyGetInfoPointer(IntPtr handle, CURLINFO info, out IntPtr value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoPointer")]
public static extern CURLcode EasyGetInfoPointer(SafeCurlHandle handle, CURLINFO info, out IntPtr value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoLong")]
public static extern CURLcode EasyGetInfoLong(SafeCurlHandle handle, CURLINFO info, out long value);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyPerform")]
public static extern CURLcode EasyPerform(SafeCurlHandle curl);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyUnpause")]
public static extern CURLcode EasyUnpause(SafeCurlHandle easy);
public delegate CurlSeekResult SeekCallback(IntPtr userPointer, long offset, int origin);
public delegate ulong ReadWriteCallback(IntPtr buffer, ulong bufferSize, ulong nitems, IntPtr userPointer);
public delegate CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer);
public delegate void DebugCallback(IntPtr curl, CurlInfoType type, IntPtr data, ulong size, IntPtr userPointer);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSeekCallback")]
public static extern void RegisterSeekCallback(
SafeCurlHandle curl,
SeekCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterReadWriteCallback")]
public static extern void RegisterReadWriteCallback(
SafeCurlHandle curl,
ReadWriteFunction functionType,
ReadWriteCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSslCtxCallback")]
public static extern CURLcode RegisterSslCtxCallback(
SafeCurlHandle curl,
SslCtxCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterDebugCallback")]
public static extern CURLcode RegisterDebugCallback(
SafeCurlHandle curl,
DebugCallback callback,
IntPtr userPointer,
ref SafeCallbackHandle callbackHandle);
[DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_FreeCallbackHandle")]
private static extern void FreeCallbackHandle(IntPtr handle);
// Curl options are of the format <type base> + <n>
private const int CurlOptionLongBase = 0;
private const int CurlOptionObjectPointBase = 10000;
private const int CurlOptionOffTBase = 30000;
// Enum for constants defined for the enum CURLoption in curl.h
internal enum CURLoption
{
CURLOPT_INFILESIZE = CurlOptionLongBase + 14,
CURLOPT_SSLVERSION = CurlOptionLongBase + 32,
CURLOPT_VERBOSE = CurlOptionLongBase + 41,
CURLOPT_NOBODY = CurlOptionLongBase + 44,
CURLOPT_UPLOAD = CurlOptionLongBase + 46,
CURLOPT_POST = CurlOptionLongBase + 47,
CURLOPT_FOLLOWLOCATION = CurlOptionLongBase + 52,
CURLOPT_PROXYPORT = CurlOptionLongBase + 59,
CURLOPT_POSTFIELDSIZE = CurlOptionLongBase + 60,
CURLOPT_SSL_VERIFYPEER = CurlOptionLongBase + 64,
CURLOPT_MAXREDIRS = CurlOptionLongBase + 68,
CURLOPT_SSL_VERIFYHOST = CurlOptionLongBase + 81,
CURLOPT_HTTP_VERSION = CurlOptionLongBase + 84,
CURLOPT_DNS_CACHE_TIMEOUT = CurlOptionLongBase + 92,
CURLOPT_NOSIGNAL = CurlOptionLongBase + 99,
CURLOPT_PROXYTYPE = CurlOptionLongBase + 101,
CURLOPT_HTTPAUTH = CurlOptionLongBase + 107,
CURLOPT_TCP_NODELAY = CurlOptionLongBase + 121,
CURLOPT_CONNECTTIMEOUT_MS = CurlOptionLongBase + 156,
CURLOPT_ADDRESS_SCOPE = CurlOptionLongBase + 171,
CURLOPT_PROTOCOLS = CurlOptionLongBase + 181,
CURLOPT_REDIR_PROTOCOLS = CurlOptionLongBase + 182,
CURLOPT_URL = CurlOptionObjectPointBase + 2,
CURLOPT_PROXY = CurlOptionObjectPointBase + 4,
CURLOPT_PROXYUSERPWD = CurlOptionObjectPointBase + 6,
CURLOPT_COOKIE = CurlOptionObjectPointBase + 22,
CURLOPT_HTTPHEADER = CurlOptionObjectPointBase + 23,
CURLOPT_CUSTOMREQUEST = CurlOptionObjectPointBase + 36,
CURLOPT_ACCEPT_ENCODING = CurlOptionObjectPointBase + 102,
CURLOPT_PRIVATE = CurlOptionObjectPointBase + 103,
CURLOPT_COPYPOSTFIELDS = CurlOptionObjectPointBase + 165,
CURLOPT_USERNAME = CurlOptionObjectPointBase + 173,
CURLOPT_PASSWORD = CurlOptionObjectPointBase + 174,
CURLOPT_INFILESIZE_LARGE = CurlOptionOffTBase + 115,
CURLOPT_POSTFIELDSIZE_LARGE = CurlOptionOffTBase + 120,
}
internal enum ReadWriteFunction
{
Write = 0,
Read = 1,
Header = 2,
}
// Curl info are of the format <type base> + <n>
private const int CurlInfoStringBase = 0x100000;
private const int CurlInfoLongBase = 0x200000;
// Enum for constants defined for CURL_HTTP_VERSION
internal enum CurlHttpVersion
{
CURL_HTTP_VERSION_NONE = 0,
CURL_HTTP_VERSION_1_0 = 1,
CURL_HTTP_VERSION_1_1 = 2,
CURL_HTTP_VERSION_2_0 = 3,
};
// Enum for constants defined for CURL_SSLVERSION
internal enum CurlSslVersion
{
CURL_SSLVERSION_TLSv1 = 1, /* TLS 1.x */
CURL_SSLVERSION_TLSv1_0 = 4, /* TLS 1.0 */
CURL_SSLVERSION_TLSv1_1 = 5, /* TLS 1.1 */
CURL_SSLVERSION_TLSv1_2 = 6, /* TLS 1.2 */
};
// Enum for constants defined for the enum CURLINFO in curl.h
internal enum CURLINFO
{
CURLINFO_EFFECTIVE_URL = CurlInfoStringBase + 1,
CURLINFO_PRIVATE = CurlInfoStringBase + 21,
CURLINFO_HTTPAUTH_AVAIL = CurlInfoLongBase + 23,
}
// AUTH related constants
[Flags]
internal enum CURLAUTH
{
None = 0,
Basic = 1 << 0,
Digest = 1 << 1,
Negotiate = 1 << 2,
NTLM = 1 << 3,
}
// Enum for constants defined for the enum curl_proxytype in curl.h
internal enum curl_proxytype
{
CURLPROXY_HTTP = 0,
}
[Flags]
internal enum CurlProtocols
{
CURLPROTO_HTTP = (1 << 0),
CURLPROTO_HTTPS = (1 << 1),
}
// Enum for constants defined for the results of CURL_SEEKFUNCTION
internal enum CurlSeekResult : int
{
CURL_SEEKFUNC_OK = 0,
CURL_SEEKFUNC_FAIL = 1,
CURL_SEEKFUNC_CANTSEEK = 2,
}
internal enum CurlInfoType : int
{
CURLINFO_TEXT = 0,
CURLINFO_HEADER_IN = 1,
CURLINFO_HEADER_OUT = 2,
CURLINFO_DATA_IN = 3,
CURLINFO_DATA_OUT = 4,
CURLINFO_SSL_DATA_IN = 5,
CURLINFO_SSL_DATA_OUT = 6,
};
// constants defined for the results of a CURL_READ or CURL_WRITE function
internal const ulong CURL_READFUNC_ABORT = 0x10000000;
internal const ulong CURL_READFUNC_PAUSE = 0x10000001;
internal const ulong CURL_WRITEFUNC_PAUSE = 0x10000001;
internal const ulong CURL_MAX_HTTP_HEADER = 100 * 1024;
internal sealed class SafeCurlHandle : SafeHandle
{
public SafeCurlHandle() : base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
EasyDestroy(handle);
SetHandle(IntPtr.Zero);
return true;
}
}
internal sealed class SafeCallbackHandle : SafeHandle
{
public SafeCallbackHandle()
: base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
FreeCallbackHandle(handle);
SetHandle(IntPtr.Zero);
return true;
}
}
}
}
| |
using System;
using System.Security.Cryptography;
using System.Text;
using Common.Logging;
using ToolKit.Validation;
namespace ToolKit.Cryptography
{
/// <summary>
/// Asymmetric Encryption is a form of Encryption where keys come in pairs. What one key
/// encrypts, only the other can decrypt. Frequently (but not necessarily), the keys are
/// interchangeable, in the sense that if key A encrypts a message, then B can decrypt it, and if
/// key B encrypts a message, then key A can decrypt it. Asymmetric Encryption is also known as
/// Public Key Cryptography, since users typically create a matching key pair, and make one
/// public while keeping the other secret.
/// </summary>
/// <remarks>
/// Adapted from code originally written by Jeff Atwood. This code had no explicit license
/// attached to it. If licensing is a concern, you should contact the original author.
/// </remarks>
public class RsaEncryption
{
private static readonly ILog _log = LogManager.GetLogger<RsaEncryption>();
/// <summary>
/// Initializes a new instance of the <see cref="RsaEncryption"/> class.
/// </summary>
/// <param name="keySize">Size of the key in bits.</param>
public RsaEncryption(int keySize)
{
KeySizeBits = keySize;
}
/// <summary>
/// Initializes a new instance of the <see cref="RsaEncryption"/> class.
/// </summary>
public RsaEncryption()
{
}
/// <summary>
/// Gets the default private key as stored in the application configuration file.
/// </summary>
public static RsaPrivateKey DefaultPrivateKey => RsaPrivateKey.LoadFromEnvironment();
/// <summary>
/// Gets the default public key as stored in the *.config file.
/// </summary>
public static RsaPublicKey DefaultPublicKey => RsaPublicKey.LoadFromEnvironment();
/// <summary>
/// Gets the name of the key container used to store this key on disk; this is an
/// unavoidable side effect of the underlying Microsoft CryptoAPI.
/// </summary>
public string KeyContainerName { get; } = "ToolKit.AsymmetricEncryption.DefaultContainerName";
/// <summary>
/// Gets the current key size, in bits.
/// </summary>
public int KeySizeBits { get; } = 1024;
/// <summary>
/// Gets the maximum supported key size, in bits.
/// </summary>
public int KeySizeMaxBits
{
get
{
var rsa = GetRsaProvider();
var keyMaxSize = rsa.LegalKeySizes[0].MaxSize;
rsa.Clear();
rsa.Dispose();
return keyMaxSize;
}
}
/// <summary>
/// Gets the minimum supported key size, in bits.
/// </summary>
public int KeySizeMinBits
{
get
{
var rsa = GetRsaProvider();
var keyMinSize = rsa.LegalKeySizes[0].MinSize;
rsa.Clear();
rsa.Dispose();
return keyMinSize;
}
}
/// <summary>
/// Gets the valid key step sizes, in bits.
/// </summary>
public int KeySizeStepBits
{
get
{
var rsa = GetRsaProvider();
var keyStepBits = rsa.LegalKeySizes[0].SkipSize;
rsa.Clear();
rsa.Dispose();
return keyStepBits;
}
}
/// <summary>
/// Decrypts data using the default private key.
/// </summary>
/// <param name="encryptedData">The data to be decrypted.</param>
/// <returns>The decrypted data.</returns>
public EncryptionData Decrypt(EncryptionData encryptedData)
{
return Decrypt(encryptedData, RsaPrivateKey.LoadFromEnvironment());
}
/// <summary>
/// Decrypts data using the provided private key.
/// </summary>
/// <param name="encryptedData">The data to be decrypted.</param>
/// <param name="privateKey">The private key.</param>
/// <returns>The decrypted data.</returns>
public EncryptionData Decrypt(EncryptionData encryptedData, RsaPrivateKey privateKey)
{
var rsa = GetRsaProvider();
rsa.ImportParameters(Check.NotNull(privateKey, nameof(privateKey)).ToParameters());
// Be aware the RSACryptoServiceProvider reverses the order of encrypted bytes after
// encryption and before decryption. In order to provide compatibility with other
// providers, we reverse the order of the bytes to match what other providers output.
Array.Reverse(Check.NotNull(encryptedData, nameof(encryptedData)).Bytes);
var decrypted = new EncryptionData(rsa.Decrypt(encryptedData.Bytes, true));
rsa.Clear();
rsa.Dispose();
return decrypted;
}
/// <summary>
/// Encrypts data using the default public key.
/// </summary>
/// <param name="data">The data to be encrypted..</param>
/// <returns>The encrypted data.</returns>
public EncryptionData Encrypt(EncryptionData data)
{
return Encrypt(data, DefaultPublicKey);
}
/// <summary>
/// Encrypts data using the provided public key.
/// </summary>
/// <param name="data">The data to be encrypted..</param>
/// <param name="publicKey">The public key.</param>
/// <returns>The encrypted data.</returns>
public EncryptionData Encrypt(EncryptionData data, RsaPublicKey publicKey)
{
var rsa = GetRsaProvider();
rsa.ImportParameters(Check.NotNull(publicKey, nameof(publicKey)).ToParameters());
try
{
var encryptedBytes = rsa.Encrypt(Check.NotNull(data, nameof(data)).Bytes, true);
// Be aware the RSACryptoServiceProvider reverses the order of encrypted bytes after
// encryption and before decryption. In order to provide compatibility with other
// providers, we reverse the order of the bytes to match what other providers output.
Array.Reverse(encryptedBytes);
return new EncryptionData(encryptedBytes);
}
catch (CryptographicException ex)
{
_log.Error(ex.Message, ex);
var sb = new StringBuilder();
sb.Append("Your data is too large; RSA implementation in .Net is designed to encrypt ");
sb.Append("relatively small amounts of data. The exact byte limit depends ");
sb.Append("on the key size. To encrypt more data, use symmetric encryption ");
sb.Append("and then encrypt that symmetric key with ");
sb.Append("asymmetric encryption.");
_log.Warn(sb.ToString());
throw new CryptographicException(sb.ToString(), ex);
}
catch (Exception ex)
{
_log.Error(ex.ToString(), ex);
throw;
}
finally
{
rsa.Clear();
rsa.Dispose();
}
}
/// <summary>
/// Generates a new public/private key pair as objects.
/// </summary>
/// <param name="publicKey">The public key.</param>
/// <param name="privateKey">The private key.</param>
public void GenerateNewKeyset(ref RsaPublicKey publicKey, ref RsaPrivateKey privateKey)
{
if (publicKey == null)
{
throw new ArgumentNullException(nameof(publicKey));
}
if (privateKey == null)
{
throw new ArgumentNullException(nameof(privateKey));
}
var rsa = GetRsaProvider();
var publicKeyXml = rsa.ToXmlString(false);
var privateKeyXml = rsa.ToXmlString(true);
rsa.Clear();
rsa.Dispose();
publicKey = new RsaPublicKey(publicKeyXml);
privateKey = new RsaPrivateKey(privateKeyXml);
}
/// <summary>
/// Signs data using the provided private key.
/// </summary>
/// <param name="dataToSign">The data to be signed.</param>
/// <param name="privateKey">The private key.</param>
/// <returns>The signature of the data as signed by the private key.</returns>
public EncryptionData Sign(EncryptionData dataToSign, RsaPrivateKey privateKey)
{
var rsa = GetRsaProvider();
rsa.ImportParameters(Check.NotNull(privateKey, nameof(privateKey)).ToParameters());
var hash = new SHA256Managed();
var sig = rsa.SignData(Check.NotNull(dataToSign, nameof(dataToSign)).Bytes, hash);
rsa.Clear();
rsa.Dispose();
hash.Dispose();
return new EncryptionData(sig);
}
/// <summary>
/// Verifies that the provided data has not changed since it was signed.
/// </summary>
/// <param name="data">The data to be validated.</param>
/// <param name="signature">The signature to use to verify data.</param>
/// <param name="publicKey">The public key.</param>
/// <returns>
/// <c>true</c> if the provided data has not changed since it was signed, otherwise <c>false</c>.
/// </returns>
public bool Verify(EncryptionData data, EncryptionData signature, RsaPublicKey publicKey)
{
var rsa = GetRsaProvider();
rsa.ImportParameters(Check.NotNull(publicKey, nameof(publicKey)).ToParameters());
var hash = new SHA256Managed();
var valid = rsa.VerifyData(
Check.NotNull(data, nameof(data)).Bytes,
hash,
Check.NotNull(signature, nameof(signature)).Bytes);
rsa.Clear();
rsa.Dispose();
hash.Dispose();
return valid;
}
private RSACryptoServiceProvider GetRsaProvider()
{
var csp = new CspParameters
{
KeyContainerName = KeyContainerName
};
var rsa = new RSACryptoServiceProvider(KeySizeBits, csp)
{
PersistKeyInCsp = false
};
RSACryptoServiceProvider.UseMachineKeyStore = true;
return rsa;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Principal;
namespace System.Security.Claims
{
/// <summary>
/// An Identity that is represented by a set of claims.
/// </summary>
[Serializable]
public class ClaimsIdentity : IIdentity
{
private const string PreFix = "System.Security.ClaimsIdentity.";
private const string AuthenticationTypeKey = PreFix + "authenticationType";
private const string LabelKey = PreFix + "label";
private const string NameClaimTypeKey = PreFix + "nameClaimType";
private const string RoleClaimTypeKey = PreFix + "roleClaimType";
private const string VersionKey = PreFix + "version";
private enum SerializationMask
{
None = 0,
AuthenticationType = 1,
BootstrapConext = 2,
NameClaimType = 4,
RoleClaimType = 8,
HasClaims = 16,
HasLabel = 32,
Actor = 64,
UserData = 128,
}
[NonSerialized]
private byte[] _userSerializationData;
private ClaimsIdentity _actor;
private string _authenticationType;
private object _bootstrapContext;
[NonSerialized]
private List<List<Claim>> _externalClaims;
private string _label;
[NonSerialized]
private List<Claim> _instanceClaims = new List<Claim>();
[NonSerialized]
private string _nameClaimType = DefaultNameClaimType;
[NonSerialized]
private string _roleClaimType = DefaultRoleClaimType;
private string _serializedNameType;
private string _serializedRoleType;
public const string DefaultIssuer = @"LOCAL AUTHORITY";
public const string DefaultNameClaimType = ClaimTypes.Name;
public const string DefaultRoleClaimType = ClaimTypes.Role;
// NOTE about _externalClaims.
// GenericPrincpal and RolePrincipal set role claims here so that .IsInRole will be consistent with a 'role' claim found by querying the identity or principal.
// _externalClaims are external to the identity and assumed to be dynamic, they not serialized or copied through Clone().
// Access through public method: ClaimProviders.
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
public ClaimsIdentity()
: this((IIdentity)null, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IIdentity identity)
: this(identity, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <remarks>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
/// </remarks>
public ClaimsIdentity(IEnumerable<Claim> claims)
: this((IIdentity)null, claims, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="authenticationType">The authentication method used to establish this identity.</param>
public ClaimsIdentity(string authenticationType)
: this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The authentication method used to establish this identity.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType)
: this((IIdentity)null, claims, authenticationType, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims)
: this(identity, claims, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(string authenticationType, string nameType, string roleType)
: this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, nameType, roleType)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
: this((IIdentity)null, claims, authenticationType, nameType, roleType)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
/// <remarks>If 'identity' is a <see cref="ClaimsIdentity"/>, then there are potentially multiple sources for AuthenticationType, NameClaimType, RoleClaimType.
/// <para>Priority is given to the parameters: authenticationType, nameClaimType, roleClaimType.</para>
/// <para>All <see cref="Claim"/>s are copied into this instance in a <see cref="List{Claim}"/>. Each Claim is examined and if Claim.Subject != this, then Claim.Clone(this) is called before the claim is added.</para>
/// <para>Any 'External' claims are ignored.</para>
/// </remarks>
/// <exception cref="InvalidOperationException">if 'identity' is a <see cref="ClaimsIdentity"/> and <see cref="ClaimsIdentity.Actor"/> results in a circular refrence back to 'this'.</exception>
public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
{
ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
_authenticationType = !string.IsNullOrWhiteSpace(authenticationType) ? authenticationType : (identity != null ? identity.AuthenticationType : null);
_nameClaimType = !string.IsNullOrEmpty(nameType) ? nameType : (claimsIdentity != null ? claimsIdentity._nameClaimType : DefaultNameClaimType);
_roleClaimType = !string.IsNullOrEmpty(roleType) ? roleType : (claimsIdentity != null ? claimsIdentity._roleClaimType : DefaultRoleClaimType);
if (claimsIdentity != null)
{
_label = claimsIdentity._label;
_bootstrapContext = claimsIdentity._bootstrapContext;
if (claimsIdentity.Actor != null)
{
//
// Check if the Actor is circular before copying. That check is done while setting
// the Actor property and so not really needed here. But checking just for sanity sake
//
if (!IsCircular(claimsIdentity.Actor))
{
_actor = claimsIdentity.Actor;
}
else
{
throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular);
}
}
SafeAddClaims(claimsIdentity._instanceClaims);
}
else
{
if (identity != null && !string.IsNullOrEmpty(identity.Name))
{
SafeAddClaim(new Claim(_nameClaimType, identity.Name, ClaimValueTypes.String, DefaultIssuer, DefaultIssuer, this));
}
}
if (claims != null)
{
SafeAddClaims(claims);
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> using a <see cref="BinaryReader"/>.
/// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
public ClaimsIdentity(BinaryReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
Initialize(reader);
}
/// <summary>
/// Copy constructor.
/// </summary>
/// <param name="other"><see cref="ClaimsIdentity"/> to copy.</param>
/// <exception cref="ArgumentNullException">if 'other' is null.</exception>
protected ClaimsIdentity(ClaimsIdentity other)
{
if (other == null)
{
throw new ArgumentNullException(nameof(other));
}
if (other._actor != null)
{
_actor = other._actor.Clone();
}
_authenticationType = other._authenticationType;
_bootstrapContext = other._bootstrapContext;
_label = other._label;
_nameClaimType = other._nameClaimType;
_roleClaimType = other._roleClaimType;
if (other._userSerializationData != null)
{
_userSerializationData = other._userSerializationData.Clone() as byte[];
}
SafeAddClaims(other._instanceClaims);
}
protected ClaimsIdentity(SerializationInfo info, StreamingContext context)
{
if (null == info)
{
throw new ArgumentNullException(nameof(info));
}
Deserialize(info, context, true);
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> from a serialized stream created via
/// <see cref="ISerializable"/>.
/// </summary>
/// <param name="info">
/// The <see cref="SerializationInfo"/> to read from.
/// </param>
/// <exception cref="ArgumentNullException">Thrown is the <paramref name="info"/> is null.</exception>
[SecurityCritical]
protected ClaimsIdentity(SerializationInfo info)
{
if (null == info)
{
throw new ArgumentNullException(nameof(info));
}
Deserialize(info, new StreamingContext(), false);
}
/// <summary>
/// Gets the authentication type that can be used to determine how this <see cref="ClaimsIdentity"/> authenticated to an authority.
/// </summary>
public virtual string AuthenticationType
{
get { return _authenticationType; }
}
/// <summary>
/// Gets a value that indicates if the user has been authenticated.
/// </summary>
public virtual bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(_authenticationType); }
}
/// <summary>
/// Gets or sets a <see cref="ClaimsIdentity"/> that was granted delegation rights.
/// </summary>
/// <exception cref="InvalidOperationException">if 'value' results in a circular reference back to 'this'.</exception>
public ClaimsIdentity Actor
{
get { return _actor; }
set
{
if (value != null)
{
if (IsCircular(value))
{
throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular);
}
}
_actor = value;
}
}
/// <summary>
/// Gets or sets a context that was used to create this <see cref="ClaimsIdentity"/>.
/// </summary>
public object BootstrapContext
{
get { return _bootstrapContext; }
set { _bootstrapContext = value; }
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsIdentity"/>.
/// </summary>
/// <remarks>May contain nulls.</remarks>
public virtual IEnumerable<Claim> Claims
{
get
{
if (_externalClaims == null)
{
return _instanceClaims;
}
return CombinedClaimsIterator();
}
}
private IEnumerable<Claim> CombinedClaimsIterator()
{
for (int i = 0; i < _instanceClaims.Count; i++)
{
yield return _instanceClaims[i];
}
for (int j = 0; j < _externalClaims.Count; j++)
{
if (_externalClaims[j] != null)
{
foreach (Claim claim in _externalClaims[j])
{
yield return claim;
}
}
}
}
/// <summary>
/// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>.
/// </summary>
protected virtual byte[] CustomSerializationData
{
get
{
return _userSerializationData;
}
}
/// <summary>
/// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>.
/// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to <see cref="ClaimsIdentity.Claims"/>.
/// </summary>
internal List<List<Claim>> ExternalClaims
{
get
{
if (_externalClaims == null)
{
_externalClaims = new List<List<Claim>>();
}
return _externalClaims;
}
}
/// <summary>
/// Gets or sets the label for this <see cref="ClaimsIdentity"/>
/// </summary>
public string Label
{
get { return _label; }
set { _label = value; }
}
/// <summary>
/// Gets the Name of this <see cref="ClaimsIdentity"/>.
/// </summary>
/// <remarks>Calls <see cref="FindFirst(string)"/> where string == NameClaimType, if found, returns <see cref="Claim.Value"/> otherwise null.</remarks>
public virtual string Name
{
// just an accessor for getting the name claim
get
{
Claim claim = FindFirst(_nameClaimType);
if (claim != null)
{
return claim.Value;
}
return null;
}
}
/// <summary>
/// Gets the value that identifies 'Name' claims. This is used when returning the property <see cref="ClaimsIdentity.Name"/>.
/// </summary>
public string NameClaimType
{
get { return _nameClaimType; }
}
/// <summary>
/// Gets the value that identifies 'Role' claims. This is used when calling <see cref="ClaimsPrincipal.IsInRole"/>.
/// </summary>
public string RoleClaimType
{
get { return _roleClaimType; }
}
/// <summary>
/// Creates a new instance of <see cref="ClaimsIdentity"/> with values copied from this object.
/// </summary>
public virtual ClaimsIdentity Clone()
{
return new ClaimsIdentity(this);
}
/// <summary>
/// Adds a single <see cref="Claim"/> to an internal list.
/// </summary>
/// <param name="claim">the <see cref="Claim"/>add.</param>
/// <remarks>If <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks>
/// <exception cref="ArgumentNullException">if 'claim' is null.</exception>
public virtual void AddClaim(Claim claim)
{
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
Contract.EndContractBlock();
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
/// <summary>
/// Adds a <see cref="IEnumerable{Claim}"/> to the internal list.
/// </summary>
/// <param name="claims">Enumeration of claims to add.</param>
/// <remarks>Each claim is examined and if <see cref="Claim.Subject"/> != this, then then Claim.Clone(this) is called before the claim is added.</remarks>
/// <exception cref="ArgumentNullException">if 'claims' is null.</exception>
public virtual void AddClaims(IEnumerable<Claim> claims)
{
if (claims == null)
{
throw new ArgumentNullException(nameof(claims));
}
Contract.EndContractBlock();
foreach (Claim claim in claims)
{
if (claim == null)
{
continue;
}
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
}
/// <summary>
/// Attempts to remove a <see cref="Claim"/> the internal list.
/// </summary>
/// <param name="claim">the <see cref="Claim"/> to match.</param>
/// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference.
/// <para>object.ReferenceEquals is used to 'match'.</para>
/// </remarks>
public virtual bool TryRemoveClaim(Claim claim)
{
if (claim == null)
{
return false;
}
bool removed = false;
for (int i = 0; i < _instanceClaims.Count; i++)
{
if (object.ReferenceEquals(_instanceClaims[i], claim))
{
_instanceClaims.RemoveAt(i);
removed = true;
break;
}
}
return removed;
}
/// <summary>
/// Removes a <see cref="Claim"/> from the internal list.
/// </summary>
/// <param name="claim">the <see cref="Claim"/> to match.</param>
/// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference.
/// <para>object.ReferenceEquals is used to 'match'.</para>
/// </remarks>
/// <exception cref="InvalidOperationException">if 'claim' cannot be removed.</exception>
public virtual void RemoveClaim(Claim claim)
{
if (!TryRemoveClaim(claim))
{
throw new InvalidOperationException(string.Format(SR.InvalidOperation_ClaimCannotBeRemoved, claim));
}
}
/// <summary>
/// Adds claims to internal list. Calling Claim.Clone if Claim.Subject != this.
/// </summary>
/// <param name="claims">a <see cref="IEnumerable{Claim}"/> to add to </param>
/// <remarks>private only call from constructor, adds to internal list.</remarks>
private void SafeAddClaims(IEnumerable<Claim> claims)
{
foreach (Claim claim in claims)
{
if (claim == null)
continue;
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
}
/// <summary>
/// Adds claim to internal list. Calling Claim.Clone if Claim.Subject != this.
/// </summary>
/// <remarks>private only call from constructor, adds to internal list.</remarks>
private void SafeAddClaim(Claim claim)
{
if (claim == null)
return;
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <paramref name="match"/>.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (match(claim))
{
yield return claim;
}
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual IEnumerable<Claim> FindAll(string type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (claim != null)
{
if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase))
{
yield return claim;
}
}
}
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> that is matched by <paramref name="match"/>.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual Claim FindFirst(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (match(claim))
{
return claim;
}
}
return null;
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> where Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual Claim FindFirst(string type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (claim != null)
{
if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase))
{
return claim;
}
}
}
return null;
}
/// <summary>
/// Determines if a claim is contained within this ClaimsIdentity.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>true if a claim is found, false otherwise.</returns>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual bool HasClaim(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (match(claim))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines if a claim with type AND value is contained within this ClaimsIdentity.
/// </summary>
/// <param name="type">the type of the claim to match.</param>
/// <param name="value">the value of the claim to match.</param>
/// <returns>true if a claim is matched, false otherwise.</returns>
/// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase for Claim.Type, StringComparison.Ordinal for Claim.Value.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception>
public virtual bool HasClaim(string type, string value)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (claim != null
&& string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)
&& string.Equals(claim.Value, value, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
/// <summary>
/// Initializes from a <see cref="BinaryReader"/>. Normally the reader is initialized with the results from <see cref="WriteTo(BinaryWriter)"/>
/// Normally the <see cref="BinaryReader"/> is initialized in the same way as the <see cref="BinaryWriter"/> passed to <see cref="WriteTo(BinaryWriter)"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
private void Initialize(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
SerializationMask mask = (SerializationMask)reader.ReadInt32();
int numPropertiesRead = 0;
int numPropertiesToRead = reader.ReadInt32();
if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType)
{
_authenticationType = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext)
{
_bootstrapContext = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType)
{
_nameClaimType = reader.ReadString();
numPropertiesRead++;
}
else
{
_nameClaimType = ClaimsIdentity.DefaultNameClaimType;
}
if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType)
{
_roleClaimType = reader.ReadString();
numPropertiesRead++;
}
else
{
_roleClaimType = ClaimsIdentity.DefaultRoleClaimType;
}
if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel)
{
_label = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims)
{
int numberOfClaims = reader.ReadInt32();
for (int index = 0; index < numberOfClaims; index++)
{
_instanceClaims.Add(CreateClaim(reader));
}
numPropertiesRead++;
}
if ((mask & SerializationMask.Actor) == SerializationMask.Actor)
{
_actor = new ClaimsIdentity(reader);
numPropertiesRead++;
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
int cb = reader.ReadInt32();
_userSerializationData = reader.ReadBytes(cb);
numPropertiesRead++;
}
for (int i = numPropertiesRead; i < numPropertiesToRead; i++)
{
reader.ReadString();
}
}
/// <summary>
/// Provides an extensibility point for derived types to create a custom <see cref="Claim"/>.
/// </summary>
/// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param>
/// <returns>a new <see cref="Claim"/>.</returns>
protected virtual Claim CreateClaim(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
return new Claim(reader, this);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
public virtual void WriteTo(BinaryWriter writer)
{
WriteTo(writer, null);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <param name="userData">additional data provided by derived type.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
protected virtual void WriteTo(BinaryWriter writer, byte[] userData)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
int numberOfPropertiesWritten = 0;
var mask = SerializationMask.None;
if (_authenticationType != null)
{
mask |= SerializationMask.AuthenticationType;
numberOfPropertiesWritten++;
}
if (_bootstrapContext != null)
{
string rawData = _bootstrapContext as string;
if (rawData != null)
{
mask |= SerializationMask.BootstrapConext;
numberOfPropertiesWritten++;
}
}
if (!string.Equals(_nameClaimType, ClaimsIdentity.DefaultNameClaimType, StringComparison.Ordinal))
{
mask |= SerializationMask.NameClaimType;
numberOfPropertiesWritten++;
}
if (!string.Equals(_roleClaimType, ClaimsIdentity.DefaultRoleClaimType, StringComparison.Ordinal))
{
mask |= SerializationMask.RoleClaimType;
numberOfPropertiesWritten++;
}
if (!string.IsNullOrWhiteSpace(_label))
{
mask |= SerializationMask.HasLabel;
numberOfPropertiesWritten++;
}
if (_instanceClaims.Count > 0)
{
mask |= SerializationMask.HasClaims;
numberOfPropertiesWritten++;
}
if (_actor != null)
{
mask |= SerializationMask.Actor;
numberOfPropertiesWritten++;
}
if (userData != null && userData.Length > 0)
{
numberOfPropertiesWritten++;
mask |= SerializationMask.UserData;
}
writer.Write((int)mask);
writer.Write(numberOfPropertiesWritten);
if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType)
{
writer.Write(_authenticationType);
}
if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext)
{
writer.Write(_bootstrapContext as string);
}
if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType)
{
writer.Write(_nameClaimType);
}
if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType)
{
writer.Write(_roleClaimType);
}
if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel)
{
writer.Write(_label);
}
if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims)
{
writer.Write(_instanceClaims.Count);
foreach (var claim in _instanceClaims)
{
claim.WriteTo(writer);
}
}
if ((mask & SerializationMask.Actor) == SerializationMask.Actor)
{
_actor.WriteTo(writer);
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
writer.Write(userData.Length);
writer.Write(userData);
}
writer.Flush();
}
/// <summary>
/// Checks if a circular reference exists to 'this'
/// </summary>
/// <param name="subject"></param>
/// <returns></returns>
private bool IsCircular(ClaimsIdentity subject)
{
if (ReferenceEquals(this, subject))
{
return true;
}
ClaimsIdentity currSubject = subject;
while (currSubject.Actor != null)
{
if (ReferenceEquals(this, currSubject.Actor))
{
return true;
}
currSubject = currSubject.Actor;
}
return false;
}
[OnSerializing]
private void OnSerializingMethod(StreamingContext context)
{
if (this is ISerializable)
{
return;
}
_serializedNameType = _nameClaimType;
_serializedRoleType = _roleClaimType;
if (_instanceClaims != null && _instanceClaims.Count > 0)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_Serialization); // BinaryFormatter would be needed
}
}
[OnDeserialized]
private void OnDeserializedMethod(StreamingContext context)
{
if (this is ISerializable)
{
return;
}
_nameClaimType = string.IsNullOrEmpty(_serializedNameType) ? DefaultNameClaimType : _serializedNameType;
_roleClaimType = string.IsNullOrEmpty(_serializedRoleType) ? DefaultRoleClaimType : _serializedRoleType;
}
[OnDeserializing]
private void OnDeserializingMethod(StreamingContext context)
{
if (this is ISerializable)
return;
_instanceClaims = new List<Claim>();
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the serialization data for the ClaimsIdentity
/// </summary>
/// <param name="info">The serialization information stream to write to. Satisfies ISerializable contract.</param>
/// <param name="context">Context for serialization. Can be null.</param>
/// <exception cref="ArgumentNullException">Thrown if the info parameter is null.</exception>
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (null == info)
{
throw new ArgumentNullException(nameof(info));
}
const string Version = "1.0";
info.AddValue(VersionKey, Version);
if (!string.IsNullOrEmpty(_authenticationType))
{
info.AddValue(AuthenticationTypeKey, _authenticationType);
}
info.AddValue(NameClaimTypeKey, _nameClaimType);
info.AddValue(RoleClaimTypeKey, _roleClaimType);
if (!string.IsNullOrEmpty(_label))
{
info.AddValue(LabelKey, _label);
}
// actor
if (_actor != null || _bootstrapContext != null || (_instanceClaims != null && _instanceClaims.Count > 0))
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_Serialization); // BinaryFormatter needed
}
}
private void Deserialize(SerializationInfo info, StreamingContext context, bool useContext)
{
if (null == info)
{
throw new ArgumentNullException(nameof(info));
}
SerializationInfoEnumerator enumerator = info.GetEnumerator();
while (enumerator.MoveNext())
{
switch (enumerator.Name)
{
case VersionKey:
string version = info.GetString(VersionKey);
break;
case AuthenticationTypeKey:
_authenticationType = info.GetString(AuthenticationTypeKey);
break;
case NameClaimTypeKey:
_nameClaimType = info.GetString(NameClaimTypeKey);
break;
case RoleClaimTypeKey:
_roleClaimType = info.GetString(RoleClaimTypeKey);
break;
case LabelKey:
_label = info.GetString(LabelKey);
break;
default:
// Ignore other fields for forward compatability.
break;
}
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes the launch specification for one or more Spot instances.
/// </summary>
public partial class SpotFleetLaunchSpecification
{
private string _addressingType;
private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>();
private bool? _ebsOptimized;
private IamInstanceProfileSpecification _iamInstanceProfile;
private string _imageId;
private InstanceType _instanceType;
private string _kernelId;
private string _keyName;
private SpotFleetMonitoring _monitoring;
private List<InstanceNetworkInterfaceSpecification> _networkInterfaces = new List<InstanceNetworkInterfaceSpecification>();
private SpotPlacement _placement;
private string _ramdiskId;
private List<GroupIdentifier> _securityGroups = new List<GroupIdentifier>();
private string _spotPrice;
private string _subnetId;
private string _userData;
private double? _weightedCapacity;
/// <summary>
/// Gets and sets the property AddressingType.
/// <para>
/// Deprecated.
/// </para>
/// </summary>
public string AddressingType
{
get { return this._addressingType; }
set { this._addressingType = value; }
}
// Check to see if AddressingType property is set
internal bool IsSetAddressingType()
{
return this._addressingType != null;
}
/// <summary>
/// Gets and sets the property BlockDeviceMappings.
/// <para>
/// One or more block device mapping entries.
/// </para>
/// </summary>
public List<BlockDeviceMapping> BlockDeviceMappings
{
get { return this._blockDeviceMappings; }
set { this._blockDeviceMappings = value; }
}
// Check to see if BlockDeviceMappings property is set
internal bool IsSetBlockDeviceMappings()
{
return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property EbsOptimized.
/// <para>
/// Indicates whether the instances are optimized for EBS I/O. This optimization provides
/// dedicated throughput to Amazon EBS and an optimized configuration stack to provide
/// optimal EBS I/O performance. This optimization isn't available with all instance types.
/// Additional usage charges apply when using an EBS Optimized instance.
/// </para>
///
/// <para>
/// Default: <code>false</code>
/// </para>
/// </summary>
public bool EbsOptimized
{
get { return this._ebsOptimized.GetValueOrDefault(); }
set { this._ebsOptimized = value; }
}
// Check to see if EbsOptimized property is set
internal bool IsSetEbsOptimized()
{
return this._ebsOptimized.HasValue;
}
/// <summary>
/// Gets and sets the property IamInstanceProfile.
/// <para>
/// The IAM instance profile.
/// </para>
/// </summary>
public IamInstanceProfileSpecification IamInstanceProfile
{
get { return this._iamInstanceProfile; }
set { this._iamInstanceProfile = value; }
}
// Check to see if IamInstanceProfile property is set
internal bool IsSetIamInstanceProfile()
{
return this._iamInstanceProfile != null;
}
/// <summary>
/// Gets and sets the property ImageId.
/// <para>
/// The ID of the AMI.
/// </para>
/// </summary>
public string ImageId
{
get { return this._imageId; }
set { this._imageId = value; }
}
// Check to see if ImageId property is set
internal bool IsSetImageId()
{
return this._imageId != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type.
/// </para>
/// </summary>
public InstanceType InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property KernelId.
/// <para>
/// The ID of the kernel.
/// </para>
/// </summary>
public string KernelId
{
get { return this._kernelId; }
set { this._kernelId = value; }
}
// Check to see if KernelId property is set
internal bool IsSetKernelId()
{
return this._kernelId != null;
}
/// <summary>
/// Gets and sets the property KeyName.
/// <para>
/// The name of the key pair.
/// </para>
/// </summary>
public string KeyName
{
get { return this._keyName; }
set { this._keyName = value; }
}
// Check to see if KeyName property is set
internal bool IsSetKeyName()
{
return this._keyName != null;
}
/// <summary>
/// Gets and sets the property Monitoring.
/// <para>
/// Enable or disable monitoring for the instances.
/// </para>
/// </summary>
public SpotFleetMonitoring Monitoring
{
get { return this._monitoring; }
set { this._monitoring = value; }
}
// Check to see if Monitoring property is set
internal bool IsSetMonitoring()
{
return this._monitoring != null;
}
/// <summary>
/// Gets and sets the property NetworkInterfaces.
/// <para>
/// One or more network interfaces.
/// </para>
/// </summary>
public List<InstanceNetworkInterfaceSpecification> NetworkInterfaces
{
get { return this._networkInterfaces; }
set { this._networkInterfaces = value; }
}
// Check to see if NetworkInterfaces property is set
internal bool IsSetNetworkInterfaces()
{
return this._networkInterfaces != null && this._networkInterfaces.Count > 0;
}
/// <summary>
/// Gets and sets the property Placement.
/// <para>
/// The placement information.
/// </para>
/// </summary>
public SpotPlacement Placement
{
get { return this._placement; }
set { this._placement = value; }
}
// Check to see if Placement property is set
internal bool IsSetPlacement()
{
return this._placement != null;
}
/// <summary>
/// Gets and sets the property RamdiskId.
/// <para>
/// The ID of the RAM disk.
/// </para>
/// </summary>
public string RamdiskId
{
get { return this._ramdiskId; }
set { this._ramdiskId = value; }
}
// Check to see if RamdiskId property is set
internal bool IsSetRamdiskId()
{
return this._ramdiskId != null;
}
/// <summary>
/// Gets and sets the property SecurityGroups.
/// <para>
/// One or more security groups. When requesting instances in a VPC, you must specify
/// the IDs of the security groups. When requesting instances in EC2-Classic, you can
/// specify the names or the IDs of the security groups.
/// </para>
/// </summary>
public List<GroupIdentifier> SecurityGroups
{
get { return this._securityGroups; }
set { this._securityGroups = value; }
}
// Check to see if SecurityGroups property is set
internal bool IsSetSecurityGroups()
{
return this._securityGroups != null && this._securityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property SpotPrice.
/// <para>
/// The bid price per unit hour for the specified instance type. If this value is not
/// specified, the default is the Spot bid price specified for the fleet. To determine
/// the bid price per unit hour, divide the Spot bid price by the value of <code>WeightedCapacity</code>.
/// </para>
/// </summary>
public string SpotPrice
{
get { return this._spotPrice; }
set { this._spotPrice = value; }
}
// Check to see if SpotPrice property is set
internal bool IsSetSpotPrice()
{
return this._spotPrice != null;
}
/// <summary>
/// Gets and sets the property SubnetId.
/// <para>
/// The ID of the subnet in which to launch the instances.
/// </para>
/// </summary>
public string SubnetId
{
get { return this._subnetId; }
set { this._subnetId = value; }
}
// Check to see if SubnetId property is set
internal bool IsSetSubnetId()
{
return this._subnetId != null;
}
/// <summary>
/// Gets and sets the property UserData.
/// <para>
/// The Base64-encoded MIME user data to make available to the instances.
/// </para>
/// </summary>
public string UserData
{
get { return this._userData; }
set { this._userData = value; }
}
// Check to see if UserData property is set
internal bool IsSetUserData()
{
return this._userData != null;
}
/// <summary>
/// Gets and sets the property WeightedCapacity.
/// <para>
/// The number of units provided by the specified instance type. These are the same units
/// that you chose to set the target capacity in terms (instances or a performance characteristic
/// such as vCPUs, memory, or I/O).
/// </para>
///
/// <para>
/// If the target capacity divided by this value is not a whole number, we round the number
/// of instances to the next whole number. If this value is not specified, the default
/// is 1.
/// </para>
/// </summary>
public double WeightedCapacity
{
get { return this._weightedCapacity.GetValueOrDefault(); }
set { this._weightedCapacity = value; }
}
// Check to see if WeightedCapacity property is set
internal bool IsSetWeightedCapacity()
{
return this._weightedCapacity.HasValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Examine;
using Examine.Search;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.Logging;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Runtime;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Infrastructure.HostedServices;
using Umbraco.Cms.Infrastructure.Search;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Examine
{
/// <summary>
/// Indexing handler for Examine indexes
/// </summary>
internal class ExamineUmbracoIndexingHandler : IUmbracoIndexingHandler
{
// the default enlist priority is 100
// enlist with a lower priority to ensure that anything "default" runs after us
// but greater that SafeXmlReaderWriter priority which is 60
private const int EnlistPriority = 80;
private readonly IMainDom _mainDom;
private readonly ILogger<ExamineUmbracoIndexingHandler> _logger;
private readonly IProfilingLogger _profilingLogger;
private readonly IScopeProvider _scopeProvider;
private readonly IExamineManager _examineManager;
private readonly IBackgroundTaskQueue _backgroundTaskQueue;
private readonly IContentValueSetBuilder _contentValueSetBuilder;
private readonly IPublishedContentValueSetBuilder _publishedContentValueSetBuilder;
private readonly IValueSetBuilder<IMedia> _mediaValueSetBuilder;
private readonly IValueSetBuilder<IMember> _memberValueSetBuilder;
private readonly Lazy<bool> _enabled;
public ExamineUmbracoIndexingHandler(
IMainDom mainDom,
ILogger<ExamineUmbracoIndexingHandler> logger,
IProfilingLogger profilingLogger,
IScopeProvider scopeProvider,
IExamineManager examineManager,
IBackgroundTaskQueue backgroundTaskQueue,
IContentValueSetBuilder contentValueSetBuilder,
IPublishedContentValueSetBuilder publishedContentValueSetBuilder,
IValueSetBuilder<IMedia> mediaValueSetBuilder,
IValueSetBuilder<IMember> memberValueSetBuilder)
{
_mainDom = mainDom;
_logger = logger;
_profilingLogger = profilingLogger;
_scopeProvider = scopeProvider;
_examineManager = examineManager;
_backgroundTaskQueue = backgroundTaskQueue;
_contentValueSetBuilder = contentValueSetBuilder;
_publishedContentValueSetBuilder = publishedContentValueSetBuilder;
_mediaValueSetBuilder = mediaValueSetBuilder;
_memberValueSetBuilder = memberValueSetBuilder;
_enabled = new Lazy<bool>(IsEnabled);
}
/// <summary>
/// Used to lazily check if Examine Index handling is enabled
/// </summary>
/// <returns></returns>
private bool IsEnabled()
{
//let's deal with shutting down Examine with MainDom
var examineShutdownRegistered = _mainDom.Register(release: () =>
{
using (_profilingLogger.TraceDuration<ExamineUmbracoIndexingHandler>("Examine shutting down"))
{
_examineManager.Dispose();
}
});
if (!examineShutdownRegistered)
{
_logger.LogInformation("Examine shutdown not registered, this AppDomain is not the MainDom, Examine will be disabled");
//if we could not register the shutdown examine ourselves, it means we are not maindom! in this case all of examine should be disabled!
Suspendable.ExamineEvents.SuspendIndexers(_logger);
return false; //exit, do not continue
}
_logger.LogDebug("Examine shutdown registered with MainDom");
var registeredIndexers = _examineManager.Indexes.OfType<IUmbracoIndex>().Count(x => x.EnableDefaultEventHandler);
_logger.LogInformation("Adding examine event handlers for {RegisteredIndexers} index providers.", registeredIndexers);
// don't bind event handlers if we're not suppose to listen
if (registeredIndexers == 0)
{
return false;
}
return true;
}
/// <inheritdoc />
public bool Enabled => _enabled.Value;
/// <inheritdoc />
public void DeleteIndexForEntity(int entityId, bool keepIfUnpublished)
{
var actions = DeferedActions.Get(_scopeProvider);
if (actions != null)
{
actions.Add(new DeferedDeleteIndex(this, entityId, keepIfUnpublished));
}
else
{
DeferedDeleteIndex.Execute(this, entityId, keepIfUnpublished);
}
}
/// <inheritdoc />
public void DeleteIndexForEntities(IReadOnlyCollection<int> entityIds, bool keepIfUnpublished)
{
var actions = DeferedActions.Get(_scopeProvider);
if (actions != null)
{
actions.Add(new DeferedDeleteIndex(this, entityIds, keepIfUnpublished));
}
else
{
DeferedDeleteIndex.Execute(this, entityIds, keepIfUnpublished);
}
}
/// <inheritdoc />
public void ReIndexForContent(IContent sender, bool isPublished)
{
var actions = DeferedActions.Get(_scopeProvider);
if (actions != null)
{
actions.Add(new DeferedReIndexForContent(_backgroundTaskQueue, this, sender, isPublished));
}
else
{
DeferedReIndexForContent.Execute(_backgroundTaskQueue, this, sender, isPublished);
}
}
/// <inheritdoc />
public void ReIndexForMedia(IMedia sender, bool isPublished)
{
var actions = DeferedActions.Get(_scopeProvider);
if (actions != null)
{
actions.Add(new DeferedReIndexForMedia(_backgroundTaskQueue, this, sender, isPublished));
}
else
{
DeferedReIndexForMedia.Execute(_backgroundTaskQueue, this, sender, isPublished);
}
}
/// <inheritdoc />
public void ReIndexForMember(IMember member)
{
var actions = DeferedActions.Get(_scopeProvider);
if (actions != null)
{
actions.Add(new DeferedReIndexForMember(_backgroundTaskQueue, this, member));
}
else
{
DeferedReIndexForMember.Execute(_backgroundTaskQueue, this, member);
}
}
/// <inheritdoc />
public void DeleteDocumentsForContentTypes(IReadOnlyCollection<int> removedContentTypes)
{
const int pageSize = 500;
//Delete all content of this content/media/member type that is in any content indexer by looking up matched examine docs
foreach (var id in removedContentTypes)
{
foreach (var index in _examineManager.Indexes.OfType<IUmbracoIndex>())
{
var page = 0;
var total = long.MaxValue;
while (page * pageSize < total)
{
//paging with examine, see https://shazwazza.com/post/paging-with-examine/
var results = index.Searcher
.CreateQuery()
.Field("nodeType", id.ToInvariantString())
.Execute(QueryOptions.SkipTake(page * pageSize, pageSize));
total = results.TotalItemCount;
foreach (ISearchResult item in results)
{
if (int.TryParse(item.Id, NumberStyles.Integer, CultureInfo.InvariantCulture, out int contentId))
{
DeleteIndexForEntity(contentId, false);
}
}
page++;
}
}
}
}
#region Deferred Actions
private class DeferedActions
{
private readonly List<DeferedAction> _actions = new List<DeferedAction>();
public static DeferedActions Get(IScopeProvider scopeProvider)
{
IScopeContext scopeContext = scopeProvider.Context;
return scopeContext?.Enlist("examineEvents",
() => new DeferedActions(), // creator
(completed, actions) => // action
{
if (completed)
{
actions.Execute();
}
}, EnlistPriority);
}
public void Add(DeferedAction action) => _actions.Add(action);
private void Execute()
{
foreach (DeferedAction action in _actions)
{
action.Execute();
}
}
}
/// <summary>
/// An action that will execute at the end of the Scope being completed
/// </summary>
private abstract class DeferedAction
{
public virtual void Execute()
{ }
}
/// <summary>
/// Re-indexes an <see cref="IContent"/> item on a background thread
/// </summary>
private class DeferedReIndexForContent : DeferedAction
{
private readonly IBackgroundTaskQueue _backgroundTaskQueue;
private readonly ExamineUmbracoIndexingHandler _examineUmbracoIndexingHandler;
private readonly IContent _content;
private readonly bool _isPublished;
public DeferedReIndexForContent(IBackgroundTaskQueue backgroundTaskQueue, ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IContent content, bool isPublished)
{
_backgroundTaskQueue = backgroundTaskQueue;
_examineUmbracoIndexingHandler = examineUmbracoIndexingHandler;
_content = content;
_isPublished = isPublished;
}
public override void Execute() => Execute(_backgroundTaskQueue, _examineUmbracoIndexingHandler, _content, _isPublished);
public static void Execute(IBackgroundTaskQueue backgroundTaskQueue, ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IContent content, bool isPublished)
=> backgroundTaskQueue.QueueBackgroundWorkItem(cancellationToken =>
{
using IScope scope = examineUmbracoIndexingHandler._scopeProvider.CreateScope(autoComplete: true);
// for content we have a different builder for published vs unpublished
// we don't want to build more value sets than is needed so we'll lazily build 2 one for published one for non-published
var builders = new Dictionary<bool, Lazy<List<ValueSet>>>
{
[true] = new Lazy<List<ValueSet>>(() => examineUmbracoIndexingHandler._publishedContentValueSetBuilder.GetValueSets(content).ToList()),
[false] = new Lazy<List<ValueSet>>(() => examineUmbracoIndexingHandler._contentValueSetBuilder.GetValueSets(content).ToList())
};
// This is only for content - so only index items for IUmbracoContentIndex (to exlude members)
foreach (IUmbracoIndex index in examineUmbracoIndexingHandler._examineManager.Indexes.OfType<IUmbracoContentIndex>()
//filter the indexers
.Where(x => isPublished || !x.PublishedValuesOnly)
.Where(x => x.EnableDefaultEventHandler))
{
if (cancellationToken.IsCancellationRequested)
{
return Task.CompletedTask;
}
List<ValueSet> valueSet = builders[index.PublishedValuesOnly].Value;
index.IndexItems(valueSet);
}
return Task.CompletedTask;
});
}
/// <summary>
/// Re-indexes an <see cref="IMedia"/> item on a background thread
/// </summary>
private class DeferedReIndexForMedia : DeferedAction
{
private readonly IBackgroundTaskQueue _backgroundTaskQueue;
private readonly ExamineUmbracoIndexingHandler _examineUmbracoIndexingHandler;
private readonly IMedia _media;
private readonly bool _isPublished;
public DeferedReIndexForMedia(IBackgroundTaskQueue backgroundTaskQueue, ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IMedia media, bool isPublished)
{
_backgroundTaskQueue = backgroundTaskQueue;
_examineUmbracoIndexingHandler = examineUmbracoIndexingHandler;
_media = media;
_isPublished = isPublished;
}
public override void Execute() => Execute(_backgroundTaskQueue, _examineUmbracoIndexingHandler, _media, _isPublished);
public static void Execute(IBackgroundTaskQueue backgroundTaskQueue, ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IMedia media, bool isPublished) =>
// perform the ValueSet lookup on a background thread
backgroundTaskQueue.QueueBackgroundWorkItem(cancellationToken =>
{
using IScope scope = examineUmbracoIndexingHandler._scopeProvider.CreateScope(autoComplete: true);
var valueSet = examineUmbracoIndexingHandler._mediaValueSetBuilder.GetValueSets(media).ToList();
// This is only for content - so only index items for IUmbracoContentIndex (to exlude members)
foreach (IUmbracoIndex index in examineUmbracoIndexingHandler._examineManager.Indexes.OfType<IUmbracoContentIndex>()
//filter the indexers
.Where(x => isPublished || !x.PublishedValuesOnly)
.Where(x => x.EnableDefaultEventHandler))
{
index.IndexItems(valueSet);
}
return Task.CompletedTask;
});
}
/// <summary>
/// Re-indexes an <see cref="IMember"/> item on a background thread
/// </summary>
private class DeferedReIndexForMember : DeferedAction
{
private readonly ExamineUmbracoIndexingHandler _examineUmbracoIndexingHandler;
private readonly IMember _member;
private readonly IBackgroundTaskQueue _backgroundTaskQueue;
public DeferedReIndexForMember(IBackgroundTaskQueue backgroundTaskQueue, ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IMember member)
{
_examineUmbracoIndexingHandler = examineUmbracoIndexingHandler;
_member = member;
_backgroundTaskQueue = backgroundTaskQueue;
}
public override void Execute() => Execute(_backgroundTaskQueue, _examineUmbracoIndexingHandler, _member);
public static void Execute(IBackgroundTaskQueue backgroundTaskQueue, ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IMember member) =>
// perform the ValueSet lookup on a background thread
backgroundTaskQueue.QueueBackgroundWorkItem(cancellationToken =>
{
using IScope scope = examineUmbracoIndexingHandler._scopeProvider.CreateScope(autoComplete: true);
var valueSet = examineUmbracoIndexingHandler._memberValueSetBuilder.GetValueSets(member).ToList();
// only process for IUmbracoMemberIndex (not content indexes)
foreach (IUmbracoIndex index in examineUmbracoIndexingHandler._examineManager.Indexes.OfType<IUmbracoMemberIndex>()
//filter the indexers
.Where(x => x.EnableDefaultEventHandler))
{
index.IndexItems(valueSet);
}
return Task.CompletedTask;
});
}
private class DeferedDeleteIndex : DeferedAction
{
private readonly ExamineUmbracoIndexingHandler _examineUmbracoIndexingHandler;
private readonly int _id;
private readonly IReadOnlyCollection<int> _ids;
private readonly bool _keepIfUnpublished;
public DeferedDeleteIndex(ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, int id, bool keepIfUnpublished)
{
_examineUmbracoIndexingHandler = examineUmbracoIndexingHandler;
_id = id;
_keepIfUnpublished = keepIfUnpublished;
}
public DeferedDeleteIndex(ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IReadOnlyCollection<int> ids, bool keepIfUnpublished)
{
_examineUmbracoIndexingHandler = examineUmbracoIndexingHandler;
_ids = ids;
_keepIfUnpublished = keepIfUnpublished;
}
public override void Execute()
{
if (_ids is null)
{
Execute(_examineUmbracoIndexingHandler, _id, _keepIfUnpublished);
}
else
{
Execute(_examineUmbracoIndexingHandler, _ids, _keepIfUnpublished);
}
}
public static void Execute(ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, int id, bool keepIfUnpublished)
{
foreach (var index in examineUmbracoIndexingHandler._examineManager.Indexes.OfType<IUmbracoIndex>()
.Where(x => x.PublishedValuesOnly || !keepIfUnpublished)
.Where(x => x.EnableDefaultEventHandler))
{
index.DeleteFromIndex(id.ToString(CultureInfo.InvariantCulture));
}
}
public static void Execute(ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IReadOnlyCollection<int> ids, bool keepIfUnpublished)
{
foreach (var index in examineUmbracoIndexingHandler._examineManager.Indexes.OfType<IUmbracoIndex>()
.Where(x => x.PublishedValuesOnly || !keepIfUnpublished)
.Where(x => x.EnableDefaultEventHandler))
{
index.DeleteFromIndex(ids.Select(x => x.ToString(CultureInfo.InvariantCulture)));
}
}
}
#endregion
}
}
| |
using Xunit;
using System;
using System.IO;
using System.Diagnostics;
using System.Management.Automation;
namespace PSTests
{
[Collection("AssemblyLoadContext")]
public static class PlatformTests
{
[Fact]
public static void TestIsCoreCLR()
{
Assert.True(Platform.IsCoreCLR);
}
[Fact]
public static void TestGetUserName()
{
var startInfo = new ProcessStartInfo
{
FileName = @"/usr/bin/env",
Arguments = "whoami",
RedirectStandardOutput = true,
UseShellExecute = false
};
using (Process process = Process.Start(startInfo))
{
// Get output of call to whoami without trailing newline
string username = process.StandardOutput.ReadToEnd().Trim();
process.WaitForExit();
// The process should return an exit code of 0 on success
Assert.Equal(0, process.ExitCode);
// It should be the same as what our platform code returns
Assert.Equal(username, Platform.Unix.UserName());
}
}
[Fact(Skip="Bad arguments for OS X")]
public static void TestGetMachineName()
{
var startInfo = new ProcessStartInfo
{
FileName = @"/usr/bin/env",
Arguments = "hostname",
RedirectStandardOutput = true,
UseShellExecute = false
};
using (Process process = Process.Start(startInfo))
{
// Get output of call to hostname without trailing newline
string hostname = process.StandardOutput.ReadToEnd().Trim();
process.WaitForExit();
// The process should return an exit code of 0 on success
Assert.Equal(0, process.ExitCode);
// It should be the same as what our platform code returns
Assert.Equal(hostname, System.Management.Automation.Environment.MachineName);
}
}
[Fact(Skip="Bad arguments for OS X")]
public static void TestGetFQDN()
{
var startInfo = new ProcessStartInfo
{
FileName = @"/usr/bin/env",
Arguments = "hostname --fqdn",
RedirectStandardOutput = true,
UseShellExecute = false
};
using (Process process = Process.Start(startInfo))
{
// Get output of call to hostname without trailing newline
string hostname = process.StandardOutput.ReadToEnd().Trim();
process.WaitForExit();
// The process should return an exit code of 0 on success
Assert.Equal(0, process.ExitCode);
// It should be the same as what our platform code returns
Assert.Equal(hostname, Platform.NonWindowsGetHostName());
}
}
[Fact(Skip="Bad arguments for OS X")]
public static void TestGetDomainName()
{
var startInfo = new ProcessStartInfo
{
FileName = @"/usr/bin/env",
Arguments = "dnsdomainname",
RedirectStandardOutput = true,
UseShellExecute = false
};
using (Process process = Process.Start(startInfo))
{
// Get output of call to hostname without trailing newline
string domainName = process.StandardOutput.ReadToEnd().Trim();
process.WaitForExit();
// The process should return an exit code of 0 on success
Assert.Equal(0, process.ExitCode);
// It should be the same as what our platform code returns
Assert.Equal(domainName, Platform.NonWindowsGetDomainName());
}
}
[Fact]
public static void TestIsExecutable()
{
Assert.True(Platform.NonWindowsIsExecutable("/bin/ls"));
}
[Fact]
public static void TestIsNotExecutable()
{
Assert.False(Platform.NonWindowsIsExecutable("/etc/hosts"));
}
[Fact]
public static void TestDirectoryIsNotExecutable()
{
Assert.False(Platform.NonWindowsIsExecutable("/etc"));
}
[Fact]
public static void TestFileIsNotHardLink()
{
string path = @"/tmp/nothardlink";
if (File.Exists(path))
{
File.Delete(path);
}
File.Create(path);
FileSystemInfo fd = new FileInfo(path);
// Since this is the only reference to the file, it is not considered a
// hardlink by our API (though all files are hardlinks on Linux)
Assert.False(Platform.NonWindowsIsHardLink(fd));
File.Delete(path);
}
[Fact]
public static void TestFileIsHardLink()
{
string path = @"/tmp/originallink";
if (File.Exists(path))
{
File.Delete(path);
}
File.Create(path);
string link = "/tmp/newlink";
if (File.Exists(link))
{
File.Delete(link);
}
var startInfo = new ProcessStartInfo
{
FileName = @"/usr/bin/env",
Arguments = "ln " + path + " " + link,
RedirectStandardOutput = true,
UseShellExecute = false
};
using (Process process = Process.Start(startInfo))
{
process.WaitForExit();
Assert.Equal(0, process.ExitCode);
}
// Since there are now two references to the file, both are considered
// hardlinks by our API (though all files are hardlinks on Linux)
FileSystemInfo fd = new FileInfo(path);
Assert.True(Platform.NonWindowsIsHardLink(fd));
fd = new FileInfo(link);
Assert.True(Platform.NonWindowsIsHardLink(fd));
File.Delete(path);
File.Delete(link);
}
[Fact]
public static void TestDirectoryIsNotHardLink()
{
string path = @"/tmp";
FileSystemInfo fd = new FileInfo(path);
Assert.False(Platform.NonWindowsIsHardLink(fd));
}
[Fact]
public static void TestNonExistentIsHardLink()
{
// A file that should *never* exist on a test machine:
string path = @"/tmp/ThisFileShouldNotExistOnTestMachines";
// If the file exists, then there's a larger issue that needs to be looked at
Assert.False(File.Exists(path));
// Convert `path` string to FileSystemInfo data type. And now, it should return true
FileSystemInfo fd = new FileInfo(path);
Assert.False(Platform.NonWindowsIsHardLink(fd));
}
[Fact]
public static void TestFileIsSymLink()
{
string path = @"/tmp/originallink";
if (File.Exists(path))
{
File.Delete(path);
}
File.Create(path);
string link = "/tmp/newlink";
if (File.Exists(link))
{
File.Delete(link);
}
var startInfo = new ProcessStartInfo
{
FileName = @"/usr/bin/env",
Arguments = "ln -s " + path + " " + link,
RedirectStandardOutput = true,
UseShellExecute = false
};
using (Process process = Process.Start(startInfo))
{
process.WaitForExit();
Assert.Equal(0, process.ExitCode);
}
FileSystemInfo fd = new FileInfo(path);
Assert.False(Platform.NonWindowsIsSymLink(fd));
fd = new FileInfo(link);
Assert.True(Platform.NonWindowsIsSymLink(fd));
File.Delete(path);
File.Delete(link);
}
}
}
| |
// 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;
public struct ValX0 { }
public struct ValY0 { }
public struct ValX1<T> { }
public struct ValY1<T> { }
public struct ValX2<T, U> { }
public struct ValY2<T, U> { }
public struct ValX3<T, U, V> { }
public struct ValY3<T, U, V> { }
public class RefX0 { }
public class RefY0 { }
public class RefX1<T> { }
public class RefY1<T> { }
public class RefX2<T, U> { }
public class RefY2<T, U> { }
public class RefX3<T, U, V> { }
public class RefY3<T, U, V> { }
public interface IGen<T>
{
void _Init(T fld1);
bool InstVerify(System.Type t1);
}
public interface IGenSub<T> : IGen<T> { }
public struct GenInt : IGenSub<int>
{
int Fld1;
public void _Init(int fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<int>));
}
return result;
}
}
public struct GenDouble : IGenSub<double>
{
double Fld1;
public void _Init(double fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<double>));
}
return result;
}
}
public struct GenString : IGenSub<String>
{
string Fld1;
public void _Init(string fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<string>));
}
return result;
}
}
public struct GenObject : IGenSub<object>
{
object Fld1;
public void _Init(object fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<object>));
}
return result;
}
}
public struct GenGuid : IGenSub<Guid>
{
Guid Fld1;
public void _Init(Guid fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<Guid>));
}
return result;
}
}
public struct GenConstructedReference : IGenSub<RefX1<int>>
{
RefX1<int> Fld1;
public void _Init(RefX1<int> fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<RefX1<int>>));
}
return result;
}
}
public struct GenConstructedValue : IGenSub<ValX1<string>>
{
ValX1<string> Fld1;
public void _Init(ValX1<string> fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<ValX1<string>>));
}
return result;
}
}
public struct Gen1DIntArray : IGenSub<int[]>
{
int[] Fld1;
public void _Init(int[] fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<int[]>));
}
return result;
}
}
public struct Gen2DStringArray : IGenSub<string[,]>
{
string[,] Fld1;
public void _Init(string[,] fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<string[,]>));
}
return result;
}
}
public struct GenJaggedObjectArray : IGenSub<object[][]>
{
object[][] Fld1;
public void _Init(object[][] fld1)
{
Fld1 = fld1;
}
public bool InstVerify(System.Type t1)
{
bool result = true;
if (!(Fld1.GetType().Equals(t1)))
{
result = false;
Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<object[][]>));
}
return result;
}
}
public struct Test
{
public static int counter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
IGen<int> IGenInt = new GenInt();
IGenInt._Init(new int());
Eval(IGenInt.InstVerify(typeof(int)));
IGen<double> IGenDouble = new GenDouble();
IGenDouble._Init(new double());
Eval(IGenDouble.InstVerify(typeof(double)));
IGen<string> IGenString = new GenString();
IGenString._Init("string");
Eval(IGenString.InstVerify(typeof(string)));
IGen<object> IGenObject = new GenObject();
IGenObject._Init(new object());
Eval(IGenObject.InstVerify(typeof(object)));
IGen<Guid> IGenGuid = new GenGuid();
IGenGuid._Init(new Guid());
Eval(IGenGuid.InstVerify(typeof(Guid)));
IGen<RefX1<int>> IGenConstructedReference = new GenConstructedReference();
IGenConstructedReference._Init(new RefX1<int>());
Eval(IGenConstructedReference.InstVerify(typeof(RefX1<int>)));
IGen<ValX1<string>> IGenConstructedValue = new GenConstructedValue();
IGenConstructedValue._Init(new ValX1<string>());
Eval(IGenConstructedValue.InstVerify(typeof(ValX1<string>)));
IGen<int[]> IGen1DIntArray = new Gen1DIntArray();
IGen1DIntArray._Init(new int[1]);
Eval(IGen1DIntArray.InstVerify(typeof(int[])));
IGen<string[,]> IGen2DStringArray = new Gen2DStringArray();
IGen2DStringArray._Init(new string[1, 1]);
Eval(IGen2DStringArray.InstVerify(typeof(string[,])));
IGen<object[][]> IGenJaggedObjectArray = new GenJaggedObjectArray();
IGenJaggedObjectArray._Init(new object[1][]);
Eval(IGenJaggedObjectArray.InstVerify(typeof(object[][])));
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| |
//
// Copyright (c) 2017, Bianco Veigel
//
// 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.Text;
using DiscUtils.Btrfs.Base;
using DiscUtils.Btrfs.Base.Items;
using DiscUtils.Streams;
namespace DiscUtils.Btrfs
{
internal class SuperBlock : IByteArraySerializable
{
public static readonly int Length = 0x1000;
public static readonly ulong BtrfsMagic = BitConverter.ToUInt64(Encoding.ASCII.GetBytes("_BHRfS_M"),0);
/// <summary>
/// Checksum of everything past this field (from 20 to 1000)
/// </summary>
public byte[] Checksum { get; private set; }
/// <summary>
/// FS UUID
/// </summary>
public Guid FsUuid { get; private set; }
/// <summary>
/// physical address of this block (different for mirrors)
/// </summary>
public ulong PhysicalAddress { get; private set; }
/// <summary>
/// flags
/// </summary>
public ulong Flags { get; private set; }
/// <summary>
/// magic ("_BHRfS_M")
/// </summary>
public ulong Magic { get; private set; }
/// <summary>
/// generation
/// </summary>
public ulong Generation { get; private set; }
/// <summary>
/// logical address of the root tree root
/// </summary>
public ulong Root { get; private set; }
/// <summary>
/// logical address of the chunk tree root
/// </summary>
public ulong ChunkRoot { get; private set; }
/// <summary>
/// logical address of the log tree root
/// </summary>
public ulong LogRoot { get; private set; }
/// <summary>
/// log_root_transid
/// </summary>
public ulong LogRootTransId { get; private set; }
/// <summary>
/// total_bytes
/// </summary>
public ulong TotalBytes { get; private set; }
/// <summary>
/// bytes_used
/// </summary>
public ulong BytesUsed { get; private set; }
/// <summary>
/// root_dir_objectid (usually 6)
/// </summary>
public ulong RootDirObjectid { get; private set; }
/// <summary>
/// num_devices
/// </summary>
public ulong NumDevices { get; private set; }
/// <summary>
/// sectorsize
/// </summary>
public uint SectorSize { get; private set; }
/// <summary>
/// nodesize
/// </summary>
public uint NodeSize { get; private set; }
/// <summary>
/// leafsize
/// </summary>
public uint LeafSize { get; private set; }
/// <summary>
/// stripesize
/// </summary>
public uint StripeSize { get; private set; }
/// <summary>
/// chunk_root_generation
/// </summary>
public ulong ChunkRootGeneration { get; private set; }
/// <summary>
/// compat_flags
/// </summary>
public ulong CompatFlags { get; private set; }
/// <summary>
/// compat_ro_flags - only implementations that support the flags can write to the filesystem
/// </summary>
public ulong CompatRoFlags { get; private set; }
/// <summary>
/// incompat_flags - only implementations that support the flags can use the filesystem
/// </summary>
public ulong IncompatFlags { get; private set; }
/// <summary>
/// csum_type - Btrfs currently uses the CRC32c little-endian hash function with seed -1.
/// </summary>
public ChecksumType ChecksumType { get; private set; }
/// <summary>
/// root_level
/// </summary>
public byte RootLevel { get; private set; }
/// <summary>
/// chunk_root_level
/// </summary>
public byte ChunkRootLevel { get; private set; }
/// <summary>
/// log_root_level
/// </summary>
public byte LogRootLevel { get; private set; }
/// <summary>
/// label (may not contain '/' or '\\')
/// </summary>
public string Label { get; private set; }
public ChunkItem[] SystemChunkArray { get; private set; }
public int Size
{
get { return Length; }
}
public int ReadFrom(byte[] buffer, int offset)
{
Magic = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x40);
if (Magic != BtrfsMagic) return Size;
Checksum = EndianUtilities.ToByteArray(buffer, offset, 0x20);
FsUuid = EndianUtilities.ToGuidLittleEndian(buffer, offset + 0x20);
PhysicalAddress = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x30);
Flags = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x38);
Generation = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x48);
Root = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x50);
ChunkRoot = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x58);
LogRoot = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x60);
LogRootTransId = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x68);
TotalBytes = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x70);
BytesUsed = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x78);
RootDirObjectid = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x80);
NumDevices = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x88);
SectorSize = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x90);
NodeSize = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x94);
LeafSize = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x98);
StripeSize = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x9c);
ChunkRootGeneration = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0xa4);
CompatFlags = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0xac);
CompatRoFlags = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0xb4);
IncompatFlags = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0xbc);
ChecksumType = (ChecksumType)EndianUtilities.ToUInt16LittleEndian(buffer, offset + 0xc4);
RootLevel = buffer[offset + 0xc6];
ChunkRootLevel = buffer[offset + 0xc7];
LogRootLevel = buffer[offset + 0xc8];
//c9 62 DEV_ITEM data for this device
var labelData = EndianUtilities.ToByteArray(buffer, offset + 0x12b, 0x100);
int eos = Array.IndexOf(labelData, (byte) 0);
if (eos != -1)
{
Label = Encoding.UTF8.GetString(labelData, 0, eos);
}
//22b 100 reserved
var n = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0xa0);
offset += 0x32b;
var systemChunks = new List<ChunkItem>();
while (n > 0)
{
var key = new Key();
offset += key.ReadFrom(buffer, offset);
var chunkItem = new ChunkItem(key);
offset += chunkItem.ReadFrom(buffer, offset);
systemChunks.Add(chunkItem);
n = n - (uint)key.Size - (uint)chunkItem.Size;
}
SystemChunkArray = systemChunks.ToArray();
//32b 800 (n bytes valid) Contains (KEY, CHUNK_ITEM) pairs for all SYSTEM chunks. This is needed to bootstrap the mapping from logical addresses to physical.
//b2b 4d5 Currently unused
return Size;
}
public void WriteTo(byte[] buffer, int offset)
{
throw new NotImplementedException();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace OKHOSTING.ERP.Local.Mexico.Facturacion
{
/// <summary>
/// Permite converir numeros a su representacion en texto (EXPERIMENTAL)
/// </summary>
public class NumberToText
{
string resultado;
/***************************************************************************
* Ejemplo: Conversion de cantidades a letras (caso general)
* Algunas excepciones no estan consideradas. Estudie como hacerlo!!!
***************************************************************************/
/***************************************************************************
* Funcion que calcula la n-esima potencia de 10. Tanto el argumento de
* entrada (n) como el valor de retorno son de tipo int. No se controla
* la entrada de argumentos invalidos (potencias negativas, por ejemplo).
* 10**n = 10 * 10 * 10 * ... * 10 (n veces)
***************************************************************************/
protected int potencia10(int n) {
int i; /* Control de iteraciones: numero de multiplicaciones */
int pot; /* Acumulador para el resultado */
/* Verifica si n es cero, en cuyo caso guarda un 1 como resultado */
if (n == 0) {
pot = 1;
}
else {
/* Si n es distinto de cero, lleva a cabo el calculo */
pot = 10; /* El acumulador inicialmente vale 10 (n=1)
/* Este ciclo lleva a cabo el calculo, i varia desde 2 hasta n */
for (i=2; i<=n; i++)
/* Multiplica el acumulado actual por 10 */
pot = pot * 10;
}
/* Devuelve como valor de retorno el resultado obtenido (guardado en pot) */
return(pot);
}
/***************************************************************************
* Funcion que retorna el numero de digitos en la cantidad (cant) pasada
* como parametro. Se hace una iteracion, eliminando cada vez el digito de
* la derecha, e incrementando un contador (digitos). El ciclo se detiene
* cuando la cantidad es cero, es decir, se terminaron los digitos.
***************************************************************************/
protected int obtener_digitos(int cant) {
int digitos; /* Cantidad de digitos */
for (digitos=0; cant>0; digitos++)
cant = cant / 10;
return(digitos);
}
/***************************************************************************
* Funcion que extrae y retorna el digito de mas a la izquierda de una
* cantidad (cant) con digs digitos. Lo que hace es dividir la cantidad por
* la (digs-1)-esima potencia de 10. Por ej., si hay 5 digitos, se dividira
* la cantidad por 1000. Pruebelo!!!
***************************************************************************/
protected int obtener_digito_izq(int cant, int digs) {
return(cant / potencia10(digs-1));
}
/***************************************************************************
* Funcion que elimina el digito de mas a la izquierda de una cantidad
* (cant) pasada como parametro. La funcion recibe el numero de digitos
* (digs) en la cantidad y obtiene el resto de la division de la cantidad
* por la (digs-1)-esima potencia de 10. Por ej., si hay 5 digitos, se
* dividira la cantidad por 1000 y se tomara el resto. Pruebelo!!!
***************************************************************************/
protected int quitar_digito_izq(int cant, int digs) {
return(cant % potencia10(digs-1));
}
/***************************************************************************
* Funcion que obtiene la posicion decimal (centenas, decenas, unidades) de
* una cantidad con digs digitos. Esta posiciones podrian ser simples, de
* miles o de millones. Para esto, se aplica modulo 3 a digs, obteniendose
* posibles valores de 0 (centenas), 1 (unidades) y 2 (decenas). La funcion
* retorna este valor. Por ej., si la cantidad es 12500, digs valdra 5, por
* lo que se retornara un 2 que indica que la primera posicion de la
* izquierda es una posicion de decenas (en este caso, decenas de miles).
***************************************************************************/
protected int obtener_posicion_decimal(int digs) {
return(digs % 3);
}
/***************************************************************************
* Funcion que procesa un digito dig, dependiendo de su posicion pos en la
* cantidad (unidades, decenas o centenas). Para esto se emplea un switch
* que selecciona segun la posicion. Para el caso de las unidades es
* necesario ademas analizar el grupo decimal (unidades simples, miles,
* millones), para poder desplegar el texto adicional necesario.
***************************************************************************/
protected void procesar_digito(int dig, int pos, int digitos) {
int grupo; /* Grupo decimal a que pertenece el digito si es de unidades */
switch (pos) {
case 1: { /* unidades */
switch (dig) {
case 0: {printf(""); break;}
case 1: {printf("uno "); break;}
case 2: {printf("dos "); break;}
case 3: {printf("tres "); break;}
case 4: {printf("cuatro "); break;}
case 5: {printf("cinco "); break;}
case 6: {printf("seis "); break;}
case 7: {printf("siete "); break;}
case 8: {printf("ocho "); break;}
case 9: {printf("nueve "); break;}
}
/* Se estima el grupo en que se esta trabajando, para saber asi si es */
/* necesario incluir palabras como mil, millones, etc. Esto se logra */
/* dividiendo (dig-1) entre 3. Si el resultado es 0, se trata del */
/* primer grupo de tres digitos (unidades simples), si es 1 se trata */
/* del segundo (miles), 2 (millones), 3 (miles de millones). */
/* Este estudio se requiere solo en las unidades (por que?). */
grupo = (digitos-1) / 3;
switch (grupo) {
case 0: {printf("unidades\n"); break;} /* Puede cambiarse x PESOS */
case 1: {printf("mil "); break;}
case 2: {printf("millones "); break;}
case 3: {printf("mil "); break;}
}
break;
}
case 2: { /* decenas */
switch (dig) {
case 0: {printf(""); break;}
case 1: {printf("dieci"); break;}
case 2: {printf("veinte y "); break;}
case 3: {printf("treinta y "); break;}
case 4: {printf("cuarenta y "); break;}
case 5: {printf("cincuenta y "); break;}
case 6: {printf("sesenta y "); break;}
case 7: {printf("setenta y "); break;}
case 8: {printf("ochenta y "); break;}
case 9: {printf("noventa y "); break;}
}
break;
}
case 0: { /* centenas */
switch (dig) {
case 0: {printf(""); break;}
case 1: {printf("ciento "); break;}
case 2: {printf("doscientos "); break;}
case 3: {printf("trescientos "); break;}
case 4: {printf("cuatrocientos "); break;}
case 5: {printf("quinientos "); break;}
case 6: {printf("seiscientos "); break;}
case 7: {printf("setecientos "); break;}
case 8: {printf("ochocientos "); break;}
case 9: {printf("novecientos "); break;}
}
break;
}
}
}
/***************************************************************************
* Programa que convierte una cantidad numerica en su equivalente en letras.
* Solicita al usuario la cantidad en cuestion y le devuelve el equivalente.
* Existen algunas excepciones que no fueron consideradas para no complicar
* demasiado el ejemplo. Ademas, se permiten cantidades de hasta 9 digitos.
* Estudie los cambios necesarios para considerar todas las excepciones!.
***************************************************************************/
public string Convertir(int cantidad)
{
//int cantidad; /* La cantidad a convertir, dada por el usuario */
int digitos; /* Cantidad de digitos en la cantidad dada */
int dig; /* Digito con el que se esta trabajando actualmente */
int posicion; /* Indica si se esta trabajando sobre unidades, decenas o centenas */
int cant; /* Cantidad a la que se iran quitando uno a uno los digitos */
resultado = "";
/* Determina la cantidad de digitos en la cantidad */
digitos = obtener_digitos(cantidad);
/* Ciclo de procesamiento de la cantidad. En cada iteracion se trabaja con un digito. */
/* El ciclo se lleva a cabo tantas veces como digitos existen (la variable digitos se */
/* decrementa en cada iteracion, y el ciclo para cuando llega a cero). Se trabaja con */
/* una copia de la cantidad hecha en la variable cant (para no destruir la original). */
for (cant=cantidad; digitos>0; digitos--) {
/* Se obtiene en dig el digito mas a la izquierda */
dig = obtener_digito_izq(cant, digitos);
/* Se obtiene la posicion decimal del digito (unidades, decenas, centenas) */
posicion = obtener_posicion_decimal(digitos);
/* Se procesa el digito (se convierte a letras) */
procesar_digito(dig, posicion, digitos);
/* Se quita el digito de la cantidad */
cant = quitar_digito_izq(cant, digitos);
}
return resultado;
}
protected void printf(string s)
{
resultado += s;
}
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Daniel Grunwald" email="[email protected]"/>
// <version>$Revision: 3630 $</version>
// </file>
using System;
using System.Collections;
using System.Collections.Generic;
namespace ICSharpCode.SharpDevelop.Dom
{
#region ResolveResult
/// <summary>
/// The base class of all resolve results.
/// This class is used whenever an expression is not one of the special expressions
/// (having their own ResolveResult class).
/// The ResolveResult specified the location where Resolve was called (Class+Member)
/// and the type of the resolved expression.
/// </summary>
public class ResolveResult : AbstractFreezable, ICloneable
{
IClass callingClass;
IMember callingMember;
IReturnType resolvedType;
public ResolveResult(IClass callingClass, IMember callingMember, IReturnType resolvedType)
{
this.callingClass = callingClass;
this.callingMember = callingMember;
this.resolvedType = resolvedType;
}
public virtual bool IsValid {
get { return true; }
}
/// <summary>
/// Gets the class that contained the expression used to get this ResolveResult.
/// Can be null when the class is unknown.
/// </summary>
public IClass CallingClass {
get { return callingClass; }
}
/// <summary>
/// Gets the member (method or property in <see cref="CallingClass"/>) that contained the
/// expression used to get this ResolveResult.
/// Can be null when the expression was not inside a member or the member is unknown.
/// </summary>
public IMember CallingMember {
get { return callingMember; }
}
/// <summary>
/// Gets the type of the resolved expression.
/// Can be null when the type cannot be represented by a IReturnType (e.g. when the
/// expression was a namespace name).
/// </summary>
public IReturnType ResolvedType {
get { return resolvedType; }
set {
CheckBeforeMutation();
resolvedType = value;
}
}
public virtual ResolveResult Clone()
{
return new ResolveResult(callingClass, callingMember, resolvedType);
}
object ICloneable.Clone()
{
return this.Clone();
}
public virtual ArrayList GetCompletionData(IProjectContent projectContent)
{
return GetCompletionData(projectContent.Language, false);
}
protected ArrayList GetCompletionData(LanguageProperties language, bool showStatic)
{
if (resolvedType == null) return null;
ArrayList res = new ArrayList();
foreach (IMember m in MemberLookupHelper.GetAccessibleMembers(resolvedType, callingClass, language)) {
if (language.ShowMember(m, showStatic))
res.Add(m);
}
if (!showStatic && callingClass != null) {
AddExtensions(language, res, callingClass, resolvedType);
}
return res;
}
/// <summary>
/// Adds extension methods to <paramref name="res"/>.
/// </summary>
public static void AddExtensions(LanguageProperties language, ArrayList res, IClass callingClass, IReturnType resolvedType)
{
if (language == null)
throw new ArgumentNullException("language");
if (res == null)
throw new ArgumentNullException("res");
if (resolvedType == null)
throw new ArgumentNullException("resolvedType");
if (callingClass == null)
throw new ArgumentNullException("callingClass");
// convert resolvedType into direct type to speed up the IsApplicable lookups
resolvedType = resolvedType.GetDirectReturnType();
foreach (IMethodOrProperty mp in CtrlSpaceResolveHelper.FindAllExtensions(language, callingClass)) {
TryAddExtension(language, res, mp, resolvedType);
}
}
static void TryAddExtension(LanguageProperties language, ArrayList res, IMethodOrProperty ext, IReturnType resolvedType)
{
// now add the extension method if it fits the type
if (MemberLookupHelper.IsApplicable(resolvedType, ext.Parameters[0].ReturnType, ext as IMethod)) {
IMethod method = ext as IMethod;
if (method != null && method.TypeParameters.Count > 0) {
IReturnType[] typeArguments = new IReturnType[method.TypeParameters.Count];
MemberLookupHelper.InferTypeArgument(method.Parameters[0].ReturnType, resolvedType, typeArguments);
for (int i = 0; i < typeArguments.Length; i++) {
if (typeArguments[i] != null) {
ext = (IMethod)ext.CreateSpecializedMember();
ext.ReturnType = ConstructedReturnType.TranslateType(ext.ReturnType, typeArguments, true);
for (int j = 0; j < ext.Parameters.Count; ++j) {
ext.Parameters[j].ReturnType = ConstructedReturnType.TranslateType(ext.Parameters[j].ReturnType, typeArguments, true);
}
break;
}
}
}
res.Add(ext);
}
}
public virtual FilePosition GetDefinitionPosition()
{
// this is only possible on some subclasses of ResolveResult
return FilePosition.Empty;
}
/// <summary>
/// Gets if this ResolveResult represents a reference to the specified entity.
/// </summary>
public virtual bool IsReferenceTo(IEntity entity)
{
return false;
}
}
#endregion
#region MixedResolveResult
/// <summary>
/// The MixedResolveResult is used when an expression can have multiple meanings, for example
/// "Size" in a class deriving from "Control".
/// </summary>
public class MixedResolveResult : ResolveResult
{
ResolveResult primaryResult, secondaryResult;
protected override void FreezeInternal()
{
base.FreezeInternal();
primaryResult.Freeze();
secondaryResult.Freeze();
}
public ResolveResult PrimaryResult {
get {
return primaryResult;
}
}
public IEnumerable<ResolveResult> Results {
get {
yield return primaryResult;
yield return secondaryResult;
}
}
public TypeResolveResult TypeResult {
get {
if (primaryResult is TypeResolveResult)
return (TypeResolveResult)primaryResult;
if (secondaryResult is TypeResolveResult)
return (TypeResolveResult)secondaryResult;
return null;
}
}
public MixedResolveResult(ResolveResult primaryResult, ResolveResult secondaryResult)
: base(primaryResult.CallingClass, primaryResult.CallingMember, primaryResult.ResolvedType)
{
if (primaryResult == null)
throw new ArgumentNullException("primaryResult");
if (secondaryResult == null)
throw new ArgumentNullException("secondaryResult");
this.primaryResult = primaryResult;
this.secondaryResult = secondaryResult;
}
public override FilePosition GetDefinitionPosition()
{
return primaryResult.GetDefinitionPosition();
}
public override ArrayList GetCompletionData(IProjectContent projectContent)
{
ArrayList result = primaryResult.GetCompletionData(projectContent);
ArrayList result2 = secondaryResult.GetCompletionData(projectContent);
if (result == null) return result2;
if (result2 == null) return result;
foreach (object o in result2) {
if (!result.Contains(o))
result.Add(o);
}
return result;
}
public override ResolveResult Clone()
{
return new MixedResolveResult(primaryResult.Clone(), secondaryResult.Clone());
}
public override bool IsReferenceTo(IEntity entity)
{
return primaryResult.IsReferenceTo(entity) || secondaryResult.IsReferenceTo(entity);
}
}
#endregion
#region LocalResolveResult
/// <summary>
/// The LocalResolveResult is used when an expression was a simple local variable
/// or parameter.
/// </summary>
/// <remarks>
/// For fields in the current class, a MemberResolveResult is used, so "e" is not always
/// a LocalResolveResult.
/// </remarks>
public class LocalResolveResult : ResolveResult
{
IField field;
public LocalResolveResult(IMember callingMember, IField field)
: base(callingMember.DeclaringType, callingMember, field.ReturnType)
{
if (callingMember == null)
throw new ArgumentNullException("callingMember");
if (field == null)
throw new ArgumentNullException("field");
this.field = field;
if (!field.IsParameter && !field.IsLocalVariable) {
throw new ArgumentException("the field must either be a local variable-field or a parameter-field");
}
}
public LocalResolveResult(IMember callingMember, IParameter parameter)
: this(callingMember, new DefaultField.ParameterField(parameter.ReturnType, parameter.Name, parameter.Region, callingMember.DeclaringType))
{
}
public override ResolveResult Clone()
{
return new LocalResolveResult(this.CallingMember, this.Field);
}
/// <summary>
/// Gets the field representing the local variable.
/// </summary>
public IField Field {
get { return field; }
}
/// <summary>
/// Gets if the variable is a parameter (true) or a local variable (false).
/// </summary>
public bool IsParameter {
get { return field.IsParameter; }
}
/// <summary>
/// Gets the name of the parameter/local variable.
/// </summary>
public string VariableName {
get { return field.Name; }
}
/// <summary>
/// Gets th position where the parameter/local variable is declared.
/// </summary>
public DomRegion VariableDefinitionRegion {
get { return field.Region; }
}
public override FilePosition GetDefinitionPosition()
{
ICompilationUnit cu = this.CallingClass.CompilationUnit;
if (cu == null) {
return FilePosition.Empty;
}
if (cu.FileName == null || cu.FileName.Length == 0) {
return FilePosition.Empty;
}
DomRegion reg = field.Region;
if (!reg.IsEmpty) {
return new FilePosition(cu.FileName, reg.BeginLine, reg.BeginColumn);
} else {
LoggingService.Warn("GetDefinitionPosition: field.Region is empty");
return new FilePosition(cu.FileName);
}
}
public override bool IsReferenceTo(IEntity entity)
{
IField f = entity as IField;
if (f != null && (f.IsLocalVariable || f.IsParameter)) {
return field.Region.BeginLine == f.Region.BeginLine
&& field.Region.BeginColumn == f.Region.BeginColumn;
}
return base.IsReferenceTo(entity);
}
}
#endregion
#region NamespaceResolveResult
/// <summary>
/// The NamespaceResolveResult is used when an expression was the name of a namespace.
/// <see cref="ResolveResult.ResolvedType"/> is always null on a NamespaceReturnType.
/// </summary>
/// <example>
/// Example expressions:
/// "System"
/// "System.Windows.Forms"
/// "using Win = System.Windows; Win.Forms"
/// </example>
public class NamespaceResolveResult : ResolveResult
{
string name;
public NamespaceResolveResult(IClass callingClass, IMember callingMember, string name)
: base(callingClass, callingMember, null)
{
if (name == null)
throw new ArgumentNullException("name");
this.name = name;
}
/// <summary>
/// Gets the name of the namespace.
/// </summary>
public string Name {
get {
return name;
}
}
public override ArrayList GetCompletionData(IProjectContent projectContent)
{
return projectContent.GetNamespaceContents(name);
}
public override ResolveResult Clone()
{
return new NamespaceResolveResult(this.CallingClass, this.CallingMember, this.Name);
}
}
#endregion
#region IntegerLiteralResolveResult
/// <summary>
/// The IntegerLiteralResolveResult is used when an expression was an integer literal.
/// It is a normal ResolveResult with a type of "int", but does not provide
/// any code completion data.
/// </summary>
public class IntegerLiteralResolveResult : ResolveResult
{
public IntegerLiteralResolveResult(IClass callingClass, IMember callingMember, IReturnType systemInt32)
: base(callingClass, callingMember, systemInt32)
{
}
public override ArrayList GetCompletionData(IProjectContent projectContent)
{
return null;
}
public override ResolveResult Clone()
{
return new IntegerLiteralResolveResult(this.CallingClass, this.CallingMember, this.ResolvedType);
}
}
#endregion
#region TypeResolveResult
/// <summary>
/// The TypeResolveResult is used when an expression was the name of a type.
/// This resolve result makes code completion show the static members instead
/// of the instance members.
/// </summary>
/// <example>
/// Example expressions:
/// "System.EventArgs"
/// "using System; EventArgs"
/// </example>
public class TypeResolveResult : ResolveResult
{
IClass resolvedClass;
public TypeResolveResult(IClass callingClass, IMember callingMember, IClass resolvedClass)
: base(callingClass, callingMember, resolvedClass.DefaultReturnType)
{
this.resolvedClass = resolvedClass;
}
public TypeResolveResult(IClass callingClass, IMember callingMember, IReturnType resolvedType, IClass resolvedClass)
: base(callingClass, callingMember, resolvedType)
{
this.resolvedClass = resolvedClass;
}
public TypeResolveResult(IClass callingClass, IMember callingMember, IReturnType resolvedType)
: base(callingClass, callingMember, resolvedType)
{
this.resolvedClass = resolvedType.GetUnderlyingClass();
}
public override ResolveResult Clone()
{
return new TypeResolveResult(this.CallingClass, this.CallingMember, this.ResolvedType, this.ResolvedClass);
}
/// <summary>
/// Gets the class corresponding to the resolved type.
/// This property can be null when the type has no class (for example a type parameter).
/// </summary>
public IClass ResolvedClass {
get {
return resolvedClass;
}
}
public override ArrayList GetCompletionData(IProjectContent projectContent)
{
ArrayList ar = GetCompletionData(projectContent.Language, true);
if (resolvedClass != null) {
ar.AddRange(resolvedClass.GetCompoundClass().GetAccessibleTypes(CallingClass));
}
return ar;
}
public override FilePosition GetDefinitionPosition()
{
if (resolvedClass == null) {
return FilePosition.Empty;
}
ICompilationUnit cu = resolvedClass.CompilationUnit;
if (cu == null || cu.FileName == null || cu.FileName.Length == 0) {
return FilePosition.Empty;
}
DomRegion reg = resolvedClass.Region;
if (!reg.IsEmpty)
return new FilePosition(cu.FileName, reg.BeginLine, reg.BeginColumn);
else
return new FilePosition(cu.FileName);
}
public override bool IsReferenceTo(IEntity entity)
{
IClass c = entity as IClass;
return c != null
&& resolvedClass.FullyQualifiedName == c.FullyQualifiedName
&& resolvedClass.TypeParameters.Count == c.TypeParameters.Count;
}
}
#endregion
#region MemberResolveResult
/// <summary>
/// The TypeResolveResult is used when an expression was a member
/// (field, property, event or method call).
/// </summary>
/// <example>
/// Example expressions:
/// "(any expression).fieldName"
/// "(any expression).eventName"
/// "(any expression).propertyName"
/// "(any expression).methodName(arguments)" (methods only when method parameters are part of expression)
/// "using System; EventArgs.Empty"
/// "fieldName" (when fieldName is a field in the current class)
/// "new System.Windows.Forms.Button()" (constructors are also methods)
/// "SomeMethod()" (when SomeMethod is a method in the current class)
/// "System.Console.WriteLine(text)"
/// </example>
public class MemberResolveResult : ResolveResult
{
IMember resolvedMember;
public MemberResolveResult(IClass callingClass, IMember callingMember, IMember resolvedMember)
: base(callingClass, callingMember, resolvedMember.ReturnType)
{
if (resolvedMember == null)
throw new ArgumentNullException("resolvedMember");
this.resolvedMember = resolvedMember;
}
public override ResolveResult Clone()
{
return new MemberResolveResult(this.CallingClass, this.CallingMember, this.ResolvedMember) {
IsExtensionMethodCall = IsExtensionMethodCall
};
}
bool isExtensionMethodCall;
public bool IsExtensionMethodCall {
get { return isExtensionMethodCall; }
set {
CheckBeforeMutation();
isExtensionMethodCall = value;
}
}
/// <summary>
/// Gets the member that was resolved.
/// </summary>
public IMember ResolvedMember {
get { return resolvedMember; }
}
public override FilePosition GetDefinitionPosition()
{
return GetDefinitionPosition(resolvedMember);
}
internal static FilePosition GetDefinitionPosition(IMember resolvedMember)
{
IClass declaringType = resolvedMember.DeclaringType;
if (declaringType == null) {
return FilePosition.Empty;
}
ICompilationUnit cu = declaringType.CompilationUnit;
if (cu == null) {
return FilePosition.Empty;
}
if (cu.FileName == null || cu.FileName.Length == 0) {
return FilePosition.Empty;
}
DomRegion reg = resolvedMember.Region;
if (!reg.IsEmpty)
return new FilePosition(cu.FileName, reg.BeginLine, reg.BeginColumn);
else
return new FilePosition(cu.FileName);
}
public override bool IsReferenceTo(IEntity entity)
{
IClass c = entity as IClass;
if (c != null) {
IMethod m = resolvedMember as IMethod;
return m != null && m.IsConstructor
&& m.DeclaringType.FullyQualifiedName == c.FullyQualifiedName
&& m.DeclaringType.TypeParameters.Count == c.TypeParameters.Count;
} else {
return MemberLookupHelper.IsSimilarMember(resolvedMember, entity as IMember);
}
}
}
#endregion
#region MethodResolveResult
public class MethodGroup : AbstractFreezable, IList<IMethod>
{
IList<IMethod> innerList;
bool isExtensionMethodGroup;
public MethodGroup() : this(new List<IMethod>())
{
}
public MethodGroup(IList<IMethod> innerList)
{
if (innerList == null)
throw new ArgumentNullException("innerList");
this.innerList = innerList;
}
public bool IsExtensionMethodGroup {
get { return isExtensionMethodGroup; }
set {
CheckBeforeMutation();
isExtensionMethodGroup = value;
}
}
protected override void FreezeInternal()
{
base.FreezeInternal();
innerList = FreezeList(innerList);
}
public IMethod this[int index] {
get { return innerList[index]; }
set { innerList[index] = value; }
}
public int Count {
get { return innerList.Count; }
}
public bool IsReadOnly {
get { return innerList.IsReadOnly; }
}
public int IndexOf(IMethod item)
{
return innerList.IndexOf(item);
}
public void Insert(int index, IMethod item)
{
innerList.Insert(index, item);
}
public void RemoveAt(int index)
{
innerList.RemoveAt(index);
}
public void Add(IMethod item)
{
innerList.Add(item);
}
public void Clear()
{
innerList.Clear();
}
public bool Contains(IMethod item)
{
return innerList.Contains(item);
}
public void CopyTo(IMethod[] array, int arrayIndex)
{
innerList.CopyTo(array, arrayIndex);
}
public bool Remove(IMethod item)
{
return innerList.Remove(item);
}
public IEnumerator<IMethod> GetEnumerator()
{
return innerList.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
/// <summary>
/// The MethodResolveResult is used when an expression was the name of a method,
/// but there were no parameters specified so the exact overload could not be found.
/// <see cref="ResolveResult.ResolvedType"/> is always null on a MethodReturnType.
/// </summary>
/// <example>
/// Example expressions:
/// "System.Console.WriteLine"
/// "a.Add" (where a is List<string>)
/// "SomeMethod" (when SomeMethod is a method in the current class)
/// </example>
public class MethodGroupResolveResult : ResolveResult
{
string name;
IReturnType containingType;
IList<MethodGroup> possibleMethods;
public MethodGroupResolveResult(IClass callingClass, IMember callingMember, IReturnType containingType, string name)
: base(callingClass, callingMember, null)
{
if (containingType == null)
throw new ArgumentNullException("containingType");
if (name == null)
throw new ArgumentNullException("name");
this.containingType = containingType;
this.name = name;
this.ResolvedType = new MethodGroupReturnType();
}
public MethodGroupResolveResult(IClass callingClass, IMember callingMember, IReturnType containingType, string name,
IList<MethodGroup> possibleMethods)
: base(callingClass, callingMember, null)
{
if (containingType == null)
throw new ArgumentNullException("containingType");
if (name == null)
throw new ArgumentNullException("name");
if (possibleMethods == null)
throw new ArgumentNullException("possibleMethods");
this.containingType = containingType;
this.name = name;
this.possibleMethods = possibleMethods;
this.ResolvedType = new MethodGroupReturnType();
}
public override ResolveResult Clone()
{
return new MethodGroupResolveResult(this.CallingClass, this.CallingMember, this.ContainingType, this.Name, this.Methods);
}
protected override void FreezeInternal()
{
base.FreezeInternal();
if (possibleMethods != null) {
possibleMethods = FreezeList(possibleMethods);
}
}
/// <summary>
/// Gets the name of the method.
/// </summary>
public string Name {
get { return name; }
}
/// <summary>
/// Gets the class that contains the method.
/// </summary>
public IReturnType ContainingType {
get { return containingType; }
}
/// <summary>
/// The list of possible methods.
/// </summary>
public IList<MethodGroup> Methods {
get {
if (possibleMethods == null) {
possibleMethods = FreezeList(
new MethodGroup[] {
new MethodGroup(
containingType.GetMethods().FindAll((IMethod m) => m.Name == this.name)
)
});
}
return possibleMethods;
}
}
public IMethod GetMethodIfSingleOverload()
{
if (this.Methods.Count > 0 && this.Methods[0].Count == 1)
return this.Methods[0][0];
else
return null;
}
public override FilePosition GetDefinitionPosition()
{
IMethod m = GetMethodIfSingleOverload();
if (m != null)
return MemberResolveResult.GetDefinitionPosition(m);
else
return base.GetDefinitionPosition();
}
public override bool IsReferenceTo(IEntity entity)
{
return MemberLookupHelper.IsSimilarMember(GetMethodIfSingleOverload(), entity as IMember);
}
}
#endregion
#region VBBaseOrThisReferenceInConstructorResolveResult
/// <summary>
/// Is used for "MyBase" or "Me" in VB constructors to show "New" in the completion list.
/// </summary>
public class VBBaseOrThisReferenceInConstructorResolveResult : ResolveResult
{
public VBBaseOrThisReferenceInConstructorResolveResult(IClass callingClass, IMember callingMember, IReturnType referencedType)
: base(callingClass, callingMember, referencedType)
{
}
public override ArrayList GetCompletionData(IProjectContent projectContent)
{
ArrayList res = base.GetCompletionData(projectContent);
foreach (IMethod m in this.ResolvedType.GetMethods()) {
if (m.IsConstructor && !m.IsStatic && m.IsAccessible(this.CallingClass, true))
res.Add(m);
}
return res;
}
public override ResolveResult Clone()
{
return new VBBaseOrThisReferenceInConstructorResolveResult(this.CallingClass, this.CallingMember, this.ResolvedType);
}
}
#endregion
#region BaseResolveResult
/// <summary>
/// Is used for "base"/"MyBase" expression.
/// The completion list always shows protected members.
/// </summary>
public class BaseResolveResult : ResolveResult
{
public BaseResolveResult(IClass callingClass, IMember callingMember, IReturnType baseClassType)
: base(callingClass, callingMember, baseClassType)
{
}
public override ArrayList GetCompletionData(IProjectContent projectContent)
{
if (this.ResolvedType == null) return null;
ArrayList res = new ArrayList();
foreach (IMember m in MemberLookupHelper.GetAccessibleMembers(this.ResolvedType, this.CallingClass, projectContent.Language, true)) {
if (projectContent.Language.ShowMember(m, false))
res.Add(m);
}
if (this.CallingClass != null) {
AddExtensions(projectContent.Language, res, this.CallingClass, this.ResolvedType);
}
return res;
}
public override ResolveResult Clone()
{
return new BaseResolveResult(this.CallingClass, this.CallingMember, this.ResolvedType);
}
}
#endregion
#region DelegateCallResolveResult
/// <summary>
/// Is used for calls to delegates/events.
/// </summary>
public class DelegateCallResolveResult : ResolveResult
{
IMethod delegateInvokeMethod;
ResolveResult targetRR;
protected override void FreezeInternal()
{
base.FreezeInternal();
delegateInvokeMethod.Freeze();
targetRR.Freeze();
}
public DelegateCallResolveResult(ResolveResult targetRR, IMethod delegateInvokeMethod)
: base(targetRR.CallingClass, targetRR.CallingMember, delegateInvokeMethod.ReturnType)
{
this.targetRR = targetRR;
this.delegateInvokeMethod = delegateInvokeMethod;
}
/// <summary>
/// Gets the Invoke() method of the delegate.
/// </summary>
public IMethod DelegateInvokeMethod {
get { return delegateInvokeMethod; }
}
/// <summary>
/// Gets the type of the delegate.
/// </summary>
public IReturnType DelegateType {
get { return targetRR.ResolvedType; }
}
/// <summary>
/// Gets the resolve result referring to the delegate.
/// </summary>
public ResolveResult Target {
get { return targetRR; }
}
public override ResolveResult Clone()
{
return new DelegateCallResolveResult(targetRR, delegateInvokeMethod);
}
public override FilePosition GetDefinitionPosition()
{
return targetRR.GetDefinitionPosition();
}
public override bool IsReferenceTo(ICSharpCode.SharpDevelop.Dom.IEntity entity)
{
return targetRR.IsReferenceTo(entity);
}
}
#endregion
#region UnknownIdentifierResolveResult
/// <summary>
/// Used for unknown identifiers.
/// </summary>
public class UnknownIdentifierResolveResult : ResolveResult
{
string identifier;
public UnknownIdentifierResolveResult(IClass callingClass, IMember callingMember, string identifier)
: base(callingClass, callingMember, null)
{
this.identifier = identifier;
}
public string Identifier {
get { return identifier; }
}
public override bool IsValid {
get { return false; }
}
public override ResolveResult Clone()
{
return new UnknownIdentifierResolveResult(this.CallingClass, this.CallingMember, this.Identifier);
}
}
#endregion
#region UnknownConstructorCallResolveResult
/// <summary>
/// Used for constructor calls on unknown types.
/// </summary>
public class UnknownConstructorCallResolveResult : ResolveResult
{
string typeName;
public UnknownConstructorCallResolveResult(IClass callingClass, IMember callingMember, string typeName)
: base(callingClass, callingMember, null)
{
this.typeName = typeName;
}
public string TypeName {
get { return typeName; }
}
public override bool IsValid {
get { return false; }
}
public override ResolveResult Clone()
{
return new UnknownConstructorCallResolveResult(this.CallingClass, this.CallingMember, this.TypeName);
}
}
#endregion
}
| |
/*
* Copyright (C) 2016-2020. Autumn Beauchesne. All rights reserved.
* Author: Autumn Beauchesne
* Date: 24 May 2018
*
* File: SplineTweenShortcuts.cs
* Purpose: Contains shortcuts for splines.
*/
using UnityEngine;
namespace BeauRoutine.Splines
{
/// <summary>
/// Contains tweens related to splines.
/// </summary>
static public class SplineTweenShortcuts
{
#region Transform
private sealed class TweenData_Transform_PositionSpline : ITweenData
{
private Transform m_Transform;
private ISpline m_Spline;
private Space m_Space;
private Axis m_Axis;
private SplineTweenSettings m_SplineSettings;
private Vector3 m_Start;
public TweenData_Transform_PositionSpline(Transform inTransform, ISpline inSpline, Space inSpace, Axis inAxis, SplineTweenSettings inSettings)
{
m_Transform = inTransform;
m_Spline = inSpline;
m_Space = inSpace;
m_Axis = inAxis;
m_SplineSettings = inSettings;
}
public void OnTweenStart()
{
m_Start = m_SplineSettings.Offset == SplineOffset.Relative ? (m_Space == Space.World ? m_Transform.position : m_Transform.localPosition) : Vector3.zero;
m_Spline.Process();
}
public void OnTweenEnd() { }
public void ApplyTween(float inPercent)
{
SplineUpdateInfo info;
Splines.Spline.GetUpdateInfo(m_Spline, inPercent, m_SplineSettings, out info);
info.Point.x += m_Start.x;
info.Point.y += m_Start.y;
info.Point.z += m_Start.z;
m_Transform.SetPosition(info.Point, m_Axis, m_Space);
m_SplineSettings.Orient.Apply(ref info, m_Transform, m_Space);
if (m_SplineSettings.UpdateCallback != null)
{
m_SplineSettings.UpdateCallback(info);
}
}
public override string ToString()
{
return "Transform: Position (Spline)";
}
}
/// <summary>
/// Moves the Transform along a spline over time.
/// </summary>
static public Tween MoveAlong(this Transform inTransform, ISpline inSpline, float inTime, Axis inAxis = Axis.XYZ, Space inSpace = Space.World)
{
return BeauRoutine.Tween.Create(new TweenData_Transform_PositionSpline(inTransform, inSpline, inSpace, inAxis, SplineTweenSettings.Default), inTime);
}
/// <summary>
/// Moves the Transform along a spline over time.
/// </summary>
static public Tween MoveAlong(this Transform inTransform, ISpline inSpline, float inTime, Axis inAxis, Space inSpace, SplineTweenSettings inSplineSettings)
{
return BeauRoutine.Tween.Create(new TweenData_Transform_PositionSpline(inTransform, inSpline, inSpace, inAxis, inSplineSettings), inTime);
}
/// <summary>
/// Moves the Transform along a spline over time.
/// </summary>
static public Tween MoveAlong(this Transform inTransform, ISpline inSpline, TweenSettings inSettings, Axis inAxis = Axis.XYZ, Space inSpace = Space.World)
{
return BeauRoutine.Tween.Create(new TweenData_Transform_PositionSpline(inTransform, inSpline, inSpace, inAxis, SplineTweenSettings.Default), inSettings);
}
/// <summary>
/// Moves the Transform along a spline over time.
/// </summary>
static public Tween MoveAlong(this Transform inTransform, ISpline inSpline, TweenSettings inSettings, Axis inAxis, Space inSpace, SplineTweenSettings inSplineSettings)
{
return BeauRoutine.Tween.Create(new TweenData_Transform_PositionSpline(inTransform, inSpline, inSpace, inAxis, inSplineSettings), inSettings);
}
/// <summary>
/// Moves the Transform along a spline with the given average speed.
/// </summary>
static public Tween MoveAlongWithSpeed(this Transform inTransform, ISpline inSpline, float inSpeed, Axis inAxis = Axis.XYZ, Space inSpace = Space.World)
{
return MoveAlongWithSpeed(inTransform, inSpline, inSpeed, inAxis, inSpace, SplineTweenSettings.Default);
}
/// <summary>
/// Moves the Transform along a spline with the given average speed.
/// </summary>
static public Tween MoveAlongWithSpeed(this Transform inTransform, ISpline inSpline, float inSpeed, Axis inAxis, Space inSpace, SplineTweenSettings inSplineSettings)
{
float time;
switch (inSplineSettings.LerpMethod)
{
case SplineLerp.Direct:
case SplineLerp.Vertex:
time = inSpline.GetDirectDistance() / inSpeed;
break;
case SplineLerp.Precise:
default:
time = inSpline.GetDistance() / inSpeed;
break;
}
return BeauRoutine.Tween.Create(new TweenData_Transform_PositionSpline(inTransform, inSpline, inSpace, inAxis, inSplineSettings), time);
}
#endregion // Transform
#region RectTransform
private sealed class TweenData_RectTransform_AnchorPosSpline : ITweenData
{
private RectTransform m_RectTransform;
private ISpline m_Spline;
private Axis m_Axis;
private SplineTweenSettings m_SplineSettings;
private Vector2 m_Start;
public TweenData_RectTransform_AnchorPosSpline(RectTransform inRectTransform, ISpline inSpline, Axis inAxis, SplineTweenSettings inSettings)
{
m_RectTransform = inRectTransform;
m_Spline = inSpline;
m_Axis = inAxis;
m_SplineSettings = inSettings;
}
public void OnTweenStart()
{
m_Start = m_SplineSettings.Offset == SplineOffset.Relative ? m_RectTransform.anchoredPosition : Vector2.zero;
m_Spline.Process();
}
public void OnTweenEnd() { }
public void ApplyTween(float inPercent)
{
SplineUpdateInfo info;
Splines.Spline.GetUpdateInfo(m_Spline, inPercent, m_SplineSettings, out info);
info.Point.x += m_Start.x;
info.Point.y += m_Start.y;
m_RectTransform.SetAnchorPos(info.Point, m_Axis);
m_SplineSettings.Orient.Apply(ref info, m_RectTransform, Space.Self);
if (m_SplineSettings.UpdateCallback != null)
{
m_SplineSettings.UpdateCallback(info);
}
}
public override string ToString()
{
return "RectTransform: AnchorPos (Spline)";
}
}
/// <summary>
/// Moves the RectTransform's anchorPosition along a spline over time.
/// </summary>
static public Tween AnchorPosAlong(this RectTransform inRectTransform, ISpline inSpline, float inTime, Axis inAxis = Axis.XY)
{
return BeauRoutine.Tween.Create(new TweenData_RectTransform_AnchorPosSpline(inRectTransform, inSpline, inAxis, SplineTweenSettings.Default), inTime);
}
/// <summary>
/// Moves the RectTransform's anchorPosition along a spline over time.
/// </summary>
static public Tween AnchorPosAlong(this RectTransform inRectTransform, ISpline inSpline, float inTime, Axis inAxis, SplineTweenSettings inSplineSettings)
{
return BeauRoutine.Tween.Create(new TweenData_RectTransform_AnchorPosSpline(inRectTransform, inSpline, inAxis, inSplineSettings), inTime);
}
/// <summary>
/// Moves the RectTransform's anchorPosition along a spline over time.
/// </summary>
static public Tween AnchorPosAlong(this RectTransform inRectTransform, ISpline inSpline, TweenSettings inSettings, Axis inAxis = Axis.XY)
{
return BeauRoutine.Tween.Create(new TweenData_RectTransform_AnchorPosSpline(inRectTransform, inSpline, inAxis, SplineTweenSettings.Default), inSettings);
}
/// <summary>
/// Moves the RectTransform's anchorPosition along a spline over time.
/// </summary>
static public Tween AnchorPosAlong(this RectTransform inRectTransform, ISpline inSpline, TweenSettings inSettings, Axis inAxis, SplineTweenSettings inSplineSettings)
{
return BeauRoutine.Tween.Create(new TweenData_RectTransform_AnchorPosSpline(inRectTransform, inSpline, inAxis, inSplineSettings), inSettings);
}
/// <summary>
/// Moves the RectTransform's anchorPosition along a spline with the given average speed.
/// </summary>
static public Tween AnchorPosAlongWithSpeed(this RectTransform inRectTransform, ISpline inSpline, float inSpeed, Axis inAxis = Axis.XY)
{
return AnchorPosAlongWithSpeed(inRectTransform, inSpline, inSpeed, inAxis, SplineTweenSettings.Default);
}
/// <summary>
/// Moves the RectTransform's anchorPosition along a spline with the given average speed.
/// </summary>
static public Tween AnchorPosAlongWithSpeed(this RectTransform inRectTransform, ISpline inSpline, float inSpeed, Axis inAxis, SplineTweenSettings inSplineSettings)
{
float time;
switch (inSplineSettings.LerpMethod)
{
case SplineLerp.Direct:
case SplineLerp.Vertex:
time = inSpline.GetDirectDistance() / inSpeed;
break;
case SplineLerp.Precise:
default:
time = inSpline.GetDistance() / inSpeed;
break;
}
return BeauRoutine.Tween.Create(new TweenData_RectTransform_AnchorPosSpline(inRectTransform, inSpline, inAxis, inSplineSettings), time);
}
#endregion // RectTransform
#region Spline Vertices
private sealed class TweenData_SplineVertex_Position : ITweenData
{
private ISpline m_Spline;
private int m_Index;
private Vector3 m_Target;
private Axis m_Axis;
private Vector3 m_Start;
private Vector3 m_Delta;
public TweenData_SplineVertex_Position(ISpline inSpline, int inIndex, Vector3 inTarget, Axis inAxis)
{
m_Spline = inSpline;
m_Index = inIndex;
m_Target = inTarget;
m_Axis = inAxis;
}
public void OnTweenStart()
{
m_Start = m_Spline.GetVertex(m_Index);
m_Delta = m_Target - m_Start;
}
public void OnTweenEnd() { }
public void ApplyTween(float inPercent)
{
Vector3 final = new Vector3(
m_Start.x + m_Delta.x * inPercent,
m_Start.y + m_Delta.y * inPercent,
m_Start.z + m_Delta.z * inPercent);
Vector3 current;
if ((m_Axis & Axis.XYZ) == Axis.XYZ)
{
current = final;
}
else
{
current = m_Spline.GetVertex(m_Index);
VectorUtil.CopyFrom(ref current, final, m_Axis);
}
m_Spline.SetVertex(m_Index, current);
}
public override string ToString()
{
return "Spline: Vertex Position";
}
}
private sealed class TweenData_SplineControl_Position : ITweenData
{
private ISpline m_Spline;
private int m_Index;
private Vector3 m_Target;
private Axis m_Axis;
private Vector3 m_Start;
private Vector3 m_Delta;
public TweenData_SplineControl_Position(ISpline inSpline, int inIndex, Vector3 inTarget, Axis inAxis)
{
m_Spline = inSpline;
m_Index = inIndex;
m_Target = inTarget;
m_Axis = inAxis;
}
public void OnTweenStart()
{
m_Start = m_Spline.GetControlPoint(m_Index);
m_Delta = m_Target - m_Start;
}
public void OnTweenEnd() { }
public void ApplyTween(float inPercent)
{
Vector3 final = new Vector3(
m_Start.x + m_Delta.x * inPercent,
m_Start.y + m_Delta.y * inPercent,
m_Start.z + m_Delta.z * inPercent);
Vector3 current;
if ((m_Axis & Axis.XYZ) == Axis.XYZ)
{
current = final;
}
else
{
current = m_Spline.GetControlPoint(m_Index);
VectorUtil.CopyFrom(ref current, final, m_Axis);
}
m_Spline.SetControlPoint(m_Index, current);
}
public override string ToString()
{
return "Spline: Control Position";
}
}
/// <summary>
/// Tween a spline vertex position to the given position over time.
/// </summary>
static public Tween VertexPosTo(this ISpline inSpline, int inIndex, Vector3 inTarget, float inTime, Axis inAxis = Axis.XYZ)
{
return BeauRoutine.Tween.Create(new TweenData_SplineVertex_Position(inSpline, inIndex, inTarget, inAxis), inTime);
}
/// <summary>
/// Tween a spline vertex position to the given position over time.
/// </summary>
static public Tween VertexPosTo(this ISpline inSpline, int inIndex, Vector3 inTarget, TweenSettings inSettings, Axis inAxis = Axis.XYZ)
{
return BeauRoutine.Tween.Create(new TweenData_SplineVertex_Position(inSpline, inIndex, inTarget, inAxis), inSettings);
}
/// <summary>
/// Tween a spline control position to the given position over time.
/// </summary>
static public Tween ControlPosTo(this ISpline inSpline, int inIndex, Vector3 inTarget, float inTime, Axis inAxis = Axis.XYZ)
{
return BeauRoutine.Tween.Create(new TweenData_SplineControl_Position(inSpline, inIndex, inTarget, inAxis), inTime);
}
/// <summary>
/// Tween a spline control position to the given position over time.
/// </summary>
static public Tween ControlPosTo(this ISpline inSpline, int inIndex, Vector3 inTarget, TweenSettings inSettings, Axis inAxis = Axis.XYZ)
{
return BeauRoutine.Tween.Create(new TweenData_SplineControl_Position(inSpline, inIndex, inTarget, inAxis), inSettings);
}
#endregion // Spline Vertices
}
}
| |
using GraphQL.SystemTextJson;
using GraphQL.Types;
using Xunit;
namespace GraphQL.Tests.Execution
{
public class InputsTests : QueryTestBase<EnumMutationSchema>
{
[Fact]
public void mutation_input()
{
AssertQuerySuccess(
@"
mutation createUser {
createUser(userInput:{
profileImage:""myimage.png"",
gender: Female
}){
id
gender
profileImage
}
}
",
@"{
""createUser"": {
""id"": 1,
""gender"": ""Female"",
""profileImage"": ""myimage.png""
}
}");
}
[Fact]
public void mutation_input_from_variables()
{
var inputs = @"{ ""userInput"": { ""profileImage"": ""myimage.png"", ""gender"": ""Female"" } }".ToInputs();
AssertQuerySuccess(
@"
mutation createUser($userInput: UserInput!) {
createUser(userInput: $userInput){
id
gender
profileImage
}
}
",
@"{
""createUser"": {
""id"": 1,
""gender"": ""Female"",
""profileImage"": ""myimage.png""
}
}", inputs);
}
[Fact]
public void query_can_get_enum_argument()
{
AssertQuerySuccess(
@"{ user { id, gender, printGender(g: Male) }}",
@"{
""user"": {
""id"": 1,
""gender"": ""Male"",
""printGender"": ""gender: Male""
}
}");
}
[Fact]
public void query_can_get_long_variable()
{
var inputs = @"{ ""userId"": 1000000000000000001 }".ToInputs();
AssertQuerySuccess(
@"query aQuery($userId: Long!) { getLongUser(userId: $userId) { idLong }}",
@"{
""getLongUser"": {
""idLong"": 1000000000000000001
}
}", inputs);
}
[Fact]
public void query_can_get_long_inline()
{
AssertQuerySuccess(
@"query aQuery { getLongUser(userId: 1000000000000000001) { idLong }}",
@"{
""getLongUser"": {
""idLong"": 1000000000000000001
}
}");
}
[Fact]
public void query_can_get_int_variable()
{
var inputs = @"{ ""userId"": 3 }".ToInputs();
AssertQuerySuccess(
@"query aQuery($userId: Int!) { getIntUser(userId: $userId) { id }}",
@"{
""getIntUser"": {
""id"": 3
}
}", inputs);
}
}
public class EnumMutationSchema : Schema
{
public EnumMutationSchema()
{
Query = new UserQuery();
Mutation = new MutationRoot();
}
}
public class UserQuery : ObjectGraphType
{
public UserQuery()
{
Field<UserType>(
"user",
resolve: c => new User
{
Id = 1,
Gender = Gender.Male,
ProfileImage = "hello.png"
});
Field<UserType>("getIntUser", "get user api",
new QueryArguments(
new QueryArgument<NonNullGraphType<IntGraphType>>
{
Name = "userId",
Description = "user id"
}
),
context =>
{
var id = context.GetArgument<int>("userId");
return new User
{
Id = id
};
}
);
Field<UserType>("getLongUser", "get user api",
new QueryArguments(
new QueryArgument<NonNullGraphType<LongGraphType>>
{
Name = "userId",
Description = "user id"
}
),
context =>
{
var id = context.GetArgument<long>("userId");
return new User
{
IdLong = id
};
}
);
}
}
public class UserInputType : InputObjectGraphType
{
public UserInputType()
{
Name = "UserInput";
Description = "User information for user creation";
Field<StringGraphType>("profileImage", "profileImage of user.");
Field<GenderEnum>("gender", "user gender.");
}
}
public class GenderEnum : EnumerationGraphType
{
public GenderEnum()
{
Name = "Gender";
Description = "User gender";
AddValue("NotSpecified", "NotSpecified gender.", Gender.NotSpecified);
AddValue("Male", "gender Male", Gender.Male);
AddValue("Female", "gender female", Gender.Female);
}
}
public class MutationRoot : ObjectGraphType
{
public MutationRoot()
{
Name = "MutationRoot";
Description = "GraphQL MutationRoot for supporting create, update, delete or perform custom actions";
Field<UserType>("createUser", "create user api",
new QueryArguments(
new QueryArgument<NonNullGraphType<UserInputType>>
{
Name = "userInput",
Description = "user info details"
}
),
context =>
{
var input = context.GetArgument<CreateUser>("userInput");
return new User
{
Id = 1,
ProfileImage = input.ProfileImage,
Gender = input.Gender
};
});
}
}
public class UserType : ObjectGraphType
{
public UserType()
{
Name = "User";
Field<IntGraphType>("id");
Field<LongGraphType>("idLong");
Field<StringGraphType>("profileImage");
Field<GenderEnum>("gender");
Field<StringGraphType>(
"printGender",
arguments: new QueryArguments(new QueryArgument<GenderEnum> { Name = "g" }),
resolve: c =>
{
var gender = c.GetArgument<Gender>("g");
return $"gender: {gender}";
});
}
}
public class User
{
public int Id { get; set; }
public long IdLong { get; set; }
public string ProfileImage { get; set; }
public Gender Gender { get; set; }
}
public class CreateUser
{
public string ProfileImage { get; set; }
public Gender Gender { get; set; }
}
public enum Gender
{
NotSpecified,
Male,
Female
}
}
| |
// 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;
namespace Rotate
{
internal class App
{
public static int s_weightCount = 1;
private class BaseNode
{
private byte _BASEPAD_0;
private ulong _BASEPAD_1;
private int _BASEPAD_2;
private ulong _BASEPAD_3;
private String _BASEPAD_4;
private byte _BASEPAD_5;
private String _BASEPAD_6;
private uint _BASEPAD_7;
private ushort _BASEPAD_8;
private byte _BASEPAD_9;
private String _BASEPAD_10;
private int _BASEPAD_11;
private int _BASEPAD_12;
public BaseNode()
{
_BASEPAD_0 = 124;
_BASEPAD_1 = 42;
_BASEPAD_2 = 114;
_BASEPAD_3 = 8;
_BASEPAD_4 = "8319";
_BASEPAD_5 = 207;
_BASEPAD_6 = "26397";
_BASEPAD_7 = 207;
_BASEPAD_8 = 46;
_BASEPAD_9 = 35;
_BASEPAD_10 = "16085";
_BASEPAD_11 = 44;
_BASEPAD_12 = 138;
}
public virtual void VerifyValid()
{
if (_BASEPAD_0 != 124) throw new Exception("m_BASEPAD_0");
if (_BASEPAD_1 != 42) throw new Exception("m_BASEPAD_1");
if (_BASEPAD_2 != 114) throw new Exception("m_BASEPAD_2");
if (_BASEPAD_3 != 8) throw new Exception("m_BASEPAD_3");
if (_BASEPAD_4 != "8319") throw new Exception("m_BASEPAD_4");
if (_BASEPAD_5 != 207) throw new Exception("m_BASEPAD_5");
if (_BASEPAD_6 != "26397") throw new Exception("m_BASEPAD_6");
if (_BASEPAD_7 != 207) throw new Exception("m_BASEPAD_7");
if (_BASEPAD_8 != 46) throw new Exception("m_BASEPAD_8");
if (_BASEPAD_9 != 35) throw new Exception("m_BASEPAD_9");
if (_BASEPAD_10 != "16085") throw new Exception("m_BASEPAD_10");
if (_BASEPAD_11 != 44) throw new Exception("m_BASEPAD_11");
if (_BASEPAD_12 != 138) throw new Exception("m_BASEPAD_12");
}
}
private class Node : BaseNode
{
private int _PREPAD_0;
private uint _PREPAD_1;
private char _PREPAD_2;
private uint _PREPAD_3;
private ushort _PREPAD_4;
public Node m_leftChild;
private ulong _MID1PAD_0;
private uint _MID1PAD_1;
private byte _MID1PAD_2;
private int _MID1PAD_3;
private char _MID1PAD_4;
private ushort _MID1PAD_5;
private ushort _MID1PAD_6;
private int _MID1PAD_7;
private String _MID1PAD_8;
private byte _MID1PAD_9;
private int _MID1PAD_10;
private String _MID1PAD_11;
private uint _MID1PAD_12;
private ulong _MID1PAD_13;
private uint _MID1PAD_14;
private String _MID1PAD_15;
public int m_weight;
private uint _MID2PAD_0;
private String _MID2PAD_1;
private uint _MID2PAD_2;
private byte _MID2PAD_3;
private char _MID2PAD_4;
private ulong _MID2PAD_5;
private byte _MID2PAD_6;
private ulong _MID2PAD_7;
private ushort _MID2PAD_8;
private byte _MID2PAD_9;
private int _MID2PAD_10;
private int _MID2PAD_11;
private String _MID2PAD_12;
private String _MID2PAD_13;
private int _MID2PAD_14;
private char _MID2PAD_15;
public Node m_rightChild;
private ulong _AFTERPAD_0;
private int _AFTERPAD_1;
private ulong _AFTERPAD_2;
private int _AFTERPAD_3;
private ulong _AFTERPAD_4;
private ulong _AFTERPAD_5;
private ulong _AFTERPAD_6;
private ulong _AFTERPAD_7;
private String _AFTERPAD_8;
public Node()
{
m_weight = s_weightCount++;
_PREPAD_0 = 219;
_PREPAD_1 = 230;
_PREPAD_2 = '`';
_PREPAD_3 = 33;
_PREPAD_4 = 67;
_MID1PAD_0 = 50;
_MID1PAD_1 = 44;
_MID1PAD_2 = 152;
_MID1PAD_3 = 168;
_MID1PAD_4 = '{';
_MID1PAD_5 = 202;
_MID1PAD_6 = 251;
_MID1PAD_7 = 135;
_MID1PAD_8 = "28824";
_MID1PAD_9 = 201;
_MID1PAD_10 = 106;
_MID1PAD_11 = "12481";
_MID1PAD_12 = 83;
_MID1PAD_13 = 127;
_MID1PAD_14 = 243;
_MID1PAD_15 = "28096";
_MID2PAD_0 = 107;
_MID2PAD_1 = "22265";
_MID2PAD_2 = 178;
_MID2PAD_3 = 73;
_MID2PAD_4 = 'A';
_MID2PAD_5 = 40;
_MID2PAD_6 = 3;
_MID2PAD_7 = 18;
_MID2PAD_8 = 97;
_MID2PAD_9 = 194;
_MID2PAD_10 = 30;
_MID2PAD_11 = 62;
_MID2PAD_12 = "11775";
_MID2PAD_13 = "19219";
_MID2PAD_14 = 176;
_MID2PAD_15 = 'b';
_AFTERPAD_0 = 56;
_AFTERPAD_1 = 249;
_AFTERPAD_2 = 153;
_AFTERPAD_3 = 67;
_AFTERPAD_4 = 52;
_AFTERPAD_5 = 232;
_AFTERPAD_6 = 164;
_AFTERPAD_7 = 111;
_AFTERPAD_8 = "25014";
}
public override void VerifyValid()
{
base.VerifyValid();
if (_PREPAD_0 != 219) throw new Exception("m_PREPAD_0");
if (_PREPAD_1 != 230) throw new Exception("m_PREPAD_1");
if (_PREPAD_2 != '`') throw new Exception("m_PREPAD_2");
if (_PREPAD_3 != 33) throw new Exception("m_PREPAD_3");
if (_PREPAD_4 != 67) throw new Exception("m_PREPAD_4");
if (_MID1PAD_0 != 50) throw new Exception("m_MID1PAD_0");
if (_MID1PAD_1 != 44) throw new Exception("m_MID1PAD_1");
if (_MID1PAD_2 != 152) throw new Exception("m_MID1PAD_2");
if (_MID1PAD_3 != 168) throw new Exception("m_MID1PAD_3");
if (_MID1PAD_4 != '{') throw new Exception("m_MID1PAD_4");
if (_MID1PAD_5 != 202) throw new Exception("m_MID1PAD_5");
if (_MID1PAD_6 != 251) throw new Exception("m_MID1PAD_6");
if (_MID1PAD_7 != 135) throw new Exception("m_MID1PAD_7");
if (_MID1PAD_8 != "28824") throw new Exception("m_MID1PAD_8");
if (_MID1PAD_9 != 201) throw new Exception("m_MID1PAD_9");
if (_MID1PAD_10 != 106) throw new Exception("m_MID1PAD_10");
if (_MID1PAD_11 != "12481") throw new Exception("m_MID1PAD_11");
if (_MID1PAD_12 != 83) throw new Exception("m_MID1PAD_12");
if (_MID1PAD_13 != 127) throw new Exception("m_MID1PAD_13");
if (_MID1PAD_14 != 243) throw new Exception("m_MID1PAD_14");
if (_MID1PAD_15 != "28096") throw new Exception("m_MID1PAD_15");
if (_MID2PAD_0 != 107) throw new Exception("m_MID2PAD_0");
if (_MID2PAD_1 != "22265") throw new Exception("m_MID2PAD_1");
if (_MID2PAD_2 != 178) throw new Exception("m_MID2PAD_2");
if (_MID2PAD_3 != 73) throw new Exception("m_MID2PAD_3");
if (_MID2PAD_4 != 'A') throw new Exception("m_MID2PAD_4");
if (_MID2PAD_5 != 40) throw new Exception("m_MID2PAD_5");
if (_MID2PAD_6 != 3) throw new Exception("m_MID2PAD_6");
if (_MID2PAD_7 != 18) throw new Exception("m_MID2PAD_7");
if (_MID2PAD_8 != 97) throw new Exception("m_MID2PAD_8");
if (_MID2PAD_9 != 194) throw new Exception("m_MID2PAD_9");
if (_MID2PAD_10 != 30) throw new Exception("m_MID2PAD_10");
if (_MID2PAD_11 != 62) throw new Exception("m_MID2PAD_11");
if (_MID2PAD_12 != "11775") throw new Exception("m_MID2PAD_12");
if (_MID2PAD_13 != "19219") throw new Exception("m_MID2PAD_13");
if (_MID2PAD_14 != 176) throw new Exception("m_MID2PAD_14");
if (_MID2PAD_15 != 'b') throw new Exception("m_MID2PAD_15");
if (_AFTERPAD_0 != 56) throw new Exception("m_AFTERPAD_0");
if (_AFTERPAD_1 != 249) throw new Exception("m_AFTERPAD_1");
if (_AFTERPAD_2 != 153) throw new Exception("m_AFTERPAD_2");
if (_AFTERPAD_3 != 67) throw new Exception("m_AFTERPAD_3");
if (_AFTERPAD_4 != 52) throw new Exception("m_AFTERPAD_4");
if (_AFTERPAD_5 != 232) throw new Exception("m_AFTERPAD_5");
if (_AFTERPAD_6 != 164) throw new Exception("m_AFTERPAD_6");
if (_AFTERPAD_7 != 111) throw new Exception("m_AFTERPAD_7");
if (_AFTERPAD_8 != "25014") throw new Exception("m_AFTERPAD_8");
}
public virtual Node growTree(int maxHeight, String indent)
{
//Console.WriteLine(indent + m_weight.ToString());
if (maxHeight > 0)
{
m_leftChild = new Node();
m_leftChild.growTree(maxHeight - 1, indent + " ");
m_rightChild = new Node();
m_rightChild.growTree(maxHeight - 1, indent + " ");
}
else
m_leftChild = m_rightChild = null;
return this;
}
public virtual void rotateTree(ref int leftWeight, ref int rightWeight)
{
//Console.WriteLine("rotateTree(" + m_weight.ToString() + ")");
VerifyValid();
// create node objects for children
Node newLeftChild = null, newRightChild = null;
if (m_leftChild != null)
{
newRightChild = new Node();
newRightChild.m_leftChild = m_leftChild.m_leftChild;
newRightChild.m_rightChild = m_leftChild.m_rightChild;
newRightChild.m_weight = m_leftChild.m_weight;
}
if (m_rightChild != null)
{
newLeftChild = new Node();
newLeftChild.m_leftChild = m_rightChild.m_leftChild;
newLeftChild.m_rightChild = m_rightChild.m_rightChild;
newLeftChild.m_weight = m_rightChild.m_weight;
}
// replace children
m_leftChild = newLeftChild;
m_rightChild = newRightChild;
for (int I = 0; I < 32; I++) { int[] u = new int[1024]; }
// verify all valid
if (m_rightChild != null)
{
if (m_rightChild.m_leftChild != null &&
m_rightChild.m_rightChild != null)
{
m_rightChild.m_leftChild.VerifyValid();
m_rightChild.m_rightChild.VerifyValid();
m_rightChild.rotateTree(
ref m_rightChild.m_leftChild.m_weight,
ref m_rightChild.m_rightChild.m_weight);
}
else
{
int minus1 = -1;
m_rightChild.rotateTree(ref minus1, ref minus1);
}
if (leftWeight != m_rightChild.m_weight)
{
Console.WriteLine("left weight do not match.");
throw new Exception();
}
}
if (m_leftChild != null)
{
if (m_leftChild.m_leftChild != null &&
m_leftChild.m_rightChild != null)
{
m_leftChild.m_leftChild.VerifyValid();
m_leftChild.m_rightChild.VerifyValid();
m_leftChild.rotateTree(
ref m_leftChild.m_leftChild.m_weight,
ref m_leftChild.m_rightChild.m_weight);
}
else
{
int minus1 = -1;
m_leftChild.rotateTree(ref minus1, ref minus1);
}
if (rightWeight != m_leftChild.m_weight)
{
Console.WriteLine("right weight do not match.");
throw new Exception();
}
}
}
}
private static int Main()
{
try
{
Node root = new Node();
root.growTree(6, "").rotateTree(
ref root.m_leftChild.m_weight,
ref root.m_rightChild.m_weight);
}
catch (Exception)
{
Console.WriteLine("*** FAILED ***");
return 1;
}
Console.WriteLine("*** PASSED ***");
return 100;
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace MS.Internal.Xml.XPath
{
internal sealed class SortQuery : Query
{
private List<SortKey> _results;
private XPathSortComparer _comparer;
private Query _qyInput;
public SortQuery(Query qyInput)
{
Debug.Assert(qyInput != null, "Sort Query needs an input query tree to work on");
_results = new List<SortKey>();
_comparer = new XPathSortComparer();
_qyInput = qyInput;
count = 0;
}
private SortQuery(SortQuery other) : base(other)
{
_results = new List<SortKey>(other._results);
_comparer = other._comparer.Clone();
_qyInput = Clone(other._qyInput);
count = 0;
}
public override void Reset() { count = 0; }
public override void SetXsltContext(XsltContext xsltContext)
{
_qyInput.SetXsltContext(xsltContext);
if (
_qyInput.StaticType != XPathResultType.NodeSet &&
_qyInput.StaticType != XPathResultType.Any
)
{
throw XPathException.Create(SR.Xp_NodeSetExpected);
}
}
private void BuildResultsList()
{
Int32 numSorts = _comparer.NumSorts;
Debug.Assert(numSorts > 0, "Why was the sort query created?");
XPathNavigator eNext;
while ((eNext = _qyInput.Advance()) != null)
{
SortKey key = new SortKey(numSorts, /*originalPosition:*/_results.Count, eNext.Clone());
for (Int32 j = 0; j < numSorts; j++)
{
key[j] = _comparer.Expression(j).Evaluate(_qyInput);
}
_results.Add(key);
}
_results.Sort(_comparer);
}
public override object Evaluate(XPathNodeIterator context)
{
_qyInput.Evaluate(context);
_results.Clear();
BuildResultsList();
count = 0;
return this;
}
public override XPathNavigator Advance()
{
Debug.Assert(0 <= count && count <= _results.Count);
if (count < _results.Count)
{
return _results[count++].Node;
}
return null;
}
public override XPathNavigator Current
{
get
{
Debug.Assert(0 <= count && count <= _results.Count);
if (count == 0)
{
return null;
}
return _results[count - 1].Node;
}
}
internal void AddSort(Query evalQuery, IComparer comparer)
{
_comparer.AddSort(evalQuery, comparer);
}
public override XPathNodeIterator Clone() { return new SortQuery(this); }
public override XPathResultType StaticType { get { return XPathResultType.NodeSet; } }
public override int CurrentPosition { get { return count; } }
public override int Count { get { return _results.Count; } }
public override QueryProps Properties { get { return QueryProps.Cached | QueryProps.Position | QueryProps.Count; } }
public override void PrintQuery(XmlWriter w)
{
w.WriteStartElement(this.GetType().Name);
_qyInput.PrintQuery(w);
w.WriteElementString("XPathSortComparer", "... PrintTree() not implemented ...");
w.WriteEndElement();
}
} // class SortQuery
internal sealed class SortKey
{
private Int32 _numKeys;
private object[] _keys;
private int _originalPosition;
private XPathNavigator _node;
public SortKey(int numKeys, int originalPosition, XPathNavigator node)
{
_numKeys = numKeys;
_keys = new object[numKeys];
_originalPosition = originalPosition;
_node = node;
}
public object this[int index]
{
get { return _keys[index]; }
set { _keys[index] = value; }
}
public int NumKeys { get { return _numKeys; } }
public int OriginalPosition { get { return _originalPosition; } }
public XPathNavigator Node { get { return _node; } }
} // class SortKey
internal sealed class XPathSortComparer : IComparer<SortKey>
{
private const int minSize = 3;
private Query[] _expressions;
private IComparer[] _comparers;
private int _numSorts;
public XPathSortComparer(int size)
{
if (size <= 0) size = minSize;
_expressions = new Query[size];
_comparers = new IComparer[size];
}
public XPathSortComparer() : this(minSize) { }
public void AddSort(Query evalQuery, IComparer comparer)
{
Debug.Assert(_expressions.Length == _comparers.Length);
Debug.Assert(0 < _expressions.Length);
Debug.Assert(0 <= _numSorts && _numSorts <= _expressions.Length);
// Ajust array sizes if needed.
if (_numSorts == _expressions.Length)
{
Query[] newExpressions = new Query[_numSorts * 2];
IComparer[] newComparers = new IComparer[_numSorts * 2];
for (int i = 0; i < _numSorts; i++)
{
newExpressions[i] = _expressions[i];
newComparers[i] = _comparers[i];
}
_expressions = newExpressions;
_comparers = newComparers;
}
Debug.Assert(_numSorts < _expressions.Length);
// Fixup expression to handle node-set return type:
if (evalQuery.StaticType == XPathResultType.NodeSet || evalQuery.StaticType == XPathResultType.Any)
{
evalQuery = new StringFunctions(Function.FunctionType.FuncString, new Query[] { evalQuery });
}
_expressions[_numSorts] = evalQuery;
_comparers[_numSorts] = comparer;
_numSorts++;
}
public int NumSorts { get { return _numSorts; } }
public Query Expression(int i)
{
return _expressions[i];
}
int IComparer<SortKey>.Compare(SortKey x, SortKey y)
{
Debug.Assert(x != null && y != null, "Oops!! what happened?");
int result = 0;
for (int i = 0; i < x.NumKeys; i++)
{
result = _comparers[i].Compare(x[i], y[i]);
if (result != 0)
{
return result;
}
}
// if after all comparisions, the two sort keys are still equal, preserve the doc order
return x.OriginalPosition - y.OriginalPosition;
}
internal XPathSortComparer Clone()
{
XPathSortComparer clone = new XPathSortComparer(_numSorts);
for (int i = 0; i < _numSorts; i++)
{
clone._comparers[i] = _comparers[i];
clone._expressions[i] = (Query)_expressions[i].Clone(); // Expressions should be cloned because Query should be cloned
}
clone._numSorts = _numSorts;
return clone;
}
} // class XPathSortComparer
} // namespace
| |
// -----------------------------------------------------------------------
// <copyright file="FrameworkElement.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Avalonia
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
using Avalonia.Media;
public enum HorizontalAlignment
{
Left,
Center,
Right,
Stretch,
}
public enum VerticalAlignment
{
Top = 0,
Center = 1,
Bottom = 2,
Stretch = 3,
}
[RuntimeNameProperty("Name")]
public class FrameworkElement : UIElement, ISupportInitialize
{
public static readonly DependencyProperty DataContextProperty =
DependencyProperty.Register(
"DataContext",
typeof(object),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.Inherits));
public static readonly DependencyProperty DefaultStyleKeyProperty =
DependencyProperty.Register(
"DefaultStyleKey",
typeof(object),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty HeightProperty =
DependencyProperty.Register(
"Height",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
double.NaN,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty HorizontalAlignmentProperty =
DependencyProperty.Register(
"HorizontalAlignment",
typeof(HorizontalAlignment),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
HorizontalAlignment.Stretch,
FrameworkPropertyMetadataOptions.AffectsArrange));
public static readonly DependencyProperty MarginProperty =
DependencyProperty.Register(
"Margin",
typeof(Thickness),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
new Thickness(),
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty MaxHeightProperty =
DependencyProperty.Register(
"MaxHeight",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
double.PositiveInfinity,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty MaxWidthProperty =
DependencyProperty.Register(
"MaxWidth",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
double.PositiveInfinity,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty MinHeightProperty =
DependencyProperty.Register(
"MinHeight",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty MinWidthProperty =
DependencyProperty.Register(
"MinWidth",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty StyleProperty =
DependencyProperty.Register(
"Style",
typeof(Style),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsMeasure,
StyleChanged));
public static readonly DependencyProperty VerticalAlignmentProperty =
DependencyProperty.Register(
"VerticalAlignment",
typeof(VerticalAlignment),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
VerticalAlignment.Stretch,
FrameworkPropertyMetadataOptions.AffectsArrange));
public static readonly DependencyProperty WidthProperty =
DependencyProperty.Register(
"Width",
typeof(double),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
double.NaN,
FrameworkPropertyMetadataOptions.AffectsMeasure));
internal static readonly DependencyProperty TemplatedParentProperty =
DependencyProperty.Register(
"TemplatedParent",
typeof(DependencyObject),
typeof(FrameworkElement),
new PropertyMetadata(TemplatedParentChanged));
private bool isInitialized;
public FrameworkElement()
{
this.Resources = new ResourceDictionary();
}
public event EventHandler Initialized;
public double ActualWidth
{
get { return this.RenderSize.Width; }
}
public double ActualHeight
{
get { return this.RenderSize.Height; }
}
public object DataContext
{
get { return this.GetValue(DataContextProperty); }
set { this.SetValue(DataContextProperty, value); }
}
public double Height
{
get { return (double)this.GetValue(HeightProperty); }
set { this.SetValue(HeightProperty, value); }
}
public HorizontalAlignment HorizontalAlignment
{
get { return (HorizontalAlignment)this.GetValue(HorizontalAlignmentProperty); }
set { this.SetValue(HorizontalAlignmentProperty, value); }
}
public bool IsInitialized
{
get
{
return this.isInitialized;
}
internal set
{
this.isInitialized = value;
if (this.isInitialized)
{
this.OnInitialized(EventArgs.Empty);
}
}
}
public Thickness Margin
{
get { return (Thickness)this.GetValue(MarginProperty); }
set { this.SetValue(MarginProperty, value); }
}
public double MaxHeight
{
get { return (double)this.GetValue(MaxHeightProperty); }
set { this.SetValue(MaxHeightProperty, value); }
}
public double MaxWidth
{
get { return (double)this.GetValue(MaxWidthProperty); }
set { this.SetValue(MaxWidthProperty, value); }
}
public double MinHeight
{
get { return (double)this.GetValue(MinHeightProperty); }
set { this.SetValue(MinHeightProperty, value); }
}
public double MinWidth
{
get { return (double)this.GetValue(MinWidthProperty); }
set { this.SetValue(MinWidthProperty, value); }
}
public string Name
{
get;
set;
}
public DependencyObject Parent
{
get;
private set;
}
[Ambient]
public ResourceDictionary Resources
{
get;
set;
}
public Style Style
{
get { return (Style)this.GetValue(StyleProperty); }
set { this.SetValue(StyleProperty, value); }
}
public DependencyObject TemplatedParent
{
get { return (DependencyObject)this.GetValue(TemplatedParentProperty); }
internal set { this.SetValue(TemplatedParentProperty, value); }
}
public VerticalAlignment VerticalAlignment
{
get { return (VerticalAlignment)this.GetValue(VerticalAlignmentProperty); }
set { this.SetValue(VerticalAlignmentProperty, value); }
}
public double Width
{
get { return (double)this.GetValue(WidthProperty); }
set { this.SetValue(WidthProperty, value); }
}
protected internal object DefaultStyleKey
{
get { return this.GetValue(DefaultStyleKeyProperty); }
set { this.SetValue(DefaultStyleKeyProperty, value); }
}
protected internal virtual IEnumerator LogicalChildren
{
get { return new object[0].GetEnumerator(); }
}
public virtual bool ApplyTemplate()
{
// NOTE: this isn't virtual in WPF, but the Template property isn't defined until
// Control so I don't see how it is applied at this level. Making it virtual makes
// the most sense for now.
return false;
}
public object FindName(string name)
{
INameScope nameScope = this.FindNameScope(this);
return (nameScope != null) ? nameScope.FindName(name) : null;
}
public object FindResource(object resourceKey)
{
object resource = this.TryFindResource(resourceKey);
if (resource != null)
{
return resource;
}
else
{
throw new ResourceReferenceKeyNotFoundException(
string.Format("'{0}' resource not found", resourceKey),
resourceKey);
}
}
public virtual void OnApplyTemplate()
{
}
public object TryFindResource(object resourceKey)
{
FrameworkElement element = this;
object resource = null;
while (resource == null && element != null)
{
resource = element.Resources[resourceKey];
element = (FrameworkElement)VisualTreeHelper.GetParent(element);
}
if (resource == null && Application.Current != null)
{
resource = Application.Current.Resources[resourceKey];
}
if (resource == null)
{
resource = Application.GenericTheme[resourceKey];
}
return resource;
}
void ISupportInitialize.BeginInit()
{
}
void ISupportInitialize.EndInit()
{
this.IsInitialized = true;
}
protected internal void AddLogicalChild(object child)
{
FrameworkElement fe = child as FrameworkElement;
if (fe != null)
{
if (fe.Parent != null)
{
throw new InvalidOperationException("FrameworkElement already has a parent.");
}
fe.Parent = this;
if (this.TemplatedParent != null)
{
this.PropagateTemplatedParent(fe, this.TemplatedParent);
}
this.InvalidateMeasure();
}
}
protected internal void RemoveLogicalChild(object child)
{
FrameworkElement fe = child as FrameworkElement;
if (fe != null)
{
if (fe.Parent != this)
{
throw new InvalidOperationException("FrameworkElement is not a child of this object.");
}
fe.Parent = null;
this.InvalidateMeasure();
}
}
protected internal virtual DependencyObject GetTemplateChild(string childName)
{
return null;
}
protected internal virtual void OnStyleChanged(Style oldStyle, Style newStyle)
{
if (oldStyle != null)
{
oldStyle.Detach(this);
}
if (newStyle != null)
{
newStyle.Attach(this);
}
}
protected internal override void OnVisualParentChanged(DependencyObject oldParent)
{
if (this.VisualParent != null)
{
this.IsInitialized = true;
}
}
protected sealed override Size MeasureCore(Size availableSize)
{
this.ApplyTemplate();
availableSize = new Size(
Math.Max(0, availableSize.Width - this.Margin.Left - this.Margin.Right),
Math.Max(0, availableSize.Height - this.Margin.Top - this.Margin.Bottom));
Size size = this.MeasureOverride(availableSize);
size = new Size(
Math.Min(availableSize.Width, size.Width + this.Margin.Left + this.Margin.Right),
Math.Min(availableSize.Height, size.Height + this.Margin.Top + this.Margin.Bottom));
return size;
}
protected virtual Size MeasureOverride(Size constraint)
{
return new Size();
}
protected sealed override void ArrangeCore(Rect finalRect)
{
Point origin = new Point(
finalRect.Left + this.Margin.Left,
finalRect.Top + this.Margin.Top);
Size size = new Size(
Math.Max(0, finalRect.Width - this.Margin.Left - this.Margin.Right),
Math.Max(0, finalRect.Height - this.Margin.Top - this.Margin.Bottom));
if (this.HorizontalAlignment != HorizontalAlignment.Stretch)
{
size = new Size(Math.Min(size.Width, this.DesiredSize.Width), size.Height);
}
if (this.VerticalAlignment != VerticalAlignment.Stretch)
{
size = new Size(size.Width, Math.Min(size.Height, this.DesiredSize.Height));
}
Size taken = this.ArrangeOverride(size);
size = new Size(
Math.Min(taken.Width, size.Width),
Math.Min(taken.Height, size.Height));
switch (this.HorizontalAlignment)
{
case HorizontalAlignment.Center:
origin.X += (finalRect.Width - size.Width) / 2;
break;
case HorizontalAlignment.Right:
origin.X += finalRect.Width - size.Width;
break;
}
switch (this.VerticalAlignment)
{
case VerticalAlignment.Center:
origin.Y += (finalRect.Height - size.Height) / 2;
break;
case VerticalAlignment.Bottom:
origin.Y += finalRect.Height - size.Height;
break;
}
base.ArrangeCore(new Rect(origin, size));
}
protected virtual Size ArrangeOverride(Size finalSize)
{
return finalSize;
}
protected virtual void OnInitialized(EventArgs e)
{
if (this.Initialized != null)
{
this.Initialized(this, e);
}
}
private static void StyleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((FrameworkElement)sender).OnStyleChanged((Style)e.OldValue, (Style)e.NewValue);
}
private static void TemplatedParentChanged(object sender, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
element.PropagateTemplatedParent(element, element.TemplatedParent);
}
private INameScope FindNameScope(FrameworkElement e)
{
while (e != null)
{
INameScope nameScope = e as INameScope ?? NameScope.GetNameScope(e);
if (nameScope != null)
{
return nameScope;
}
e = LogicalTreeHelper.GetParent(e) as FrameworkElement;
}
return null;
}
private void PropagateTemplatedParent(FrameworkElement element, DependencyObject templatedParent)
{
element.TemplatedParent = templatedParent;
foreach (FrameworkElement child in LogicalTreeHelper.GetChildren(element).OfType<FrameworkElement>())
{
child.TemplatedParent = templatedParent;
}
}
}
}
| |
#region Header
/**
* JsonMapper.cs
* JSON to .Net object and object to JSON conversions.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace LitJson2
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
public class JsonMapper
{
#region Fields
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
if (type.GetInterface ("System.Collections.IList") != null)
data.IsList = true;
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
if (type.GetInterface ("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (string))
data.ElementType = p_info.PropertyType;
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = t1.GetMethod (
"op_Implicit", new Type[] { t2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
Type underlying_type = Nullable.GetUnderlyingType(inst_type);
Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_type.IsClass || underlying_type != null) {
return null;
}
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType ();
if (value_type.IsAssignableFrom (json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
custom_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
base_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe it's an enum
if (value_type.IsEnum)
return Enum.ToObject (value_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (value_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (value_type);
ObjectMetadata t_data = object_metadata[value_type];
instance = Activator.CreateInstance (value_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary) {
if (! reader.SkipNonMembers) {
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
} else {
ReadSkip (reader);
continue;
}
}
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void ReadSkip (JsonReader reader)
{
ToWrapper (
delegate { return new JsonMockWrapper (); }, reader);
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
MethodInfo method = obj.GetType().GetMethod("get_" + p_info.Name);
object val = method.Invoke(obj, null);
WriteValue (val,
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpResponseMessageTest
{
[Fact]
public void Ctor_Default_CorrectDefaults()
{
using (var rm = new HttpResponseMessage())
{
Assert.Equal(HttpStatusCode.OK, rm.StatusCode);
Assert.Equal("OK", rm.ReasonPhrase);
Assert.Equal(new Version(1, 1), rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(null, rm.RequestMessage);
}
}
[Fact]
public void Ctor_SpecifiedValues_CorrectValues()
{
using (var rm = new HttpResponseMessage(HttpStatusCode.Accepted))
{
Assert.Equal(HttpStatusCode.Accepted, rm.StatusCode);
Assert.Equal("Accepted", rm.ReasonPhrase);
Assert.Equal(new Version(1, 1), rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(null, rm.RequestMessage);
}
}
[Fact]
public void Ctor_InvalidStatusCodeRange_Throw()
{
int x = -1;
Assert.Throws<ArgumentOutOfRangeException>(() => new HttpResponseMessage((HttpStatusCode)x));
x = 1000;
Assert.Throws<ArgumentOutOfRangeException>(() => new HttpResponseMessage((HttpStatusCode)x));
}
[Fact]
public void Dispose_DisposeObject_ContentGetsDisposedAndSettersWillThrowButGettersStillWork()
{
using (var rm = new HttpResponseMessage(HttpStatusCode.OK))
{
var content = new MockContent();
rm.Content = content;
Assert.False(content.IsDisposed);
rm.Dispose();
rm.Dispose(); // Multiple calls don't throw.
Assert.True(content.IsDisposed);
Assert.Throws<ObjectDisposedException>(() => { rm.StatusCode = HttpStatusCode.BadRequest; });
Assert.Throws<ObjectDisposedException>(() => { rm.ReasonPhrase = "Bad Request"; });
Assert.Throws<ObjectDisposedException>(() => { rm.Version = new Version(1, 0); });
Assert.Throws<ObjectDisposedException>(() => { rm.Content = null; });
// Property getters should still work after disposing.
Assert.Equal(HttpStatusCode.OK, rm.StatusCode);
Assert.Equal("OK", rm.ReasonPhrase);
Assert.Equal(new Version(1, 1), rm.Version);
Assert.Equal(content, rm.Content);
}
}
[Fact]
public void Headers_ReadProperty_HeaderCollectionInitialized()
{
using (var rm = new HttpResponseMessage())
{
Assert.NotNull(rm.Headers);
}
}
[Theory]
[InlineData(null, true)]
[InlineData(HttpStatusCode.OK, true)]
[InlineData(HttpStatusCode.PartialContent, true)]
[InlineData(HttpStatusCode.MultipleChoices, false)]
[InlineData(HttpStatusCode.Continue, false)]
[InlineData(HttpStatusCode.BadRequest, false)]
[InlineData(HttpStatusCode.BadGateway, false)]
public void IsSuccessStatusCode_VariousStatusCodes_ReturnTrueFor2xxFalseOtherwise(HttpStatusCode? status, bool expectedSuccess)
{
using (var m = status.HasValue ? new HttpResponseMessage(status.Value) : new HttpResponseMessage())
{
Assert.Equal(expectedSuccess, m.IsSuccessStatusCode);
}
}
[Fact]
public void EnsureSuccessStatusCode_VariousStatusCodes_ThrowIfNot2xx()
{
using (var m = new HttpResponseMessage(HttpStatusCode.MultipleChoices))
{
Assert.Throws<HttpRequestException>(() => m.EnsureSuccessStatusCode());
}
using (var m = new HttpResponseMessage(HttpStatusCode.BadGateway))
{
Assert.Throws<HttpRequestException>(() => m.EnsureSuccessStatusCode());
}
using (var response = new HttpResponseMessage(HttpStatusCode.OK))
{
Assert.Same(response, response.EnsureSuccessStatusCode());
}
}
[Fact]
public void EnsureSuccessStatusCode_AddContentToMessage_ContentIsDisposed()
{
using (var response404 = new HttpResponseMessage(HttpStatusCode.NotFound))
{
response404.Content = new MockContent();
Assert.Throws<HttpRequestException>(() => response404.EnsureSuccessStatusCode());
Assert.True((response404.Content as MockContent).IsDisposed);
}
using (var response200 = new HttpResponseMessage(HttpStatusCode.OK))
{
response200.Content = new MockContent();
response200.EnsureSuccessStatusCode(); // No exception.
Assert.False((response200.Content as MockContent).IsDisposed);
}
}
[Fact]
public void Properties_SetPropertiesAndGetTheirValue_MatchingValues()
{
using (var rm = new HttpResponseMessage())
{
var content = new MockContent();
HttpStatusCode statusCode = HttpStatusCode.LengthRequired;
string reasonPhrase = "Length Required";
var version = new Version(1, 0);
var requestMessage = new HttpRequestMessage();
rm.Content = content;
rm.ReasonPhrase = reasonPhrase;
rm.RequestMessage = requestMessage;
rm.StatusCode = statusCode;
rm.Version = version;
Assert.Equal(content, rm.Content);
Assert.Equal(reasonPhrase, rm.ReasonPhrase);
Assert.Equal(requestMessage, rm.RequestMessage);
Assert.Equal(statusCode, rm.StatusCode);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
}
}
[Fact]
public void Version_SetToNull_ThrowsArgumentNullException()
{
using (var rm = new HttpResponseMessage())
{
Assert.Throws<ArgumentNullException>(() => { rm.Version = null; });
}
}
[Fact]
public void ReasonPhrase_ContainsCRChar_ThrowsFormatException()
{
using (var rm = new HttpResponseMessage())
{
Assert.Throws<FormatException>(() => { rm.ReasonPhrase = "text\rtext"; });
}
}
[Fact]
public void ReasonPhrase_ContainsLFChar_ThrowsFormatException()
{
using (var rm = new HttpResponseMessage())
{
Assert.Throws<FormatException>(() => { rm.ReasonPhrase = "text\ntext"; });
}
}
[Fact]
public void ReasonPhrase_SetToNull_Accepted()
{
using (var rm = new HttpResponseMessage())
{
rm.ReasonPhrase = null;
Assert.Equal("OK", rm.ReasonPhrase); // Default provided.
}
}
[Fact]
public void ReasonPhrase_UnknownStatusCode_Null()
{
using (var rm = new HttpResponseMessage())
{
rm.StatusCode = (HttpStatusCode)150; // Default reason unknown.
Assert.Null(rm.ReasonPhrase); // No default provided.
}
}
[Fact]
public void ReasonPhrase_SetToEmpty_Accepted()
{
using (var rm = new HttpResponseMessage())
{
rm.ReasonPhrase = String.Empty;
Assert.Equal(String.Empty, rm.ReasonPhrase);
}
}
[Fact]
public void Content_SetToNull_Accepted()
{
using (var rm = new HttpResponseMessage())
{
rm.Content = null;
Assert.Null(rm.Content);
}
}
[Fact]
public void StatusCode_InvalidStatusCodeRange_ThrowsArgumentOutOfRangeException()
{
using (var rm = new HttpResponseMessage())
{
int x = -1;
Assert.Throws<ArgumentOutOfRangeException>(() => { rm.StatusCode = (HttpStatusCode)x; });
x = 1000;
Assert.Throws<ArgumentOutOfRangeException>(() => { rm.StatusCode = (HttpStatusCode)x; });
}
}
[Fact]
public void ToString_DefaultAndNonDefaultInstance_DumpAllFields()
{
using (var rm = new HttpResponseMessage())
{
Assert.Equal("StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: <null>, Headers:\r\n{\r\n}", rm.ToString());
rm.StatusCode = HttpStatusCode.BadRequest;
rm.ReasonPhrase = null;
rm.Version = new Version(1, 0);
rm.Content = new StringContent("content");
// Note that there is no Content-Length header: The reason is that the value for Content-Length header
// doesn't get set by StringContent..ctor, but only if someone actually accesses the ContentLength property.
Assert.Equal(
"StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:\r\n" +
"{\r\n" +
" Content-Type: text/plain; charset=utf-8\r\n" +
"}", rm.ToString());
rm.Headers.AcceptRanges.Add("bytes");
rm.Headers.AcceptRanges.Add("pages");
rm.Headers.Add("Custom-Response-Header", "value1");
rm.Content.Headers.Add("Custom-Content-Header", "value2");
Assert.Equal(
"StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:\r\n" +
"{\r\n" +
" Accept-Ranges: bytes\r\n" +
" Accept-Ranges: pages\r\n" +
" Custom-Response-Header: value1\r\n" +
" Content-Type: text/plain; charset=utf-8\r\n" +
" Custom-Content-Header: value2\r\n" +
"}", rm.ToString());
}
}
#region Helper methods
private class MockContent : HttpContent
{
public bool IsDisposed { get; private set; }
protected override bool TryComputeLength(out long length)
{
throw new NotImplementedException();
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
throw new NotImplementedException();
}
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
}
#endregion
}
}
| |
/*
* 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.Collections.Specialized;
using System.Linq;
using System.Management.Automation;
using Trisoft.ISHRemote.DocumentObj25ServiceReference;
using Trisoft.ISHRemote.Objects;
using Trisoft.ISHRemote.Objects.Public;
using Trisoft.ISHRemote.Exceptions;
namespace Trisoft.ISHRemote.Cmdlets.DocumentObj
{
/// <summary>
/// <para type="synopsis">The Remove-IshDocumentObj cmdlet removes the document objects that are passed through the pipeline or determined via provided parameters This commandlet allows to remove all types of objects (Illustrations, Maps, etc. ), except for publication (outputs).
/// For publication (outputs) you need to use Remove-IshPublicationOutput.</para>
/// <para type="description">The Remove-IshDocumentObj cmdlet removes the document objects that are passed through the pipeline or determined via provided parameters This commandlet allows to remove all types of objects (Illustrations, Maps, etc. ), except for publication (outputs).
/// For publication (outputs) you need to use Remove-IshPublicationOutput.</para>
/// </summary>
/// <example>
/// <code>
/// $ishSession = New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -PSCredential Admin
/// Get-IshFolder -FolderPath $folderCmdletRootPath -Recurse |
/// Get-IshFolderContent |
/// Remove-IshDocumentObj -Force
/// </code>
/// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Removes all content objects from the listed folder and its subfolders.</para>
/// </example>
[Cmdlet(VerbsCommon.Remove, "IshDocumentObj", SupportsShouldProcess = true)]
public sealed class RemoveIshDocumentObj : DocumentObjCmdlet
{
/// <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 = "ParameterGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")]
[ValidateNotNullOrEmpty]
public IshSession IshSession { get; set; }
/// <summary>
/// <para type="description">The logical identifier of the document object</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty]
public string LogicalId { get; set; }
/// <summary>
/// <para type="description">The version of the document object</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty]
public string Version { get; set; }
/// <summary>
/// <para type="description">The language of the document object</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty]
public string Lng { get; set; }
/// <summary>
/// <para type="description">The resolution of the document object</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty]
public string Resolution { get; set; }
/// <summary>
/// <para type="description">The required current metadata of the document object. This parameter can be used to avoid that users override changes done by other users. The cmdlet will check whether the fields provided in this parameter still have the same values in the repository:</para>
/// <para type="description">If the metadata is still the same, the document object is removed.</para>
/// <para type="description">If the metadata is not the same anymore, an error is given and the document object is not removed.</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")]
[ValidateNotNullOrEmpty]
public IshField[] RequiredCurrentMetadata { get; set; }
/// <summary>
/// <para type="description">Array with the objects to remove. This array can be passed through the pipeline or explicitly passed via the parameter.</para>
/// </summary>
/// TODO [Should] Promote parameter IshObject to IshObject[] processing
[Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshObjectsGroup")]
public IshObject IshObject { get; set; }
/// <summary>
/// <para type="description">When the Force switch is set, after deleting the language object, the version object and logical object will be deleted if they don't have any language objects anymore</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")]
[ValidateNotNullOrEmpty]
public SwitchParameter Force { get; set; }
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 Remove-IshDocumentObj commandlet.
/// </summary>
/// <exception cref="TrisoftAutomationException"></exception>
/// <exception cref="Exception"></exception>
protected override void ProcessRecord()
{
try
{
// 1. Validating the input
WriteDebug("Validating");
var logicalIdsVersionsCollection = new NameValueCollection();
WriteDebug("Removing");
IshFields requiredCurrentMetadata = new IshFields(RequiredCurrentMetadata);
if (IshObject != null)
{
long lngRef = Convert.ToInt64(IshObject.ObjectRef[Enumerations.ReferenceType.Lng]);
WriteDebug($"Removing lngCardId[{lngRef}]");
if (ShouldProcess(Convert.ToString(lngRef)))
{
IshSession.DocumentObj25.DeleteByIshLngRef(lngRef, requiredCurrentMetadata.ToXml());
}
logicalIdsVersionsCollection.Add(IshObject.IshRef, IshObject.IshFields.GetFieldValue("VERSION", Enumerations.Level.Version, Enumerations.ValueType.Value));
}
else
{
string resolution = Resolution ?? "";
string lng = Lng ?? "";
if (lng.Length > 0)
{
// only delete when you have a lanuage, lower the version delete (so empty lng) is handled
WriteDebug($"Removing LogicalId[{LogicalId}] Version[{Version}] Lng[{lng}] Resolution[{resolution}]");
if (ShouldProcess(LogicalId + "=" + Version + "=" + lng + "=" + resolution))
{
IshSession.DocumentObj25.Delete(
LogicalId,
Version,
lng,
resolution,
requiredCurrentMetadata.ToXml());
}
}
logicalIdsVersionsCollection.Add(LogicalId, Version);
}
if (Force.IsPresent && logicalIdsVersionsCollection.Count > 0)
{
var xmlIshObjects = IshSession.DocumentObj25.RetrieveMetadata(logicalIdsVersionsCollection.AllKeys.ToArray(),
StatusFilter.ISHNoStatusFilter, "", "<ishfields><ishfield name='VERSION' level='version'/><ishfield name='DOC-LANGUAGE' level='lng'/></ishfields>");
List<IshObject> retrievedObjects = new List<IshObject>();
retrievedObjects.AddRange(new IshObjects(xmlIshObjects).Objects);
// Delete versions which do not have any language card anymore
foreach (string logicalId in logicalIdsVersionsCollection.AllKeys)
{
var versions = logicalIdsVersionsCollection.GetValues(logicalId).Distinct();
foreach (var version in versions)
{
bool versionWithLanguagesFound = false;
foreach (var retrievedObject in retrievedObjects)
{
if (retrievedObject.IshRef == logicalId && retrievedObject.IshFields.GetFieldValue("VERSION", Enumerations.Level.Version, Enumerations.ValueType.Value) == version)
{
versionWithLanguagesFound = true;
}
}
if (!versionWithLanguagesFound)
{
if (ShouldProcess(LogicalId + "=" + version + "=" + "="))
{
IshSession.DocumentObj25.Delete(logicalId, version, "", "", "");
}
}
}
}
// Delete logical cards which do not have any languages anymore
foreach (string logicalId in logicalIdsVersionsCollection.AllKeys)
{
bool logicalIdFound = false;
foreach (var retrievedObject in retrievedObjects)
{
if (retrievedObject.IshRef == logicalId)
{
logicalIdFound = true;
}
}
if (!logicalIdFound)
{
if (ShouldProcess(LogicalId + "=" + "=" + "="))
{
IshSession.DocumentObj25.Delete(logicalId, "", "", "", "");
}
}
}
}
WriteVerbose("returned object count[0]");
}
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));
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
internal enum State
{
Start = 0,
Property = 1,
ObjectStart = 2,
Object = 3,
ArrayStart = 4,
Array = 5,
ConstructorStart = 6,
Constructor = 7,
Closed = 8,
Error = 9
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] StateArray;
internal static readonly State[][] StateArrayTempate = new[]
{
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }
};
internal static State[][] BuildStateArray()
{
var allStates = StateArrayTempate.ToList();
var errorStates = StateArrayTempate[0];
var valueStates = StateArrayTempate[7];
foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken)))
{
if (allStates.Count <= (int)valueToken)
{
switch (valueToken)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
allStates.Add(valueStates);
break;
default:
allStates.Add(errorStates);
break;
}
}
}
return allStates.ToArray();
}
static JsonWriter()
{
StateArray = BuildStateArray();
}
private readonly List<JsonPosition> _stack;
private JsonPosition _currentPosition;
private State _currentState;
private State _lastStateForWriteIndent;
private Formatting _formatting;
private bool _isIndentPrimitiveArray = true;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the writer is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the writer is closed; otherwise false. The default is true.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get
{
int depth = _stack.Count;
if (Peek() != JsonContainerType.None)
depth++;
return depth;
}
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null);
}
}
}
internal string ContainerPath
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
return JsonPosition.BuildPath(_stack);
}
}
/// <summary>
/// Gets the path of the writer.
/// </summary>
public string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
IEnumerable<JsonPosition> positions = (!insideContainer)
? _stack
: _stack.Concat(new[] { _currentPosition });
return JsonPosition.BuildPath(positions);
}
}
private DateFormatHandling _dateFormatHandling;
private DateTimeZoneHandling _dateTimeZoneHandling;
private StringEscapeHandling _stringEscapeHandling;
private FloatFormatHandling _floatFormatHandling;
private string _dateFormatString;
private CultureInfo _culture;
/// <summary>
/// Indicates how JSON text output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set { _formatting = value; }
}
/// <summary>
/// IsIndentPrimitiveArray
/// </summary>
public bool IsIndentPrimitiveArray
{
get { return _isIndentPrimitiveArray; }
set { _isIndentPrimitiveArray = value; }
}
/// <summary>
/// Get or set how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get { return _dateFormatHandling; }
set { _dateFormatHandling = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when writing JSON text.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get { return _stringEscapeHandling; }
set
{
_stringEscapeHandling = value;
OnStringEscapeHandlingChanged();
}
}
internal virtual void OnStringEscapeHandlingChanged()
{
// hacky but there is a calculated value that relies on StringEscapeHandling
}
/// <summary>
/// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>,
/// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>,
/// are written to JSON text.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get { return _floatFormatHandling; }
set { _floatFormatHandling = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString; }
set { _dateFormatString = value; }
}
/// <summary>
/// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class.
/// </summary>
protected JsonWriter()
{
_stack = new List<JsonPosition>(4);
_currentState = State.Start;
_formatting = Formatting.None;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
CloseOutput = true;
}
internal void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
_currentPosition.Position++;
}
private void Push(JsonContainerType value)
{
if (_currentPosition.Type != JsonContainerType.None)
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
}
private JsonContainerType Pop()
{
JsonPosition oldPosition = _currentPosition;
if (_stack.Count > 0)
{
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
_currentPosition = new JsonPosition();
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public virtual void Close()
{
AutoCompleteAll();
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
public virtual void WriteStartObject()
{
InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);
}
/// <summary>
/// Writes the end of a JSON object.
/// </summary>
public virtual void WriteEndObject()
{
InternalWriteEnd(JsonContainerType.Object);
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
public virtual void WriteStartArray()
{
InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
InternalWriteEnd(JsonContainerType.Array);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
InternalWriteEnd(JsonContainerType.Constructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
InternalWritePropertyName(name);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param>
public virtual void WritePropertyName(string name, bool escape)
{
WritePropertyName(name);
}
/// <summary>
/// Writes the end of the current JSON object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token and its children.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
WriteToken(reader, true, true);
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
/// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param>
public void WriteToken(JsonReader reader, bool writeChildren)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
WriteToken(reader, writeChildren, true);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token and its value.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
/// <param name="value">
/// The value to write.
/// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>.
/// A null value can be passed to the method for token's that don't have a value, e.g. <see cref="JsonToken.StartObject"/>.</param>
public void WriteToken(JsonToken token, object value)
{
WriteTokenInternal(token, value);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
public void WriteToken(JsonToken token)
{
WriteTokenInternal(token, null);
}
internal void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate)
{
int initialDepth;
if (reader.TokenType == JsonToken.None)
initialDepth = -1;
else if (!JsonTokenUtils.IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1;
else
initialDepth = reader.Depth;
WriteToken(reader, initialDepth, writeChildren, writeDateConstructorAsDate);
}
internal void WriteToken(JsonReader reader, int initialDepth, bool writeChildren, bool writeDateConstructorAsDate)
{
do
{
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
WriteConstructorDate(reader);
else
WriteTokenInternal(reader.TokenType, reader.Value);
} while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
}
private void WriteTokenInternal(JsonToken tokenType, object value)
{
switch (tokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
ValidationUtils.ArgumentNotNull(value, "value");
WriteStartConstructor(value.ToString());
break;
case JsonToken.PropertyName:
ValidationUtils.ArgumentNotNull(value, "value");
WritePropertyName(value.ToString());
break;
case JsonToken.Comment:
WriteComment((value != null) ? value.ToString() : null);
break;
case JsonToken.Integer:
ValidationUtils.ArgumentNotNull(value, "value");
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
if (value is BigInteger)
{
WriteValue((BigInteger)value);
}
else
#endif
{
WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
ValidationUtils.ArgumentNotNull(value, "value");
if (value is decimal)
WriteValue((decimal)value);
else if (value is double)
WriteValue((double)value);
else if (value is float)
WriteValue((float)value);
else
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
break;
case JsonToken.String:
ValidationUtils.ArgumentNotNull(value, "value");
WriteValue(value.ToString());
break;
case JsonToken.Boolean:
ValidationUtils.ArgumentNotNull(value, "value");
WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
ValidationUtils.ArgumentNotNull(value, "value");
#if !NET20
if (value is DateTimeOffset)
WriteValue((DateTimeOffset)value);
else
#endif
WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture));
break;
case JsonToken.Raw:
WriteRawValue((value != null) ? value.ToString() : null);
break;
case JsonToken.Bytes:
ValidationUtils.ArgumentNotNull(value, "value");
if (value is Guid)
WriteValue((Guid)value);
else
WriteValue((byte[])value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", tokenType, "Unexpected token type.");
}
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
if (reader.TokenType != JsonToken.Integer)
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null);
long ticks = (long)reader.Value;
DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
if (reader.TokenType != JsonToken.EndConstructor)
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null);
WriteValue(date);
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
WriteEndObject();
break;
case JsonContainerType.Array:
WriteEndArray();
break;
case JsonContainerType.Constructor:
WriteEndConstructor();
break;
default:
throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null);
}
}
private void AutoCompleteAll()
{
while (Top > 0)
{
WriteEnd();
}
}
private JsonToken GetCloseTokenForType(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
return JsonToken.EndObject;
case JsonContainerType.Array:
return JsonToken.EndArray;
case JsonContainerType.Constructor:
return JsonToken.EndConstructor;
default:
throw JsonWriterException.Create(this, "No close token for type: " + type, null);
}
}
private void AutoCompleteClose(JsonContainerType type)
{
// write closing symbol and calculate new state
int levelsToComplete = 0;
if (_currentPosition.Type == type)
{
levelsToComplete = 1;
}
else
{
int top = Top - 2;
for (int i = top; i >= 0; i--)
{
int currentLevel = top - i;
if (_stack[currentLevel].Type == type)
{
levelsToComplete = i + 2;
break;
}
}
}
if (levelsToComplete == 0)
throw JsonWriterException.Create(this, "No token to close.", null);
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
#if DEBUG
WriteDebugInfo(_currentState.ToString() + "--token:" + token.ToString());
#endif
if (_currentState == State.Property)
WriteNull();
if (_formatting == Formatting.Indented)
{
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
WriteIndent();
}
WriteEnd(token);
JsonContainerType currentLevelType = Peek();
switch (currentLevelType)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Array;
break;
case JsonContainerType.None:
_currentState = State.Start;
break;
default:
throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null);
}
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
// gets new state based on the current state and what is being written
State newState = StateArray[(int)tokenBeingWritten][(int)_currentState];
if (newState == State.Error)
throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null);
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
if (_formatting == Formatting.Indented)
{
#if DEBUG
WriteDebugInfo(_currentState.ToString() + "->" + newState.ToString() + "--token:" + tokenBeingWritten);
#endif
if (_currentState == State.Property)
WriteIndentSpace();
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart)
|| (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start))
{
if (_isIndentPrimitiveArray)
{
WriteIndent();
}
else
{
if (_currentState == State.Array)
{
if (_lastStateForWriteIndent != State.Array && _lastStateForWriteIndent != State.ArrayStart
|| newState != State.Array
)
{
WriteIndent();
}
else
{
WriteIndentSpace();
}
}
else
{
WriteIndent();
}
}
}
}
_lastStateForWriteIndent = _currentState;
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
InternalWriteValue(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
InternalWriteValue(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
InternalWriteRaw();
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
UpdateScopeWithFinishedValue();
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
InternalWriteValue(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
InternalWriteValue(JsonToken.Date);
}
#if !NET20
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
InternalWriteValue(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{Int32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Single}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Double}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Boolean}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Char}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Byte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{SByte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Decimal}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{DateTime}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#if !NET20
/// <summary>
/// Writes a <see cref="Nullable{DateTimeOffset}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{Guid}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{TimeSpan}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
WriteNull();
else
InternalWriteValue(JsonToken.Bytes);
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
{
if (value == null)
WriteNull();
else
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
}
else
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
// this is here because adding a WriteValue(BigInteger) to JsonWriter will
// mean the user has to add a reference to System.Numerics.dll
if (value is BigInteger)
throw CreateUnsupportedTypeException(this, value);
#endif
WriteValue(this, ConvertUtils.GetTypeCode(value.GetType()), value);
}
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
InternalWriteComment();
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
InternalWriteWhitespace(ws);
}
void IDisposable.Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_currentState != State.Closed)
Close();
}
internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value)
{
switch (typeCode)
{
case PrimitiveTypeCode.Char:
writer.WriteValue((char)value);
break;
case PrimitiveTypeCode.CharNullable:
writer.WriteValue((value == null) ? (char?)null : (char)value);
break;
case PrimitiveTypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case PrimitiveTypeCode.BooleanNullable:
writer.WriteValue((value == null) ? (bool?)null : (bool)value);
break;
case PrimitiveTypeCode.SByte:
writer.WriteValue((sbyte)value);
break;
case PrimitiveTypeCode.SByteNullable:
writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value);
break;
case PrimitiveTypeCode.Int16:
writer.WriteValue((short)value);
break;
case PrimitiveTypeCode.Int16Nullable:
writer.WriteValue((value == null) ? (short?)null : (short)value);
break;
case PrimitiveTypeCode.UInt16:
writer.WriteValue((ushort)value);
break;
case PrimitiveTypeCode.UInt16Nullable:
writer.WriteValue((value == null) ? (ushort?)null : (ushort)value);
break;
case PrimitiveTypeCode.Int32:
writer.WriteValue((int)value);
break;
case PrimitiveTypeCode.Int32Nullable:
writer.WriteValue((value == null) ? (int?)null : (int)value);
break;
case PrimitiveTypeCode.Byte:
writer.WriteValue((byte)value);
break;
case PrimitiveTypeCode.ByteNullable:
writer.WriteValue((value == null) ? (byte?)null : (byte)value);
break;
case PrimitiveTypeCode.UInt32:
writer.WriteValue((uint)value);
break;
case PrimitiveTypeCode.UInt32Nullable:
writer.WriteValue((value == null) ? (uint?)null : (uint)value);
break;
case PrimitiveTypeCode.Int64:
writer.WriteValue((long)value);
break;
case PrimitiveTypeCode.Int64Nullable:
writer.WriteValue((value == null) ? (long?)null : (long)value);
break;
case PrimitiveTypeCode.UInt64:
writer.WriteValue((ulong)value);
break;
case PrimitiveTypeCode.UInt64Nullable:
writer.WriteValue((value == null) ? (ulong?)null : (ulong)value);
break;
case PrimitiveTypeCode.Single:
writer.WriteValue((float)value);
break;
case PrimitiveTypeCode.SingleNullable:
writer.WriteValue((value == null) ? (float?)null : (float)value);
break;
case PrimitiveTypeCode.Double:
writer.WriteValue((double)value);
break;
case PrimitiveTypeCode.DoubleNullable:
writer.WriteValue((value == null) ? (double?)null : (double)value);
break;
case PrimitiveTypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case PrimitiveTypeCode.DateTimeNullable:
writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value);
break;
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
writer.WriteValue((DateTimeOffset)value);
break;
case PrimitiveTypeCode.DateTimeOffsetNullable:
writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value);
break;
#endif
case PrimitiveTypeCode.Decimal:
writer.WriteValue((decimal)value);
break;
case PrimitiveTypeCode.DecimalNullable:
writer.WriteValue((value == null) ? (decimal?)null : (decimal)value);
break;
case PrimitiveTypeCode.Guid:
writer.WriteValue((Guid)value);
break;
case PrimitiveTypeCode.GuidNullable:
writer.WriteValue((value == null) ? (Guid?)null : (Guid)value);
break;
case PrimitiveTypeCode.TimeSpan:
writer.WriteValue((TimeSpan)value);
break;
case PrimitiveTypeCode.TimeSpanNullable:
writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value);
break;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
// this will call to WriteValue(object)
writer.WriteValue((BigInteger)value);
break;
case PrimitiveTypeCode.BigIntegerNullable:
// this will call to WriteValue(object)
writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value);
break;
#endif
case PrimitiveTypeCode.Uri:
writer.WriteValue((Uri)value);
break;
case PrimitiveTypeCode.String:
writer.WriteValue((string)value);
break;
case PrimitiveTypeCode.Bytes:
writer.WriteValue((byte[])value);
break;
#if !(PORTABLE || DOTNET)
case PrimitiveTypeCode.DBNull:
writer.WriteNull();
break;
#endif
default:
#if !PORTABLE
if (value is IConvertible)
{
// the value is a non-standard IConvertible
// convert to the underlying value and retry
IConvertible convertable = (IConvertible)value;
TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertable);
// if convertable has an underlying typecode of Object then attempt to convert it to a string
PrimitiveTypeCode resolvedTypeCode = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? PrimitiveTypeCode.String : typeInformation.TypeCode;
Type resolvedType = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? typeof(string) : typeInformation.Type;
object convertedValue = convertable.ToType(resolvedType, CultureInfo.InvariantCulture);
WriteValue(writer, resolvedTypeCode, convertedValue);
break;
}
else
#endif
{
throw CreateUnsupportedTypeException(writer, value);
}
}
}
private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value)
{
return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
/// <summary>
/// Sets the state of the JsonWriter,
/// </summary>
/// <param name="token">The JsonToken being written.</param>
/// <param name="value">The value being written.</param>
protected void SetWriteState(JsonToken token, object value)
{
switch (token)
{
case JsonToken.StartObject:
InternalWriteStart(token, JsonContainerType.Object);
break;
case JsonToken.StartArray:
InternalWriteStart(token, JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
InternalWriteStart(token, JsonContainerType.Constructor);
break;
case JsonToken.PropertyName:
if (!(value is string))
throw new ArgumentException("A name is required when setting property name state.", "value");
InternalWritePropertyName((string)value);
break;
case JsonToken.Comment:
InternalWriteComment();
break;
case JsonToken.Raw:
InternalWriteRaw();
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
case JsonToken.Null:
case JsonToken.Undefined:
InternalWriteValue(token);
break;
case JsonToken.EndObject:
InternalWriteEnd(JsonContainerType.Object);
break;
case JsonToken.EndArray:
InternalWriteEnd(JsonContainerType.Array);
break;
case JsonToken.EndConstructor:
InternalWriteEnd(JsonContainerType.Constructor);
break;
default:
throw new ArgumentOutOfRangeException("token");
}
}
internal void InternalWriteEnd(JsonContainerType container)
{
AutoCompleteClose(container);
}
internal void InternalWritePropertyName(string name)
{
_currentPosition.PropertyName = name;
AutoComplete(JsonToken.PropertyName);
}
internal void InternalWriteRaw()
{
}
internal void InternalWriteStart(JsonToken token, JsonContainerType container)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
Push(container);
}
internal void InternalWriteValue(JsonToken token)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
}
internal void InternalWriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
throw JsonWriterException.Create(this, "Only white space characters should be used.", null);
}
}
internal void InternalWriteComment()
{
AutoComplete(JsonToken.Comment);
}
#if DEBUG
internal virtual void WriteDebugInfo(string info)
{
}
#endif
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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;
namespace Google.Protobuf
{
// This part of CodedOutputStream provides all the static entry points that are used
// by generated code and internally to compute the size of messages prior to being
// written to an instance of CodedOutputStream.
public sealed partial class CodedOutputStream
{
private const int LittleEndian64Size = 8;
private const int LittleEndian32Size = 4;
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// double field, including the tag.
/// </summary>
public static int ComputeDoubleSize(double value)
{
return LittleEndian64Size;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// float field, including the tag.
/// </summary>
public static int ComputeFloatSize(float value)
{
return LittleEndian32Size;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// uint64 field, including the tag.
/// </summary>
public static int ComputeUInt64Size(ulong value)
{
return ComputeRawVarint64Size(value);
}
/// <summary>
/// Computes the number of bytes that would be needed to encode an
/// int64 field, including the tag.
/// </summary>
public static int ComputeInt64Size(long value)
{
return ComputeRawVarint64Size((ulong) value);
}
/// <summary>
/// Computes the number of bytes that would be needed to encode an
/// int32 field, including the tag.
/// </summary>
public static int ComputeInt32Size(int value)
{
if (value >= 0)
{
return ComputeRawVarint32Size((uint) value);
}
else
{
// Must sign-extend.
return 10;
}
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// fixed64 field, including the tag.
/// </summary>
public static int ComputeFixed64Size(ulong value)
{
return LittleEndian64Size;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// fixed32 field, including the tag.
/// </summary>
public static int ComputeFixed32Size(uint value)
{
return LittleEndian32Size;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// bool field, including the tag.
/// </summary>
public static int ComputeBoolSize(bool value)
{
return 1;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// string field, including the tag.
/// </summary>
public static int ComputeStringSize(String value)
{
int byteArraySize = Utf8Encoding.GetByteCount(value);
return ComputeLengthSize(byteArraySize) + byteArraySize;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// group field, including the tag.
/// </summary>
public static int ComputeGroupSize(IMessage value)
{
return value.CalculateSize();
}
/// <summary>
/// Computes the number of bytes that would be needed to encode an
/// embedded message field, including the tag.
/// </summary>
public static int ComputeMessageSize(IMessage value)
{
int size = value.CalculateSize();
return ComputeLengthSize(size) + size;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// bytes field, including the tag.
/// </summary>
public static int ComputeBytesSize(ByteString value)
{
return ComputeLengthSize(value.Length) + value.Length;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// uint32 field, including the tag.
/// </summary>
public static int ComputeUInt32Size(uint value)
{
return ComputeRawVarint32Size(value);
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a
/// enum field, including the tag. The caller is responsible for
/// converting the enum value to its numeric value.
/// </summary>
public static int ComputeEnumSize(int value)
{
// Currently just a pass-through, but it's nice to separate it logically.
return ComputeInt32Size(value);
}
/// <summary>
/// Computes the number of bytes that would be needed to encode an
/// sfixed32 field, including the tag.
/// </summary>
public static int ComputeSFixed32Size(int value)
{
return LittleEndian32Size;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode an
/// sfixed64 field, including the tag.
/// </summary>
public static int ComputeSFixed64Size(long value)
{
return LittleEndian64Size;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode an
/// sint32 field, including the tag.
/// </summary>
public static int ComputeSInt32Size(int value)
{
return ComputeRawVarint32Size(EncodeZigZag32(value));
}
/// <summary>
/// Computes the number of bytes that would be needed to encode an
/// sint64 field, including the tag.
/// </summary>
public static int ComputeSInt64Size(long value)
{
return ComputeRawVarint64Size(EncodeZigZag64(value));
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a length,
/// as written by <see cref="WriteLength"/>.
/// </summary>
public static int ComputeLengthSize(int length)
{
return ComputeRawVarint32Size((uint) length);
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a varint.
/// </summary>
public static int ComputeRawVarint32Size(uint value)
{
if ((value & (0xffffffff << 7)) == 0)
{
return 1;
}
if ((value & (0xffffffff << 14)) == 0)
{
return 2;
}
if ((value & (0xffffffff << 21)) == 0)
{
return 3;
}
if ((value & (0xffffffff << 28)) == 0)
{
return 4;
}
return 5;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a varint.
/// </summary>
public static int ComputeRawVarint64Size(ulong value)
{
if ((value & (0xffffffffffffffffL << 7)) == 0)
{
return 1;
}
if ((value & (0xffffffffffffffffL << 14)) == 0)
{
return 2;
}
if ((value & (0xffffffffffffffffL << 21)) == 0)
{
return 3;
}
if ((value & (0xffffffffffffffffL << 28)) == 0)
{
return 4;
}
if ((value & (0xffffffffffffffffL << 35)) == 0)
{
return 5;
}
if ((value & (0xffffffffffffffffL << 42)) == 0)
{
return 6;
}
if ((value & (0xffffffffffffffffL << 49)) == 0)
{
return 7;
}
if ((value & (0xffffffffffffffffL << 56)) == 0)
{
return 8;
}
if ((value & (0xffffffffffffffffL << 63)) == 0)
{
return 9;
}
return 10;
}
/// <summary>
/// Computes the number of bytes that would be needed to encode a tag.
/// </summary>
public static int ComputeTagSize(int fieldNumber)
{
return ComputeRawVarint32Size(WireFormat.MakeTag(fieldNumber, 0));
}
}
}
| |
/*
* 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.SS.Formula.Functions
{
using System;
using System.Text;
using System.Text.RegularExpressions;
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using System.Globalization;
/**
* Implementation for the function COUNTIF<p/>
*
* Syntax: COUNTIF ( range, criteria )
* <table border="0" cellpAdding="1" cellspacing="0" summary="Parameter descriptions">
* <tr><th>range </th><td>is the range of cells to be Counted based on the criteria</td></tr>
* <tr><th>criteria</th><td>is used to determine which cells to Count</td></tr>
* </table>
* <p/>
*
* @author Josh Micich
*/
public class Countif : Fixed2ArgFunction
{
internal class CmpOp
{
public const int NONE = 0;
public const int EQ = 1;
public const int NE = 2;
public const int LE = 3;
public const int LT = 4;
public const int GT = 5;
public const int GE = 6;
public static readonly CmpOp OP_NONE = op("", NONE);
public static readonly CmpOp OP_EQ = op("=", EQ);
public static readonly CmpOp OP_NE = op("<>", NE);
public static readonly CmpOp OP_LE = op("<=", LE);
public static readonly CmpOp OP_LT = op("<", LT);
public static readonly CmpOp OP_GT = op(">", GT);
public static readonly CmpOp OP_GE = op(">=", GE);
private String _representation;
private int _code;
private static CmpOp op(String rep, int code)
{
return new CmpOp(rep, code);
}
private CmpOp(String representation, int code)
{
_representation = representation;
_code = code;
}
/**
* @return number of characters used to represent this operator
*/
public int Length
{
get
{
return _representation.Length;
}
}
public int Code
{
get
{
return _code;
}
}
public static CmpOp GetOperator(String value)
{
int len = value.Length;
if (len < 1)
{
return OP_NONE;
}
char firstChar = value[0];
switch (firstChar)
{
case '=':
return OP_EQ;
case '>':
if (len > 1)
{
switch (value[1])
{
case '=':
return OP_GE;
}
}
return OP_GT;
case '<':
if (len > 1)
{
switch (value[1])
{
case '=':
return OP_LE;
case '>':
return OP_NE;
}
}
return OP_LT;
}
return OP_NONE;
}
public bool Evaluate(bool cmpResult)
{
switch (_code)
{
case NONE:
case EQ:
return cmpResult;
case NE:
return !cmpResult;
}
throw new Exception("Cannot call bool Evaluate on non-equality operator '"
+ _representation + "'");
}
public bool Evaluate(int cmpResult)
{
switch (_code)
{
case NONE:
case EQ:
return cmpResult == 0;
case NE: return cmpResult != 0;
case LT: return cmpResult < 0;
case LE: return cmpResult <= 0;
case GT: return cmpResult > 0;
case GE: return cmpResult >= 0;
}
throw new Exception("Cannot call bool Evaluate on non-equality operator '"
+ _representation + "'");
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(this.GetType().Name);
sb.Append(" [").Append(_representation).Append("]");
return sb.ToString();
}
public String Representation
{
get
{
return _representation;
}
}
}
internal abstract class MatcherBase : IMatchPredicate
{
private CmpOp _operator;
protected MatcherBase(CmpOp operator1)
{
_operator = operator1;
}
protected int Code
{
get
{
return _operator.Code;
}
}
protected bool Evaluate(int cmpResult)
{
return _operator.Evaluate(cmpResult);
}
protected bool Evaluate(bool cmpResult)
{
return _operator.Evaluate(cmpResult);
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(this.GetType().Name).Append(" [");
sb.Append(_operator.Representation);
sb.Append(ValueText);
sb.Append("]");
return sb.ToString();
}
protected abstract String ValueText { get; }
public abstract bool Matches(ValueEval x);
}
private class ErrorMatcher : MatcherBase
{
private int _value;
public ErrorMatcher(int errorCode, CmpOp operator1)
: base(operator1)
{
;
_value = errorCode;
}
protected override String ValueText
{
get
{
return ErrorConstants.GetText(_value);
}
}
public override bool Matches(ValueEval x)
{
if (x is ErrorEval)
{
int testValue = ((ErrorEval)x).ErrorCode;
return Evaluate(testValue - _value);
}
return false;
}
}
private class NumberMatcher : MatcherBase
{
private double _value;
public NumberMatcher(double value, CmpOp optr)
: base(optr)
{
_value = value;
}
public override bool Matches(ValueEval x)
{
double testValue;
if (x is StringEval)
{
// if the target(x) is a string, but parses as a number
// it may still count as a match, only for the equality operator
switch (Code)
{
case CmpOp.EQ:
case CmpOp.NONE:
break;
case CmpOp.NE:
// Always matches (inconsistent with above two cases).
// for example '<>123' matches '123', '4', 'abc', etc
return true;
default:
// never matches (also inconsistent with above three cases).
// for example '>5' does not match '6',
return false;
}
StringEval se = (StringEval)x;
Double val = OperandResolver.ParseDouble(se.StringValue);
if (double.IsNaN(val))
{
// x is text that is not a number
return false;
}
return _value == val;
}
else if ((x is NumberEval))
{
NumberEval ne = (NumberEval)x;
testValue = ne.NumberValue;
}
else if ((x is BlankEval))
{
switch (Code)
{
case CmpOp.NE:
// Excel counts blank values in range as not equal to any value. See Bugzilla 51498
return true;
default:
return false;
}
}
else
{
return false;
}
return Evaluate(testValue.CompareTo(_value));
}
protected override string ValueText
{
get { return _value.ToString(CultureInfo.InvariantCulture); }
}
}
private class BooleanMatcher : MatcherBase
{
private int _value;
public BooleanMatcher(bool value, CmpOp optr)
: base(optr)
{
_value = BoolToInt(value);
}
private static int BoolToInt(bool value)
{
return value == true ? 1 : 0;
}
public override bool Matches(ValueEval x)
{
int testValue;
if (x is StringEval)
{
#if !HIDE_UNREACHABLE_CODE
if (true)
{ // change to false to observe more intuitive behaviour
// Note - Unlike with numbers, it seems that COUNTIF never matches
// boolean values when the target(x) is a string
return false;
}
StringEval se = (StringEval)x;
Boolean? val = ParseBoolean(se.StringValue);
if (val == null)
{
// x is text that is not a boolean
return false;
}
testValue = BoolToInt(val.Value);
#else
return false;
#endif
}
else if ((x is BoolEval))
{
BoolEval be = (BoolEval)x;
testValue = BoolToInt(be.BooleanValue);
}
else if ((x is BlankEval))
{
switch (Code)
{
case CmpOp.NE:
// Excel counts blank values in range as not equal to any value. See Bugzilla 51498
return true;
default:
return false;
}
}
else if ((x is NumberEval))
{
switch (Code)
{
case CmpOp.NE:
// not-equals comparison of a number to boolean always returnes false
return true;
default:
return false;
}
}
else
{
return false;
}
return Evaluate(testValue - _value);
}
protected override string ValueText
{
get { return _value == 1 ? "TRUE" : "FALSE"; }
}
}
internal class StringMatcher : MatcherBase
{
private String _value;
private CmpOp _operator;
private Regex _pattern;
public StringMatcher(String value, CmpOp optr):base(optr)
{
_value = value;
_operator = optr;
switch (optr.Code)
{
case CmpOp.NONE:
case CmpOp.EQ:
case CmpOp.NE:
_pattern = GetWildCardPattern(value);
break;
default:
_pattern = null;
break;
}
}
public override bool Matches(ValueEval x)
{
if (x is BlankEval)
{
switch (_operator.Code)
{
case CmpOp.NONE:
case CmpOp.EQ:
return _value.Length == 0;
case CmpOp.NE:
// pred '<>' matches empty string but not blank cell
// pred '<>ABC' matches blank and 'not ABC'
return _value.Length != 0;
}
// no other criteria matches a blank cell
return false;
}
if (!(x is StringEval))
{
// must always be string
// even if match str is wild, but contains only digits
// e.g. '4*7', NumberEval(4567) does not match
return false;
}
String testedValue = ((StringEval)x).StringValue;
if ((testedValue.Length < 1 && _value.Length < 1))
{
// odd case: criteria '=' behaves differently to criteria ''
switch (_operator.Code)
{
case CmpOp.NONE: return true;
case CmpOp.EQ: return false;
case CmpOp.NE: return true;
}
return false;
}
if (_pattern != null)
{
return Evaluate(_pattern.IsMatch(testedValue));
}
//return Evaluate(testedValue.CompareTo(_value));
return Evaluate(string.Compare(testedValue, _value, StringComparison.CurrentCultureIgnoreCase));
}
/// <summary>
/// Translates Excel countif wildcard strings into .NET regex strings
/// </summary>
/// <param name="value">Excel wildcard expression</param>
/// <returns>return null if the specified value contains no special wildcard characters.</returns>
internal static Regex GetWildCardPattern(String value)
{
int len = value.Length;
StringBuilder sb = new StringBuilder(len);
sb.Append("^");
bool hasWildCard = false;
for (int i = 0; i < len; i++)
{
char ch = value[i];
switch (ch)
{
case '?':
hasWildCard = true;
// match exactly one character
sb.Append('.');
continue;
case '*':
hasWildCard = true;
// match one or more occurrences of any character
sb.Append(".*");
continue;
case '~':
if (i + 1 < len)
{
ch = value[i + 1];
switch (ch)
{
case '?':
case '*':
hasWildCard = true;
//sb.Append("\\").Append(ch);
sb.Append('[').Append(ch).Append(']');
i++; // Note - incrementing loop variable here
continue;
}
}
// else not '~?' or '~*'
sb.Append('~'); // just plain '~'
continue;
case '.':
case '$':
case '^':
case '[':
case ']':
case '(':
case ')':
// escape literal characters that would have special meaning in regex
sb.Append("\\").Append(ch);
continue;
}
sb.Append(ch);
}
sb.Append("$");
if (hasWildCard)
{
return new Regex(sb.ToString(), RegexOptions.IgnoreCase);
}
return null;
}
protected override string ValueText
{
get
{
if (_pattern == null)
{
return _value;
}
return _pattern.ToString();
}
}
}
/**
* @return the number of evaluated cells in the range that match the specified criteria
*/
private double CountMatchingCellsInArea(ValueEval rangeArg, IMatchPredicate criteriaPredicate)
{
if (rangeArg is RefEval)
{
return CountUtils.CountMatchingCellsInRef((RefEval)rangeArg, criteriaPredicate);
}
else if (rangeArg is ThreeDEval)
{
return CountUtils.CountMatchingCellsInArea((ThreeDEval)rangeArg, criteriaPredicate);
}
else
{
throw new ArgumentException("Bad range arg type (" + rangeArg.GetType().Name + ")");
}
}
/**
*
* @return the de-referenced criteria arg (possibly {@link ErrorEval})
*/
private static ValueEval EvaluateCriteriaArg(ValueEval arg, int srcRowIndex, int srcColumnIndex)
{
try
{
return OperandResolver.GetSingleValue(arg, srcRowIndex, (short)srcColumnIndex);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
}
/**
* When the second argument is a string, many things are possible
*/
private static IMatchPredicate CreateGeneralMatchPredicate(StringEval stringEval)
{
String value = stringEval.StringValue;
CmpOp operator1 = CmpOp.GetOperator(value);
value = value.Substring(operator1.Length);
bool? booleanVal = ParseBoolean(value);
if (booleanVal != null)
{
return new BooleanMatcher(booleanVal.Value, operator1);
}
Double doubleVal = OperandResolver.ParseDouble(value);
if (!double.IsNaN(doubleVal))
{
return new NumberMatcher(doubleVal, operator1);
}
ErrorEval ee = ParseError(value);
if (ee != null)
{
return new ErrorMatcher(ee.ErrorCode, operator1);
}
//else - just a plain string with no interpretation.
return new StringMatcher(value, operator1);
}
/**
* Creates a criteria predicate object for the supplied criteria arg
* @return <code>null</code> if the arg evaluates to blank.
*/
public static IMatchPredicate CreateCriteriaPredicate(ValueEval arg, int srcRowIndex, int srcColumnIndex)
{
ValueEval evaluatedCriteriaArg = EvaluateCriteriaArg(arg, srcRowIndex, srcColumnIndex);
if (evaluatedCriteriaArg is NumberEval)
{
return new NumberMatcher(((NumberEval)evaluatedCriteriaArg).NumberValue, CmpOp.OP_NONE);
}
if (evaluatedCriteriaArg is BoolEval)
{
return new BooleanMatcher(((BoolEval)evaluatedCriteriaArg).BooleanValue, CmpOp.OP_NONE);
}
if (evaluatedCriteriaArg is StringEval)
{
return CreateGeneralMatchPredicate((StringEval)evaluatedCriteriaArg);
}
if (evaluatedCriteriaArg is ErrorEval)
{
return new ErrorMatcher(((ErrorEval)evaluatedCriteriaArg).ErrorCode, CmpOp.OP_NONE);
}
if (evaluatedCriteriaArg == BlankEval.instance)
{
return null;
}
throw new Exception("Unexpected type for criteria ("
+ evaluatedCriteriaArg.GetType().Name + ")");
}
private static ErrorEval ParseError(String value)
{
if (value.Length < 4 || value[0] != '#')
{
return null;
}
if (value.Equals("#NULL!")) return ErrorEval.NULL_INTERSECTION;
if (value.Equals("#DIV/0!")) return ErrorEval.DIV_ZERO;
if (value.Equals("#VALUE!")) return ErrorEval.VALUE_INVALID;
if (value.Equals("#REF!")) return ErrorEval.REF_INVALID;
if (value.Equals("#NAME?")) return ErrorEval.NAME_INVALID;
if (value.Equals("#NUM!")) return ErrorEval.NUM_ERROR;
if (value.Equals("#N/A")) return ErrorEval.NA;
return null;
}
/**
* bool literals ('TRUE', 'FALSE') treated similarly but NOT same as numbers.
*/
/* package */
public static bool? ParseBoolean(String strRep)
{
if (strRep.Length < 1)
{
return null;
}
switch (strRep[0])
{
case 't':
case 'T':
if ("TRUE".Equals(strRep, StringComparison.OrdinalIgnoreCase))
{
return true;
}
break;
case 'f':
case 'F':
if ("FALSE".Equals(strRep, StringComparison.OrdinalIgnoreCase))
{
return false;
}
break;
}
return null;
}
public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1)
{
IMatchPredicate mp = CreateCriteriaPredicate(arg1, srcRowIndex, srcColumnIndex);
if (mp == null)
{
// If the criteria arg is a reference to a blank cell, countif always returns zero.
return NumberEval.ZERO;
}
double result = CountMatchingCellsInArea(arg0, mp);
return new NumberEval(result);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Reflection;
using Umbraco.Core;
using Umbraco.Core.Logging;
using umbraco.BasePages;
using umbraco.BusinessLogic.Utils;
using umbraco.cms;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.workflow;
using umbraco.interfaces;
using System.Text.RegularExpressions;
using System.Linq;
using TypeFinder = Umbraco.Core.TypeFinder;
namespace umbraco.BusinessLogic.Actions
{
/// <summary>
/// Actions and Actionhandlers are a key concept to umbraco and a developer whom wish to apply
/// businessrules whenever data is changed within umbraco, by implementing the IActionHandler
/// interface it's possible to invoke methods (foreign to umbraco) - this can be used whenever
/// there is a specific rule which needs to be applied to content.
///
/// The Action class itself has responsibility for registering actions and actionhandlers,
/// and contains methods which will be invoked whenever a change is made to ex. a document, media or member
///
/// An action/actionhandler will automatically be registered, using reflection
/// which is enabling thirdparty developers to extend the core functionality of
/// umbraco without changing the codebase.
/// </summary>
[Obsolete("Actions and ActionHandlers are obsolete and should no longer be used")]
public class Action
{
private static readonly Dictionary<string, string> ActionJs = new Dictionary<string, string>();
private static readonly object Lock = new object();
static Action()
{
ReRegisterActionsAndHandlers();
}
/// <summary>
/// This is used when an IAction or IActionHandler is installed into the system
/// and needs to be loaded into memory.
/// </summary>
/// <remarks>
/// TODO: this shouldn't be needed... we should restart the app pool when a package is installed!
/// </remarks>
public static void ReRegisterActionsAndHandlers()
{
lock (Lock)
{
using (Umbraco.Core.ObjectResolution.Resolution.DirtyBackdoorToConfiguration)
{
//TODO: Based on the above, this is a big hack as types should all be cleared on package install!
ActionsResolver.Reset(false); // and do NOT reset the whole resolution!
//TODO: Based on the above, this is a big hack as types should all be cleared on package install!
ActionsResolver.Current = new ActionsResolver(
() => TypeFinder.FindClassesOfType<IAction>(PluginManager.Current.AssembliesToScan));
}
}
}
/// <summary>
/// Jacascript for the contextmenu
/// Suggestion: this method should be moved to the presentation layer.
/// </summary>
/// <param name="language"></param>
/// <returns>String representation</returns>
public string ReturnJavascript(string language)
{
return findActions(language);
}
/// <summary>
/// Returns a list of JavaScript file paths.
/// </summary>
/// <returns></returns>
public static List<string> GetJavaScriptFileReferences()
{
return ActionsResolver.Current.Actions
.Where(x => !string.IsNullOrWhiteSpace(x.JsSource))
.Select(x => x.JsSource).ToList();
//return ActionJsReference;
}
/// <summary>
/// Javascript menuitems - tree contextmenu
/// Umbraco console
///
/// Suggestion: this method should be moved to the presentation layer.
/// </summary>
/// <param name="language"></param>
/// <returns></returns>
private static string findActions(string language)
{
if (!ActionJs.ContainsKey(language))
{
string _actionJsList = "";
foreach (IAction action in ActionsResolver.Current.Actions)
{
// Adding try/catch so this rutine doesn't fail if one of the actions fail
// Add to language JsList
try
{
// NH: Add support for css sprites
string icon = action.Icon;
if (!string.IsNullOrEmpty(icon) && icon.StartsWith("."))
icon = icon.Substring(1, icon.Length - 1);
else
icon = "images/" + icon;
_actionJsList += string.Format(",\n\tmenuItem(\"{0}\", \"{1}\", \"{2}\", \"{3}\")",
action.Letter, icon, ui.GetText("actions", action.Alias, language), action.JsFunctionName);
}
catch (Exception ee)
{
LogHelper.Error<Action>("Error registrering action to javascript", ee);
}
}
if (_actionJsList.Length > 0)
_actionJsList = _actionJsList.Substring(2, _actionJsList.Length - 2);
_actionJsList = "\nvar menuMethods = new Array(\n" + _actionJsList + "\n)\n";
ActionJs.Add(language, _actionJsList);
}
return ActionJs[language];
}
/// <summary>
///
/// </summary>
/// <returns>An arraylist containing all javascript variables for the contextmenu in the tree</returns>
[Obsolete("Use ActionsResolver.Current.Actions instead")]
public static ArrayList GetAll()
{
return new ArrayList(ActionsResolver.Current.Actions.ToList());
}
/// <summary>
/// This method will return a list of IAction's based on a string list. Each character in the list may represent
/// an IAction. This will associate any found IActions based on the Letter property of the IAction with the character being referenced.
/// </summary>
/// <param name="actions"></param>
/// <returns>returns a list of actions that have an associated letter found in the action string list</returns>
public static List<IAction> FromString(string actions)
{
List<IAction> list = new List<IAction>();
foreach (char c in actions.ToCharArray())
{
IAction action = ActionsResolver.Current.Actions.ToList().Find(
delegate(IAction a)
{
return a.Letter == c;
}
);
if (action != null)
list.Add(action);
}
return list;
}
/// <summary>
/// Returns the string representation of the actions that make up the actions collection
/// </summary>
/// <returns></returns>
public static string ToString(List<IAction> actions)
{
string[] strMenu = Array.ConvertAll<IAction, string>(actions.ToArray(), delegate(IAction a) { return (a.Letter.ToString()); });
return string.Join("", strMenu);
}
/// <summary>
/// Returns a list of IActions that are permission assignable
/// </summary>
/// <returns></returns>
public static List<IAction> GetPermissionAssignable()
{
return ActionsResolver.Current.Actions.ToList().FindAll(
delegate(IAction a)
{
return (a.CanBePermissionAssigned);
}
);
}
/// <summary>
/// Check if the current IAction is using legacy javascript methods
/// </summary>
/// <param name="action"></param>
/// <returns>false if the Iaction is incompatible with 4.5</returns>
public static bool ValidateActionJs(IAction action)
{
return !action.JsFunctionName.Contains("+");
}
/// <summary>
/// Method to convert the old modal calls to the new ones
/// </summary>
/// <param name="javascript"></param>
/// <returns></returns>
public static string ConvertLegacyJs(string javascript)
{
MatchCollection tags =
Regex.Matches(javascript, "openModal[^;]*;", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match tag in tags)
{
string[] function = tag.Value.Split(',');
if (function.Length > 0)
{
string newFunction = "UmbClientMgr.openModalWindow" + function[0].Substring(9).Replace("parent.nodeID", "UmbClientMgr.mainTree().getActionNode().nodeId").Replace("nodeID", "UmbClientMgr.mainTree().getActionNode().nodeId").Replace("parent.returnRandom()", "'" + Guid.NewGuid().ToString() + "'");
newFunction += ", " + function[1];
newFunction += ", true";
newFunction += ", " + function[2];
newFunction += ", " + function[3];
javascript = javascript.Replace(tag.Value, newFunction);
}
}
return javascript;
}
}
/// <summary>
/// This class is used to manipulate IActions that are implemented in a wrong way
/// For instance incompatible trees with 4.0 vs 4.5
/// </summary>
public class PlaceboAction : IAction
{
public char Letter { get; set; }
public bool ShowInNotifier { get; set; }
public bool CanBePermissionAssigned { get; set; }
public string Icon { get; set; }
public string Alias { get; set; }
public string JsFunctionName { get; set; }
public string JsSource { get; set; }
public PlaceboAction() { }
public PlaceboAction(IAction legacyAction)
{
Letter = legacyAction.Letter;
ShowInNotifier = legacyAction.ShowInNotifier;
CanBePermissionAssigned = legacyAction.CanBePermissionAssigned;
Icon = legacyAction.Icon;
Alias = legacyAction.Alias;
JsFunctionName = legacyAction.JsFunctionName;
JsSource = legacyAction.JsSource;
}
}
}
| |
// <copyright file="GPGSIOSSetupUI.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayGames.Editor
{
using System;
using System.IO;
using System.Collections;
using UnityEngine;
using UnityEditor;
public class GPGSIOSSetupUI : EditorWindow
{
private string mBundleId = string.Empty;
private string mWebClientId = string.Empty;
private string mClassName = "GooglePlayGames.GPGSIds";
private string mClassDirectory = "Assets";
private string mConfigData = string.Empty;
private bool mRequiresGooglePlus = false;
private Vector2 scroll;
[MenuItem("Window/Google Play Games/Setup/iOS setup...", false, 2)]
public static void MenuItemGPGSIOSSetup()
{
EditorWindow window = EditorWindow.GetWindow(
typeof(GPGSIOSSetupUI), true, GPGSStrings.IOSSetup.Title);
window.minSize = new Vector2(500, 600);
}
public void OnEnable()
{
mBundleId = GPGSProjectSettings.Instance.Get(GPGSUtil.IOSBUNDLEIDKEY);
mWebClientId = GPGSProjectSettings.Instance.Get(GPGSUtil.WEBCLIENTIDKEY);
mClassDirectory = GPGSProjectSettings.Instance.Get(GPGSUtil.CLASSDIRECTORYKEY, mClassDirectory);
mClassName = GPGSProjectSettings.Instance.Get(GPGSUtil.CLASSNAMEKEY);
mConfigData = GPGSProjectSettings.Instance.Get(GPGSUtil.IOSRESOURCEKEY);
mRequiresGooglePlus = GPGSProjectSettings.Instance.GetBool(GPGSUtil.REQUIREGOOGLEPLUSKEY, false);
if (mBundleId.Trim().Length == 0)
{
mBundleId = PlayerSettings.bundleIdentifier;
}
}
/// <summary>
/// Save the specified clientId and bundleId to properties file.
/// This maintains the configuration across instances of running Unity.
/// </summary>
/// <param name="clientId">Client identifier.</param>
/// <param name="bundleId">Bundle identifier.</param>
/// <param name="webClientId">web app clientId.</param>
/// <param name="requiresGooglePlus">App requires G+ access</param>
internal static void Save(string clientId,
string bundleId,
string webClientId,
bool requiresGooglePlus)
{
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSCLIENTIDKEY, clientId);
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSBUNDLEIDKEY, bundleId);
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
GPGSProjectSettings.Instance.Set(GPGSUtil.REQUIREGOOGLEPLUSKEY, requiresGooglePlus);
GPGSProjectSettings.Instance.Save();
}
public void OnGUI()
{
GUIStyle link = new GUIStyle(GUI.skin.label);
link.normal.textColor = new Color(.7f, .7f, 1f);
// Title
GUILayout.BeginVertical();
GUILayout.Space(10);
GUILayout.Label(GPGSStrings.IOSSetup.Blurb);
GUILayout.Space(10);
if (GUILayout.Button("Open Play Games Console", link, GUILayout.ExpandWidth(false)))
{
Application.OpenURL("https://play.google.com/apps/publish");
}
Rect last = GUILayoutUtility.GetLastRect();
last.y += last.height - 2;
last.x += 3;
last.width -= 6;
last.height = 2;
GUI.Box(last, string.Empty);
GUILayout.Space(15);
// Bundle ID field
GUILayout.Label(GPGSStrings.IOSSetup.BundleIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.IOSSetup.BundleIdBlurb, EditorStyles.wordWrappedLabel);
mBundleId = EditorGUILayout.TextField(GPGSStrings.IOSSetup.BundleId, mBundleId,
GUILayout.Width(450));
GUILayout.Space(30);
// Requires G+ field
GUILayout.BeginHorizontal();
GUILayout.Label(GPGSStrings.Setup.RequiresGPlusTitle, EditorStyles.boldLabel);
mRequiresGooglePlus = EditorGUILayout.Toggle(mRequiresGooglePlus);
GUILayout.EndHorizontal();
GUILayout.Label(GPGSStrings.Setup.RequiresGPlusBlurb);
// Client ID field
GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb, EditorStyles.wordWrappedLabel);
GUILayout.Space(10);
mWebClientId = EditorGUILayout.TextField(GPGSStrings.Setup.ClientId,
mWebClientId, GUILayout.Width(450));
GUILayout.Space(10);
GUILayout.FlexibleSpace();
GUILayout.Label("Constants class name", EditorStyles.boldLabel);
GUILayout.Label("Enter the fully qualified name of the class to create containing the constants");
GUILayout.Space(10);
mClassDirectory = EditorGUILayout.TextField("Directory to save constants",
mClassDirectory, GUILayout.Width(480));
mClassName = EditorGUILayout.TextField("Constants class name",
mClassName, GUILayout.Width(480));
GUILayout.Label("Resources Definition", EditorStyles.boldLabel);
GUILayout.Label("Paste in the Objective-C Resources from the Play Console");
GUILayout.Space(10);
scroll = GUILayout.BeginScrollView(scroll);
mConfigData = EditorGUILayout.TextArea(mConfigData,
GUILayout.Width(475), GUILayout.Height(Screen.height));
GUILayout.EndScrollView();
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
// Setup button
if (GUILayout.Button(GPGSStrings.Setup.SetupButton))
{
// check that the classname entered is valid
try
{
if (GPGSUtil.LooksLikeValidPackageName(mClassName))
{
DoSetup();
}
}
catch (Exception e)
{
GPGSUtil.Alert(GPGSStrings.Error,
"Invalid classname: " + e.Message);
}
}
if (GUILayout.Button(GPGSStrings.Cancel))
{
this.Close();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.EndVertical();
}
/// <summary>
/// Called by the UI to process the configuration.
/// </summary>
internal void DoSetup()
{
if (PerformSetup(mClassDirectory, mClassName, mConfigData, mWebClientId, mBundleId, null, mRequiresGooglePlus))
{
GPGSUtil.Alert(GPGSStrings.Success, GPGSStrings.IOSSetup.SetupComplete);
Close();
}
else
{
GPGSUtil.Alert(GPGSStrings.Error,
"Missing or invalid resource data. Check that CLIENT_ID is defined.");
}
}
/// <summary>
/// Performs setup using the Android resources downloaded XML file
/// from the play console.
/// </summary>
/// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns>
/// <param name="className">Fully qualified class name for the resource Ids.</param>
/// <param name="resourceXmlData">Resource xml data.</param>
/// <param name="webClientId">Client identifier.</param>
/// <param name="bundleId">Bundle identifier.</param>
/// <param name="nearbySvcId">Nearby svc identifier.</param>
/// <param name="requiresGooglePlus">App Requires Google Plus API.</param>
public static bool PerformSetup(
string classDirectory,
string className,
string resourceXmlData,
string webClientId,
string bundleId,
string nearbySvcId,
bool requiresGooglePlus)
{
if (ParseResources(classDirectory, className, resourceXmlData))
{
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className);
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSRESOURCEKEY, resourceXmlData);
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
if (string.IsNullOrEmpty(bundleId))
{
// get from settings
bundleId = GPGSProjectSettings.Instance.Get(GPGSUtil.IOSBUNDLEIDKEY);
PlayerSettings.bundleIdentifier = bundleId;
}
return PerformSetup(GPGSProjectSettings.Instance.Get(GPGSUtil.IOSCLIENTIDKEY),
bundleId, webClientId, nearbySvcId, requiresGooglePlus);
}
Debug.LogError("Failed to parse resources, returing false.");
return false;
}
private static bool ParseResources(string classDirectory, string className, string res)
{
// parse the resources, they keys are in the form of
// #define <KEY> @"<VALUE>"
// transform the string to make it easier to parse
string input = res.Replace("#define ", string.Empty);
input = input.Replace("@\"", string.Empty);
input = input.Replace("\"", string.Empty);
// now input is name value, one per line
StringReader reader = new StringReader(input);
string line = reader.ReadLine();
string key;
string value;
string clientId = null;
Hashtable resourceKeys = new Hashtable();
while (line != null)
{
string[] parts = line.Split(' ');
key = parts[0];
if (parts.Length > 1)
{
value = parts[1];
}
else
{
value = null;
}
if (!string.IsNullOrEmpty(value))
{
if (key == "CLIENT_ID")
{
clientId = value;
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSCLIENTIDKEY, clientId);
}
else if (key == "BUNDLE_ID")
{
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSBUNDLEIDKEY, value);
}
else if (key.StartsWith("ACH_"))
{
string prop = "achievement_" + key.Substring(4).ToLower();
resourceKeys[prop] = value;
}
else if (key.StartsWith("LEAD_"))
{
string prop = "leaderboard_" + key.Substring(5).ToLower();
resourceKeys[prop] = value;
}
else if (key.StartsWith("EVENT_"))
{
string prop = "event_" + key.Substring(6).ToLower();
resourceKeys[prop] = value;
}
else if (key.StartsWith("QUEST_"))
{
string prop = "quest_" + key.Substring(6).ToLower();
resourceKeys[prop] = value;
}
else
{
resourceKeys[key] = value;
}
}
line = reader.ReadLine();
}
reader.Close();
if (resourceKeys.Count > 0)
{
GPGSUtil.WriteResourceIds(classDirectory, className, resourceKeys);
}
GPGSProjectSettings.Instance.Save();
return !string.IsNullOrEmpty(clientId);
}
/// <summary>
/// Performs the setup. This is called externally to facilitate
/// build automation.
/// </summary>
/// <param name="clientId">Client identifier.</param>
/// <param name="bundleId">Bundle identifier.</param>
/// <param name="webClientId">web app client id.</param>
/// <param name="nearbySvcId">Nearby connections service Id.</param>
/// <param name="requiresGooglePlus">App requires G+ access</param>
public static bool PerformSetup(string clientId, string bundleId,
string webClientId, string nearbySvcId, bool requiresGooglePlus)
{
if (!GPGSUtil.LooksLikeValidClientId(clientId))
{
GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError);
return false;
}
if (!GPGSUtil.LooksLikeValidBundleId(bundleId))
{
GPGSUtil.Alert(GPGSStrings.IOSSetup.BundleIdError);
return false;
}
// nearby is optional - only set it up if present.
if (nearbySvcId != null)
{
bool ok = NearbyConnectionUI.PerformSetup(nearbySvcId, false);
if (!ok)
{
Debug.LogError("NearbyConnection Setup failed, returing false.");
return false;
}
}
Save(clientId, bundleId, webClientId, requiresGooglePlus);
GPGSUtil.UpdateGameInfo();
// Finished!
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSSETUPDONEKEY, true);
GPGSProjectSettings.Instance.Save();
AssetDatabase.Refresh();
return true;
}
}
}
| |
namespace SPALM.SPSF.Library.CustomWizardPages
{
using System;
using System.Windows.Forms;
public partial class SiteColumnWizard : UserControl
{
public event SchemaChangedDelegate SchemaChanged;
public delegate void SchemaChangedDelegate();
public SiteColumnWizard()
{
InitializeComponent();
RegisterChangeEvent(this);
UpdateControls();
}
private void RegisterChangeEvent(Control control)
{
if (control is TextBox)
{
(control as TextBox).TextChanged += new EventHandler(required_YES_CheckedChanged);
}
else if (control is CheckBox)
{
(control as CheckBox).CheckedChanged += new EventHandler(required_YES_CheckedChanged);
}
else if (control is RadioButton)
{
(control as RadioButton).CheckedChanged += new EventHandler(required_YES_CheckedChanged);
}
else if (control is ComboBox)
{
(control as ComboBox).SelectedIndexChanged += new EventHandler(required_YES_CheckedChanged);
}
foreach (Control subcontrol in control.Controls)
{
RegisterChangeEvent(subcontrol);
}
}
private void required_YES_CheckedChanged(object sender, EventArgs e)
{
this.RaiseSchemaChangedEvent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateControls();
}
private void RaiseSchemaChangedEvent()
{
if (SchemaChanged != null)
{
SchemaChanged();
}
}
private string GetRequired()
{
if (required_YES.Checked)
{
return "TRUE";
}
return "FALSE";
}
private string GetMaxLength()
{
return maxLength.Text;
}
private string GetDefaultValue()
{
if (textBoxdefaultValue.Text != "")
{
if (defaultValueIsCalc.Checked)
{
return "<DefaultFormula>" + textBoxdefaultValue.Text + "</DefaultFormula>";
}
else
{
return "<Default>" + textBoxdefaultValue.Text + "</Default>";
}
}
return "";
}
public string UpdateXML()
{
string Schema = "<Field Group=\"ColumnsGroup\" DisplayName=\"Column\" ID=\"{cfcb2a43-2a4e-4406-8fa4-e9d1fcf99818}\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"Multiline\" Name=\"MultilinePlain\" ";
if (comboBox1.SelectedIndex == 0)
{
Schema += " Type=\"Text\" Required=\"" + GetRequired() + "\" MaxLength=\"" + GetMaxLength() + "\" >";
if (GetDefaultValue() != "")
{
Schema += GetDefaultValue();
}
}
else if (comboBox1.SelectedIndex == 1)
{
Schema += " Type=\"Note\" Sortable=\"FALSE\"";
Schema += " NumLines=\"" + GetNumLines() + "\"";
Schema += " Required=\"" + GetRequired() + "\"";
Schema += " AppendOnly=\"" + GetAppendOnly() + "\"";
Schema += " UnlimitedLengthInDocumentLibrary=\"" + GetUnlimitedLength() + "\"";
if (multilineplain.Checked)
{
//plain
Schema += " RichText=\"FALSE\"";
}
else if (multilinerich.Checked)
{
//rich
Schema += " RichText=\"TRUE\" RichTextMode=\"Compatible\"";
}
else if (multilineenhancedrich.Checked)
{
//extendedrich
Schema += " RichText=\"TRUE\" RichTextMode=\"FullHtml\" IsolateStyles=\"TRUE\"";
}
Schema += ">";
}
else if (comboBox1.SelectedIndex == 2)
{
if (choiceCheckboxes.Checked)
{
Schema += " Type=\"MultiChoice\"";
}
else
{
Schema += " Type=\"Choice\"";
if (choiceDropdown.Checked)
{
Schema += " Format=\"Dropdown\"";
}
else
{
Schema += " Format=\"RadioButtons\"";
}
}
Schema += " Required=\"" + GetRequired() + "\"";
Schema += " FillInChoice=\"" + GetFillInChoice() + "\"";
Schema += ">";
Schema += GetDefaultValue();
Schema += GetChoices();
}
else if (comboBox1.SelectedIndex == 3)
{
//number
/*
* <Field Type="Number" Min="-.10" Max=".10" Percentage="TRUE" Decimals="2"
* */
Schema += " Type=\"Number\"";
Schema += " Required=\"" + GetRequired() + "\"";
Schema += " Percentage=\"" + GetPercentage() + "\"";
Schema += " Min=\"" + GetMinNumber(checkBoxPercentage.Checked) + "\"";
Schema += " Max=\"" + GetMaxNumber(checkBoxPercentage.Checked) + "\"";
if (GetDecimals() != "")
{
Schema += " Decimals=\"" + GetDecimals() + "\"";
}
Schema += ">";
Schema += GetDefaultValue();
}
else if (comboBox1.SelectedIndex == 4)
{
Schema += " Type=\"Currency\"";
Schema += " Required=\"" + GetRequired() + "\"";
Schema += " Min=\"" + GetMinNumber(false) + "\"";
Schema += " Max=\"" + GetMaxNumber(false) + "\"";
if (GetDecimals() != "")
{
Schema += " Decimals=\"" + GetDecimals() + "\"";
}
Schema += " LCID=\"" + GetLCID() + "\"";
/*currency
<Field Type="Currency" Min="-10" Max="10" Decimals="2" LCID="2057"
*/
Schema += ">";
Schema += GetDefaultValue();
}
else if (comboBox1.SelectedIndex == 5)
{
Schema += " Type=\"DateTime\"";
Schema += " Required=\"" + GetRequired() + "\"";
Schema += " Format=\"" + GetDateFormat() + "\"";
//datetime
//<Field Type="DateTime" Format="DateOnly"
//<Default>[today]</Default>
Schema += ">";
Schema += GetDefaultDateValue();
}
else if (comboBox1.SelectedIndex == 6)
{
Schema += " Type=\"Lookup\"";
Schema += " List=\"" + textBox10.Text + "\"";
Schema += " ShowField=\"" + textBox11.Text + "\"";
Schema += " Mult=\"" + checkBox3.Checked.ToString() + "\"";
Schema += " UnlimitedLengthInDocumentLibrary=\"" + checkBox4.Checked.ToString() + "\"";
//lookup
//<Field Type="Lookup" L
Schema += ">";
}
else if (comboBox1.SelectedIndex == 7)
{
Schema += " Type=\"Boolean\"";
Schema += ">";
if (comboBoxDefaultBool.Text == "Yes")
{
Schema += "<Default>1</Default>";
}
else
{
Schema += "<Default>0</Default>";
}
}
else if (comboBox1.SelectedIndex == 8)
{
if (AllowMultiUserYES.Checked)
{
Schema += " Type=\"UserMulti\"";
Schema += " Mult=\"TRUE\" Sortable=\"FALSE\"";
}
else
{
Schema += " Type=\"User\"";
}
Schema += " Required=\"" + GetRequired() + "\"";
Schema += " List=\"UserInfo\"";
Schema += " ShowField=\"ImnName\"";
//person group
//<Field Type="User" List="UserInfo" ShowField="ImnName"
//<Field Type="UserMulti" List="UserInfo" ShowField="ImnName"
Schema += ">";
}
else if (comboBox1.SelectedIndex == 9)
{
Schema += " Type=\"URL\"";
Schema += " Required=\"" + GetRequired() + "\"";
Schema += " Format=\"" + this.comboBoxHyperlinkOrPicture.Text + "\"";
Schema += ">";
//hyperlink picture
//Type="URL" Format="Hyperlink"
}
else if (comboBox1.SelectedIndex == 10)
{
Schema += " Type=\"Calculated\"";
//calc
/*
<Field Type="Calculated" DisplayName="CalculatedColumn" Format="DateOnly" LCID="1033" ResultType="Number" ReadOnly="TRUE" Group="Custom Columns" ID="{6ae3d7eb-3b8c-42a8-9d1e-b5baea1492b2}" SourceID="{c6cb73a7-763c-4a1d-a39a-06b0b3877f3e}" StaticName="CalculatedColumn" Name="CalculatedColumn" xmlns="http://schemas.microsoft.com/sharepoint/">
<Formula>=ActualWork</Formula>
<FieldRefs>
<FieldRef Name="ActualWork" ID="{b0b3407e-1c33-40ed-a37c-2430b7a5d081}" />
</FieldRefs>
</Field>
*/
Schema += ">";
}
// http://www.cnblogs.com/aivdesign/articles/1308759.html
else if (comboBox1.SelectedIndex == 11){
// Full HTML content with formatting and constraints for publishing
Schema += " Type=\"HTML\" ";
Schema += " RichText=\"TRUE\" RichTextMode=\"FullHtml\" ";
Schema += ">";
}
else if (comboBox1.SelectedIndex == 12)
{
// Image with formatting and constraints for publishing
Schema += " Type=\"Image\" ";
Schema += " RichText=\"TRUE\" RichTextMode=\"FullHtml\" ";
Schema += ">";
}
else if (comboBox1.SelectedIndex == 13)
{
// Hyperlink with formatting and constraints for publishing
Schema += " Type=\"Link\" ";
Schema += " RichText=\"TRUE\" RichTextMode=\"FullHtml\" ";
Schema += ">";
}
else if (comboBox1.SelectedIndex == 14)
{
// Summary Links data
Schema += " Type=\"SummaryLinks\" ";
Schema += ">";
}
Schema += "</Field>";
return Schema;
}
private string GetShowField()
{
return comboBox9.Text;
}
private string GetDefaultDateValue()
{
if (DefaultDateToday.Checked)
{
return "<DefaultFormula>[today]</DefaultFormula>";
}
else if (DefaultDateCalculatedYES.Checked)
{
return "<DefaultFormula>" + DefaultDateCalculated.Text + "</DefaultFormula>";
}
else if (DefaultDateFixed.Checked)
{
//<Default>2010-04-18T22:05:00Z</Default>
return "<Default>" + dateTimePickerDefault.Value.ToString("MM-dd-yyyy") + "T" + dateTimePickerDefaultTime.Value.ToString("HH:mm:ss") + "Z</Default>";
}
return "";
}
private string GetDateFormat()
{
if (radioButtonDateOnlyYES.Checked)
{
return "DateOnly";
}
return "DateTime";
}
private string GetLCID()
{
return comboBoxLCID.Text;
}
private string GetDecimals()
{
try
{
int value = Int32.Parse(comboBoxDecimals.Text);
return value.ToString();
}
catch (Exception)
{
}
return "";
}
private string GetMaxNumber(bool percentage)
{
try
{
double value = 0;
value = Double.Parse(textBoxMaxNumber.Text);
if (percentage)
{
value = value / 100;
}
return value.ToString().Replace(",", ".");
}
catch (Exception)
{
}
return "";
}
private string GetMinNumber(bool percentage)
{
try
{
double value = 0;
value = Double.Parse(textBoxMinNumber.Text);
if (percentage)
{
value = value / 100;
}
return value.ToString().Replace(",", ".");
}
catch (Exception)
{
}
return "";
}
private string GetPercentage()
{
if (checkBoxPercentage.Checked)
{
return "TRUE";
}
return "FALSE";
}
private string GetChoices()
{
/*
<CHOICES>
<CHOICE>Enter Choice #1</CHOICE>
<CHOICE>Enter Choice #2</CHOICE>
<CHOICE>Enter Choice #3</CHOICE>
</CHOICES>
* */
string res = "<CHOICES>";
foreach (string s in textBoxChoices.Lines)
{
res += "<CHOICE>" + s + "</CHOICE>";
}
res += "</CHOICES>";
return res;
}
private string GetFillInChoice()
{
if (AllowFillInYES.Checked)
{
return "TRUE";
}
return "FALSE";
}
private string GetUnlimitedLength()
{
if (unlimitedLengthYES.Checked)
{
return "TRUE";
}
return "FALSE";
}
private string GetAppendOnly()
{
if (AppendYES.Checked)
{
return "TRUE";
}
return "FALSE";
}
private string GetNumLines()
{
return textBoxNumLines.Text;
}
private void UpdateControls()
{
foreach (Control c in panel1.Controls)
{
c.Visible = false;
}
if (comboBox1.SelectedIndex == 0)
{
//single line
panel_required.Visible = true;
panel_MaxChars.Visible = true;
panel_DefaultValue.Visible = true;
}
else if (comboBox1.SelectedIndex == 1)
{
//multi line
panel_required.Visible = true;
panel_MaxChars.Visible = false;
panel_DefaultValue.Visible = false;
panel_MultiColumn.Visible = true;
}
else if (comboBox1.SelectedIndex == 2)
{
//choice
panel_required.Visible = true;
panel_Choice.Visible = true;
panel_DefaultValue.Visible = true;
}
else if (comboBox1.SelectedIndex == 3)
{
//number
panel_required.Visible = true;
panel_Number.Visible = true;
panel_DefaultValue.Visible = true;
}
else if (comboBox1.SelectedIndex == 4)
{
//currency
panel_required.Visible = true;
panel_Number.Visible = true;
panel_Currency.Visible = true;
panel_DefaultValue.Visible = true;
}
else if (comboBox1.SelectedIndex == 5)
{
//datetime
panel_required.Visible = true;
panel_DateTime.Visible = true;
}
else if (comboBox1.SelectedIndex == 6)
{
//lookup
panel_required.Visible = true;
panel_LookUp.Visible = true;
}
else if (comboBox1.SelectedIndex == 7)
{
//yes no
panel_YesNo.Visible = true;
}
else if (comboBox1.SelectedIndex == 8)
{
//person group
panel_required.Visible = true;
panel_User.Visible = true;
}
else if (comboBox1.SelectedIndex == 9)
{
//hyperlink picture
panel_required.Visible = true;
panel_HyperlinkPicture.Visible = true;
}
else if (comboBox1.SelectedIndex == 10)
{
//calc
panel_Calculated.Visible = true;
}
}
private void label13_Click(object sender, EventArgs 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.Collections.Generic;
using System.Diagnostics;
using System.Security;
using System.Reflection;
using System.Collections.Concurrent;
using System.Linq;
namespace System.Threading.Tasks.Tests
{
//
// Task scheduler basics.
//
public static class TaskSchedulerTests
{
// Just ensure we eventually complete when many blocked tasks are created.
[OuterLoop]
[Fact]
public static void RunBlockedInjectionTest()
{
Debug.WriteLine("* RunBlockedInjectionTest() -- if it deadlocks, it failed");
ManualResetEvent mre = new ManualResetEvent(false);
// we need to run this test in a local task scheduler, because it needs to perform
// the verification based on a known number of initially available threads.
//
//
// @TODO: When we reach the _planB branch we need to add a trick here using ThreadPool.SetMaxThread
// to bring down the TP worker count. This is because previous activity in the test process might have
// injected workers.
TaskScheduler tm = TaskScheduler.Default;
// Create many tasks blocked on the MRE.
int processorCount = Environment.ProcessorCount;
Task[] tasks = new Task[processorCount];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Factory.StartNew(delegate { mre.WaitOne(); }, CancellationToken.None, TaskCreationOptions.None, tm);
}
// Create one task that signals the MRE, and wait for it.
Task.Factory.StartNew(delegate { mre.Set(); }, CancellationToken.None, TaskCreationOptions.None, tm).Wait();
// Lastly, wait for the others to complete.
Task.WaitAll(tasks);
}
[Fact]
public static void RunBuggySchedulerTests()
{
Debug.WriteLine("* RunBuggySchedulerTests()");
BuggyTaskScheduler bts = new BuggyTaskScheduler();
Task t1 = new Task(delegate { });
Task t2 = new Task(delegate { });
//
// Test Task.Start(buggy scheduler)
//
Debug.WriteLine(" -- testing Task.Start(buggy scheduler)");
try
{
t1.Start(bts);
Assert.True(false, string.Format(" > FAILED. No exception thrown."));
}
catch (TaskSchedulerException)
{
}
catch (Exception e)
{
Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e));
}
if (t1.Status != TaskStatus.Faulted)
{
Assert.True(false, string.Format(" > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status));
}
Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)...");
try
{
t1.Wait();
Assert.True(false, string.Format(" > FAILED. No exception thrown from Wait()."));
}
catch (AggregateException ae)
{
if (!(ae.InnerExceptions[0] is TaskSchedulerException))
{
Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name));
}
}
//
// Test Task.RunSynchronously(buggy scheduler)
//
Debug.WriteLine(" -- testing Task.RunSynchronously(buggy scheduler)");
try
{
t2.RunSynchronously(bts);
Assert.True(false, string.Format(" > FAILED. No exception thrown."));
}
catch (TaskSchedulerException) { }
catch (Exception e)
{
Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e));
}
if (t2.Status != TaskStatus.Faulted)
{
Assert.True(false, string.Format(" > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status));
}
Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)...");
try
{
t2.Wait();
Assert.True(false, string.Format(" > FAILED. No exception thrown from Wait()."));
}
catch (AggregateException ae)
{
if (!(ae.InnerExceptions[0] is TaskSchedulerException))
{
Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name));
}
}
//
// Test StartNew(buggy scheduler)
//
Debug.WriteLine(" -- testing Task.Factory.StartNew(buggy scheduler)");
try
{
Task t3 = Task.Factory.StartNew(delegate { }, CancellationToken.None, TaskCreationOptions.None, bts);
Assert.True(false, string.Format(" > FAILED. No exception thrown."));
}
catch (TaskSchedulerException) { }
catch (Exception e)
{
Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e));
}
//
// Test continuations
//
Debug.WriteLine(" -- testing Task.ContinueWith(buggy scheduler)");
Task completedTask = Task.Factory.StartNew(delegate { });
completedTask.Wait();
Task tc1 = completedTask.ContinueWith(delegate { }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, bts);
Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)...");
try
{
tc1.Wait();
Assert.True(false, string.Format(" > FAILED. No exception thrown (sync)."));
}
catch (AggregateException ae)
{
if (!(ae.InnerExceptions[0] is TaskSchedulerException))
{
Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait() (sync): {0}", ae.InnerExceptions[0].GetType().Name));
}
}
catch (Exception e)
{
Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (sync): {0}", e));
}
Task tc2 = completedTask.ContinueWith(delegate { }, CancellationToken.None, TaskContinuationOptions.None, bts);
Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)...");
try
{
tc2.Wait();
Assert.True(false, string.Format(" > FAILED. No exception thrown (async)."));
}
catch (AggregateException ae)
{
if (!(ae.InnerExceptions[0] is TaskSchedulerException))
{
Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait() (async): {0}", ae.InnerExceptions[0].GetType().Name));
}
}
catch (Exception e)
{
Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (async): {0}", e));
}
// Test Wait()/inlining
Debug.WriteLine(" -- testing Task.Wait(task started on buggy scheduler)");
BuggyTaskScheduler bts2 = new BuggyTaskScheduler(false); // won't throw on QueueTask
Task t4 = new Task(delegate { });
t4.Start(bts2);
try
{
t4.Wait();
Assert.True(false, string.Format(" > FAILED. Expected inlining exception"));
}
catch (TaskSchedulerException) { }
catch (Exception e)
{
Assert.True(false, string.Format(" > FAILED. Wrong exception thrown: {0}", e));
}
}
[Fact]
[OuterLoop]
public static void RunSynchronizationContextTaskSchedulerTests()
{
// Remember the current SynchronizationContext, so that we can restore it
SynchronizationContext previousSC = SynchronizationContext.Current;
// Now make up a "real" SynchronizationContext and install it
SimpleSynchronizationContext newSC = new SimpleSynchronizationContext();
SetSynchronizationContext(newSC);
// Create a scheduler based on the current SC
TaskScheduler scTS = TaskScheduler.FromCurrentSynchronizationContext();
//
// Launch a Task on scTS, make sure that it is processed in the expected fashion
//
bool sideEffect = false;
Task task = Task.Factory.StartNew(() => { sideEffect = true; }, CancellationToken.None, TaskCreationOptions.None, scTS);
Exception ex = null;
try
{
task.Wait();
}
catch (Exception e)
{
ex = e;
}
Assert.True(task.IsCompleted, "Expected task to have completed");
Assert.True(ex == null, "Did not expect exception on Wait");
Assert.True(sideEffect, "Task appears not to have run");
Assert.True(newSC.PostCount == 1, "Expected exactly one post to underlying SynchronizationContext");
//
// Run a Task synchronously on scTS, make sure that it completes
//
sideEffect = false;
Task syncTask = new Task(() => { sideEffect = true; });
ex = null;
try
{
syncTask.RunSynchronously(scTS);
}
catch (Exception e)
{
ex = e;
}
Assert.True(task.IsCompleted, "Expected task to have completed");
Assert.True(ex == null, "Did not expect exception on RunSynchronously");
Assert.True(sideEffect, "Task appears not to have run");
Assert.True(newSC.PostCount == 1, "Did not expect a new Post to underlying SynchronizationContext");
//
// Miscellaneous things to test
//
Assert.True(scTS.MaximumConcurrencyLevel == 1, "Expected scTS.MaximumConcurrencyLevel to be 1");
// restore original SC
SetSynchronizationContext(previousSC);
}
[Fact]
public static void RunSynchronizationContextTaskSchedulerTests_Negative()
{
// Remember the current SynchronizationContext, so that we can restore it
SynchronizationContext previousSC = SynchronizationContext.Current;
//
// Test exceptions on construction of SCTaskScheduler
//
SetSynchronizationContext(null);
Assert.Throws<InvalidOperationException>(
() => { TaskScheduler.FromCurrentSynchronizationContext(); });
}
[Fact]
public static void GetTaskSchedulersForDebugger_ReturnsDefaultScheduler()
{
MethodInfo getTaskSchedulersForDebuggerMethod = typeof(TaskScheduler).GetTypeInfo().GetDeclaredMethod("GetTaskSchedulersForDebugger");
TaskScheduler[] foundSchedulers = getTaskSchedulersForDebuggerMethod.Invoke(null, null) as TaskScheduler[];
Assert.NotNull(foundSchedulers);
Assert.Contains(TaskScheduler.Default, foundSchedulers);
}
[ConditionalFact(nameof(DebuggerIsAttached))]
public static void GetTaskSchedulersForDebugger_DebuggerAttached_ReturnsAllSchedulers()
{
MethodInfo getTaskSchedulersForDebuggerMethod = typeof(TaskScheduler).GetTypeInfo().GetDeclaredMethod("GetTaskSchedulersForDebugger");
var cesp = new ConcurrentExclusiveSchedulerPair();
TaskScheduler[] foundSchedulers = getTaskSchedulersForDebuggerMethod.Invoke(null, null) as TaskScheduler[];
Assert.NotNull(foundSchedulers);
Assert.Contains(TaskScheduler.Default, foundSchedulers);
Assert.Contains(cesp.ConcurrentScheduler, foundSchedulers);
Assert.Contains(cesp.ExclusiveScheduler, foundSchedulers);
GC.KeepAlive(cesp);
}
[ConditionalFact(nameof(DebuggerIsAttached))]
public static void GetScheduledTasksForDebugger_DebuggerAttached_ReturnsTasksFromCustomSchedulers()
{
var nonExecutingScheduler = new BuggyTaskScheduler(faultQueues: false);
Task[] queuedTasks =
(from i in Enumerable.Range(0, 10)
select Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.None, nonExecutingScheduler)).ToArray();
MethodInfo getScheduledTasksForDebuggerMethod = typeof(TaskScheduler).GetTypeInfo().GetDeclaredMethod("GetScheduledTasksForDebugger");
Task[] foundTasks = getScheduledTasksForDebuggerMethod.Invoke(nonExecutingScheduler, null) as Task[];
Assert.Superset(new HashSet<Task>(queuedTasks), new HashSet<Task>(foundTasks));
GC.KeepAlive(nonExecutingScheduler);
}
private static bool DebuggerIsAttached { get { return Debugger.IsAttached; } }
#region Helper Methods / Helper Classes
// Buggy task scheduler to make sure that we handle QueueTask()/TryExecuteTaskInline()
// exceptions correctly. Used in RunBuggySchedulerTests() below.
public class BuggyTaskScheduler : TaskScheduler
{
private readonly ConcurrentQueue<Task> _tasks = new ConcurrentQueue<Task>();
private bool _faultQueues;
protected override void QueueTask(Task task)
{
if (_faultQueues)
throw new InvalidOperationException("I don't queue tasks!");
// else do nothing other than store the task -- still a pretty buggy scheduler!!
_tasks.Enqueue(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
throw new ArgumentException("I am your worst nightmare!");
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return _tasks;
}
public BuggyTaskScheduler()
: this(true)
{
}
public BuggyTaskScheduler(bool faultQueues)
{
_faultQueues = faultQueues;
}
}
private class SimpleSynchronizationContext : SynchronizationContext
{
private int _postCount = 0;
public override void Post(SendOrPostCallback d, object state)
{
_postCount++;
base.Post(d, state);
}
public int PostCount { get { return _postCount; } }
}
private static void SetSynchronizationContext(SynchronizationContext sc)
{
SynchronizationContext.SetSynchronizationContext(sc);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
internal static class ContainedLanguageCodeSupport
{
public static bool IsValidId(Document document, string identifier)
{
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
return syntaxFacts.IsValidIdentifier(identifier);
}
public static bool TryGetBaseClassName(Document document, string className, CancellationToken cancellationToken, out string baseClassName)
{
baseClassName = null;
var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className);
if (type == null || type.BaseType == null)
{
return false;
}
baseClassName = type.BaseType.ToDisplayString();
return true;
}
public static string CreateUniqueEventName(
Document document, string className, string objectName, string nameOfEvent, CancellationToken cancellationToken)
{
var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className);
var name = objectName + "_" + nameOfEvent;
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var typeNode = type.DeclaringSyntaxReferences.Where(r => r.SyntaxTree == tree).Select(r => r.GetSyntax(cancellationToken)).First();
var codeModel = document.Project.LanguageServices.GetService<ICodeModelNavigationPointService>();
var point = codeModel.GetStartPoint(typeNode, EnvDTE.vsCMPart.vsCMPartBody);
var reservedNames = semanticModel.LookupSymbols(point.Value.Position, type).Select(m => m.Name);
return NameGenerator.EnsureUniqueness(name, reservedNames, document.Project.LanguageServices.GetService<ISyntaxFactsService>().IsCaseSensitive);
}
/// <summary>
/// Determine what methods of <paramref name=" className"/> could possibly be used as event
/// handlers.
/// </summary>
/// <param name="document">The document containing <paramref name="className"/>.</param>
/// <param name="className">The name of the type whose methods should be considered.</param>
/// <param name="objectTypeName">The fully qualified name of the type containing a member
/// that is an event. (E.g. "System.Web.Forms.Button")</param>
/// <param name="nameOfEvent">The name of the member in <paramref name="objectTypeName"/>
/// that is the event (E.g. "Clicked")</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The display name of the method, and a unique to for the method.</returns>
public static IEnumerable<Tuple<string, string>> GetCompatibleEventHandlers(
Document document, string className, string objectTypeName, string nameOfEvent, CancellationToken cancellationToken)
{
var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var type = compilation.GetTypeByMetadataName(className);
if (type == null)
{
throw new InvalidOperationException();
}
var eventMember = GetEventSymbol(document, objectTypeName, nameOfEvent, type, cancellationToken);
if (eventMember == null)
{
throw new InvalidOperationException();
}
var eventType = ((IEventSymbol)eventMember).Type;
if (eventType.Kind != SymbolKind.NamedType)
{
throw new InvalidOperationException(ServicesVSResources.EventTypeIsInvalid);
}
var methods = type.GetMembers().OfType<IMethodSymbol>().Where(m => m.CompatibleSignatureToDelegate((INamedTypeSymbol)eventType));
return methods.Select(m => Tuple.Create(m.Name, ConstructMemberId(m)));
}
public static string GetEventHandlerMemberId(Document document, string className, string objectTypeName, string nameOfEvent, string eventHandlerName, CancellationToken cancellationToken)
{
var nameAndId = GetCompatibleEventHandlers(document, className, objectTypeName, nameOfEvent, cancellationToken).SingleOrDefault(pair => pair.Item1 == eventHandlerName);
return nameAndId == null ? null : nameAndId.Item2;
}
/// <summary>
/// Ensure that an event handler exists for a given event.
/// </summary>
/// <param name="thisDocument">The document corresponding to this operation.</param>
/// <param name="targetDocument">The document to generate the event handler in if it doesn't
/// exist.</param>
/// <param name="className">The name of the type to generate the event handler in.</param>
/// <param name="objectName">The name of the event member (if <paramref
/// name="useHandlesClause"/> is true)</param>
/// <param name="objectTypeName">The name of the type containing the event.</param>
/// <param name="nameOfEvent">The name of the event member in <paramref
/// name="objectTypeName"/></param>
/// <param name="eventHandlerName">The name of the method to be hooked up to the
/// event.</param>
/// <param name="itemidInsertionPoint">The VS itemid of the file to generate the event
/// handler in.</param>
/// <param name="useHandlesClause">If true, a vb "Handles" clause will be generated for the
/// handler.</param>
/// <param name="additionalFormattingRule">An additional formatting rule that can be used to
/// format the newly inserted method</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Either the unique id of the method if it already exists, or the unique id of
/// the to be generated method, the text of the to be generated method, and the position in
/// <paramref name="itemidInsertionPoint"/> where the text should be inserted.</returns>
public static Tuple<string, string, VsTextSpan> EnsureEventHandler(
Document thisDocument,
Document targetDocument,
string className,
string objectName,
string objectTypeName,
string nameOfEvent,
string eventHandlerName,
uint itemidInsertionPoint,
bool useHandlesClause,
IFormattingRule additionalFormattingRule,
CancellationToken cancellationToken)
{
var thisCompilation = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var type = thisCompilation.GetTypeByMetadataName(className);
var existingEventHandlers = GetCompatibleEventHandlers(targetDocument, className, objectTypeName, nameOfEvent, cancellationToken);
var existingHandler = existingEventHandlers.SingleOrDefault(e => e.Item1 == eventHandlerName);
if (existingHandler != null)
{
return Tuple.Create(existingHandler.Item2, (string)null, default(VsTextSpan));
}
// Okay, it doesn't exist yet. Let's create it.
var codeGenerationService = targetDocument.GetLanguageService<ICodeGenerationService>();
var syntaxFactory = targetDocument.GetLanguageService<SyntaxGenerator>();
var eventMember = GetEventSymbol(thisDocument, objectTypeName, nameOfEvent, type, cancellationToken);
if (eventMember == null)
{
throw new InvalidOperationException();
}
var eventType = ((IEventSymbol)eventMember).Type;
if (eventType.Kind != SymbolKind.NamedType || ((INamedTypeSymbol)eventType).DelegateInvokeMethod == null)
{
throw new InvalidOperationException(ServicesVSResources.EventTypeIsInvalid);
}
var handlesExpressions = useHandlesClause ?
new[]
{
syntaxFactory.MemberAccessExpression(
objectName != null ? syntaxFactory.IdentifierName(objectName) : syntaxFactory.ThisExpression(),
syntaxFactory.IdentifierName(nameOfEvent))
}
: null;
var invokeMethod = ((INamedTypeSymbol)eventType).DelegateInvokeMethod;
var newMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: null,
accessibility: Accessibility.Protected,
modifiers: new DeclarationModifiers(),
returnType: targetDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetSpecialType(SpecialType.System_Void),
explicitInterfaceSymbol: null,
name: eventHandlerName,
typeParameters: null,
parameters: invokeMethod.Parameters.ToArray(),
statements: null,
handlesExpressions: handlesExpressions);
var annotation = new SyntaxAnnotation();
newMethod = annotation.AddAnnotationToSymbol(newMethod);
var codeModel = targetDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>();
var syntaxFacts = targetDocument.Project.LanguageServices.GetService<ISyntaxFactsService>();
var targetSyntaxTree = targetDocument.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var position = type.Locations.First(loc => loc.SourceTree == targetSyntaxTree).SourceSpan.Start;
var destinationType = syntaxFacts.GetContainingTypeDeclaration(targetSyntaxTree.GetRoot(cancellationToken), position);
var insertionPoint = codeModel.GetEndPoint(destinationType, EnvDTE.vsCMPart.vsCMPartBody);
if (insertionPoint == null)
{
throw new InvalidOperationException(ServicesVSResources.MemberInsertionFailed);
}
var newType = codeGenerationService.AddMethod(destinationType, newMethod, new CodeGenerationOptions(autoInsertionLocation: false), cancellationToken);
var newRoot = targetSyntaxTree.GetRoot(cancellationToken).ReplaceNode(destinationType, newType);
newRoot = Simplifier.ReduceAsync(targetDocument.WithSyntaxRoot(newRoot), Simplifier.Annotation, null, cancellationToken).WaitAndGetResult(cancellationToken).GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var formattingRules = additionalFormattingRule.Concat(Formatter.GetDefaultFormattingRules(targetDocument));
var workspace = targetDocument.Project.Solution.Workspace;
newRoot = Formatter.FormatAsync(newRoot, Formatter.Annotation, workspace, workspace.Options, formattingRules, cancellationToken).WaitAndGetResult(cancellationToken);
var newMember = newRoot.GetAnnotatedNodesAndTokens(annotation).Single();
var newMemberText = newMember.ToFullString();
// In VB, the final newline is likely a statement terminator in the parent - just add
// one on so that things don't get messed.
if (!newMemberText.EndsWith(Environment.NewLine, StringComparison.Ordinal))
{
newMemberText += Environment.NewLine;
}
return Tuple.Create(ConstructMemberId(newMethod), newMemberText, insertionPoint.Value.ToVsTextSpan());
}
public static bool TryGetMemberNavigationPoint(
Document thisDocument,
string className,
string uniqueMemberID,
out VsTextSpan textSpan,
out Document targetDocument,
CancellationToken cancellationToken)
{
targetDocument = null;
textSpan = default(VsTextSpan);
var type = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className);
var member = LookupMemberId(type, uniqueMemberID);
if (member == null)
{
return false;
}
var codeModel = thisDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>();
var memberNode = member.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault();
if (memberNode != null)
{
var navigationPoint = codeModel.GetStartPoint(memberNode, EnvDTE.vsCMPart.vsCMPartNavigate);
if (navigationPoint != null)
{
targetDocument = thisDocument.Project.Solution.GetDocument(memberNode.SyntaxTree);
textSpan = navigationPoint.Value.ToVsTextSpan();
return true;
}
}
return false;
}
/// <summary>
/// Get the display names and unique ids of all the members of the given type in <paramref
/// name="className"/>.
/// </summary>
public static IEnumerable<Tuple<string, string>> GetMembers(
Document document, string className, CODEMEMBERTYPE codeMemberType, CancellationToken cancellationToken)
{
var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className);
var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var allMembers = codeMemberType == CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS ?
semanticModel.LookupSymbols(position: type.Locations[0].SourceSpan.Start, container: type, name: null) :
type.GetMembers();
var members = allMembers.Where(m => IncludeMember(m, codeMemberType, compilation));
return members.Select(m => Tuple.Create(m.Name, ConstructMemberId(m)));
}
/// <summary>
/// Try to do a symbolic rename the specified symbol.
/// </summary>
/// <returns>False ONLY if it can't resolve the name. Other errors result in the normal
/// exception being propagated.</returns>
public static bool TryRenameElement(
Document document,
ContainedLanguageRenameType clrt,
string oldFullyQualifiedName,
string newFullyQualifiedName,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
CancellationToken cancellationToken)
{
var symbol = FindSymbol(document, clrt, oldFullyQualifiedName, cancellationToken);
if (symbol == null)
{
return false;
}
Workspace workspace;
if (Workspace.TryGetWorkspace(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).Container, out workspace))
{
var newName = newFullyQualifiedName.Substring(newFullyQualifiedName.LastIndexOf('.') + 1);
var optionSet = document.Project.Solution.Workspace.Options;
var newSolution = Renamer.RenameSymbolAsync(document.Project.Solution, symbol, newName, optionSet, cancellationToken).WaitAndGetResult(cancellationToken);
var changedDocuments = newSolution.GetChangedDocuments(document.Project.Solution);
var undoTitle = string.Format(EditorFeaturesResources.RenameTo, symbol.Name, newName);
using (var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoTitle))
{
// Notify third parties about the coming rename operation on the workspace, and let
// any exceptions propagate through
refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
if (!workspace.TryApplyChanges(newSolution))
{
Exceptions.ThrowEFail();
}
// Notify third parties about the completed rename operation on the workspace, and
// let any exceptions propagate through
refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
workspaceUndoTransaction.Commit();
}
RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments);
return true;
}
else
{
return false;
}
}
private static bool IncludeMember(ISymbol member, CODEMEMBERTYPE memberType, Compilation compilation)
{
if (!member.CanBeReferencedByName)
{
return false;
}
switch (memberType)
{
case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS:
// NOTE: the Dev10 C# codebase just returned
if (member.Kind != SymbolKind.Method)
{
return false;
}
var method = (IMethodSymbol)member;
if (!method.ReturnsVoid)
{
return false;
}
if (method.Parameters.Length != 2)
{
return false;
}
if (!method.Parameters[0].Type.Equals(compilation.ObjectType))
{
return false;
}
if (!method.Parameters[1].Type.InheritsFromOrEquals(compilation.EventArgsType()))
{
return false;
}
return true;
case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS:
return member.Kind == SymbolKind.Event;
case CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS:
return member.Kind == SymbolKind.Method;
default:
throw new ArgumentException("InvalidValue", "memberType");
}
}
private static ISymbol FindSymbol(
Document document, ContainedLanguageRenameType renameType, string fullyQualifiedName, CancellationToken cancellationToken)
{
switch (renameType)
{
case ContainedLanguageRenameType.CLRT_CLASS:
return document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(fullyQualifiedName);
case ContainedLanguageRenameType.CLRT_CLASSMEMBER:
var lastDot = fullyQualifiedName.LastIndexOf('.');
var typeName = fullyQualifiedName.Substring(0, lastDot);
var memberName = fullyQualifiedName.Substring(lastDot + 1, fullyQualifiedName.Length - lastDot - 1);
var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(typeName);
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var membersOfName = type.GetMembers(memberName);
return membersOfName.SingleOrDefault();
case ContainedLanguageRenameType.CLRT_NAMESPACE:
var ns = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GlobalNamespace;
var parts = fullyQualifiedName.Split('.');
for (int i = 0; i < parts.Length && ns != null; i++)
{
ns = ns.GetNamespaceMembers().SingleOrDefault(n => n.Name == parts[i]);
}
return ns;
case ContainedLanguageRenameType.CLRT_OTHER:
throw new NotSupportedException(ServicesVSResources.ElementRenameFailed);
default:
throw new InvalidOperationException(ServicesVSResources.UnknownRenameType);
}
}
internal static string ConstructMemberId(ISymbol member)
{
if (member.Kind == SymbolKind.Method)
{
return string.Format("{0}({1})", member.Name, string.Join(",", ((IMethodSymbol)member).Parameters.Select(p => p.Type.ToDisplayString())));
}
else if (member.Kind == SymbolKind.Event)
{
return member.Name + "(EVENT)";
}
else
{
throw new NotSupportedException(ServicesVSResources.SymbolTypeIdInvalid);
}
}
internal static ISymbol LookupMemberId(INamedTypeSymbol type, string uniqueMemberID)
{
var memberName = uniqueMemberID.Substring(0, uniqueMemberID.IndexOf('('));
var members = type.GetMembers(memberName).Where(m => m.Kind == SymbolKind.Method);
foreach (var m in members)
{
if (ConstructMemberId(m) == uniqueMemberID)
{
return m;
}
}
return null;
}
private static ISymbol GetEventSymbol(
Document document, string objectTypeName, string nameOfEvent, INamedTypeSymbol type, CancellationToken cancellationToken)
{
var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var objectType = compilation.GetTypeByMetadataName(objectTypeName);
if (objectType == null)
{
throw new InvalidOperationException();
}
var containingTree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var typeLocation = type.Locations.FirstOrDefault(d => d.SourceTree == containingTree);
if (typeLocation == null)
{
throw new InvalidOperationException();
}
return semanticModel.LookupSymbols(typeLocation.SourceSpan.Start, objectType, nameOfEvent).SingleOrDefault(m => m.Kind == SymbolKind.Event);
}
}
}
| |
using System;
using System.Collections.Generic;
using Lucene.Net.Documents;
namespace Lucene.Net.Codecs.Lucene3x
{
using Lucene.Net.Support;
using NUnit.Framework;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using Fields = Lucene.Net.Index.Fields;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using IOContext = Lucene.Net.Store.IOContext;
using LogMergePolicy = Lucene.Net.Index.LogMergePolicy;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockTokenizer = Lucene.Net.Analysis.MockTokenizer;
using MultiFields = Lucene.Net.Index.MultiFields;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SegmentReader = Lucene.Net.Index.SegmentReader;
using Term = Lucene.Net.Index.Term;
using TermQuery = Lucene.Net.Search.TermQuery;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TestUtil = Lucene.Net.Util.TestUtil;
using TopDocs = Lucene.Net.Search.TopDocs;
#pragma warning disable 612, 618
[TestFixture]
public class TestTermInfosReaderIndex : LuceneTestCase
{
private static int NUMBER_OF_DOCUMENTS;
private static int NUMBER_OF_FIELDS;
private static TermInfosReaderIndex Index;
private static Directory Directory;
private static SegmentTermEnum TermEnum;
private static int IndexDivisor;
private static int TermIndexInterval;
private static IndexReader Reader;
private static IList<Term> SampleTerms;
/// <summary>
/// we will manually instantiate preflex-rw here
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
// NOTE: turn off compound file, this test will open some index files directly.
OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true;
IndexWriterConfig config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.KEYWORD, false)).SetUseCompoundFile(false);
TermIndexInterval = config.TermIndexInterval;
IndexDivisor = TestUtil.NextInt(Random(), 1, 10);
NUMBER_OF_DOCUMENTS = AtLeast(100);
NUMBER_OF_FIELDS = AtLeast(Math.Max(10, 3 * TermIndexInterval * IndexDivisor / NUMBER_OF_DOCUMENTS));
Directory = NewDirectory();
config.SetCodec(new PreFlexRWCodec());
LogMergePolicy mp = NewLogMergePolicy();
// NOTE: turn off compound file, this test will open some index files directly.
mp.NoCFSRatio = 0.0;
config.SetMergePolicy(mp);
Populate(Directory, config);
DirectoryReader r0 = IndexReader.Open(Directory);
SegmentReader r = LuceneTestCase.GetOnlySegmentReader(r0);
string segment = r.SegmentName;
r.Dispose();
FieldInfosReader infosReader = (new PreFlexRWCodec()).FieldInfosFormat.FieldInfosReader;
FieldInfos fieldInfos = infosReader.Read(Directory, segment, "", IOContext.READ_ONCE);
string segmentFileName = IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION);
long tiiFileLength = Directory.FileLength(segmentFileName);
IndexInput input = Directory.OpenInput(segmentFileName, NewIOContext(Random()));
TermEnum = new SegmentTermEnum(Directory.OpenInput(IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_EXTENSION), NewIOContext(Random())), fieldInfos, false);
int totalIndexInterval = TermEnum.indexInterval * IndexDivisor;
SegmentTermEnum indexEnum = new SegmentTermEnum(input, fieldInfos, true);
Index = new TermInfosReaderIndex(indexEnum, IndexDivisor, tiiFileLength, totalIndexInterval);
indexEnum.Dispose();
input.Dispose();
Reader = IndexReader.Open(Directory);
SampleTerms = Sample(Random(), Reader, 1000);
}
[OneTimeTearDown]
public override void AfterClass()
{
TermEnum.Dispose();
Reader.Dispose();
Directory.Dispose();
TermEnum = null;
Reader = null;
Directory = null;
Index = null;
SampleTerms = null;
base.AfterClass();
}
[Test]
public virtual void TestSeekEnum()
{
int indexPosition = 3;
SegmentTermEnum clone = (SegmentTermEnum)TermEnum.Clone();
Term term = FindTermThatWouldBeAtIndex(clone, indexPosition);
SegmentTermEnum enumerator = clone;
Index.SeekEnum(enumerator, indexPosition);
Assert.AreEqual(term, enumerator.Term());
clone.Dispose();
}
[Test]
public virtual void TestCompareTo()
{
Term term = new Term("field" + Random().Next(NUMBER_OF_FIELDS), Text);
for (int i = 0; i < Index.Length; i++)
{
Term t = Index.GetTerm(i);
int compareTo = term.CompareTo(t);
Assert.AreEqual(compareTo, Index.CompareTo(term, i));
}
}
[Test]
public virtual void TestRandomSearchPerformance()
{
IndexSearcher searcher = new IndexSearcher(Reader);
foreach (Term t in SampleTerms)
{
TermQuery query = new TermQuery(t);
TopDocs topDocs = searcher.Search(query, 10);
Assert.IsTrue(topDocs.TotalHits > 0);
}
}
private static IList<Term> Sample(Random random, IndexReader reader, int size)
{
IList<Term> sample = new List<Term>();
Fields fields = MultiFields.GetFields(reader);
foreach (string field in fields)
{
Terms terms = fields.GetTerms(field);
Assert.IsNotNull(terms);
TermsEnum termsEnum = terms.GetIterator(null);
while (termsEnum.Next() != null)
{
if (sample.Count >= size)
{
int pos = random.Next(size);
sample[pos] = new Term(field, termsEnum.Term);
}
else
{
sample.Add(new Term(field, termsEnum.Term));
}
}
}
Collections.Shuffle(sample);
return sample;
}
private Term FindTermThatWouldBeAtIndex(SegmentTermEnum termEnum, int index)
{
int termPosition = index * TermIndexInterval * IndexDivisor;
for (int i = 0; i < termPosition; i++)
{
// TODO: this test just uses random terms, so this is always possible
AssumeTrue("ran out of terms", termEnum.Next());
}
Term term = termEnum.Term();
// An indexed term is only written when the term after
// it exists, so, if the number of terms is 0 mod
// termIndexInterval, the last index term will not be
// written; so we require a term after this term
// as well:
AssumeTrue("ran out of terms", termEnum.Next());
return term;
}
private void Populate(Directory directory, IndexWriterConfig config)
{
RandomIndexWriter writer = new RandomIndexWriter(Random(), directory, config);
for (int i = 0; i < NUMBER_OF_DOCUMENTS; i++)
{
Document document = new Document();
for (int f = 0; f < NUMBER_OF_FIELDS; f++)
{
document.Add(NewStringField("field" + f, Text, Field.Store.NO));
}
writer.AddDocument(document);
}
writer.ForceMerge(1);
writer.Dispose();
}
private static string Text
{
get
{
return Convert.ToString(Random().Next());
}
}
}
#pragma warning restore 612, 618
}
| |
//
// MtpSource.cs
//
// Author:
// Gabriel Burt <[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 System.Collections.Generic;
using System.Threading;
using Mono.Unix;
using Hyena;
using Hyena.Collections;
using Mtp;
using MTP = Mtp;
using Banshee.Base;
using Banshee.Dap;
using Banshee.ServiceStack;
using Banshee.Library;
using Banshee.Sources;
using Banshee.Playlist;
using Banshee.Configuration;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Hardware;
namespace Banshee.Dap.Mtp
{
public class MtpSource : DapSource
{
// libmtp only lets us have one device connected at a time
private static MtpSource mtp_source;
private MtpDevice mtp_device;
//private bool supports_jpegs = false;
private Dictionary<int, Track> track_map;
private Dictionary<string, Album> album_cache = new Dictionary<string, Album> ();
private bool supports_jpegs = false;
private bool can_sync_albumart = NeverSyncAlbumArtSchema.Get () == false;
private int thumb_width = AlbumArtWidthSchema.Get ();
public override void DeviceInitialize (IDevice device)
{
base.DeviceInitialize (device);
if (MediaCapabilities == null || !MediaCapabilities.IsType ("mtp")) {
throw new InvalidDeviceException ();
}
// libmtp only allows us to have one MTP device active
if (mtp_source != null) {
Log.Information (
Catalog.GetString ("MTP Support Ignoring Device"),
Catalog.GetString ("Banshee's MTP audio player support can only handle one device at a time."),
true
);
throw new InvalidDeviceException ();
}
List<MtpDevice> devices = null;
try {
devices = MtpDevice.Detect ();
} catch (TypeInitializationException e) {
Log.Exception (e);
Log.Error (
Catalog.GetString ("Error Initializing MTP Device Support"),
Catalog.GetString ("There was an error intializing MTP device support. See http://www.banshee-project.org/Guide/DAPs/MTP for more information."), true
);
throw new InvalidDeviceException ();
} catch (Exception e) {
Log.Exception (e);
//ShowGeneralExceptionDialog (e);
throw new InvalidDeviceException ();
}
if (devices == null || devices.Count == 0) {
Log.Error (
Catalog.GetString ("Error Finding MTP Device Support"),
Catalog.GetString ("An MTP device was detected, but Banshee was unable to load support for it."), true
);
} else {
string mtp_serial = devices[0].SerialNumber;
if (!String.IsNullOrEmpty (mtp_serial)) {
if (mtp_serial.Contains (device.Serial)) {
mtp_device = devices[0];
mtp_source = this;
} else if (device.Serial.Contains (mtp_serial.TrimStart('0'))) {
// Special case for sony walkman players; BGO #543938
mtp_device = devices[0];
mtp_source = this;
}
}
if (mtp_device == null) {
Log.Information(
Catalog.GetString ("MTP Support Ignoring Device"),
Catalog.GetString ("Banshee's MTP audio player support can only handle one device at a time."),
true
);
}
}
if (mtp_device == null) {
throw new InvalidDeviceException ();
}
Name = mtp_device.Name;
Initialize ();
List<string> mimetypes = new List<string> ();
foreach (FileType format in mtp_device.GetFileTypes ()) {
if (format == FileType.JPEG) {
supports_jpegs = true;
} else {
string mimetype = MtpDevice.GetMimeTypeFor (format);
if (mimetype != null) {
mimetypes.Add (mimetype);
}
}
}
AcceptableMimeTypes = mimetypes.ToArray ();
AddDapProperty (Catalog.GetString ("Serial number"), mtp_device.SerialNumber);
AddDapProperty (Catalog.GetString ("Version"), mtp_device.Version);
try {
AddDapProperty (Catalog.GetString ("Battery level"), String.Format ("{0:0%}", mtp_device.BatteryLevel/100.0));
} catch (Exception e) {
Log.Exception ("Unable to get battery level from MTP device", e);
}
}
protected override void LoadFromDevice ()
{
track_map = new Dictionary<int, Track> ();
try {
List<Track> files = null;
lock (mtp_device) {
files = mtp_device.GetAllTracks (delegate (ulong current, ulong total, IntPtr data) {
//user_event.Progress = (double)current / total;
// Translators: {0} is the name of the MTP audio device (eg Gabe's Zen Player), {1} is the
// track currently being loaded, and {2} is the total # of tracks that will be loaded.
SetStatus (String.Format (Catalog.GetString ("Loading {0} - {1} of {2}"), Name, current, total), false);
return 0;
});
}
/*if (user_event.IsCancelRequested) {
return;
}*/
// Delete any empty albums
lock (mtp_device) {
foreach (Album album in mtp_device.GetAlbums ()) {
if (album.Count == 0) {
album.Remove ();
}
}
}
int [] source_ids = new int [] { DbId };
foreach (Track mtp_track in files) {
int track_id;
if ((track_id = DatabaseTrackInfo.GetTrackIdForUri (MtpTrackInfo.GetPathFromMtpTrack (mtp_track), source_ids)) > 0) {
track_map[track_id] = mtp_track;
} else {
MtpTrackInfo track = new MtpTrackInfo (mtp_device, mtp_track);
track.PrimarySource = this;
track.Save (false);
track_map[track.TrackId] = mtp_track;
}
}
Hyena.Data.Sqlite.HyenaSqliteCommand insert_cmd = new Hyena.Data.Sqlite.HyenaSqliteCommand (
@"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID)
SELECT ?, TrackID FROM CoreTracks WHERE PrimarySourceID = ? AND ExternalID = ?");
lock (mtp_device) {
foreach (MTP.Playlist playlist in mtp_device.GetPlaylists ()) {
PlaylistSource pl_src = new PlaylistSource (playlist.Name, this);
pl_src.Save ();
// TODO a transaction would make sense here (when the threading issue is fixed)
foreach (int id in playlist.TrackIds) {
ServiceManager.DbConnection.Execute (insert_cmd, pl_src.DbId, this.DbId, id);
}
pl_src.UpdateCounts ();
AddChildSource (pl_src);
}
}
} catch (Exception e) {
Log.Exception (e);
}
OnTracksAdded ();
}
public override void Import ()
{
Log.Information ("Import to Library is not implemented for MTP devices yet", true);
//new LibraryImportManager (true).QueueSource (BaseDirectory);
}
public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
if (track_map.ContainsKey (track.TrackId)) {
track_map[track.TrackId].Download (uri.LocalPath, delegate (ulong current, ulong total, IntPtr data) {
job.DetailedProgress = (double) current / total;
return 0;
});
} else {
throw new Exception ("Error copying track from MTP device");
}
}
public override void SyncPlaylists ()
{
lock (mtp_device) {
List<MTP.Playlist> device_playlists = new List<MTP.Playlist> (mtp_device.GetPlaylists ());
foreach (MTP.Playlist playlist in device_playlists) {
playlist.Remove ();
}
device_playlists.Clear ();
// Add playlists from Banshee to the device
foreach (Source child in Children) {
PlaylistSource from = child as PlaylistSource;
if (from != null && from.Count > 0) {
MTP.Playlist playlist = new MTP.Playlist (mtp_device, from.Name);
foreach (int track_id in ServiceManager.DbConnection.QueryEnumerable<int> (String.Format (
"SELECT CoreTracks.ExternalID FROM {0} WHERE {1}",
from.DatabaseTrackModel.ConditionFromFragment, from.DatabaseTrackModel.Condition)))
{
playlist.AddTrack (track_id);
}
playlist.Save ();
}
}
}
}
public override bool CanRename {
get { return !(IsAdding || IsDeleting); }
}
private static SafeUri empty_file = new SafeUri (Paths.Combine (Paths.ApplicationCache, "mtp.mp3"));
protected override void OnTracksDeleted ()
{
// Hack to get the disk usage indicate to be accurate, which seems to
// only be updated when tracks are added, not removed.
try {
lock (mtp_device) {
using (System.IO.TextWriter writer = new System.IO.StreamWriter (Banshee.IO.File.OpenWrite (empty_file, true))) {
writer.Write ("foo");
}
Track mtp_track = new Track (System.IO.Path.GetFileName (empty_file.LocalPath), 3);
mtp_device.UploadTrack (empty_file.AbsolutePath, mtp_track, mtp_device.MusicFolder);
mtp_device.Remove (mtp_track);
Banshee.IO.File.Delete (empty_file);
}
} catch {}
base.OnTracksDeleted ();
}
public override void Rename (string newName)
{
base.Rename (newName);
lock (mtp_device) {
mtp_device.Name = newName;
}
}
private long bytes_used;
public override long BytesUsed {
get {
if (Monitor.TryEnter (mtp_device)) {
bytes_used = 0;
foreach (DeviceStorage s in mtp_device.GetStorage ()) {
bytes_used += (long) s.MaxCapacity - (long) s.FreeSpaceInBytes;
}
Monitor.Exit (mtp_device);
}
return bytes_used;
}
}
private long bytes_capacity;
public override long BytesCapacity {
get {
if (Monitor.TryEnter (mtp_device)) {
bytes_capacity = 0;
foreach (DeviceStorage s in mtp_device.GetStorage ()) {
bytes_capacity += (long) s.MaxCapacity;
}
Monitor.Exit (mtp_device);
}
return bytes_capacity;
}
}
public override bool IsReadOnly {
get { return false; }
}
protected override void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri)
{
if (track.PrimarySourceId == DbId)
return;
lock (mtp_device) {
Track mtp_track = TrackInfoToMtpTrack (track, fromUri);
bool video = track.HasAttribute (TrackMediaAttributes.VideoStream);
mtp_device.UploadTrack (fromUri.LocalPath, mtp_track, GetFolderForTrack (track), OnUploadProgress);
// Add/update album art
if (!video) {
string key = MakeAlbumKey (track.AlbumArtist, track.AlbumTitle);
if (!album_cache.ContainsKey (key)) {
Album album = new Album (mtp_device, track.AlbumTitle, track.AlbumArtist, track.Genre, track.Composer);
album.AddTrack (mtp_track);
if (supports_jpegs && can_sync_albumart) {
try {
Gdk.Pixbuf pic = ServiceManager.Get<Banshee.Collection.Gui.ArtworkManager> ().LookupScalePixbuf (
track.ArtworkId, thumb_width
);
if (pic != null) {
byte [] bytes = pic.SaveToBuffer ("jpeg");
album.Save (bytes, (uint)pic.Width, (uint)pic.Height);
Banshee.Collection.Gui.ArtworkManager.DisposePixbuf (pic);
}
album_cache[key] = album;
} catch (Exception e) {
Log.Debug ("Failed to create MTP Album", e.Message);
}
} else {
album.Save ();
album_cache[key] = album;
}
} else {
Album album = album_cache[key];
album.AddTrack (mtp_track);
album.Save ();
}
}
MtpTrackInfo new_track = new MtpTrackInfo (mtp_device, mtp_track);
new_track.PrimarySource = this;
new_track.Save (false);
track_map[new_track.TrackId] = mtp_track;
}
}
private Folder GetFolderForTrack (TrackInfo track)
{
if (track.HasAttribute (TrackMediaAttributes.Podcast)) {
return mtp_device.PodcastFolder;
} else if (track.HasAttribute (TrackMediaAttributes.VideoStream)) {
return mtp_device.VideoFolder;
} else {
return mtp_device.MusicFolder;
}
}
private int OnUploadProgress (ulong sent, ulong total, IntPtr data)
{
AddTrackJob.DetailedProgress = (double) sent / (double) total;
return 0;
}
protected override bool DeleteTrack (DatabaseTrackInfo track)
{
lock (mtp_device) {
Track mtp_track = track_map [track.TrackId];
track_map.Remove (track.TrackId);
// Remove from device
mtp_device.Remove (mtp_track);
// Remove track from album, and remove album from device if it no longer has tracks
string key = MakeAlbumKey (track.ArtistName, track.AlbumTitle);
if (album_cache.ContainsKey (key)) {
Album album = album_cache[key];
album.RemoveTrack (mtp_track);
if (album.Count == 0) {
album.Remove ();
album_cache.Remove (key);
}
}
return true;
}
}
public Track TrackInfoToMtpTrack (TrackInfo track, SafeUri fromUri)
{
Track f = new Track (System.IO.Path.GetFileName (fromUri.LocalPath), (ulong) Banshee.IO.File.GetSize (fromUri));
MtpTrackInfo.ToMtpTrack (track, f);
return f;
}
private bool disposed = false;
public override void Dispose ()
{
if (disposed)
return;
disposed = true;
base.Dispose ();
if (mtp_device != null) {
lock (mtp_device) {
mtp_device.Dispose ();
}
}
ServiceManager.SourceManager.RemoveSource (this);
mtp_device = null;
mtp_source = null;
}
protected override void Eject ()
{
base.Eject ();
Dispose ();
}
private static string MakeAlbumKey (string album_artist, string album)
{
return String.Format ("{0}_{1}", album_artist, album);
}
public static readonly SchemaEntry<bool> NeverSyncAlbumArtSchema = new SchemaEntry<bool>(
"plugins.mtp", "never_sync_albumart",
false,
"Album art disabled",
"Regardless of device's capabilities, do not sync album art"
);
public static readonly SchemaEntry<int> AlbumArtWidthSchema = new SchemaEntry<int>(
"plugins.mtp", "albumart_max_width",
170,
"Album art max width",
"The maximum width to allow for album art."
);
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using System.IO;
using WeifenLuo.WinFormsUI.Docking;
using DockSample.Customization;
namespace DockSample
{
public partial class MainForm : Form
{
private bool m_bSaveLayout = true;
private DeserializeDockContent m_deserializeDockContent;
private DummySolutionExplorer m_solutionExplorer = new DummySolutionExplorer();
private DummyPropertyWindow m_propertyWindow = new DummyPropertyWindow();
private DummyToolbox m_toolbox = new DummyToolbox();
private DummyOutputWindow m_outputWindow = new DummyOutputWindow();
private DummyTaskList m_taskList = new DummyTaskList();
public MainForm()
{
InitializeComponent();
showRightToLeft.Checked = (RightToLeft == RightToLeft.Yes);
RightToLeftLayout = showRightToLeft.Checked;
m_solutionExplorer = new DummySolutionExplorer();
m_solutionExplorer.RightToLeftLayout = RightToLeftLayout;
m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
}
private void menuItemExit_Click(object sender, System.EventArgs e)
{
Close();
}
private void menuItemSolutionExplorer_Click(object sender, System.EventArgs e)
{
m_solutionExplorer.Show(dockPanel);
}
private void menuItemPropertyWindow_Click(object sender, System.EventArgs e)
{
m_propertyWindow.Show(dockPanel);
}
private void menuItemToolbox_Click(object sender, System.EventArgs e)
{
m_toolbox.Show(dockPanel);
}
private void menuItemOutputWindow_Click(object sender, System.EventArgs e)
{
m_outputWindow.Show(dockPanel);
}
private void menuItemTaskList_Click(object sender, System.EventArgs e)
{
m_taskList.Show(dockPanel);
}
private void menuItemAbout_Click(object sender, System.EventArgs e)
{
AboutDialog aboutDialog = new AboutDialog();
aboutDialog.ShowDialog(this);
}
private IDockContent FindDocument(string text)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
if (form.Text == text)
return form as IDockContent;
return null;
}
else
{
foreach (IDockContent content in dockPanel.Documents)
if (content.DockHandler.TabText == text)
return content;
return null;
}
}
private void menuItemNew_Click(object sender, System.EventArgs e)
{
DummyDoc dummyDoc = CreateNewDocument();
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
dummyDoc.MdiParent = this;
dummyDoc.Show();
}
else
dummyDoc.Show(dockPanel);
}
private DummyDoc CreateNewDocument()
{
DummyDoc dummyDoc = new DummyDoc();
int count = 1;
//string text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
string text = "Document" + count.ToString();
while (FindDocument(text) != null)
{
count ++;
//text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
text = "Document" + count.ToString();
}
dummyDoc.Text = text;
return dummyDoc;
}
private DummyDoc CreateNewDocument(string text)
{
DummyDoc dummyDoc = new DummyDoc();
dummyDoc.Text = text;
return dummyDoc;
}
private void menuItemOpen_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = Application.ExecutablePath;
openFile.Filter = "rtf files (*.rtf)|*.rtf|txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFile.FilterIndex = 1;
openFile.RestoreDirectory = true ;
if(openFile.ShowDialog() == DialogResult.OK)
{
string fullName = openFile.FileName;
string fileName = Path.GetFileName(fullName);
if (FindDocument(fileName) != null)
{
MessageBox.Show("The document: " + fileName + " has already opened!");
return;
}
DummyDoc dummyDoc = new DummyDoc();
dummyDoc.Text = fileName;
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
dummyDoc.MdiParent = this;
dummyDoc.Show();
}
else
dummyDoc.Show(dockPanel);
try
{
dummyDoc.FileName = fullName;
}
catch (Exception exception)
{
dummyDoc.Close();
MessageBox.Show(exception.Message);
}
}
}
private void menuItemFile_Popup(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
menuItemClose.Enabled = menuItemCloseAll.Enabled = (ActiveMdiChild != null);
}
else
{
menuItemClose.Enabled = (dockPanel.ActiveDocument != null);
menuItemCloseAll.Enabled = (dockPanel.DocumentsCount > 0);
}
}
private void menuItemClose_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
ActiveMdiChild.Close();
else if (dockPanel.ActiveDocument != null)
dockPanel.ActiveDocument.DockHandler.Close();
}
private void menuItemCloseAll_Click(object sender, System.EventArgs e)
{
CloseAllDocuments();
}
private void CloseAllDocuments()
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
form.Close();
}
else
{
for (int index = dockPanel.Contents.Count - 1; index >= 0; index--)
{
if (dockPanel.Contents[index] is IDockContent)
{
IDockContent content = (IDockContent)dockPanel.Contents[index];
content.DockHandler.Close();
}
}
}
}
private IDockContent GetContentFromPersistString(string persistString)
{
if (persistString == typeof(DummySolutionExplorer).ToString())
return m_solutionExplorer;
else if (persistString == typeof(DummyPropertyWindow).ToString())
return m_propertyWindow;
else if (persistString == typeof(DummyToolbox).ToString())
return m_toolbox;
else if (persistString == typeof(DummyOutputWindow).ToString())
return m_outputWindow;
else if (persistString == typeof(DummyTaskList).ToString())
return m_taskList;
else
{
// DummyDoc overrides GetPersistString to add extra information into persistString.
// Any DockContent may override this value to add any needed information for deserialization.
string[] parsedStrings = persistString.Split(new char[] { ',' });
if (parsedStrings.Length != 3)
return null;
if (parsedStrings[0] != typeof(DummyDoc).ToString())
return null;
DummyDoc dummyDoc = new DummyDoc();
if (parsedStrings[1] != string.Empty)
dummyDoc.FileName = parsedStrings[1];
if (parsedStrings[2] != string.Empty)
dummyDoc.Text = parsedStrings[2];
return dummyDoc;
}
}
private void MainForm_Load(object sender, System.EventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (File.Exists(configFile))
dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (m_bSaveLayout)
dockPanel.SaveAsXml(configFile);
else if (File.Exists(configFile))
File.Delete(configFile);
}
private void menuItemToolBar_Click(object sender, System.EventArgs e)
{
toolBar.Visible = menuItemToolBar.Checked = !menuItemToolBar.Checked;
}
private void menuItemStatusBar_Click(object sender, System.EventArgs e)
{
statusBar.Visible = menuItemStatusBar.Checked = !menuItemStatusBar.Checked;
}
private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem == toolBarButtonNew)
menuItemNew_Click(null, null);
else if (e.ClickedItem == toolBarButtonOpen)
menuItemOpen_Click(null, null);
else if (e.ClickedItem == toolBarButtonSolutionExplorer)
menuItemSolutionExplorer_Click(null, null);
else if (e.ClickedItem == toolBarButtonPropertyWindow)
menuItemPropertyWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonToolbox)
menuItemToolbox_Click(null, null);
else if (e.ClickedItem == toolBarButtonOutputWindow)
menuItemOutputWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonTaskList)
menuItemTaskList_Click(null, null);
else if (e.ClickedItem == toolBarButtonLayoutByCode)
menuItemLayoutByCode_Click(null, null);
else if (e.ClickedItem == toolBarButtonLayoutByXml)
menuItemLayoutByXml_Click(null, null);
}
private void menuItemNewWindow_Click(object sender, System.EventArgs e)
{
MainForm newWindow = new MainForm();
newWindow.Text = newWindow.Text + " - New";
newWindow.Show();
}
private void menuItemTools_Popup(object sender, System.EventArgs e)
{
menuItemLockLayout.Checked = !this.dockPanel.AllowEndUserDocking;
}
private void menuItemLockLayout_Click(object sender, System.EventArgs e)
{
dockPanel.AllowEndUserDocking = !dockPanel.AllowEndUserDocking;
}
private void menuItemLayoutByCode_Click(object sender, System.EventArgs e)
{
dockPanel.SuspendLayout(true);
m_solutionExplorer.Show(dockPanel, DockState.DockRight);
m_propertyWindow.Show(m_solutionExplorer.Pane, m_solutionExplorer);
m_toolbox.Show(dockPanel, new Rectangle(98, 133, 200, 383));
m_outputWindow.Show(m_solutionExplorer.Pane, DockAlignment.Bottom, 0.35);
m_taskList.Show(m_toolbox.Pane, DockAlignment.Left, 0.4);
CloseAllDocuments();
DummyDoc doc1 = CreateNewDocument("Document1");
DummyDoc doc2 = CreateNewDocument("Document2");
DummyDoc doc3 = CreateNewDocument("Document3");
DummyDoc doc4 = CreateNewDocument("Document4");
doc1.Show(dockPanel, DockState.Document);
doc2.Show(doc1.Pane, null);
doc3.Show(doc1.Pane, DockAlignment.Bottom, 0.5);
doc4.Show(doc3.Pane, DockAlignment.Right, 0.5);
dockPanel.ResumeLayout(true, true);
}
private void menuItemLayoutByXml_Click(object sender, System.EventArgs e)
{
dockPanel.SuspendLayout(true);
// In order to load layout from XML, we need to close all the DockContents
CloseAllContents();
Assembly assembly = Assembly.GetAssembly(typeof(MainForm));
Stream xmlStream = assembly.GetManifestResourceStream("DockSample.Resources.DockPanel.xml");
dockPanel.LoadFromXml(xmlStream, m_deserializeDockContent);
xmlStream.Close();
dockPanel.ResumeLayout(true, true);
}
private void CloseAllContents()
{
// we don't want to create another instance of tool window, set DockPanel to null
m_solutionExplorer.DockPanel = null;
m_propertyWindow.DockPanel = null;
m_toolbox.DockPanel = null;
m_outputWindow.DockPanel = null;
m_taskList.DockPanel = null;
// Close all other document windows
CloseAllDocuments();
}
private void SetSchema(object sender, System.EventArgs e)
{
CloseAllContents();
if (sender == menuItemSchemaVS2005)
Extender.SetSchema(dockPanel, Extender.Schema.VS2005);
else if (sender == menuItemSchemaVS2003)
Extender.SetSchema(dockPanel, Extender.Schema.VS2003);
menuItemSchemaVS2005.Checked = (sender == menuItemSchemaVS2005);
menuItemSchemaVS2003.Checked = (sender == menuItemSchemaVS2003);
}
private void SetDocumentStyle(object sender, System.EventArgs e)
{
DocumentStyle oldStyle = dockPanel.DocumentStyle;
DocumentStyle newStyle;
if (sender == menuItemDockingMdi)
newStyle = DocumentStyle.DockingMdi;
else if (sender == menuItemDockingWindow)
newStyle = DocumentStyle.DockingWindow;
else if (sender == menuItemDockingSdi)
newStyle = DocumentStyle.DockingSdi;
else
newStyle = DocumentStyle.SystemMdi;
if (oldStyle == newStyle)
return;
if (oldStyle == DocumentStyle.SystemMdi || newStyle == DocumentStyle.SystemMdi)
CloseAllDocuments();
dockPanel.DocumentStyle = newStyle;
menuItemDockingMdi.Checked = (newStyle == DocumentStyle.DockingMdi);
menuItemDockingWindow.Checked = (newStyle == DocumentStyle.DockingWindow);
menuItemDockingSdi.Checked = (newStyle == DocumentStyle.DockingSdi);
menuItemSystemMdi.Checked = (newStyle == DocumentStyle.SystemMdi);
menuItemLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
menuItemLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
}
private void menuItemCloseAllButThisOne_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
Form activeMdi = ActiveMdiChild;
foreach (Form form in MdiChildren)
{
if (form != activeMdi)
form.Close();
}
}
else
{
foreach (IDockContent document in dockPanel.DocumentsToArray())
{
if (!document.DockHandler.IsActivated)
document.DockHandler.Close();
}
}
}
private void menuItemShowDocumentIcon_Click(object sender, System.EventArgs e)
{
dockPanel.ShowDocumentIcon = menuItemShowDocumentIcon.Checked= !menuItemShowDocumentIcon.Checked;
}
private void showRightToLeft_Click(object sender, EventArgs e)
{
CloseAllContents();
if (showRightToLeft.Checked)
{
this.RightToLeft = RightToLeft.No;
this.RightToLeftLayout = false;
}
else
{
this.RightToLeft = RightToLeft.Yes;
this.RightToLeftLayout = true;
}
m_solutionExplorer.RightToLeftLayout = this.RightToLeftLayout;
showRightToLeft.Checked = !showRightToLeft.Checked;
}
private void exitWithoutSavingLayout_Click(object sender, EventArgs e)
{
m_bSaveLayout = false;
Close();
m_bSaveLayout = true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using HomeControl.WebApi.Areas.HelpPage.ModelDescriptions;
using HomeControl.WebApi.Areas.HelpPage.Models;
namespace HomeControl.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
#if NETFRAMEWORK
namespace System.Windows.Forms
{
using System;
using System.ComponentModel;
using System.Reactive;
using System.Reactive.Linq;
/// <summary>
/// Extension methods providing IObservable wrappers for the events on DataGrid.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ObservableDataGridEvents
{
/// <summary>
/// Returns an observable sequence wrapping the BorderStyleChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the BorderStyleChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> BorderStyleChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BorderStyleChanged += handler,
handler => instance.BorderStyleChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the CaptionVisibleChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the CaptionVisibleChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> CaptionVisibleChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.CaptionVisibleChanged += handler,
handler => instance.CaptionVisibleChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the CurrentCellChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the CurrentCellChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> CurrentCellChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.CurrentCellChanged += handler,
handler => instance.CurrentCellChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the DataSourceChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the DataSourceChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> DataSourceChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.DataSourceChanged += handler,
handler => instance.DataSourceChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ParentRowsLabelStyleChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the ParentRowsLabelStyleChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> ParentRowsLabelStyleChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ParentRowsLabelStyleChanged += handler,
handler => instance.ParentRowsLabelStyleChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the FlatModeChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the FlatModeChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> FlatModeChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.FlatModeChanged += handler,
handler => instance.FlatModeChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BackgroundColorChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the BackgroundColorChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> BackgroundColorChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BackgroundColorChanged += handler,
handler => instance.BackgroundColorChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the AllowNavigationChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the AllowNavigationChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> AllowNavigationChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.AllowNavigationChanged += handler,
handler => instance.AllowNavigationChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the CursorChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the CursorChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> CursorChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.CursorChanged += handler,
handler => instance.CursorChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BackgroundImageChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the BackgroundImageChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> BackgroundImageChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BackgroundImageChanged += handler,
handler => instance.BackgroundImageChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BackgroundImageLayoutChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the BackgroundImageLayoutChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> BackgroundImageLayoutChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BackgroundImageLayoutChanged += handler,
handler => instance.BackgroundImageLayoutChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ReadOnlyChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the ReadOnlyChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> ReadOnlyChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ReadOnlyChanged += handler,
handler => instance.ReadOnlyChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ParentRowsVisibleChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the ParentRowsVisibleChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> ParentRowsVisibleChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ParentRowsVisibleChanged += handler,
handler => instance.ParentRowsVisibleChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the TextChanged event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the TextChanged event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> TextChangedObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.TextChanged += handler,
handler => instance.TextChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Navigate event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the Navigate event on the DataGrid instance.</returns>
public static IObservable<EventPattern<NavigateEventArgs>> NavigateObservable(this DataGrid instance)
{
return Observable.FromEventPattern<NavigateEventHandler, NavigateEventArgs>(
handler => instance.Navigate += handler,
handler => instance.Navigate -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Scroll event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the Scroll event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> ScrollObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Scroll += handler,
handler => instance.Scroll -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the BackButtonClick event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the BackButtonClick event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> BackButtonClickObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.BackButtonClick += handler,
handler => instance.BackButtonClick -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ShowParentDetailsButtonClick event on the DataGrid instance.
/// </summary>
/// <param name="instance">The DataGrid instance to observe.</param>
/// <returns>An observable sequence wrapping the ShowParentDetailsButtonClick event on the DataGrid instance.</returns>
public static IObservable<EventPattern<EventArgs>> ShowParentDetailsButtonClickObservable(this DataGrid instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ShowParentDetailsButtonClick += handler,
handler => instance.ShowParentDetailsButtonClick -= handler);
}
}
}
#endif
| |
namespace GitVersion
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using GitVersion.Helpers;
class Program
{
static StringBuilder log = new StringBuilder();
const string MsBuild = @"c:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe";
static void Main()
{
var exitCode = Run();
if (Debugger.IsAttached)
{
Console.ReadKey();
}
if (exitCode != 0)
{
// Dump log to console if we fail to complete successfully
Console.Write(log.ToString());
}
Environment.Exit(exitCode);
}
static int Run()
{
try
{
Arguments arguments;
var argumentsWithoutExeName = GetArgumentsWithoutExeName();
try
{
arguments = ArgumentParser.ParseArguments(argumentsWithoutExeName);
}
catch (Exception)
{
Console.WriteLine("Failed to parse arguments: {0}", string.Join(" ", argumentsWithoutExeName));
HelpWriter.Write();
return 1;
}
if (arguments.IsHelp)
{
HelpWriter.Write();
return 0;
}
if (!string.IsNullOrEmpty(arguments.Proj) || !string.IsNullOrEmpty(arguments.Exec))
{
arguments.Output = OutputType.BuildServer;
}
ConfigureLogging(arguments);
var gitPreparer = new GitPreparer(arguments);
var gitDirectory = gitPreparer.Prepare();
if (string.IsNullOrEmpty(gitDirectory))
{
Console.Error.WriteLine("Failed to prepare or find the .git directory in path '{0}'", arguments.TargetPath);
return 1;
}
var fileSystem = new FileSystem();
if (arguments.Init)
{
ConfigurationProvider.WriteSample(gitDirectory, fileSystem);
return 0;
}
if (arguments.ShowConfig)
{
Console.WriteLine(ConfigurationProvider.GetEffectiveConfigAsString(gitDirectory, fileSystem));
return 0;
}
var workingDirectory = Directory.GetParent(gitDirectory).FullName;
Logger.WriteInfo("Working directory: " + workingDirectory);
var applicableBuildServers = GetApplicableBuildServers(arguments.Authentication).ToList();
foreach (var buildServer in applicableBuildServers)
{
buildServer.PerformPreProcessingSteps(gitDirectory);
}
VersionVariables variables;
var versionFinder = new GitVersionFinder();
var configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem);
using (var repo = RepositoryLoader.GetRepo(gitDirectory))
{
var gitVersionContext = new GitVersionContext(repo, configuration, commitId: arguments.CommitId);
var semanticVersion = versionFinder.FindVersion(gitVersionContext);
var config = gitVersionContext.Configuration;
variables = VariableProvider.GetVariablesFor(semanticVersion, config.AssemblyVersioningScheme, config.VersioningMode, config.ContinuousDeploymentFallbackTag, gitVersionContext.IsCurrentCommitTagged);
}
if (arguments.Output == OutputType.BuildServer)
{
foreach (var buildServer in applicableBuildServers)
{
buildServer.WriteIntegration(Console.WriteLine, variables);
}
}
if (arguments.Output == OutputType.Json)
{
switch (arguments.ShowVariable)
{
case null:
Console.WriteLine(JsonOutputFormatter.ToJson(variables));
break;
default:
string part;
if (!variables.TryGetValue(arguments.ShowVariable, out part))
{
throw new WarningException(string.Format("'{0}' variable does not exist", arguments.ShowVariable));
}
Console.WriteLine(part);
break;
}
}
using (var assemblyInfoUpdate = new AssemblyInfoFileUpdate(arguments, workingDirectory, variables, fileSystem))
{
var execRun = RunExecCommandIfNeeded(arguments, workingDirectory, variables);
var msbuildRun = RunMsBuildIfNeeded(arguments, workingDirectory, variables);
if (!execRun && !msbuildRun)
{
assemblyInfoUpdate.DoNotRestoreAssemblyInfo();
//TODO Put warning back
//if (!context.CurrentBuildServer.IsRunningInBuildAgent())
//{
// Console.WriteLine("WARNING: Not running in build server and /ProjectFile or /Exec arguments not passed");
// Console.WriteLine();
// Console.WriteLine("Run GitVersion.exe /? for help");
//}
}
}
if (gitPreparer.IsDynamicGitRepository)
{
DeleteHelper.DeleteGitRepository(gitPreparer.DynamicGitRepositoryPath);
}
}
catch (WarningException exception)
{
var error = string.Format("An error occurred:\r\n{0}", exception.Message);
Logger.WriteWarning(error);
return 1;
}
catch (Exception exception)
{
var error = string.Format("An unexpected error occurred:\r\n{0}", exception);
Logger.WriteError(error);
return 1;
}
return 0;
}
static IEnumerable<IBuildServer> GetApplicableBuildServers(Authentication authentication)
{
return BuildServerList.GetApplicableBuildServers(authentication);
}
static void ConfigureLogging(Arguments arguments)
{
var writeActions = new List<Action<string>>
{
s => log.AppendLine(s)
};
if (arguments.Output == OutputType.BuildServer)
{
writeActions.Add(Console.WriteLine);
}
if (arguments.LogFilePath == "console")
{
writeActions.Add(Console.WriteLine);
}
else if (arguments.LogFilePath != null)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(arguments.LogFilePath));
if (File.Exists(arguments.LogFilePath))
{
using (File.CreateText(arguments.LogFilePath)) { }
}
writeActions.Add(x => WriteLogEntry(arguments, x));
}
catch (Exception ex)
{
Console.WriteLine("Failed to configure logging: " + ex.Message);
}
}
Logger.WriteInfo = s => writeActions.ForEach(a => a(s));
Logger.WriteWarning = s => writeActions.ForEach(a => a(s));
Logger.WriteError = s => writeActions.ForEach(a => a(s));
}
static void WriteLogEntry(Arguments arguments, string s)
{
var contents = string.Format("{0}\t\t{1}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), s);
File.AppendAllText(arguments.LogFilePath, contents);
}
static List<string> GetArgumentsWithoutExeName()
{
return Environment.GetCommandLineArgs()
.Skip(1)
.ToList();
}
static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, VersionVariables variables)
{
if (string.IsNullOrEmpty(args.Proj)) return false;
Logger.WriteInfo(string.Format("Launching {0} \"{1}\" {2}", MsBuild, args.Proj, args.ProjArgs));
var results = ProcessHelper.Run(
Logger.WriteInfo, Logger.WriteError,
null, MsBuild, string.Format("\"{0}\" {1}", args.Proj, args.ProjArgs), workingDirectory,
GetEnvironmentalVariables(variables));
if (results != 0)
throw new WarningException("MsBuild execution failed, non-zero return code");
return true;
}
static bool RunExecCommandIfNeeded(Arguments args, string workingDirectory, VersionVariables variables)
{
if (string.IsNullOrEmpty(args.Exec)) return false;
Logger.WriteInfo(string.Format("Launching {0} {1}", args.Exec, args.ExecArgs));
var results = ProcessHelper.Run(
Logger.WriteInfo, Logger.WriteError,
null, args.Exec, args.ExecArgs, workingDirectory,
GetEnvironmentalVariables(variables));
if (results != 0)
throw new WarningException(string.Format("Execution of {0} failed, non-zero return code", args.Exec));
return true;
}
static KeyValuePair<string, string>[] GetEnvironmentalVariables(VersionVariables variables)
{
return variables
.Select(v => new KeyValuePair<string, string>("GitVersion_" + v.Key, v.Value))
.ToArray();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using BookShop.Server.Api.Areas.HelpPage.ModelDescriptions;
using BookShop.Server.Api.Areas.HelpPage.Models;
namespace BookShop.Server.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.