context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Xml;
using Microsoft.Test.ModuleCore;
using Xunit;
namespace CoreXml.Test.XLinq
{
public partial class XNodeReaderFunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class TCReadOuterXml : BridgeHelpers
{
// Element names to test ReadOuterXml on
private static string s_EMP1 = "EMPTY1";
private static string s_EMP2 = "EMPTY2";
private static string s_EMP3 = "EMPTY3";
private static string s_EMP4 = "EMPTY4";
private static string s_ENT1 = "ENTITY1";
private static string s_NEMP0 = "NONEMPTY0";
private static string s_NEMP1 = "NONEMPTY1";
private static string s_NEMP2 = "NONEMPTY2";
private static string s_ELEM1 = "CHARS2";
private static string s_ELEM2 = "SKIP3";
private static string s_ELEM3 = "CONTENT";
private static string s_ELEM4 = "COMPLEX";
// Element names after the ReadOuterXml call
private static string s_NEXT1 = "COMPLEX";
private static string s_NEXT2 = "ACT2";
private static string s_NEXT3 = "CHARS_ELEM1";
private static string s_NEXT4 = "AFTERSKIP3";
private static string s_NEXT5 = "TITLE";
private static string s_NEXT6 = "ENTITY2";
private static string s_NEXT7 = "DUMMY";
// Expected strings returned by ReadOuterXml
private static string s_EXP_EMP1 = "<EMPTY1 />";
private static string s_EXP_EMP2 = "<EMPTY2 val=\"abc\" />";
private static string s_EXP_EMP3 = "<EMPTY3></EMPTY3>";
private static string s_EXP_EMP4 = "<EMPTY4 val=\"abc\"></EMPTY4>";
private static string s_EXP_NEMP1 = "<NONEMPTY1>ABCDE</NONEMPTY1>";
private static string s_EXP_NEMP2 = "<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>";
private static string s_EXP_ELEM1 = "<CHARS2>xxx<MARKUP />yyy</CHARS2>";
private static string s_EXP_ELEM2 = "<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3>";
private static string s_EXP_ELEM3 = "<CONTENT><e1 a1=\"a1value\" a2=\"a2value\"><e2 a1=\"a1value\" a2=\"a2value\"><e3 a1=\"a1value\" a2=\"a2value\">leave</e3></e2></e1></CONTENT>";
private static string s_EXP_ELEM4 = "<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>";
private static string s_EXP_ENT1_EXPAND_CHAR = "<ENTITY1 att1=\"xxx<xxxAxxxCxxxe1fooxxx\">xxx>xxxBxxxDxxxe1fooxxx</ENTITY1>";
public override void Init()
{
base.Init();
}
public override void Terminate()
{
base.Terminate();
}
void TestOuterOnText(string strElem, string strOuterXml, string strNextElemName, bool bWhitespace)
{
XmlReader DataReader = GetReader();//GetReader(pGenericXml);
PositionOnElement(DataReader, strElem);
TestLog.Compare(DataReader.ReadOuterXml(), strOuterXml, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Text, string.Empty, "\n"), true, "vn2");
}
void TestOuterOnElement(string strElem, string strOuterXml, string strNextElemName, bool bWhitespace)
{
XmlReader DataReader = GetReader();//GetReader(pGenericXml);
PositionOnElement(DataReader, strElem);
TestLog.Compare(DataReader.ReadOuterXml(), strOuterXml, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, strNextElemName, string.Empty), true, "vn2");
}
void TestOuterOnAttribute(string strElem, string strName, string strValue)
{
XmlReader DataReader = GetReader();//GetReader(pGenericXml);
PositionOnElement(DataReader, strElem);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
string strExpected = string.Format("{0}=\"{1}\"", strName, strValue);
TestLog.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Attribute, strName, strValue), true, "vn");
}
void TestOuterOnNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader();//GetReader(pGenericXml);
PositionOnNodeType(DataReader, nt);
DataReader.Read();
XmlNodeType expNt = DataReader.NodeType;
string expName = DataReader.Name;
string expValue = DataReader.Value;
PositionOnNodeType(DataReader, nt);
TestLog.Compare(DataReader.ReadOuterXml(), string.Empty, "outer");
TestLog.Compare(VerifyNode(DataReader, expNt, expName, expValue), true, "vn");
}
//[Variation("ReadOuterXml on empty element w/o attributes", Priority = 0)]
public void ReadOuterXml1()
{
TestOuterOnText(s_EMP1, s_EXP_EMP1, s_EMP2, true);
}
//[Variation("ReadOuterXml on empty element w/ attributes", Priority = 0)]
public void ReadOuterXml2()
{
TestOuterOnText(s_EMP2, s_EXP_EMP2, s_EMP3, true);
}
//[Variation("ReadOuterXml on full empty element w/o attributes")]
public void ReadOuterXml3()
{
TestOuterOnText(s_EMP3, s_EXP_EMP3, s_NEMP0, true);
}
//[Variation("ReadOuterXml on full empty element w/ attributes")]
public void ReadOuterXml4()
{
TestOuterOnText(s_EMP4, s_EXP_EMP4, s_NEXT1, true);
}
//[Variation("ReadOuterXml on element with text content", Priority = 0)]
public void ReadOuterXml5()
{
TestOuterOnText(s_NEMP1, s_EXP_NEMP1, s_NEMP2, true);
}
//[Variation("ReadOuterXml on element with attributes", Priority = 0)]
public void ReadOuterXml6()
{
TestOuterOnText(s_NEMP2, s_EXP_NEMP2, s_NEXT2, true);
}
//[Variation("ReadOuterXml on element with text and markup content")]
public void ReadOuterXml7()
{
TestOuterOnText(s_ELEM1, s_EXP_ELEM1, s_NEXT3, true);
}
//[Variation("ReadOuterXml with multiple level of elements")]
public void ReadOuterXml8()
{
TestOuterOnElement(s_ELEM2, s_EXP_ELEM2, s_NEXT4, false);
}
//[Variation("ReadOuterXml with multiple level of elements, text and attributes", Priority = 0)]
public void ReadOuterXml9()
{
string strExpected = s_EXP_ELEM3;
TestOuterOnText(s_ELEM3, strExpected, s_NEXT5, true);
}
//[Variation("ReadOuterXml on element with complex content (CDATA, PIs, Comments)", Priority = 0)]
public void ReadOuterXml10()
{
TestOuterOnText(s_ELEM4, s_EXP_ELEM4, s_NEXT7, true);
}
//[Variation("ReadOuterXml on attribute node of empty element")]
public void ReadOuterXml12()
{
TestOuterOnAttribute(s_EMP2, "val", "abc");
}
//[Variation("ReadOuterXml on attribute node of full empty element")]
public void ReadOuterXml13()
{
TestOuterOnAttribute(s_EMP4, "val", "abc");
}
//[Variation("ReadOuterXml on attribute node", Priority = 0)]
public void ReadOuterXml14()
{
TestOuterOnAttribute(s_NEMP2, "val", "abc");
}
//[Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandEntities", Priority = 0)]
public void ReadOuterXml15()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, s_ENT1);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
string strExpected = "att1=\"xxx<xxxAxxxCxxxe1fooxxx\"";
TestLog.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn");
}
//[Variation("ReadOuterXml on ProcessingInstruction")]
public void ReadOuterXml17()
{
TestOuterOnNodeType(XmlNodeType.ProcessingInstruction);
}
//[Variation("ReadOuterXml on CDATA")]
public void ReadOuterXml24()
{
TestOuterOnNodeType(XmlNodeType.CDATA);
}
[Fact]
public void ReadOuterXmlOnXmlDeclarationAttributes()
{
using (XmlReader DataReader = GetPGenericXmlReader())
{
DataReader.Read();
try
{
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
throw new TestException(TestResult.Failed, "");
}
catch (ArgumentOutOfRangeException) { }
Assert.True(TestLog.Compare(DataReader.ReadOuterXml(), string.Empty, "outer"));
Assert.True((DataReader.NodeType != XmlNodeType.Attribute) || (DataReader.Name != string.Empty) || (DataReader.Value != "UTF-8"));
}
}
//[Variation("ReadOuterXml on element with entities, EntityHandling = ExpandCharEntities")]
public void TRReadOuterXml27()
{
string strExpected = s_EXP_ENT1_EXPAND_CHAR;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, s_ENT1);
TestLog.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, s_NEXT6, string.Empty), true, "vn");
}
//[Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandCharEntites")]
public void TRReadOuterXml28()
{
string strExpected = "att1=\"xxx<xxxAxxxCxxxe1fooxxx\"";
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, s_ENT1);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
TestLog.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn");
}
//[Variation("One large element")]
public void TestTextReadOuterXml29()
{
string strp = "a ";
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
string strxml = "<Name a=\"b\">" + strp + " </Name>";
XmlReader DataReader = GetReaderStr(strxml);
DataReader.Read();
TestLog.Compare(DataReader.ReadOuterXml(), strxml, "rox");
}
//[Variation("Read OuterXml when Namespaces=false and has an attribute xmlns")]
public void ReadOuterXmlWhenNamespacesEqualsToFalseAndHasAnAttributeXmlns()
{
string xml = "<?xml version='1.0' encoding='utf-8' ?> <foo xmlns=\"testing\"><bar id=\"1\" /></foo>";
XmlReader DataReader = GetReaderStr(xml);
DataReader.MoveToContent();
TestLog.Compare(DataReader.ReadOuterXml(), "<foo xmlns=\"testing\"><bar id=\"1\" /></foo>", "mismatch");
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Enyim.Caching.Memcached
{
[DebuggerDisplay("[ Address: {endpoint}, IsAlive = {IsAlive} ]")]
public partial class PooledSocket : IDisposable
{
private readonly ILogger _logger;
private bool _isAlive;
private Socket _socket;
private readonly EndPoint _endpoint;
private readonly int _connectionTimeout;
private NetworkStream _inputStream;
public PooledSocket(EndPoint endpoint, TimeSpan connectionTimeout, TimeSpan receiveTimeout, ILogger logger)
{
_logger = logger;
_isAlive = true;
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.NoDelay = true;
_connectionTimeout = connectionTimeout == TimeSpan.MaxValue
? Timeout.Infinite
: (int)connectionTimeout.TotalMilliseconds;
var rcv = receiveTimeout == TimeSpan.MaxValue
? Timeout.Infinite
: (int)receiveTimeout.TotalMilliseconds;
socket.ReceiveTimeout = rcv;
socket.SendTimeout = rcv;
_socket = socket;
_endpoint = endpoint;
}
public void Connect()
{
bool success = false;
//Learn from https://github.com/dotnet/corefx/blob/release/2.2/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.cs#L180
var cts = new CancellationTokenSource();
cts.CancelAfter(_connectionTimeout);
void Cancel()
{
if (_socket != null && !_socket.Connected)
{
_socket.Dispose();
_socket = null;
}
}
cts.Token.Register(Cancel);
try
{
_socket.Connect(_endpoint);
}
catch (PlatformNotSupportedException)
{
var ep = GetIPEndPoint(_endpoint);
_socket.Connect(ep.Address, ep.Port);
}
if (_socket != null)
{
if (_socket.Connected)
{
success = true;
}
else
{
_socket.Dispose();
_socket = null;
}
}
if (success)
{
_inputStream = new NetworkStream(_socket);
}
else
{
throw new TimeoutException($"Could not connect to {_endpoint}.");
}
}
public async Task ConnectAsync()
{
bool success = false;
try
{
var connTask = _socket.ConnectAsync(_endpoint);
if (await Task.WhenAny(connTask, Task.Delay(_connectionTimeout)) == connTask)
{
await connTask;
}
else
{
if (_socket != null)
{
_socket.Dispose();
_socket = null;
}
throw new TimeoutException($"Timeout to connect to {_endpoint}.");
}
}
catch (PlatformNotSupportedException)
{
var ep = GetIPEndPoint(_endpoint);
await _socket.ConnectAsync(ep.Address, ep.Port);
}
if (_socket != null)
{
if (_socket.Connected)
{
success = true;
}
else
{
_socket.Dispose();
_socket = null;
}
}
if (success)
{
_inputStream = new NetworkStream(_socket);
}
else
{
throw new TimeoutException($"Could not connect to {_endpoint}.");
}
}
public Action<PooledSocket> CleanupCallback { get; set; }
public int Available
{
get { return _socket.Available; }
}
public void Reset()
{
// _inputStream.Flush();
int available = _socket.Available;
if (available > 0)
{
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(
"Socket bound to {0} has {1} unread data! This is probably a bug in the code. InstanceID was {2}.",
_socket.RemoteEndPoint, available, InstanceId);
byte[] data = new byte[available];
Read(data, 0, available);
}
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("Socket {0} was reset", InstanceId);
}
public async Task ResetAsync()
{
// await _inputStream.FlushAsync();
int available = _socket.Available;
if (available > 0)
{
if (_logger.IsEnabled(LogLevel.Warning))
{
_logger.LogWarning(
"Socket bound to {0} has {1} unread data! This is probably a bug in the code. InstanceID was {2}.",
_socket.RemoteEndPoint, available, InstanceId);
}
byte[] data = new byte[available];
await ReadAsync(data, 0, available);
}
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("Socket {0} was reset", InstanceId);
}
/// <summary>
/// The ID of this instance. Used by the <see cref="T:MemcachedServer"/> to identify the instance in its inner lists.
/// </summary>
public readonly Guid InstanceId = Guid.NewGuid();
public bool IsAlive
{
get { return _isAlive; }
set { _isAlive = value; }
}
/// <summary>
/// Releases all resources used by this instance and shuts down the inner <see cref="T:Socket"/>. This instance will not be usable anymore.
/// </summary>
/// <remarks>Use the IDisposable.Dispose method if you want to release this instance back into the pool.</remarks>
public void Destroy()
{
this.Dispose(true);
}
~PooledSocket()
{
try
{
this.Dispose(true);
}
catch
{
}
}
protected void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
try
{
if (_socket != null)
{
try { _socket.Dispose(); } catch { }
}
if (_inputStream != null)
{
_inputStream.Dispose();
}
_inputStream = null;
_socket = null;
this.CleanupCallback = null;
}
catch (Exception e)
{
_logger.LogError(nameof(PooledSocket), e);
}
}
else
{
Action<PooledSocket> cc = this.CleanupCallback;
if (cc != null)
cc(this);
}
}
void IDisposable.Dispose()
{
this.Dispose(false);
}
private void CheckDisposed()
{
if (_socket == null)
throw new ObjectDisposedException("PooledSocket");
}
/// <summary>
/// Reads the next byte from the server's response.
/// </summary>
/// <remarks>This method blocks and will not return until the value is read.</remarks>
public int ReadByte()
{
this.CheckDisposed();
try
{
return _inputStream.ReadByte();
}
catch (Exception ex)
{
if (ex is IOException || ex is SocketException)
{
_isAlive = false;
}
throw;
}
}
public int ReadByteAsync()
{
this.CheckDisposed();
try
{
return _inputStream.ReadByte();
}
catch (Exception ex)
{
if (ex is IOException || ex is SocketException)
{
_isAlive = false;
}
throw;
}
}
public async Task ReadAsync(byte[] buffer, int offset, int count)
{
this.CheckDisposed();
int read = 0;
int shouldRead = count;
while (read < count)
{
try
{
int currentRead = await _inputStream.ReadAsync(buffer, offset, shouldRead);
if (currentRead == count)
break;
if (currentRead < 1)
throw new IOException("The socket seems to be disconnected");
read += currentRead;
offset += currentRead;
shouldRead -= currentRead;
}
catch (Exception ex)
{
if (ex is IOException || ex is SocketException)
{
_isAlive = false;
}
throw;
}
}
}
/// <summary>
/// Reads data from the server into the specified buffer.
/// </summary>
/// <param name="buffer">An array of <see cref="T:System.Byte"/> that is the storage location for the received data.</param>
/// <param name="offset">The location in buffer to store the received data.</param>
/// <param name="count">The number of bytes to read.</param>
/// <remarks>This method blocks and will not return until the specified amount of bytes are read.</remarks>
public void Read(byte[] buffer, int offset, int count)
{
this.CheckDisposed();
int read = 0;
int shouldRead = count;
while (read < count)
{
try
{
int currentRead = _inputStream.Read(buffer, offset, shouldRead);
if (currentRead == count)
break;
if (currentRead < 1)
throw new IOException("The socket seems to be disconnected");
read += currentRead;
offset += currentRead;
shouldRead -= currentRead;
}
catch (Exception ex)
{
if (ex is IOException || ex is SocketException)
{
_isAlive = false;
}
throw;
}
}
}
public void Write(byte[] data, int offset, int length)
{
this.CheckDisposed();
SocketError status;
_socket.Send(data, offset, length, SocketFlags.None, out status);
if (status != SocketError.Success)
{
_isAlive = false;
ThrowHelper.ThrowSocketWriteError(_endpoint, status);
}
}
public void Write(IList<ArraySegment<byte>> buffers)
{
this.CheckDisposed();
SocketError status;
try
{
_socket.Send(buffers, SocketFlags.None, out status);
if (status != SocketError.Success)
{
_isAlive = false;
ThrowHelper.ThrowSocketWriteError(_endpoint, status);
}
}
catch (Exception ex)
{
if (ex is IOException || ex is SocketException)
{
_isAlive = false;
}
_logger.LogError(ex, nameof(PooledSocket.Write));
throw;
}
}
public async Task WriteAsync(IList<ArraySegment<byte>> buffers)
{
CheckDisposed();
try
{
var bytesTransferred = await _socket.SendAsync(buffers, SocketFlags.None);
if (bytesTransferred <= 0)
{
_isAlive = false;
_logger.LogError($"Failed to {nameof(PooledSocket.WriteAsync)}. bytesTransferred: {bytesTransferred}");
ThrowHelper.ThrowSocketWriteError(_endpoint);
}
}
catch (Exception ex)
{
if (ex is IOException || ex is SocketException)
{
_isAlive = false;
}
_logger.LogError(ex, nameof(PooledSocket.WriteAsync));
throw;
}
}
private IPEndPoint GetIPEndPoint(EndPoint endpoint)
{
if (endpoint is DnsEndPoint)
{
var dnsEndPoint = (DnsEndPoint)endpoint;
var address = Dns.GetHostAddresses(dnsEndPoint.Host).FirstOrDefault(ip =>
ip.AddressFamily == AddressFamily.InterNetwork);
if (address == null)
throw new ArgumentException(String.Format("Could not resolve host '{0}'.", endpoint));
return new IPEndPoint(address, dnsEndPoint.Port);
}
else if (endpoint is IPEndPoint)
{
return endpoint as IPEndPoint;
}
else
{
throw new Exception("Not supported EndPoint type");
}
}
}
}
#region [ License information ]
/* ************************************************************
*
* Copyright (c) 2010 Attila Kisk? enyim.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ************************************************************/
#endregion
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetDegradedAzureDataReplicationRulesSpectraS3Request : Ds3Request
{
private string _dataPolicyId;
public string DataPolicyId
{
get { return _dataPolicyId; }
set { WithDataPolicyId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private DataPlacementRuleState? _state;
public DataPlacementRuleState? State
{
get { return _state; }
set { WithState(value); }
}
private string _targetId;
public string TargetId
{
get { return _targetId; }
set { WithTargetId(value); }
}
private DataReplicationRuleType? _type;
public DataReplicationRuleType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithDataPolicyId(Guid? dataPolicyId)
{
this._dataPolicyId = dataPolicyId.ToString();
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId.ToString());
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithDataPolicyId(string dataPolicyId)
{
this._dataPolicyId = dataPolicyId;
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId);
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithState(DataPlacementRuleState? state)
{
this._state = state;
if (state != null)
{
this.QueryParams.Add("state", state.ToString());
}
else
{
this.QueryParams.Remove("state");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithTargetId(Guid? targetId)
{
this._targetId = targetId.ToString();
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId.ToString());
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithTargetId(string targetId)
{
this._targetId = targetId;
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId);
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request WithType(DataReplicationRuleType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetDegradedAzureDataReplicationRulesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/degraded_azure_data_replication_rule";
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace BugLogger.Services.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Cryptography.X509Certificates;
using NUnit.Framework;
namespace OMap.Tests
{
[TestFixture]
public class ObjectMapperTests
{
public class Foo
{
public int Property1 { get; set; }
}
public class FooX : Foo
{
public int Property2 { get; set; }
}
public class FooO
{
public int Property1 { get; set; }
public Foo Foo { get; set; }
}
public class FooC
{
public int Property1 { get; set; }
public Foo[] Foos { get; set; }
}
public class FooAll
{
public int Property1 { get; set; }
public string Property2 { get; set; }
public bool Property3 { get; set; }
public DateTime Property4 { get; set; }
public Foo[] Foos { get; set; }
public Foo FooSingle { get; set; }
}
public class FooAllX : FooAll
{
public decimal Property5 { get; set; }
}
public class Bar
{
public int Property3 { get; set; }
}
public class BarX : Bar
{
public int Property4 { get; set; }
}
public class BarO
{
public int Property1 { get; set; }
public Bar Bar { get; set; }
}
public class BarC
{
public int Property1 { get; set; }
public Bar[] BarArray { get; set; }
public List<Bar> BarList { get; set; }
public IEnumerable<Bar> BarEnumerable { get; set; }
public IList<Bar> BarIList { get; set; }
public List<Bar> BarListNoSetter { get; private set; }
public List<Bar> BarListNotEmpty { get; set; }
public List<Bar> BarListNoSetterNotEmpty { get; private set; }
public BarC()
{
BarListNoSetter = new List<Bar>();
BarListNotEmpty = new List<Bar>() { new Bar() };
BarListNoSetterNotEmpty = new List<Bar>() { new Bar() };
}
}
public class BarAll
{
public int Property1 { get; set; }
public string Property2 { get; set; }
public bool Property3 { get; set; }
public DateTime Property4 { get; set; }
public Bar[] Foos { get; set; }
public Bar FooSingle { get; set; }
}
public class BarAllX : BarAll
{
public decimal Property5 { get; set; }
}
public class Dependency1
{
private static readonly Random _random = new Random();
public int RandomProperty { get; private set; }
public int GlobalProperty1 { get; set; }
public Dependency1()
{
while (RandomProperty == 0)
{
RandomProperty = _random.Next();
}
}
}
[Test]
public void ShouldMapProperty()
{
var foo = new Foo() { Property1 = 18 };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
});
var bar = mapper.Map<Bar>(foo);
Assert.AreEqual(foo.Property1, bar.Property3);
}
[Test]
public void ShouldMapPropertyExistingObject()
{
var foo = new Foo() { Property1 = 18 };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
});
var bar = new Bar();
mapper.Map(foo, bar);
Assert.AreEqual(foo.Property1, bar.Property3);
}
[Test]
public void ShouldMapPropertyWithFunction()
{
var foo = new Foo() { Property1 = 18 };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1 * 5, x => x.Property3);
});
var bar = mapper.Map<Bar>(foo);
Assert.AreEqual(foo.Property1 * 5, bar.Property3);
}
[Test]
public void ShouldMapPropertyWithFunctionExistingObject()
{
var foo = new Foo() { Property1 = 18 };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1 * 5, x => x.Property3);
});
var bar = new Bar();
mapper.Map(foo, bar);
Assert.AreEqual(foo.Property1 * 5, bar.Property3);
}
[Test]
public void ShouldMapInheritedProperty()
{
var foo = new FooX() { Property1 = 18, Property2 = 7 };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
builder.CreateMap<FooX, BarX>()
.MapProperty(x => x.Property2, x => x.Property4);
});
var bar = mapper.Map<Bar>(foo);
Assert.IsInstanceOf<BarX>(bar, "Even if you have requested 'Bar', the mapper found a more specific type and will return that instead.");
var barX = (BarX)bar;
Assert.AreEqual(foo.Property1, barX.Property3);
Assert.AreEqual(foo.Property2, barX.Property4);
}
[Test]
public void ShouldNotLookForParentsWhenMappingInheritedProperties()
{
//NOTE: By design, when calling Map<FooX>, no mappings for Foo will be used - eventhough FooX inherits from Foo.
//To get all mappings, ca
var foo = new FooX() { Property1 = 18, Property2 = 7 };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
builder.CreateMap<FooX, BarX>()
.MapProperty(x => x.Property2, x => x.Property4);
});
//Not specifying TTargetBase will skip all mappings from BarX upwards (the inheritance chain).
var barX1 = mapper.Map<BarX, BarX>(foo);
Assert.AreEqual(0, barX1.Property3);
Assert.AreEqual(7, barX1.Property4);
//Specifying TTargetBase will enture all mappings from Bar downwards (the inheritance chain) are applied.
var barX2 = mapper.Map<BarX, Bar>(foo);
Assert.AreEqual(18, barX2.Property3);
Assert.AreEqual(7, barX2.Property4);
}
[Test]
public void ShouldMapInheritedPropertyExistingObject()
{
var foo = new FooX() { Property1 = 18, Property2 = 7 };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
builder.CreateMap<FooX, BarX>()
.MapProperty(x => x.Property2, x => x.Property4);
});
var bar = new Bar();
mapper.Map(foo, bar);
Assert.AreEqual(foo.Property1, bar.Property3);
}
[Test]
public void ShouldMapComposedObject()
{
var foo = new FooO() { Property1 = 18, Foo = new Foo() { Property1 = 7 } };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
builder.CreateMap<FooO, BarO>()
.MapProperty(x => x.Property1, x => x.Property1)
.MapObject(x => x.Foo, x => x.Bar);
});
var bar = mapper.Map<BarO>(foo);
Assert.AreEqual(foo.Property1, bar.Property1);
Assert.AreEqual(foo.Foo.Property1, bar.Bar.Property3);
}
[Test]
public void ShouldMapInheritedComposedObject()
{
var foo = new FooO() { Property1 = 18, Foo = new FooX() { Property1 = 7, Property2 = 6 } };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
builder.CreateMap<FooX, BarX>()
.MapProperty(x => x.Property2, x => x.Property4);
builder.CreateMap<FooO, BarO>()
.MapProperty(x => x.Property1, x => x.Property1)
.MapObject(x => x.Foo, x => x.Bar);
});
var bar = mapper.Map<BarO>(foo);
Assert.AreEqual(foo.Property1, bar.Property1);
Assert.AreEqual(foo.Foo.Property1, bar.Bar.Property3);
Assert.IsInstanceOf<BarX>(bar.Bar);
Assert.AreEqual(((FooX)foo.Foo).Property2, ((BarX)bar.Bar).Property4);
}
[Test]
public void ShouldMapComposedObjectExistingObject()
{
var foo = new FooO() { Property1 = 18, Foo = new Foo() { Property1 = 7 } };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
builder.CreateMap<FooO, BarO>()
.MapProperty(x => x.Property1, x => x.Property1)
.MapObject(x => x.Foo, x => x.Bar);
});
var bar = new Bar();
var barO = new BarO { Bar = bar };
mapper.Map(foo, barO);
Assert.AreEqual(foo.Property1, barO.Property1);
Assert.AreEqual(foo.Foo.Property1, barO.Bar.Property3);
Assert.AreSame(bar, barO.Bar, "Should not have created a new instance of Bar");
}
[Test]
public void ShouldMapTargetArray()
{
AssertCollectionMap(x => x.BarArray);
}
[Test]
public void ShouldMapTargetList()
{
AssertCollectionMap(x => x.BarList);
}
[Test]
public void ShouldMapTargetIEnumerable()
{
AssertCollectionMap(x => x.BarEnumerable);
}
[Test]
public void ShouldMapTargetIList()
{
AssertCollectionMap(x => x.BarIList);
}
[Test]
public void ShouldMapTargetListNoSetter()
{
AssertCollectionMap(x => x.BarListNoSetter);
}
[Test]
public void ShouldMapTargetListNotEmpty()
{
AssertCollectionMap(x => x.BarListNotEmpty);
}
[Test]
public void ShouldMapTargetListNoSetterNotEmpty()
{
AssertCollectionMap(x => x.BarListNoSetterNotEmpty);
}
private void AssertCollectionMap(Expression<Func<BarC, IEnumerable<Bar>>> collectionExpression)
{
var fooC = new FooC() { Property1 = 18, Foos = new Foo[] { new Foo() { Property1 = 1 }, new Foo() { Property1 = 2 }, new FooX() { Property1 = 3, Property2 = 33} } };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
builder.CreateMap<FooX, BarX>()
.MapProperty(x => x.Property2, x => x.Property4);
builder.CreateMap<FooC, BarC>()
.MapProperty(x => x.Property1, x => x.Property1)
.MapCollection(x => x.Foos, collectionExpression);
});
var barC = mapper.Map<BarC>(fooC);
var func = collectionExpression.Compile();
var enumerable = func(barC);
Assert.AreEqual(18, barC.Property1);
Assert.AreEqual(3, enumerable.Count());
Assert.AreEqual(1, enumerable.ElementAt(0).Property3);
Assert.AreEqual(2, enumerable.ElementAt(1).Property3);
Assert.AreEqual(3, enumerable.ElementAt(2).Property3);
Assert.IsInstanceOf<BarX>(enumerable.ElementAt(2));
Assert.AreEqual(33, ((BarX)enumerable.ElementAt(2)).Property4);
}
[Test]
public void ShouldMapWithResolver()
{
var foo = new Foo() { Property1 = 891 };
var resolver = new ResolverMock();
resolver.Add(() => new Dependency1() { GlobalProperty1 = 5 });
var mapper = CreateMapper(resolver, builder =>
{
builder.CreateMap<Foo, Bar>()
.WithDependencies<Dependency1>()
.MapProperty((x, dep) => dep.Item1.GlobalProperty1 + x.Property1, x => x.Property3);
});
var bar = mapper.Map<Bar>(foo);
Assert.AreEqual(896, bar.Property3);
}
[Test]
public void ShouldMapWithResolverByName()
{
var foo = new Foo() { Property1 = 891 };
var resolver = new ResolverMock();
resolver.Add(() => new Dependency1() { GlobalProperty1 = 5 }, "dependency1");
var mapper = CreateMapper(resolver, builder =>
{
builder.CreateMap<Foo, Bar>()
.WithDependencies<Dependency1>("dependency1")
.MapProperty((x, dep) => dep.Item1.GlobalProperty1 + x.Property1, x => x.Property3);
});
var bar = mapper.Map<Bar>(foo);
Assert.AreEqual(896, bar.Property3);
}
[Test]
public void ShouldMapWithDifferentDependenciesResolvedByName()
{
var foo = new FooX() { Property1 = 10, Property2 = 100 };
var resolver = new ResolverMock();
resolver.Add(() => new Dependency1() { GlobalProperty1 = 1 }, "dependency1");
resolver.Add(() => new Dependency1() { GlobalProperty1 = 2 }, "dependency2");
var mapper = CreateMapper(resolver, builder =>
{
builder.CreateMap<Foo, Bar>()
.WithDependencies<Dependency1>("dependency1")
.MapProperty((x, dep) => dep.Item1.GlobalProperty1 + x.Property1, x => x.Property3);
builder.CreateMap<FooX, BarX>()
.WithDependencies<Dependency1>("dependency2")
.MapProperty((x, dep) => dep.Item1.GlobalProperty1 + x.Property2, x => x.Property4);
});
var bar = (BarX)mapper.Map<Bar>(foo);
Assert.AreEqual(11, bar.Property3);
Assert.AreEqual(102, bar.Property4);
}
[Test]
public void ShouldUseSameDependencyDuringMappingOperation()
{
//While Mapping, if requesting the same dependency on multiple maps, the same dependency should be
//used (instead of going back to the IOC container).
//The idea is that mapping an object is a single function (and therefore the dependencies should be resolved only once).
var foo = new FooX();
var resolver = new ResolverMock();
resolver.Add(() => new Dependency1());
var mapper = CreateMapper(resolver, builder =>
{
builder.CreateMap<FooX, BarX>()
.WithDependencies<Dependency1>()
.MapProperty((x, dep) => dep.Item1.RandomProperty, x => x.Property4)
.MapProperty((x, dep) => dep.Item1.RandomProperty, x => x.Property3);
});
var bar1 = mapper.Map<BarX>(foo);
var bar2 = mapper.Map<BarX>(foo);
Assert.AreEqual(bar1.Property3, bar1.Property4, "Those properties must be the same!");
Assert.AreEqual(bar2.Property3, bar2.Property4, "Those properties must be the same!");
Assert.AreNotEqual(bar1.Property3, bar2.Property3, "Those properties cannot be the same!");
Assert.AreNotEqual(bar1.Property4, bar2.Property4, "Those properties cannot be the same!");
}
[Test]
public void ShouldUseSameDependencyDuringMappingOperationOfComposedChildren()
{
var fooC = new FooC() { Foos = new Foo[] { new Foo(), new Foo(), new Foo() } };
var resolver = new ResolverMock();
resolver.Add(() => new Dependency1());
var mapper = CreateMapper(resolver, builder =>
{
builder.CreateMap<Foo, Bar>()
.WithDependencies<Dependency1>()
.MapProperty((x, d) => d.Item1.RandomProperty, x => x.Property3);
builder.CreateMap<FooC, BarC>()
.MapCollection(x => x.Foos, x => x.BarArray);
});
var barC = mapper.Map<BarC>(fooC);
var randomNumber = barC.BarArray.Select(x => x.Property3).Distinct().ToArray();
Assert.AreEqual(1, randomNumber.Length, "Expected all Bars to have the same Property3 because they should have used the same dependency");
Assert.AreNotEqual(0, randomNumber[0], "Should be a random int - not equal to zero");
}
[Test]
public void ShouldUseMappingFunction()
{
var foo = new Foo() { Property1 = 18 };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapFunction((src, tgt) => tgt.Property3 = src.Property1);
});
var bar = mapper.Map<Bar>(foo);
Assert.AreEqual(foo.Property1, bar.Property3);
}
[Test]
public void ShouldUseMappingFunctionWithDependencies()
{
var foo = new Foo() { Property1 = 18 };
var resolver = new ResolverMock();
resolver.Add(() => new Dependency1() { GlobalProperty1 = 10 });
var mapper = CreateMapper(resolver, builder =>
{
builder.CreateMap<Foo, Bar>()
.WithDependencies<Dependency1>()
.MapFunction((src, tgt, dependencies) => tgt.Property3 = src.Property1 + dependencies.Item1.GlobalProperty1);
});
var bar = mapper.Map<Bar>(foo);
Assert.AreEqual(28, bar.Property3);
}
[Test]
public void ShouldUseMappingFunctionWithDependenciesDoNotUseDependency()
{
var foo = new Foo() { Property1 = 6 };
var resolver = new ResolverMock();
var mapper = CreateMapper(resolver, builder =>
{
builder.CreateMap<Foo, Bar>()
.WithDependencies<Dependency1>()
.MapFunction((src, tgt) => tgt.Property3 = src.Property1);
});
var bar = mapper.Map<Bar>(foo);
Assert.AreEqual(6, bar.Property3);
}
[Test]
public void ShouldUseMappingFunctionInherited()
{
var fooX = new FooX() { Property1 = 1, Property2 = 7 };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
//NOTE: This is interesting because FooBarMapping function take Foo and Bar, not FooX and BarX
builder.CreateMap<FooX, BarX>()
.MapFunction(FooBarMappingFunction)
.MapProperty(x => x.Property2, x => x.Property4);
});
var barX = mapper.Map<BarX>(fooX);
Assert.AreEqual(1, barX.Property3);
Assert.AreEqual(7, barX.Property4);
}
[Test]
public void ShouldMapAll()
{
var now = DateTime.Now;
var fooAll = new FooAll() { Property1 = 59, Property2 = "Hello", Property3 = true, Property4 = now };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<FooAll, BarAll>()
.MapAll()
.Ignore(x => x.FooSingle)
.Ignore(x => x.Foos);
});
var barAll = mapper.Map<BarAll>(fooAll);
Assert.AreEqual(59, barAll.Property1);
Assert.AreEqual("Hello", barAll.Property2);
Assert.AreEqual(true, barAll.Property3);
Assert.AreEqual(now, barAll.Property4);
}
[Test]
public void ShouldMapAllInherited()
{
var now = DateTime.Now;
var fooAllX = new FooAllX() { Property1 = 59, Property2 = "Hello", Property3 = true, Property4 = now, Property5 = 8};
var mapper = CreateMapper(new ResolverMock(), builder =>
{
//NOTE: Map All on parent has Exclusions... those should be respected when mapping child classes (i.e. no need to specify x => x.FooSingle when mapping FooAllX->BarAllX).
builder.CreateMap<FooAll, BarAll>().MapAll().Ignore(x => x.FooSingle).Ignore(x => x.Foos);
builder.CreateMap<FooAllX, BarAllX>().MapAll();
});
var barAllX = mapper.Map<BarAllX, BarAll>(fooAllX);
Assert.AreEqual(59, barAllX.Property1);
Assert.AreEqual("Hello", barAllX.Property2);
Assert.AreEqual(true, barAllX.Property3);
Assert.AreEqual(now, barAllX.Property4);
Assert.AreEqual(8, barAllX.Property5);
}
[Test]
public void ShouldMapAllExcept()
{
var now = DateTime.Now;
var fooAll = new FooAll() { Property1 = 59, Property2 = "Hello", Property3 = true, Property4 = now };
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<FooAll, BarAll>()
.MapAll()
.Ignore(x => x.FooSingle).Ignore(x => x.Foos).Ignore(x => x.Property1).Ignore(x => x.Property2);
});
var barAll = mapper.Map<BarAll>(fooAll);
Assert.AreEqual(0, barAll.Property1);
Assert.AreEqual(null, barAll.Property2);
Assert.AreEqual(true, barAll.Property3);
Assert.AreEqual(now, barAll.Property4);
}
[Test]
public void ShouldMapAllWithObject()
{
var now = DateTime.Now;
var fooAll = new FooAll()
{
Property1 = 87,
Property2 = "Hello",
Property3 = true,
Property4 = now,
FooSingle = new Foo() { Property1 = 51 },
Foos = new [] { new Foo() { Property1 = 1 }, new Foo() { Property1 = 2 } , new Foo() { Property1 = 3 } , new FooX() { Property1 = 4, Property2 = 11 } }
};
var mapper = CreateMapper(new ResolverMock(), builder =>
{
builder.CreateMap<Foo, Bar>()
.MapProperty(x => x.Property1, x => x.Property3);
builder.CreateMap<FooX, BarX>()
.MapProperty(x => x.Property2, x => x.Property4);
builder.CreateMap<FooAll, BarAll>()
.MapAll();
});
var barAll = mapper.Map<BarAll>(fooAll);
Assert.AreEqual(87, barAll.Property1);
Assert.AreEqual(now, barAll.Property4);
Assert.AreEqual(1, barAll.Foos[0].Property3);
Assert.AreEqual(51, barAll.FooSingle.Property3);
Assert.AreEqual(2, barAll.Foos[1].Property3);
Assert.AreEqual(3, barAll.Foos[2].Property3);
Assert.AreEqual(4, barAll.Foos[3].Property3);
Assert.AreEqual(11, ((BarX)barAll.Foos[3]).Property4);
}
private static void FooBarMappingFunction(Foo foo, Bar bar)
{
bar.Property3 = foo.Property1;
}
private static IObjectMapper CreateMapper(IDependencyResolver resolver, Action<ConfigurationBuilder> builder)
{
var mappingProvider = new MappingConfigurationProvider(builder);
var mapper = new ObjectMapper(mappingProvider, resolver);
return mapper;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Threading;
using Orleans.AzureUtils;
using Orleans.Runtime.Configuration;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Logging;
using Orleans.AzureUtils.Utilities;
using Orleans.Hosting.AzureCloudServices;
using Orleans.Hosting;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Wrapper class for an Orleans silo running in the current host process.
/// </summary>
public class AzureSilo
{
/// <summary>
/// Amount of time to pause before retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 5 seconds.
/// </summary>
public TimeSpan StartupRetryPause { get; set; }
/// <summary>
/// Number of times to retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 120 times.
/// </summary>
public int MaxRetries { get; set; }
/// <summary>
/// The name of the configuration key value for locating the DataConnectionString setting from the Azure configuration for this role.
/// Defaults to <c>DataConnectionString</c>
/// </summary>
public string DataConnectionConfigurationSettingName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansSiloEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansSiloEndpoint</c>
/// </summary>
public string SiloEndpointConfigurationKeyName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansProxyEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansProxyEndpoint</c>
/// </summary>
public string ProxyEndpointConfigurationKeyName { get; set; }
/// <summary>delegate to add some configuration to the client</summary>
public Action<ISiloHostBuilder> ConfigureSiloHostDelegate { get; set; }
private SiloHost host;
private OrleansSiloInstanceManager siloInstanceManager;
private SiloInstanceTableEntry myEntry;
private readonly ILogger logger;
private readonly IServiceRuntimeWrapper serviceRuntimeWrapper;
//TODO: hook this up with SiloBuilder when SiloBuilder supports create AzureSilo
private static ILoggerFactory DefaultLoggerFactory = CreateDefaultLoggerFactory("AzureSilo.log");
private readonly ILoggerFactory loggerFactory = DefaultLoggerFactory;
public AzureSilo()
:this(new ServiceRuntimeWrapper(DefaultLoggerFactory), DefaultLoggerFactory)
{
}
/// <summary>
/// Constructor
/// </summary>
public AzureSilo(ILoggerFactory loggerFactory)
: this(new ServiceRuntimeWrapper(loggerFactory), loggerFactory)
{
}
public static ILoggerFactory CreateDefaultLoggerFactory(string filePath)
{
var factory = new LoggerFactory();
factory.AddProvider(new FileLoggerProvider(filePath));
if (ConsoleText.IsConsoleAvailable)
factory.AddConsole();
return factory;
}
internal AzureSilo(IServiceRuntimeWrapper serviceRuntimeWrapper, ILoggerFactory loggerFactory)
{
this.serviceRuntimeWrapper = serviceRuntimeWrapper;
DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName;
SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName;
ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName;
StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
this.loggerFactory = loggerFactory;
logger = loggerFactory.CreateLogger<AzureSilo>();
}
/// <summary>
/// Async method to validate specific cluster configuration
/// </summary>
/// <param name="config"></param>
/// <returns>Task object of boolean type for this async method </returns>
public async Task<bool> ValidateConfiguration(ClusterConfiguration config)
{
if (config.Globals.LivenessType == GlobalConfiguration.LivenessProviderType.AzureTable)
{
string clusterId = config.Globals.ClusterId ?? serviceRuntimeWrapper.DeploymentId;
string connectionString = config.Globals.DataConnectionString ??
serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
var manager = siloInstanceManager ?? await OrleansSiloInstanceManager.GetManager(clusterId, connectionString, loggerFactory);
var instances = await manager.DumpSiloInstanceTable();
logger.Debug(instances);
}
catch (Exception exc)
{
var error = String.Format("Connecting to the storage table has failed with {0}", LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error((int)AzureSiloErrorCode.AzureTable_34, error, exc);
return false;
}
}
return true;
}
/// <summary>
/// Default cluster configuration
/// </summary>
/// <returns>Default ClusterConfiguration </returns>
public static ClusterConfiguration DefaultConfiguration()
{
return DefaultConfiguration(new ServiceRuntimeWrapper(DefaultLoggerFactory));
}
internal static ClusterConfiguration DefaultConfiguration(IServiceRuntimeWrapper serviceRuntimeWrapper)
{
var config = new ClusterConfiguration();
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
config.Globals.ClusterId = serviceRuntimeWrapper.DeploymentId;
try
{
config.Globals.DataConnectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName);
}
catch (Exception exc)
{
if (exc.GetType().Name.Contains("RoleEnvironmentException"))
{
config.Globals.DataConnectionString = null;
}
else
{
throw;
}
}
return config;
}
/// <summary>
/// Initialize this Orleans silo for execution. Config data will be read from silo config file as normal
/// </summary>
/// <param name="deploymentId">Azure ClusterId this silo is running under. If null, defaults to the value from the configuration.</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(string deploymentId = null, string connectionString = null)
{
return Start(null, deploymentId, connectionString);
}
/// <summary>
/// Initialize this Orleans silo for execution
/// </summary>
/// <param name="config">Use the specified config data.</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(ClusterConfiguration config, string connectionString = null)
{
if (config == null)
throw new ArgumentNullException(nameof(config));
return Start(config, null, connectionString);
}
/// <summary>
/// Initialize this Orleans silo for execution with the specified Azure clusterId
/// </summary>
/// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
/// <param name="clusterId">Azure ClusterId this silo is running under</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> if the silo startup was successful</returns>
internal bool Start(ClusterConfiguration config, string clusterId, string connectionString)
{
if (config != null && clusterId != null)
throw new ArgumentException("Cannot use config and clusterId on the same time");
// Program ident
Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);
// Read endpoint info for this instance from Azure config
string instanceName = serviceRuntimeWrapper.InstanceName;
// Configure this Orleans silo instance
if (config == null)
{
host = new SiloHost(instanceName);
host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
}
else
{
host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
}
IPEndPoint myEndpoint = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);
host.SetSiloType(Silo.SiloType.Secondary);
int generation = SiloAddress.AllocateNewGeneration();
// Bootstrap this Orleans silo instance
// If clusterId was not direclty provided, take the value in the config. If it is not
// in the config too, just take the ClusterId from Azure
if (clusterId == null)
clusterId = string.IsNullOrWhiteSpace(host.Config.Globals.ClusterId)
? serviceRuntimeWrapper.DeploymentId
: host.Config.Globals.ClusterId;
myEntry = new SiloInstanceTableEntry
{
DeploymentId = clusterId,
Address = myEndpoint.Address.ToString(),
Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = generation.ToString(CultureInfo.InvariantCulture),
HostName = host.Config.GetOrCreateNodeConfigurationForSilo(host.Name).DNSHostName,
ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),
RoleName = serviceRuntimeWrapper.RoleName,
SiloName = instanceName,
UpdateZone = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture),
FaultZone = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture),
StartTime = LogFormatter.PrintDate(DateTime.UtcNow),
PartitionKey = clusterId,
RowKey = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation
};
if (connectionString == null)
connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
siloInstanceManager = OrleansSiloInstanceManager.GetManager(
clusterId, connectionString, this.loggerFactory).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
}
catch (Exception exc)
{
var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error((int)AzureSiloErrorCode.AzureTable_34, error, exc);
throw new OrleansException(error, exc);
}
// Always use Azure table for membership when running silo in Azure
host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified ||
host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain)
{
host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
siloInstanceManager.RegisterSiloInstance(myEntry);
// Initialize this Orleans silo instance
host.SetDeploymentId(clusterId, connectionString);
host.SetSiloEndpoint(myEndpoint, generation);
host.SetProxyEndpoint(proxyEndpoint);
host.ConfigureSiloHostDelegate = ConfigureSiloHostDelegate;
host.InitializeOrleansSilo();
return StartSilo();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown.
/// </summary>
public void Run()
{
RunImpl();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
public void Run(CancellationToken cancellationToken)
{
RunImpl(cancellationToken);
}
/// <summary>
/// Stop this Orleans silo executing.
/// </summary>
public void Stop()
{
logger.Info(ErrorCode.Runtime_Error_100290, "Stopping {0}", this.GetType().FullName);
serviceRuntimeWrapper.UnsubscribeFromStoppingNotification(this, HandleAzureRoleStopping);
host.ShutdownOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100291, "Orleans silo '{0}' shutdown.", host.Name);
}
private bool StartSilo()
{
logger.Info(ErrorCode.Runtime_Error_100292, "Starting Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
bool ok = host.StartOrleansSilo();
if (ok)
logger.Info(ErrorCode.Runtime_Error_100293, "Successfully started Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
else
logger.Error(ErrorCode.Runtime_Error_100285, string.Format("Failed to start Orleans silo '{0}' as a {1} node.", host.Name, host.Type));
return ok;
}
private void HandleAzureRoleStopping(object sender, object e)
{
// Try to perform gracefull shutdown of Silo when we detect Azure role instance is being stopped
logger.Info(ErrorCode.SiloStopping, "HandleAzureRoleStopping - starting to shutdown silo");
host.ShutdownOrleansSilo();
}
/// <summary>
/// Run method helper.
/// </summary>
/// <remarks>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
/// <param name="cancellationToken">Optional cancellation token.</param>
private void RunImpl(CancellationToken? cancellationToken = null)
{
logger.Info(ErrorCode.Runtime_Error_100289, "OrleansAzureHost entry point called");
// Hook up to receive notification of Azure role stopping events
serviceRuntimeWrapper.SubscribeForStoppingNotification(this, HandleAzureRoleStopping);
if (host.IsStarted)
{
if (cancellationToken.HasValue)
host.WaitForOrleansSiloShutdown(cancellationToken.Value);
else
host.WaitForOrleansSiloShutdown();
}
else
throw new Exception("Silo failed to start correctly - aborting");
}
}
}
| |
// 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;
/// <summary>
///System.Array.IndexOf<T>(T[], T,System.Int32)
/// </summary>
public class ArrayIndexOf3
{
#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;
retVal = PosTest6() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Set the argument T as int type ");
try
{
int[] i1 = new int[5] { 3, 4, 6, 7, 8 };
if (Array.IndexOf<int>(i1, 6, 0) != 2)
{
TestLibrary.TestFramework.LogError("001", " The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Set the argument T as string type ");
try
{
string[] s1 = new string[5]{"Jack",
"Tom",
"mary",
"Joan",
"Michael"};
int result = Array.IndexOf<string>(s1, "Joan", 3);
if (result != 3)
{
TestLibrary.TestFramework.LogError("003", " The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Find out no expected value ");
try
{
string[] s1 = new string[5]{"Jack",
"Tom",
"mary",
"Joan",
"Michael"};
int result = Array.IndexOf<string>(s1, "Rabelais", 0);
if (result != -1)
{
TestLibrary.TestFramework.LogError("005", " The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Find out no expected value because of the startIndex ");
try
{
string[] s1 = new string[5]{"Bachham",
"Bachham",
"Bachham",
"Joan",
"Bachham"};
int result = Array.IndexOf<string>(s1, "Joan", 4);
if (result != -1)
{
TestLibrary.TestFramework.LogError("007", " The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Find out the fourth expected value ");
try
{
string[] s1 = new string[5]{"Bachham",
"Bachham",
"Bachham",
"Joan",
"Bachham"};
int result = Array.IndexOf<string>(s1, "Bachham", 4);
if (result != 4)
{
TestLibrary.TestFramework.LogError("009", " The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Find out the null element in an array of string ");
try
{
string[] s1 = new string[5]{"Bachham",
"Bachham",
null,
"Joan",
"Bachham"};
int result = Array.IndexOf<string>(s1, null, 0);
if (result != 2)
{
TestLibrary.TestFramework.LogError("011", " The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: Input a null reference array ");
try
{
string[] s1 = null;
int result = Array.IndexOf<string>(s1, "Tom", 0);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected ");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The startIndex is negative.");
try
{
int[] i1 = { 2, 3, 4, 4, 5 };
int result = Array.IndexOf<int>(i1, 4, -1);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: The startIndex is greater than the maxIndex of the array.");
try
{
int[] i1 = new int[5] { 2, 3, 4, 4, 5 };
int result = Array.IndexOf<int>(i1, 4, 6);
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ArrayIndexOf3 test = new ArrayIndexOf3();
TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf3");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.Research.Naiad;
using Microsoft.Research.Naiad.Dataflow.Channels;
using Microsoft.Research.Naiad.Serialization;
using Microsoft.Research.Naiad.Runtime.Controlling;
using Microsoft.Research.Naiad.DataStructures;
using Microsoft.Research.Naiad.Dataflow.StandardVertices;
using Microsoft.Research.Naiad.Dataflow;
namespace Microsoft.Research.Naiad.Frameworks.Reduction
{
public abstract class ReducerBase {
public abstract ReducerBase Add(ReducerBase other);
public static ReducerBase operator +(ReducerBase l, ReducerBase r) {
return l.Add(r);
}
}
public interface IAddable<T> {
T Add(T other);
}
public static class ExtensionMethods
{
public static Stream<TState, TTime> LocalReduce<TReducer, TState, TInput, TOutput, TTime>(this Stream<TInput, TTime> stream, Func<TReducer> factory, string name)
where TReducer : IReducer<TState, TInput, TOutput>
where TTime : Time<TTime>
{
return Foundry.NewUnaryStage(stream, (i, v) => new LocalReduceVertex<TReducer, TState, TInput, TOutput, TTime>(i, v, factory), null, null, name);
}
public static Stream<TOutput, TTime> LocalCombine<TReducer, TState, TInput, TOutput, TTime>(this Stream<TState, TTime> stream, Func<TReducer> factory, string name)
where TReducer : IReducer<TState, TInput, TOutput>
where TTime : Time<TTime>
{
return Foundry.NewUnaryStage(stream, (i, v) => new LocalCombineVertex<TReducer, TState, TInput, TOutput, TTime>(i, v, factory), null, null, name);
}
public static Stream<Pair<TKey, TState>, TTime> LocalReduce<TReducer, TState, TValue, TOutput, TKey, TInput, TTime>(
this Stream<TInput, TTime> stream, Func<TInput, TKey> key, Func<TInput, TValue> val, Func<TReducer> factory, string name,
Expression<Func<TInput, int>> inPlacement, Expression<Func<Pair<TKey, TState>, int>> outPlacement)
where TReducer : IReducer<TState, TValue, TOutput>
where TTime : Time<TTime>
{
return Foundry.NewUnaryStage(stream, (i, v) => new LocalKeyedReduceVertex<TReducer, TState, TValue, TOutput, TKey, TInput, TTime>(i, v, key, val, factory), inPlacement, outPlacement, name);
}
public static Stream<Pair<K, X>, T> LocalTimeReduce<A, X, R, S, K, I, T>(
this Stream<I, T> stream, Func<I, K> key, Func<I, R> val, Func<A> factory, string name,
Expression<Func<I, int>> inPlacement, Expression<Func<Pair<K, X>, int>> outPlacement)
where A : IReducer<X, R, S>
where T : Time<T>
{
return Foundry.NewUnaryStage(stream, (i, v) => new LocalTimeKeyedReduceVertex<A, X, R, S, K, I, T>(i, v, key, val, factory), inPlacement, outPlacement, name);
}
public static Stream<Pair<K, X>, T> LocalReduce<A, X, R, S, K, I, T>(
this Stream<I, T> stream, Func<I, K> key, Func<I, R> val, Func<A> factory, string name)
where A : IReducer<X, R, S>
where T : Time<T>
{
return LocalReduce<A, X, R, S, K, I, T>(stream, key, val, factory, name, null, null);
}
public static Stream<Pair<K, S>, T> LocalCombine<A, X, R, S, K, T>(
this Stream<Pair<K, X>, T> stream, Func<A> factory, string name,
Expression<Func<Pair<K, S>, int>> outPlacement)
where A : IReducer<X, R, S>
where T : Time<T>
{
Expression<Func<Pair<K, X>, int>> inPlacement = null;
if (outPlacement != null)
{
inPlacement = x => x.First.GetHashCode();
}
return Foundry.NewUnaryStage(stream, (i, v) => new LocalKeyedCombineVertex<A, X, R, S, K, T>(i, v, factory), inPlacement, outPlacement, name);
}
public static Stream<Pair<K, S>, T> LocalTimeCombine<A, X, R, S, K, T>(
this Stream<Pair<K, X>, T> stream, Func<A> factory, string name,
Expression<Func<Pair<K, S>, int>> outPlacement)
where A : IReducer<X, R, S>
where T : Time<T>
{
Expression<Func<Pair<K, X>, int>> inPlacement = null;
if (outPlacement != null)
{
inPlacement = x => x.First.GetHashCode();
}
return Foundry.NewUnaryStage(stream, (i, v) => new LocalTimeKeyedCombineVertex<A, X, R, S, K, T>(i, v, factory), inPlacement, outPlacement, name);
}
public static Stream<Pair<K, S>, T> LocalCombine<A, X, R, S, K, T>(
this Stream<Pair<K, X>, T> stream, Func<A> factory, string name)
where A : IReducer<X, R, S>
where T : Time<T>
{
return stream.LocalCombine<A, X, R, S, K, T>(factory, name, null);
}
public static Stream<Pair<K, S>, T> Reduce<A, X, R, S, K, I, T>(
this Stream<I, T> stream, Func<I, K> key, Func<I, R> val, Func<A> factory, string name)
where A : IReducer<X, R, S>
where T : Time<T>
{
return stream.
LocalReduce<A, X, R, S, K, I, T>(key, val, factory, name + "Reduce", null, null).
LocalCombine<A, X, R, S, K, T>(factory, name + "Combine", x => x.First.GetHashCode());
}
public static Stream<R, T> Broadcast<R, T>(this Stream<R, T> stream)
where R : Cloneable<R>
where T : Time<T>
{
var controller = stream.ForStage.InternalComputation.Controller;
int threadCount = stream.ForStage.InternalComputation.DefaultPlacement.Count / controller.Configuration.Processes;
if (threadCount * controller.Configuration.Processes != stream.ForStage.InternalComputation.DefaultPlacement.Count)
{
throw new Exception("Uneven thread count?");
}
var processDests = stream.ForStage.InternalComputation.DefaultPlacement.Where(x => x.ThreadId == 0).Select(x => x.VertexId).ToArray();
var boutput = Foundry.NewUnaryStage(stream, (i, v) => new BroadcastSendVertex<R, T>(i, v, processDests), null, null, "BroadcastProcessSend");
var collectable = boutput;
if (stream.ForStage.InternalComputation.DefaultPlacement.Where(x => x.ProcessId == controller.Configuration.ProcessID).Count() > 1)
{
var threadDests = stream.ForStage.InternalComputation.DefaultPlacement
.Where(x => x.ProcessId == controller.Configuration.ProcessID)
.Select(x => x.VertexId)
.ToArray();
collectable = Foundry.NewUnaryStage(boutput, (i, v) => new BroadcastForwardVertex<R, T>(i, v, threadDests), x => x.First, null, "BroadcastVertexSend");
}
// TODO : fix this to use a streaming expression
return collectable.UnaryExpression(null, xs => xs.Select(x => x.Second), "Select");
}
public static Stream<S, T> BroadcastReduce<A, X, R, S, T>(this Stream<R, T> stream, Func<A> factory, string name)
where A : IReducer<X, R, S>
where X : Cloneable<X>
where T : Time<T>
{
return stream.LocalReduce<A, X, R, S, T>(factory, name + "Reduce").Broadcast().LocalCombine<A, X, R, S, T>(factory, name + "Combine");
}
public static Stream<X, T> BroadcastReduce<A, X, T>(this Stream<X, T> stream, Func<A> factory, string name)
where A : IReducer<X, X, X>
where X : Cloneable<X>
where T : Time<T>
{
return stream.LocalReduce<A, X, X, X, T>(factory, name + "Reduce").Broadcast().LocalCombine<A, X, X, X, T>(factory, name + "Combine");
}
}
}
namespace Microsoft.Research.Naiad.Frameworks.Reduction
{
public interface IReducer<TState, TInput, TOutput>
{
// Accumulate an object of type R
void Add(TInput r);
// This should be called if it is the first Add/Combine
void InitialAdd(TInput r);
// Accumulate another reducer
void Combine(TState r);
// This should be called if it is the first Add/Combine
void InitialCombine(TState r);
// Return the current accumulated state. Undefined if no
// call to Initial{Add,Combine} has been made
TState State();
// Return final value after adding in all records. Undefined if no
// call to Initial{Add,Combine} has been made
TOutput Value();
}
// Placeholder type for generics that support reduction, used when
// reduction is not needed
public struct DummyReducer<X> : IReducer<X, X, X>
{
public void Add(X x)
{
throw new NotImplementedException();
}
public void InitialAdd(X x)
{
throw new NotImplementedException();
}
public void Combine(X x)
{
throw new NotImplementedException();
}
public void InitialCombine(X x)
{
throw new NotImplementedException();
}
public X State()
{
throw new NotImplementedException();
}
public X Value()
{
throw new NotImplementedException();
}
}
public class Aggregation<X, R, S> : IReducer<X, R, S>
{
public void InitialAdd(R other)
{
value = initialAdd(other);
}
public void Add(R other)
{
value = add(value, other);
}
public void InitialCombine(X other)
{
value = initialCombine(other);
}
public void Combine(X other)
{
value = combine(value, other);
}
public X State()
{
return value;
}
public S Value()
{
return finalize(value);
}
public Aggregation(Func<X, R, X> a, Func<R, X> ia, Func<X, X, X> c, Func<X, X> ic, Func<X, S> f)
{
add = a;
initialAdd = ia;
combine = c;
initialCombine = ic;
finalize = f;
}
public Aggregation(Func<X, R, X> a, Func<R, X> ia, Func<X, X, X> c, Func<X, S> f)
: this(a, ia, c, x => x, f)
{
}
private readonly Func<X, R, X> add;
private readonly Func<R, X> initialAdd;
private readonly Func<X, X, X> combine;
private readonly Func<X, X> initialCombine;
private readonly Func<X, S> finalize;
X value;
}
public class Aggregation<T> : Aggregation<T, T, T>
{
public Aggregation(Func<T, T, T> c)
: base(c, x => x, c, x => x)
{
}
}
public struct CountReducer<S> : IReducer<Int64, S, Int64>
{
public void InitialAdd(S s) { value = 1; }
public void Add(S t) { ++value; }
public void InitialCombine(Int64 other) { value = other; }
public void Combine(Int64 other) { value += other; }
public Int64 State() { return value; }
public Int64 Value() { return value; }
private Int64 value;
}
public struct IntSumReducer : IReducer<Int64, Int64, Int64>
{
public void InitialAdd(Int64 r) { value = r; }
public void Add(Int64 r) { value += r; }
public void InitialCombine(Int64 other) { value = other; }
public void Combine(Int64 other) { value += other; }
public Int64 State() { return value; }
public Int64 Value() { return value; }
private Int64 value;
}
public struct FloatSumReducer : IReducer<float, float, float>
{
public void InitialAdd(float r) { value = r; }
public void Add(float r) { value += r; }
public void InitialCombine(float other) { value = other; }
public void Combine(float other) { value += other; }
public float State() { return value; }
public float Value() { return value; }
private float value;
}
public struct DoubleSumReducer : IReducer<double, double, double>
{
public void InitialAdd(double r) { value = r; }
public void Add(double r) { value += r; }
public void InitialCombine(double other) { value = other; }
public void Combine(double other) { value += other; }
public double State() { return value; }
public double Value() { return value; }
private double value;
}
public struct GenericReducer<T> : IReducer<T, T, T> where T : IAddable<T> {
public void InitialAdd(T r) {
value = r;
}
public void Add(T r) {
value.Add(r);
}
public void InitialCombine(T other) {
value = other;
}
public void Combine(T other) {
value.Add(other);
}
public T State() {
return value;
}
public T Value() {
return value;
}
private T value;
}
public struct MinReducer<T> : IReducer<T, T, T> where T : IComparable<T>
{
public void InitialAdd(T r) { value = r; }
public void Add(T r) { value = r.CompareTo(value) < 0 ? r : value; }
public void InitialCombine(T other) { value = other; }
public void Combine(T other) { value = other.CompareTo(value) < 0 ? other : value; }
public T State() { return value; }
public T Value() { return value; }
private T value;
}
public struct MaxReducer<T> : IReducer<T, T, T> where T : IComparable<T>
{
public void InitialAdd(T r) { value = r; }
public void Add(T r) { value = r.CompareTo(value) > 0 ? r : value; }
public void InitialCombine(T other) { value = other; }
public void Combine(T other) { value = other.CompareTo(value) > 0 ? other : value; }
public T State() { return value; }
public T Value() { return value; }
private T value;
}
public class LocalReduceVertex<A, X, R, S, T> : UnaryVertex<R, X, T>
where A : IReducer<X, R, S>
where T : Time<T>
{
A reducer;
T lastTime;
bool valid;
public override void OnReceive(Message<R, T> message)
{
for (int i = 0; i < message.length; i++)
{
//this.OnRecv(message.payload[i].PairWith(message.time));
var record = message.payload[i];
if (!valid)
{
reducer.InitialAdd(record);
lastTime = message.time;
valid = true;
NotifyAt(message.time);
}
else
{
if (!message.time.Equals(lastTime))
{
throw new Exception("One time at a time please!");
}
reducer.Add(record);
}
}
}
public override void OnNotify(T time)
{
var output = this.Output.GetBufferForTime(time);
output.Send(reducer.State());
valid = false;
}
public LocalReduceVertex(int index, Stage<T> stage, Func<A> factory)
: base(index, stage)
{
valid = false;
reducer = factory();
}
}
public class LocalCombineVertex<A, X, R, S, T> : UnaryVertex<X, S, T>
where A : IReducer<X, R, S>
where T : Time<T>
{
A reducer;
T lastTime;
bool valid;
public override void OnReceive(Message<X, T> message)
{
for (int i = 0; i < message.length; i++)
{
//this.OnRecv(message.payload[i].PairWith(message.time));
var record = message.payload[i];
if (!valid)
{
reducer.InitialCombine(record);
lastTime = message.time;
valid = true;
NotifyAt(message.time);
}
else
{
if (!message.time.Equals(lastTime))
{
throw new Exception("One time at a time please!");
}
reducer.Combine(record);
}
}
}
public override void OnNotify(T time)
{
this.Output.GetBufferForTime(time).Send(reducer.Value());
valid = false;
}
public LocalCombineVertex(int index, Stage<T> stage, Func<A> factory)
: base(index, stage)
{
valid = false;
reducer = factory();
}
}
public class LocalKeyedReduceVertex<A, X, R, S, K, I, T> : UnaryVertex<I, Pair<K, X>, T>
where A : IReducer<X, R, S>
where T : Time<T>
{
private readonly Func<I, K> key;
private readonly Func<I, R> val;
private readonly Func<A> factory;
private Int64 recordsIn;
///private A[] reducers;
private SpinedList<A> reducers;
private int nextReducer;
private Dictionary<K, int> index;
private T lastTime;
public override void OnReceive(Message<I, T> message)
{
if (reducers == null)
{
//reducers = new A[4];
// Console.Error.WriteLine("Making a SpinedList in reducer");
reducers = new SpinedList<A>();
nextReducer = 0;
index = new Dictionary<K, int>(2000000);
lastTime = message.time;
recordsIn = 0;
NotifyAt(message.time);
}
else if (!message.time.Equals(lastTime))
{
throw new Exception("One time at a time please!");
}
for (int ii = 0; ii < message.length; ii++)
{
var record = message.payload[ii];
K k = key(record);
int i;
if (index.TryGetValue(k, out i))
{
A reducer = reducers[i];
reducer.Add(val(record));
reducers[i] = reducer;
}
else
{
var reducer = factory();
reducer.InitialAdd(val(record));
index.Add(k, reducers.Count);
reducers.Add(reducer);
++nextReducer;
}
++recordsIn;
}
}
public override void OnNotify(T time)
{
if (reducers != null)
{
// Console.Error.WriteLine("{0} OnNotify Reducers.count={1}", this.ToString(), reducers.Count);
if (!time.Equals(lastTime))
{
throw new Exception("One time at a time please!");
}
Context.Reporting.LogAggregate("RecordsIn", Dataflow.Reporting.AggregateType.Sum, recordsIn, time);
Context.Reporting.LogAggregate("RecordsOut", Dataflow.Reporting.AggregateType.Sum, index.Count, time);
var output = this.Output.GetBufferForTime(time);
foreach (var r in index)
output.Send(new Pair<K, X>(r.Key, reducers[r.Value].State()));
reducers = null;
index = null;
nextReducer = -1;
}
}
public LocalKeyedReduceVertex(
int i, Stage<T> stage, Func<I, K> k, Func<I, R> v, Func<A> f)
: base(i, stage)
{
factory = f;
key = k;
val = v;
lastTime = default(T);
reducers = null;
index = null;
nextReducer = -1;
}
}
public class LocalTimeKeyedReduceVertex<A, X, R, S, K, I, T> : UnaryVertex<I, Pair<K, X>, T>
where A : IReducer<X, R, S>
where T : Time<T>
{
private readonly Func<I, K> key;
private readonly Func<I, R> val;
private readonly Func<A> factory;
private readonly Dictionary<T, Time> reducers;
class Time
{
public A[] reducers;
public int nextReducer;
public Dictionary<K, int> index;
public Time(int c)
{
reducers = new A[c];
nextReducer = 0;
index = new Dictionary<K, int>();
}
}
public override void OnReceive(Message<I, T> message)
{
Time t;
if (!reducers.TryGetValue(message.time, out t))
{
t = new Time(4);
reducers.Add(message.time, t);
NotifyAt(message.time);
}
for (int ii = 0; ii < message.length; ii++)
{
//this.OnRecv(message.payload[i].PairWith(message.time));
var record = message.payload[ii];
K k = key(record);
int i;
if (t.index.TryGetValue(k, out i))
{
t.reducers[i].Add(val(record));
}
else
{
if (t.nextReducer == t.reducers.Length)
{
A[] n = new A[t.nextReducer * 2];
Array.Copy(t.reducers, n, t.nextReducer);
t.reducers = n;
}
t.reducers[t.nextReducer] = factory();
t.reducers[t.nextReducer].InitialAdd(val(record));
t.index.Add(k, t.nextReducer);
++t.nextReducer;
}
}
}
public override void OnNotify(T time)
{
Time rt = reducers[time];
var output = this.Output.GetBufferForTime(time);
foreach (var r in rt.index)
output.Send(new Pair<K, X>(r.Key, rt.reducers[r.Value].State()));
reducers.Remove(time);
}
public LocalTimeKeyedReduceVertex(
int i, Stage<T> stage, Func<I, K> k, Func<I, R> v, Func<A> f)
: base(i, stage)
{
factory = f;
key = k;
val = v;
reducers = new Dictionary<T, Time>();
}
}
public class LocalKeyedCombineVertex<A, X, R, S, K, T> : UnaryVertex<Pair<K, X>, Pair<K, S>, T>
where A : IReducer<X, R, S>
where T : Time<T>
{
private readonly Func<A> factory;
private A[] reducers;
private int nextReducer;
private Dictionary<K, int> index;
private T lastTime;
private Int64 recordsIn;
public override void OnReceive(Message<Pair<K, X>, T> message)
{
if (reducers == null)
{
reducers = new A[4];
nextReducer = 0;
index = new Dictionary<K, int>();
lastTime = message.time;
recordsIn = 0;
NotifyAt(message.time);
}
else if (!message.time.Equals(lastTime))
{
throw new Exception("One time at a time please!");
}
for (int ii = 0; ii < message.length; ii++)
{
//this.OnRecv(message.payload[i].PairWith(message.time));
var record = message.payload[ii];
K k = record.First;
int i;
if (index.TryGetValue(k, out i))
{
reducers[i].Combine(record.Second);
}
else
{
if (nextReducer == reducers.Length)
{
A[] n = new A[nextReducer * 2];
Array.Copy(reducers, n, nextReducer);
reducers = n;
}
reducers[nextReducer] = factory();
reducers[nextReducer].InitialCombine(record.Second);
index.Add(k, nextReducer);
++nextReducer;
}
++recordsIn;
}
}
public override void OnNotify(T time)
{
if (reducers != null)
{
if (!time.Equals(lastTime))
{
throw new Exception("One time at a time please!");
}
Context.Reporting.LogAggregate("RecordsIn", Dataflow.Reporting.AggregateType.Sum, recordsIn, time);
Context.Reporting.LogAggregate("RecordsOut", Dataflow.Reporting.AggregateType.Sum, index.Count, time);
var output = this.Output.GetBufferForTime(time);
foreach (var r in index)
output.Send(new Pair<K, S>(r.Key, reducers[r.Value].Value()));
reducers = null;
index = null;
nextReducer = -1;
}
}
public LocalKeyedCombineVertex(
int i, Stage<T> stage, Func<A> f)
: base(i, stage)
{
factory = f;
lastTime = default(T);
reducers = null;
index = null;
nextReducer = -1;
}
}
public class LocalTimeKeyedCombineVertex<A, X, R, S, K, T> : UnaryVertex<Pair<K, X>, Pair<K, S>, T>
where A : IReducer<X, R, S>
where T : Time<T>
{
private readonly Func<A> factory;
private readonly Dictionary<T, Time> reducers;
class Time
{
public A[] reducers;
public int nextReducer;
public Dictionary<K, int> index;
public Time(int c)
{
reducers = new A[c];
nextReducer = 0;
index = new Dictionary<K, int>();
}
}
public override void OnReceive(Message<Pair<K, X>, T> message)
{
Time r;
if (!reducers.TryGetValue(message.time, out r))
{
r = new Time(4);
reducers.Add(message.time, r);
NotifyAt(message.time);
}
for (int ii = 0; ii < message.length; ii++)
{
//this.OnRecv(message.payload[i].PairWith(message.time));
var record = message.payload[ii];
K k = record.First;
int i;
if (r.index.TryGetValue(k, out i))
{
r.reducers[i].Combine(record.Second);
}
else
{
if (r.nextReducer == r.reducers.Length)
{
A[] n = new A[r.nextReducer * 2];
Array.Copy(r.reducers, n, r.nextReducer);
r.reducers = n;
}
r.reducers[r.nextReducer] = factory();
r.reducers[r.nextReducer].InitialCombine(record.Second);
r.index.Add(k, r.nextReducer);
++r.nextReducer;
}
}
}
public override void OnNotify(T time)
{
Time rt = reducers[time];
var output = this.Output.GetBufferForTime(time);
foreach (var r in rt.index)
output.Send(new Pair<K, S>(r.Key, rt.reducers[r.Value].Value()));
reducers.Remove(time);
}
public LocalTimeKeyedCombineVertex(
int i, Stage<T> stage, Func<A> f)
: base(i, stage)
{
factory = f;
reducers = new Dictionary<T, Time>();
}
}
public interface Cloneable<T>
{
// Return a copy suitable for broadcasting. Can be a shallow copy if the object
// is known to be immutable
T MakeCopy();
}
public class BroadcastSendVertex<R, T> : UnaryVertex<R, Pair<int, R>, T>
where R : Cloneable<R>
where T : Time<T>
{
private readonly int[] destinations;
public override void OnReceive(Message<R, T> message)
{
var output = this.Output.GetBufferForTime(message.time);
for (int i = 0; i < message.length; i++)
{
//this.OnRecv(message.payload[i].PairWith(message.time));
var record = message.payload[i];
for (int j = 0; j < destinations.Length; ++i)
{
if (j < destinations.Length - 1)
{
output.Send(new Pair<int, R>(destinations[j], record.MakeCopy()));
}
else
{
output.Send(new Pair<int, R>(destinations[j], record));
}
}
}
}
public override void OnNotify(T time) { }
public BroadcastSendVertex(int index, Stage<T> stage, int[] dest)
: base(index, stage)
{
destinations = dest;
}
}
public class BroadcastForwardVertex<R, T> : UnaryVertex<Pair<int, R>, Pair<int, R>, T>
where R : Cloneable<R>
where T : Time<T>
{
private readonly int[] destinations;
public override void OnReceive(Message<Pair<int, R>, T> message)
{
var output = this.Output.GetBufferForTime(message.time);
for (int i = 0; i < message.length; i++)
{
var record = message.payload[i];
for (int j = 0; j < destinations.Length; ++j)
{
if (j < destinations.Length - 1)
{
output.Send(new Pair<int, R>(destinations[j], record.Second.MakeCopy()));
}
else
{
output.Send(new Pair<int, R>(destinations[j], record.Second));
}
}
}
}
public override void OnNotify(T time) { }
public BroadcastForwardVertex(int index, Stage<T> stage, int[] dest)
: base(index, stage)
{
destinations = dest;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsPaging
{
using Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Long-running Operation for AutoRest
/// </summary>
public partial class AutoRestPagingTestService : ServiceClient<AutoRestPagingTestService>, IAutoRestPagingTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IPagingOperations.
/// </summary>
public virtual IPagingOperations Paging { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestPagingTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestPagingTestService(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestPagingTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestPagingTestService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestPagingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestPagingTestService(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestPagingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestPagingTestService(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestPagingTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestPagingTestService(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestPagingTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestPagingTestService(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestPagingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestPagingTestService(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestPagingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestPagingTestService(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Paging = new PagingOperations(this);
BaseUri = new System.Uri("http://localhost");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
using System;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using ShopifySharp.Filters;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ShopifySharp.Infrastructure;
using ShopifySharp.Lists;
namespace ShopifySharp
{
/// <summary>
/// A service for manipulating Shopify metafields.
/// </summary>
public class MetaFieldService : ShopifyService
{
/// <summary>
/// Creates a new instance of <see cref="MetaFieldService" />.
/// </summary>
/// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
/// <param name="shopAccessToken">An API access token for the shop.</param>
public MetaFieldService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { }
private async Task<int> _CountAsync(string path, CancellationToken cancellationToken)
{
return await ExecuteGetAsync<int>(path, "count", cancellationToken: cancellationToken);
}
/// <summary>
/// Gets a count of the metafields on the shop itself.
/// </summary>
/// <remarks>
/// According to Shopify's documentation, this endpoint does not currently support any additional filter parameters for counting.
/// </remarks>
public virtual async Task<int> CountAsync(CancellationToken cancellationToken = default)
{
return await _CountAsync("metafields/count.json", cancellationToken);
}
/// <summary>
/// Gets a count of the metafields for the given entity type and filter options.
/// </summary>
/// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param>
/// <param name="resourceId">The Id for the resource type.</param>
/// <param name="cancellationToken">Cancellation Token</param>
/// <remarks>
/// According to Shopify's documentation, this endpoint does not currently support any additional filter parameters for counting.
/// </remarks>
public virtual async Task<int> CountAsync(long resourceId, string resourceType, CancellationToken cancellationToken = default)
{
return await _CountAsync($"{resourceType}/{resourceId}/metafields/count.json", cancellationToken);
}
/// <summary>
/// Gets a count of the metafields for the given entity type and filter options.
/// </summary>
/// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param>
/// <param name="resourceId">The Id for the resource type.</param>
/// <param name="parentResourceType">The type of shopify parent resource to obtain metafields for. This could be blogs, products.</param>
/// <param name="parentResourceId">The Id for the resource type.</param>
/// <param name="cancellationToken">Cancellation Token</param>
/// <remarks>
/// According to Shopify's documentation, this endpoint does not currently support any additional filter parameters for counting.
/// </remarks>
public virtual async Task<int> CountAsync(long resourceId, string resourceType, long parentResourceId, string parentResourceType, CancellationToken cancellationToken = default)
{
return await _CountAsync($"{parentResourceType}/{parentResourceId}/{resourceType}/{resourceId}/metafields/count.json", cancellationToken);
}
private async Task<ListResult<MetaField>> _ListAsync(string path, ListFilter<MetaField> filter,
CancellationToken cancellationToken)
{
return await ExecuteGetListAsync(path, "metafields", filter, cancellationToken);
}
/// <summary>
/// Gets a list of the metafields for the shop itself.
/// </summary>
/// <param name="filter">Options to filter the results.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<ListResult<MetaField>> ListAsync(ListFilter<MetaField> filter, CancellationToken cancellationToken = default)
{
return await _ListAsync("metafields.json", filter, cancellationToken);
}
/// <summary>
/// Gets a list of the metafields for the given entity type and filter options.
/// </summary>
/// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param>
/// <param name="resourceId">The Id for the resource type.</param>
/// <param name="filter">Options to filter the results.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<ListResult<MetaField>> ListAsync(long resourceId, string resourceType, ListFilter<MetaField> filter, CancellationToken cancellationToken = default)
{
return await _ListAsync($"{resourceType}/{resourceId}/metafields.json", filter, cancellationToken);
}
/// <summary>
/// Gets a list of the metafields for the given entity type and filter options.
/// </summary>
/// <param name="parentResourceType">The type of shopify parentresource to obtain metafields for. This could be blogs, products.</param>
/// <param name="parentResourceId">The Id for the parent resource type.</param>
/// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param>
/// <param name="resourceId">The Id for the resource type.</param>
/// <param name="filter">Options to filter the results.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<ListResult<MetaField>> ListAsync(long resourceId, string resourceType, long parentResourceId, string parentResourceType, ListFilter<MetaField> filter, CancellationToken cancellationToken = default)
{
return await _ListAsync($"{parentResourceType}/{parentResourceId}/{resourceType}/{resourceId}/metafields.json", filter, cancellationToken);
}
/// <summary>
/// Gets a list of the metafields for the shop itself.
/// </summary>
/// <param name="filter">Options to filter the results.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<ListResult<MetaField>> ListAsync(MetaFieldFilter filter = null, CancellationToken cancellationToken = default)
{
return await _ListAsync("metafields.json", filter, cancellationToken);
}
/// <summary>
/// Gets a list of the metafields for the given entity type and filter options.
/// </summary>
/// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param>
/// <param name="resourceId">The Id for the resource type.</param>
/// <param name="filter">Options to filter the results.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<ListResult<MetaField>> ListAsync(long resourceId, string resourceType, MetaFieldFilter filter = null, CancellationToken cancellationToken = default)
{
return await _ListAsync($"{resourceType}/{resourceId}/metafields.json", filter, cancellationToken);
}
/// <summary>
/// Gets a list of the metafields for the given entity type and filter options.
/// </summary>
/// <param name="parentResourceType">The type of shopify parentresource to obtain metafields for. This could be blogs, products.</param>
/// <param name="parentResourceId">The Id for the parent resource type.</param>
/// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param>
/// <param name="resourceId">The Id for the resource type.</param>
/// <param name="filter">Options to filter the results.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<ListResult<MetaField>> ListAsync(long resourceId, string resourceType, long parentResourceId, string parentResourceType, MetaFieldFilter filter = null, CancellationToken cancellationToken = default)
{
return await _ListAsync($"{parentResourceType}/{parentResourceId}/{resourceType}/{resourceId}/metafields.json", filter, cancellationToken);
}
/// <summary>
/// Retrieves the metafield with the given id.
/// </summary>
/// <param name="metafieldId">The id of the metafield to retrieve.</param>
/// <param name="fields">A comma-separated list of fields to return.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<MetaField> GetAsync(long metafieldId, string fields = null, CancellationToken cancellationToken = default)
{
return await ExecuteGetAsync<MetaField>($"metafields/{metafieldId}.json", "metafield", fields, cancellationToken);
}
/// <summary>
/// Creates a new metafield on the shop itself.
/// </summary>
/// <param name="metafield">A new metafield. Id should be set to null.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<MetaField> CreateAsync(MetaField metafield, CancellationToken cancellationToken = default)
{
var req = PrepareRequest("metafields.json");
var content = new JsonContent(new
{
metafield = metafield
});
var response = await ExecuteRequestAsync<MetaField>(req, HttpMethod.Post, cancellationToken, content, "metafield");
return response.Result;
}
/// <summary>
/// Creates a new metafield on the given entity.
/// </summary>
/// <param name="metafield">A new metafield. Id should be set to null.</param>
/// <param name="resourceId">The Id of the resource the metafield will be associated with. This can be variants, products, orders, customers, custom_collections, etc.</param>
/// <param name="resourceType">The resource type the metaifeld will be associated with. This can be variants, products, orders, customers, custom_collections, etc.</param>
/// <param name="parentResourceId">The Id of the parent resource the metafield will be associated with. This can be blogs, products.</param>
/// <param name="parentResourceType">The resource type the metaifeld will be associated with. This can be articles, variants.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<MetaField> CreateAsync(MetaField metafield, long resourceId, string resourceType, long parentResourceId, string parentResourceType, CancellationToken cancellationToken = default)
{
var req = PrepareRequest($"{parentResourceType}/{parentResourceId}/{resourceType}/{resourceId}/metafields.json");
var content = new JsonContent(new
{
metafield = metafield
});
var response = await ExecuteRequestAsync<MetaField>(req, HttpMethod.Post, cancellationToken, content, "metafield");
return response.Result;
}
/// <summary>
/// Creates a new metafield on the given entity.
/// </summary>
/// <param name="metafield">A new metafield. Id should be set to null.</param>
/// <param name="resourceId">The Id of the resource the metafield will be associated with. This can be variants, products, orders, customers, custom_collections, etc.</param>
/// <param name="resourceType">The resource type the metaifeld will be associated with. This can be variants, products, orders, customers, custom_collections, etc.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<MetaField> CreateAsync(MetaField metafield, long resourceId, string resourceType, CancellationToken cancellationToken = default)
{
var req = PrepareRequest($"{resourceType}/{resourceId}/metafields.json");
var content = new JsonContent(new
{
metafield = metafield
});
var response = await ExecuteRequestAsync<MetaField>(req, HttpMethod.Post, cancellationToken, content, "metafield");
return response.Result;
}
/// <summary>
/// Updates the given metafield.
/// </summary>
/// <param name="metafieldId">Id of the object being updated.</param>
/// <param name="metafield">The metafield to update.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<MetaField> UpdateAsync(long metafieldId, MetaField metafield, CancellationToken cancellationToken = default)
{
var req = PrepareRequest($"metafields/{metafieldId}.json");
var content = new JsonContent(new
{
metafield = metafield
});
var response = await ExecuteRequestAsync<MetaField>(req, HttpMethod.Put, cancellationToken, content, "metafield");
return response.Result;
}
/// <summary>
/// Deletes a metafield with the given Id.
/// </summary>
/// <param name="metafieldId">The metafield object's Id.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task DeleteAsync(long metafieldId, CancellationToken cancellationToken = default)
{
var req = PrepareRequest($"metafields/{metafieldId}.json");
await ExecuteRequestAsync(req, HttpMethod.Delete, cancellationToken);
}
}
}
| |
//-----------------------------------------------------------------------
// This file is part of Microsoft Robotics Developer Studio Code Samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// $File: SickLRF.cs $ $Revision: 1 $
//-----------------------------------------------------------------------
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Ccr.Core;
using Microsoft.Dss.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.Services.Serializer;
using Microsoft.Dss.ServiceModel.Dssp;
using submgr = Microsoft.Dss.Services.SubscriptionManager;
using Microsoft.Dss.ServiceModel.DsspServiceBase;
using Microsoft.Dss.Core.DsspHttp;
using Microsoft.Dss.Core.DsspHttpUtilities;
using System.Net;
using System.Net.Mime;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.ComponentModel;
using W3C.Soap;
using TrackRoamer.Robotics.Utility.LibSystem;
namespace TrackRoamer.Robotics.Services.TrackRoamerUsrf
{
/// <summary>
/// TrackRoamer Ultrasound Range Finder service.
/// </summary>
[Contract(Contract.Identifier)]
[DisplayName("TrackRoamer Ultrasound Range Finder")]
[Description("Provides access to a TrackRoamer Ultrasound Range Finder.")]
[DssServiceDescription("http://msdn.microsoft.com/library/cc998493.aspx")]
public class SickLRFService : DsspServiceBase
{
CommLink _link;
LRFCommLinkPort _internalPort = new LRFCommLinkPort();
[ServicePort("/sicklrf")]
SickLRFOperations _mainPort = new SickLRFOperations();
[ServiceState(StateTransform = "TrackRoamer.Robotics.Services.TrackRoamerUsrf.SickLRF.xslt")]
[InitialStatePartner(Optional = true, ServiceUri = ServicePaths.Store + "/SickLRF.config.xml")]
State _state = new State();
// This is no longer used - Use base.StateTransformPath instead (see above)
[EmbeddedResource("TrackRoamer.Robotics.Services.TrackRoamerUsrf.SickLRF.xslt")]
string _transform = null;
[Partner("SubMgr", Contract = submgr.Contract.Identifier, CreationPolicy = PartnerCreationPolicy.CreateAlways)]
submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort();
DsspHttpUtilitiesPort _httpUtilities;
DispatcherQueue _queue = null;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="creationPort">Passed to the base class for construction.</param>
public SickLRFService(DsspServiceCreationPort creationPort) :
base(creationPort)
{
Tracer.Trace("SickLRF::SickLRFService()");
}
/// <summary>
/// Send phase of construction.
/// </summary>
protected override void Start()
{
if (_state == null)
{
_state = new State();
}
Tracer.Trace("SickLRF::Start()");
LogInfo("Start");
_httpUtilities = DsspHttpUtilitiesService.Create(Environment);
//
// Kick off the connection to the Laser Range Finder device.
//
SpawnIterator(0, _state.ComPort, StartLRF);
// This service does not use base.Start() because of the way that
// the handlers are hooked up. Also, because of this, there are
// explicit Get and HttpGet handlers instead of using the default ones.
// Handlers that need write or Exclusive access to state go under
// the Exclusive group. Handlers that need read or shared access, and can be
// Concurrent to other readers, go to the Concurrent group.
// Other internal ports can be included in interleave so you can coordinate
// intermediate computation with top level handlers.
Activate(
Arbiter.Interleave(
new TeardownReceiverGroup(
Arbiter.Receive<DsspDefaultDrop>(false, _mainPort, DropHandler)
),
new ExclusiveReceiverGroup(
Arbiter.Receive<Replace>(true, _mainPort, ReplaceHandler),
Arbiter.Receive<LinkMeasurement>(true, _internalPort, MeasurementHandler),
Arbiter.ReceiveWithIterator<LinkPowerOn>(true, _internalPort, PowerOn),
Arbiter.ReceiveWithIterator<Exception>(true, _internalPort, ExceptionHandler)),
new ConcurrentReceiverGroup(
Arbiter.Receive<DsspDefaultLookup>(true, _mainPort, DefaultLookupHandler),
Arbiter.ReceiveWithIterator<Subscribe>(true, _mainPort, SubscribeHandler),
Arbiter.ReceiveWithIterator<ReliableSubscribe>(true, _mainPort, ReliableSubscribeHandler),
Arbiter.Receive<Get>(true, _mainPort, GetHandler),
Arbiter.Receive<HttpGet>(true, _mainPort, HttpGetHandler),
Arbiter.Receive<Reset>(true, _mainPort, ResetHandler))
)
);
DirectoryInsert();
}
#region Initialization
/// <summary>
/// Start conversation with the SickLRF device.
/// </summary>
IEnumerator<ITask> StartLRF(int timeout, int comPort)
{
Tracer.Trace("SickLRF::StartLRF() comPort=" + comPort);
if (timeout > 0)
{
//
// caller asked us to wait <timeout> milliseconds until we start.
//
yield return Arbiter.Receive(false, TimeoutPort(timeout),
delegate(DateTime dt)
{
LogInfo("Done Waiting");
}
);
}
if (_queue == null)
{
//
// The internal services run on their own dispatcher, we need to create that (once)
//
AllocateExecutionResource allocExecRes = new AllocateExecutionResource(0, "SickLRF");
ResourceManagerPort.Post(allocExecRes);
yield return Arbiter.Choice(
allocExecRes.Result,
delegate(ExecutionAllocationResult result)
{
_queue = result.TaskQueue;
},
delegate(Exception e)
{
LogError(e);
}
);
}
string comName;
if (comPort <= 0)
{
//
// We default to COM4, because
// a) that was our previous behavior and
// b) the hardware that we have uses COM4
//
comName = "COM4";
}
else
{
comName = "COM" + comPort;
}
_link = new CommLink(_queue ?? TaskQueue, comName, _internalPort);
_link.Parent = ServiceInfo.Service;
_link.Console = ConsoleOutputPort;
FlushPortSet(_internalPort);
yield return(
Arbiter.Choice(
_link.Open(),
delegate(SuccessResult success)
{
LogInfo("Opened link to LRF");
},
delegate(Exception exception)
{
LogError(exception);
}
)
);
}
private void FlushPortSet(IPortSet portSet)
{
Tracer.Trace("SickLRF::FlushPortSet()");
foreach (IPortReceive port in portSet.Ports)
{
while (port.Test() != null) ;
}
}
IEnumerator<ITask> PowerOn(LinkPowerOn powerOn)
{
bool failed = false;
Tracer.Trace("SickLRF::PowerOn()");
_state.Description = powerOn.Description;
_state.LinkState = "Power On: " + powerOn.Description;
LogInfo(_state.LinkState);
//
// the device has powered on. Set the BaudRate to the highest supported.
//
yield return Arbiter.Choice(
_link.SetDataRate(9600),
delegate(SuccessResult success)
{
_state.LinkState = "Baud Rate set to " + 9600;
LogInfo(_state.LinkState);
},
delegate(Exception failure)
{
_internalPort.Post(failure);
failed = true;
}
);
if (failed)
{
yield break;
}
Tracer.Trace("SickLRF::Opening the port");
/*
//
// wait for confirm to indicate that the LRF has received the new baud rate and is
// expecting the serial rate to change imminently.
//
yield return Arbiter.Choice(
Arbiter.Receive<LinkConfirm>(false,_internalPort,
delegate(LinkConfirm confirm)
{
// the confirm indicates that the LRF has recieved the new baud rate
}),
Arbiter.Receive<DateTime>(false, TimeoutPort(1000),
delegate(DateTime time)
{
_internalPort.Post(new TimeoutException("Timeout waiting for Confirm while setting data rate"));
failed = true;
})
);
if (failed)
{
yield break;
}
//
// Set the serial rate to the rate requested above.
//
yield return Arbiter.Choice(
_link.SetRate(),
delegate(SuccessResult success)
{
_state.LinkState = "Changed Rate to: " + _link.BaudRate;
LogInfo(_state.LinkState);
},
delegate(Exception failure)
{
_internalPort.Post(failure);
failed = true;
}
);
if (failed)
{
yield break;
}
//
// start continuous measurements.
//
yield return Arbiter.Choice(
_link.SetContinuous(),
delegate(SuccessResult success)
{
_state.LinkState = "Starting Continuous Measurement";
LogInfo(_state.LinkState);
},
delegate(Exception failure)
{
_internalPort.Post(failure);
failed = true;
}
);
if (failed)
{
yield break;
}
//
// wait for confirm message that signals that the LRF is now in continuous measurement mode.
//
yield return Arbiter.Choice(
Arbiter.Receive<LinkConfirm>(false, _internalPort,
delegate(LinkConfirm confirm)
{
// received Confirm
}),
Arbiter.Receive<DateTime>(false, TimeoutPort(1000),
delegate(DateTime time)
{
_internalPort.Post(new TimeoutException("Timeout waiting for Confirm after setting continuous measurement mode"));
})
);
yield break;
* */
}
#endregion
#region Laser Range Finder events
/// <summary>
/// Handle new measurement data from the LRF.
/// </summary>
/// <param name="measurement">Measurement Data</param>
void MeasurementHandler(LinkMeasurement measurement)
{
//Tracer.Trace("SickLRF::MeasurementHandler()");
try
{
//
// The SickLRF typically reports on either a 180 degrees or 100 degrees
// field of vision. From the number of readings we can calculate the
// Angular Range and Resolution.
//
switch (measurement.Ranges.Length)
{
case 181:
// we always get here:
_state.AngularRange = 180;
_state.AngularResolution = 1;
break;
case 361:
_state.AngularRange = 180;
_state.AngularResolution = 0.5;
break;
case 101:
_state.AngularRange = 100;
_state.AngularResolution = 1;
break;
case 201:
_state.AngularRange = 100;
_state.AngularResolution = 0.5;
break;
case 401:
_state.AngularRange = 100;
_state.AngularResolution = 0.25;
break;
default:
break;
}
_state.DistanceMeasurements = measurement.Ranges;
_state.Units = measurement.Units;
_state.TimeStamp = measurement.TimeStamp;
_state.LinkState = "Measurement received";
//
// Inform subscribed services that the state has changed.
//
_subMgrPort.Post(new submgr.Submit(_state, DsspActions.ReplaceRequest));
}
catch (Exception e)
{
LogError(e);
}
}
IEnumerator<ITask> ExceptionHandler(Exception exception)
{
Tracer.Trace("SickLRF::ExceptionHandler() exception=" + exception);
LogError(exception);
BadPacketException bpe = exception as BadPacketException;
if (bpe != null && bpe.Count < 2)
{
yield break;
}
_subMgrPort.Post(new submgr.Submit(new ResetType(), DsspActions.SubmitRequest));
LogInfo("Closing link to LRF");
yield return
Arbiter.Choice(
_link.Close(),
delegate(SuccessResult success)
{
},
delegate(Exception except)
{
LogError(except);
}
);
_state.LinkState = "LRF Link closed, waiting 5 seconds";
LogInfo(_state.LinkState);
_link = null;
SpawnIterator(5000, _state.ComPort, StartLRF);
yield break;
}
#endregion
#region DSSP operation handlers
void GetHandler(Get get)
{
Tracer.Trace("SickLRF::GetHandler()");
get.ResponsePort.Post(_state);
}
void ReplaceHandler(Replace replace)
{
Tracer.Trace("SickLRF::ReplaceHandler()");
_state = replace.Body;
replace.ResponsePort.Post(DefaultReplaceResponseType.Instance);
}
IEnumerator<ITask> SubscribeHandler(Subscribe subscribe)
{
Tracer.Trace("SickLRF::SubscribeHandler()");
yield return Arbiter.Choice(
SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
delegate(SuccessResult success)
{
if (_state != null &&
_state.DistanceMeasurements != null)
{
_subMgrPort.Post(new submgr.Submit(
subscribe.Body.Subscriber, DsspActions.ReplaceRequest, _state, null));
}
},
null
);
}
IEnumerator<ITask> ReliableSubscribeHandler(ReliableSubscribe subscribe)
{
Tracer.Trace("SickLRF::ReliableSubscribeHandler()");
yield return Arbiter.Choice(
SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
delegate(SuccessResult success)
{
if (_state != null &&
_state.DistanceMeasurements != null)
{
_subMgrPort.Post(new submgr.Submit(
subscribe.Body.Subscriber, DsspActions.ReplaceRequest, _state, null));
}
},
null
);
}
void DropHandler(DsspDefaultDrop drop)
{
Tracer.Trace("SickLRF::DropHandler()");
try
{
if (_link != null)
{
// release dispatcher queue resource
ResourceManagerPort.Post(new FreeExecutionResource(_link.TaskQueue));
_link.Close();
_link = null;
}
}
finally
{
base.DefaultDropHandler(drop);
}
}
void ResetHandler(Reset reset)
{
Tracer.Trace("SickLRF::ResetHandler()");
_internalPort.Post(new Exception("External Reset Requested"));
reset.ResponsePort.Post(DefaultSubmitResponseType.Instance);
}
#endregion
#region HttpGet Handlers
static readonly string _root = "/sicklrf";
static readonly string _cylinder = "/sicklrf/cylinder";
static readonly string _top = "/sicklrf/top";
static readonly string _topw = "/sicklrf/top/";
void HttpGetHandler(HttpGet httpGet)
{
HttpListenerRequest request = httpGet.Body.Context.Request;
HttpListenerResponse response = httpGet.Body.Context.Response;
Stream image = null;
string path = request.Url.AbsolutePath;
if (path == _cylinder)
{
image = GenerateCylinder();
}
else if (path == _top)
{
image = GenerateTop(400);
}
else if (path.StartsWith(_topw))
{
int width;
string remain = path.Substring(_topw.Length);
if (int.TryParse(remain, out width))
{
image = GenerateTop(width);
}
}
else if (path == _root)
{
HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK,
_state,
//base.StateTransformPath,
_transform);
httpGet.ResponsePort.Post(rsp);
}
if (image != null)
{
SendJpeg(httpGet.Body.Context, image);
}
else
{
httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason(
W3C.Soap.FaultCodes.Receiver,
DsspFaultCodes.OperationFailed,
"Unable to generate Image"));
}
}
private void SendJpeg(HttpListenerContext context, Stream stream)
{
WriteResponseFromStream write = new WriteResponseFromStream(context, stream, MediaTypeNames.Image.Jpeg);
_httpUtilities.Post(write);
Activate(
Arbiter.Choice(
write.ResultPort,
delegate(Stream res)
{
stream.Close();
},
delegate(Exception e)
{
stream.Close();
LogError(e);
}
)
);
}
#endregion
#region Image generators
private Stream GenerateCylinder()
{
if (_state.DistanceMeasurements == null)
{
return null;
}
MemoryStream memory = null;
int scalefactor = 2;
int bmpWidth = _state.DistanceMeasurements.Length * scalefactor;
int nearRange = 300;
int farRange = 2000;
int bmpHeight = 100;
int topTextHeight = 17; // leave top for the text
Font font = new Font(FontFamily.GenericSansSerif, 10, GraphicsUnit.Pixel);
using (Bitmap bmp = new Bitmap(bmpWidth, bmpHeight))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
int half = (int)Math.Round(bmp.Height * 0.65d);
int middle = _state.DistanceMeasurements.Length / 2;
int rangeMax = 0;
int pointMax = -1;
Dictionary<int, string> labels = new Dictionary<int, string>();
for (int i = 0; i < _state.DistanceMeasurements.Length; i++)
{
int range = _state.DistanceMeasurements[i];
int x = i * scalefactor;
if (i == middle)
{
g.DrawLine(Pens.Gray, x, topTextHeight, x, bmpHeight);
}
if (range > 0 && range < 8192)
{
if (range > rangeMax)
{
rangeMax = range;
pointMax = x;
}
int h = bmp.Height * 300 / range;
if (h < 0)
{
h = 0;
}
Color col = LinearColor(Color.OrangeRed, Color.LightGreen, nearRange, farRange, range);
//Color col = LinearColor(Color.DarkBlue, Color.LightGray, 0, 8192, range);
g.DrawLine(new Pen(col, (float)scalefactor), bmp.Width - x, Math.Max(topTextHeight, half - h), bmp.Width - x, Math.Min(bmpHeight, half + h));
if (i > 0 && i % 20 == 0 && i < _state.DistanceMeasurements.Length - 10)
{
double roundRange = Math.Round(range / 1000.0d, 1); // meters
string str = "" + roundRange;
labels.Add(x, str);
}
}
}
foreach(int x in labels.Keys)
{
string str = labels[x];
g.DrawString(str, font, Brushes.Black, bmp.Width - x - 8, (int)(bmpHeight - topTextHeight * 2 + Math.Abs((double)middle - x/scalefactor) * 20 / middle));
}
if (pointMax > 0)
{
double roundRangeMax = Math.Round(rangeMax/1000.0d, 1); // meters
int shift = 3; // account for the fact that we get chunks of approx 7 points for 26 scan stops
g.DrawLine(new Pen(Color.DarkGreen, (float)scalefactor), bmp.Width - pointMax - shift, half, bmp.Width - pointMax - shift, bmpHeight);
g.DrawString("" + roundRangeMax + "m", font, Brushes.DarkGreen, bmp.Width - pointMax, bmpHeight - topTextHeight);
}
g.DrawString(
_state.TimeStamp.ToString() + " max: " + rangeMax + " red: <" + nearRange + " green: >" + farRange,
font, Brushes.Black, 0, 0
);
}
memory = new MemoryStream();
bmp.Save(memory, ImageFormat.Jpeg);
memory.Position = 0;
}
return memory;
}
private Color LinearColor(Color nearColor, Color farColor, int nearLimit, int farLimit, int value)
{
if (value <= nearLimit)
{
return nearColor;
}
else if (value >= farLimit)
{
return farColor;
}
int span = farLimit - nearLimit;
int pos = value - nearLimit;
int r = (nearColor.R * (span - pos) + farColor.R * pos) / span;
int g = (nearColor.G * (span - pos) + farColor.G * pos) / span;
int b = (nearColor.B * (span - pos) + farColor.B * pos) / span;
return Color.FromArgb(r, g, b);
}
internal class Lbl
{
public float lx;
public float ly;
public string label;
}
private Stream GenerateTop(int imageWidth)
{
if (_state.DistanceMeasurements == null)
{
return null;
}
MemoryStream memory = null;
Font font = new Font(FontFamily.GenericSansSerif, 10, GraphicsUnit.Pixel);
// Ultrasonic sensor reaches to about 3.5 meters; we scale the height of our display to this range:
double maxExpectedRange = 5000.0d; // mm
int imageHeight = imageWidth / 2;
using (Bitmap bmp = new Bitmap(imageWidth, imageHeight))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
double angularOffset = -90 + _state.AngularRange / 2.0;
double piBy180 = Math.PI / 180.0;
double halfAngle = _state.AngularResolution / 2.0;
double scale = imageHeight / maxExpectedRange;
double drangeMax = 0.0d;
GraphicsPath path = new GraphicsPath();
Dictionary<int, Lbl> labels = new Dictionary<int, Lbl>();
for (int pass = 0; pass != 2; pass++)
{
for (int i = 0; i < _state.DistanceMeasurements.Length; i++)
{
int range = _state.DistanceMeasurements[i];
if (range > 0 && range < 8192)
{
double angle = i * _state.AngularResolution - angularOffset;
double lowAngle = (angle - halfAngle) * piBy180;
double highAngle = (angle + halfAngle) * piBy180;
double drange = range * scale;
float lx = (float)(imageHeight + drange * Math.Cos(lowAngle));
float ly = (float)(imageHeight - drange * Math.Sin(lowAngle));
float hx = (float)(imageHeight + drange * Math.Cos(highAngle));
float hy = (float)(imageHeight - drange * Math.Sin(highAngle));
if (pass == 0)
{
if (i == 0)
{
path.AddLine(imageHeight, imageHeight, lx, ly);
}
path.AddLine(lx, ly, hx, hy);
drangeMax = Math.Max(drangeMax, drange);
}
else
{
g.DrawLine(Pens.DarkBlue, lx, ly, hx, hy);
if (i > 0 && i % 20 == 0 && i < _state.DistanceMeasurements.Length - 10)
{
float llx = (float)(imageHeight + drangeMax * 1.3f * Math.Cos(lowAngle));
float lly = (float)(imageHeight - drangeMax * 1.3f * Math.Sin(lowAngle));
double roundRange = Math.Round(range / 1000.0d, 1); // meters
string str = "" + roundRange;
labels.Add(i, new Lbl() { label = str, lx = llx, ly = lly });
}
}
}
}
if (pass == 0)
{
g.FillPath(Brushes.White, path);
}
}
float botWidth = (float)(190 * scale);
g.DrawLine(Pens.Red, imageHeight, imageHeight - botWidth, imageHeight, imageHeight);
g.DrawLine(Pens.Red, imageHeight - 3, imageHeight - botWidth, imageHeight + 3, imageHeight - botWidth);
g.DrawLine(Pens.Red, imageHeight - botWidth, imageHeight - 3, imageHeight - botWidth, imageHeight);
g.DrawLine(Pens.Red, imageHeight + botWidth, imageHeight - 3, imageHeight + botWidth, imageHeight);
g.DrawLine(Pens.Red, imageHeight - botWidth, imageHeight - 1, imageHeight + botWidth, imageHeight - 1);
g.DrawString(_state.TimeStamp.ToString(), font, Brushes.Black, 0, 0);
foreach (int x in labels.Keys)
{
Lbl lbl = labels[x];
g.DrawString(lbl.label, font, Brushes.Black, lbl.lx, lbl.ly);
}
}
memory = new MemoryStream();
bmp.Save(memory, ImageFormat.Jpeg);
memory.Position = 0;
}
return memory;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace KERBALISM
{
public static class ScienceDB
{
public class UniqueValuesList<T>
{
private List<T> values = new List<T>();
private HashSet<T> valuesHashs = new HashSet<T>();
public void Add(T value)
{
if (valuesHashs.Contains(value))
return;
valuesHashs.Add(value);
values.Add(value);
}
public IEnumerator<T> GetEnumerator() => values.GetEnumerator();
public void Clear()
{
values.Clear();
valuesHashs.Clear();
}
}
// Dictionary-like class intended for a small number of elements that need to be iterated over
// - small memory footprint
// - iterating (foreach) should be as fast as on a list, and generate no garbage
// - key lookups are O(n) and are done by iterating and checking equality
// - other operations all have the O(n) lookup overhead, but no garbage generation
public class KeyValueList<TKey, TValue>
{
private readonly List<ObjectPair<TKey, TValue>> keyValuePairs = new List<ObjectPair<TKey, TValue>>();
public TValue this[TKey key]
{
get { return keyValuePairs[keyValuePairs.FindIndex(p => p.Key.Equals(key))].Value; }
set { keyValuePairs[keyValuePairs.FindIndex(p => p.Key.Equals(key))] = new ObjectPair<TKey, TValue>(key, value); }
}
public void Add(TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException();
if (ContainsKey(key))
throw new ArgumentException();
keyValuePairs.Add(new ObjectPair<TKey, TValue>(key, value));
}
public bool ContainsKey(TKey key) => keyValuePairs.Exists(p => p.Key.Equals(key));
public int Count => keyValuePairs.Count;
public void Clear() => keyValuePairs.Clear();
public IEnumerator<ObjectPair<TKey, TValue>> GetEnumerator() => keyValuePairs.GetEnumerator();
public bool Remove(TKey key)
{
int index = keyValuePairs.FindIndex(p => p.Key.Equals(key));
if (index == -1)
return false;
keyValuePairs.RemoveAt(index);
return true;
}
public bool TryGetValue(TKey key, out TValue value)
{
int index = keyValuePairs.FindIndex(p => p.Key.Equals(key));
if (index == -1)
{
value = default;
return false;
}
value = keyValuePairs[index].Value;
return true;
}
public void ForEach(Action<ObjectPair<TKey, TValue>> action) => keyValuePairs.ForEach(action);
}
/// <summary> KeyValueList of ObjectPair<int, List<SubjectData>>, int = biome index </summary>
public class BiomesSubject : KeyValueList<int, List<SubjectData>> { }
/// <summary> KeyValueList of ObjectPair<ScienceSituation, BiomesSubject> </summary>
public class SituationsBiomesSubject : KeyValueList<ScienceSituation, BiomesSubject> { }
/// <summary> KeyValueList of ObjectPair<int, SituationsBiomesSubject> , int = body index </summary>
public class BodiesSituationsBiomesSubject : KeyValueList<int, SituationsBiomesSubject> { }
/// <summary> Dictionary of KeyBaluePair<ExperimentInfo, BodiesSituationsBiomesSubject> </summary>
public class ExpBodiesSituationsBiomesSubject : Dictionary<ExperimentInfo, BodiesSituationsBiomesSubject>
{
public void AddSubject(ExperimentInfo expInfo, int bodyIndex, ScienceSituation scienceSituation, int biomeIndex, SubjectData subjectData)
{
BodiesSituationsBiomesSubject bodiesSituationsBiomesSubject;
if (!TryGetValue(expInfo, out bodiesSituationsBiomesSubject))
{
bodiesSituationsBiomesSubject = new BodiesSituationsBiomesSubject();
Add(expInfo, bodiesSituationsBiomesSubject);
}
SituationsBiomesSubject situationsBiomesSubject;
if (!bodiesSituationsBiomesSubject.TryGetValue(bodyIndex, out situationsBiomesSubject))
{
situationsBiomesSubject = new SituationsBiomesSubject();
bodiesSituationsBiomesSubject.Add(bodyIndex, situationsBiomesSubject);
}
BiomesSubject biomesSubject;
if (!situationsBiomesSubject.TryGetValue(scienceSituation, out biomesSubject))
{
biomesSubject = new BiomesSubject();
situationsBiomesSubject.Add(scienceSituation, biomesSubject);
}
List<SubjectData> subjectDataList;
if (!biomesSubject.TryGetValue(biomeIndex, out subjectDataList))
{
subjectDataList = new List<SubjectData>();
biomesSubject.Add(biomeIndex, subjectDataList);
}
if (subjectData != null)
{
subjectDataList.Add(subjectData);
}
}
public void RemoveSubject(ExperimentInfo expInfo, int bodyIndex, ScienceSituation scienceSituation, int biomeIndex, SubjectData subjectData)
{
BodiesSituationsBiomesSubject bodiesSituationsBiomesSubject;
if (!TryGetValue(expInfo, out bodiesSituationsBiomesSubject))
return;
SituationsBiomesSubject situationsBiomesSubject;
if (!bodiesSituationsBiomesSubject.TryGetValue(bodyIndex, out situationsBiomesSubject))
return;
BiomesSubject biomesSubject;
if (!situationsBiomesSubject.TryGetValue(scienceSituation, out biomesSubject))
return;
List<SubjectData> subjectDataList;
if (!biomesSubject.TryGetValue(biomeIndex, out subjectDataList))
return;
subjectDataList.Remove(subjectData);
}
}
/// <summary> All ExperimentInfos, accessible by experimentId </summary>
private static readonly Dictionary<string, ExperimentInfo>
experiments = new Dictionary<string, ExperimentInfo>();
/// <summary> All ExperimentInfos </summary>
public static IEnumerable<ExperimentInfo> ExperimentInfos => experiments.Values;
/// <summary>
/// For every ExperimentInfo, for every VesselSituation id, the corresponding SubjectData.
/// used to get the subject, or to test if a situation is available for a given experiment
/// </summary>
private static readonly Dictionary<ExperimentInfo, Dictionary<int, SubjectData>>
subjectByExpThenSituationId = new Dictionary<ExperimentInfo, Dictionary<int, SubjectData>>();
/// <summary>
/// For every ExperimentInfo, body index, situation index, biome index, the corresponding SubjectData.
/// Note : to handle the stock possibility of multiple subjects per unique situation (asteroids), the value is an array of SubjectDatas.
/// Used to get/display all subjects for a given experiment.
/// <para/> body indexes are from the FlightGlobals.Bodies list, and match the CelestialBody.flightGlobalsIndex value
/// <para/> situation indexes are the ScienceSituation enum value
/// <para/> biome indexes are from the CelestialBody.BiomeMap.Attribute. The -1 index correspond to the biome-agnostic situation.
/// <para/> Ex : expBodiesSituationsBiomesSubject[expInfo][2][ScienceSituation.InnerBelt][4][0] return the first subject for expInfo, bodyIndex 2, inner belt situation, biome index 4
/// </summary>
private static readonly ExpBodiesSituationsBiomesSubject
expBodiesSituationsBiomesSubject = new ExpBodiesSituationsBiomesSubject();
// HashSet of all subjects using the stock string id as key, used for RnD subjects synchronization
private static readonly HashSet<string> knownStockSubjectsId = new HashSet<string>();
private static readonly Dictionary<string, SubjectData> unknownSubjectDatas = new Dictionary<string, SubjectData>();
public static readonly Dictionary<string, ScienceSubject> sandboxSubjects = new Dictionary<string, ScienceSubject>();
/// <summary>
/// List of subjects that should be persisted in our own DB
/// </summary>
public static readonly UniqueValuesList<SubjectData> persistedSubjects = new UniqueValuesList<SubjectData>();
public static void Init()
{
Lib.Log("ScienceDB init started");
int subjectCount = 0;
double totalScience = 0.0;
// get our extra defintions
ConfigNode[] expDefNodes = GameDatabase.Instance.GetConfigNodes("EXPERIMENT_DEFINITION");
// create our subject database
// Note : GetExperimentIDs will force the creation of all ScienceExperiment objects,
// no matter if the RnD instance is null or not because the ScienceExperiment dictionary is static.
foreach (string experimentId in ResearchAndDevelopment.GetExperimentIDs())
{
if (experimentId == "recovery")
continue;
ConfigNode kerbalismExpNode = null;
foreach (ConfigNode expDefNode in expDefNodes)
{
string id = string.Empty;
if (expDefNode.TryGetValue("id", ref id) && id == experimentId)
{
kerbalismExpNode = expDefNode.GetNode("KERBALISM_EXPERIMENT"); // return null if not found
break;
}
}
ScienceExperiment stockDef = ResearchAndDevelopment.GetExperiment(experimentId);
if (stockDef == null)
{
Lib.Log("ScienceExperiment is null for experiment Id=" + experimentId + ", skipping...", Lib.LogLevel.Warning);
continue;
}
ExperimentInfo expInfo = new ExperimentInfo(stockDef, kerbalismExpNode);
if (!experiments.ContainsKey(experimentId))
experiments.Add(experimentId, expInfo);
if (!subjectByExpThenSituationId.ContainsKey(expInfo))
subjectByExpThenSituationId.Add(expInfo, new Dictionary<int, SubjectData>());
for (int bodyIndex = 0; bodyIndex < FlightGlobals.Bodies.Count; bodyIndex++)
{
CelestialBody body = FlightGlobals.Bodies[bodyIndex];
if (!expInfo.IgnoreBodyRestrictions && !expInfo.ExpBodyConditions.IsBodyAllowed(body))
continue;
// ScienceSituationUtils.validSituations is all situations in the enum, apart from the "None" value
foreach (ScienceSituation scienceSituation in ScienceSituationUtils.validSituations)
{
// test the ScienceExperiment situation mask
if (!scienceSituation.IsAvailableForExperiment(expInfo))
continue;
// don't add impossible body / situation combinations
if (!expInfo.IgnoreBodyRestrictions && !scienceSituation.IsAvailableOnBody(body))
continue;
// virtual biomes always have priority over normal biomes :
if (scienceSituation.IsVirtualBiomesRelevantForExperiment(expInfo))
{
foreach (VirtualBiome virtualBiome in expInfo.VirtualBiomes)
{
if (!virtualBiome.IsAvailableOnBody(body))
continue;
SubjectData subjectData = null;
if (expInfo.HasDBSubjects)
{
Situation situation = new Situation(bodyIndex, scienceSituation, (int)virtualBiome);
subjectData = new SubjectData(expInfo, situation);
subjectByExpThenSituationId[expInfo].Add(situation.Id, subjectData);
knownStockSubjectsId.Add(subjectData.StockSubjectId);
subjectCount++;
totalScience += subjectData.ScienceMaxValue;
}
expBodiesSituationsBiomesSubject.AddSubject(expInfo, bodyIndex, scienceSituation, (int)virtualBiome, subjectData);
}
}
// if the biome mask says the situation is biome dependant :
else if (scienceSituation.IsBodyBiomesRelevantForExperiment(expInfo) && body.BiomeMap != null && body.BiomeMap.Attributes.Length > 1)
{
for (int biomeIndex = 0; biomeIndex < body.BiomeMap.Attributes.Length; biomeIndex++)
{
SubjectData subjectData = null;
if (expInfo.HasDBSubjects)
{
Situation situation = new Situation(bodyIndex, scienceSituation, biomeIndex);
subjectData = new SubjectData(expInfo, situation);
subjectByExpThenSituationId[expInfo].Add(situation.Id, subjectData);
knownStockSubjectsId.Add(subjectData.StockSubjectId);
subjectCount++;
totalScience += subjectData.ScienceMaxValue;
}
expBodiesSituationsBiomesSubject.AddSubject(expInfo, bodyIndex, scienceSituation, biomeIndex, subjectData);
}
}
// else generate the global, biome agnostic situation
else
{
SubjectData subjectData = null;
if (expInfo.HasDBSubjects)
{
Situation situation = new Situation(bodyIndex, scienceSituation);
subjectData = new SubjectData(expInfo, situation);
subjectByExpThenSituationId[expInfo].Add(situation.Id, subjectData);
knownStockSubjectsId.Add(subjectData.StockSubjectId);
subjectCount++;
totalScience += subjectData.ScienceMaxValue;
}
expBodiesSituationsBiomesSubject.AddSubject(expInfo, bodyIndex, scienceSituation, -1, subjectData);
}
}
}
}
// cache that call
IEnumerable<ExperimentInfo> experimentInfosCache = ExperimentInfos;
// first parse all the IncludeExperiment configs
foreach (ExperimentInfo experimentInfo in experimentInfosCache)
experimentInfo.ParseIncludedExperiments();
// then check for infinite recursion from bad configs
List<ExperimentInfo> chainedExperiments = new List<ExperimentInfo>();
foreach (ExperimentInfo experimentInfo in experimentInfosCache)
{
chainedExperiments.Clear();
ExperimentInfo.CheckIncludedExperimentsRecursion(experimentInfo, chainedExperiments);
}
// now we are sure all the include experiment chains are valid
foreach (ExperimentInfo experimentInfo in experimentInfosCache)
{
// populate the included experiments chains at the subject level
foreach (KeyValuePair<int, SubjectData> subjectInfo in subjectByExpThenSituationId[experimentInfo])
{
foreach (ExperimentInfo includedInfo in experimentInfo.IncludedExperiments)
{
SubjectData subjectToInclude = GetSubjectData(includedInfo, subjectInfo.Key);
if (subjectToInclude != null)
subjectInfo.Value.IncludedSubjects.Add(subjectToInclude);
}
}
// Get the experiment description that will be shown in the science archive by calling GetInfo() on the first found partmodule using it
// TODO: this isn't ideal, if there are several modules with different values (ex : data rate, ec rate...), the archive info will use the first found one.
// Ideally we should revamp the whole handling of that (because it's a mess from the partmodule side too)
experimentInfo.CompileModuleInfos();
}
Lib.Log($"ScienceDB init done : {subjectCount} subjects found, total science points : {totalScience.ToString("F1")}");
}
public static void Load(ConfigNode node)
{
// RnD subjects don't exists in sandbox
if (!Science.GameHasRnD)
{
// load sandbox science subjects
sandboxSubjects.Clear();
if (node.HasNode("sandboxScienceSubjects"))
{
foreach (var subjectNode in node.GetNode("sandboxScienceSubjects").GetNodes())
{
ScienceSubject subject = new ScienceSubject(subjectNode);
sandboxSubjects.Add(subject.id, subject);
}
}
}
else
{
// Load API subjects (require RnD)
subjectsReceivedBuffer.Clear();
subjectsReceivedValueBuffer.Clear();
ConfigNode APISubjects = new ConfigNode();
if (node.TryGetNode("APISubjects", ref APISubjects))
{
foreach (ConfigNode subjectNode in APISubjects.GetNodes("Subject"))
{
string subjectId = Lib.ConfigValue(subjectNode, "subjectId", string.Empty);
ScienceSubject subject = ResearchAndDevelopment.GetSubjectByID(subjectId);
if (subject == null)
{
Lib.Log($"Warning : API subject '{subjectId}' not found in ResearchAndDevelopment");
continue;
}
subjectsReceivedBuffer.Add(subject);
subjectsReceivedValueBuffer.Add(Lib.ConfigValue(subjectNode, "science", 0.0));
}
}
}
// load uncredited science (transmission buffer)
uncreditedScience = Lib.ConfigValue(node, "uncreditedScience", 0.0);
// Rebuild the list of persisted subjects
persistedSubjects.Clear();
foreach (ExperimentInfo expInfo in experiments.Values)
{
foreach (SubjectData subjectData in subjectByExpThenSituationId[expInfo].Values)
{
subjectData.CheckRnD();
subjectData.ClearDataCollectedInFlight();
}
}
// load science subjects persisted data
if (node.HasNode("subjectData"))
{
foreach (var subjectNode in node.GetNode("subjectData").GetNodes())
{
string integerSubjectId = DB.From_safe_key(subjectNode.name);
SubjectData subjectData = GetSubjectData(integerSubjectId);
if (subjectData != null)
subjectData.Load(subjectNode);
}
}
//if (ResearchAndDevelopment.Instance == null)
// Lib.Log("ERROR : ResearchAndDevelopment.Instance is null on subjects load !");
// remove unknown subjects from the database
foreach (SubjectData subjectData in unknownSubjectDatas.Values)
{
int bodyIndex;
int scienceSituation;
int biomeIndex;
Situation.IdToFields(subjectData.Situation.Id, out bodyIndex, out scienceSituation, out biomeIndex);
expBodiesSituationsBiomesSubject.RemoveSubject(subjectData.ExpInfo, bodyIndex, (ScienceSituation)scienceSituation, biomeIndex, subjectData);
}
// clear the list
unknownSubjectDatas.Clear();
// find them again
IEnumerable<ScienceSubject> stockSubjects;
if (Science.GameHasRnD)
stockSubjects = ResearchAndDevelopment.GetSubjects();
else
stockSubjects = sandboxSubjects.Values;
foreach (ScienceSubject stockSubject in stockSubjects)
if (!knownStockSubjectsId.Contains(stockSubject.id))
GetSubjectDataFromStockId(stockSubject.id, stockSubject);
}
public static void Save(ConfigNode node)
{
// RnD subjects don't exists in sandbox, so we have our own subject persistence
if (!Science.GameHasRnD)
{
ConfigNode sandboxSubjectsNode = node.AddNode("sandboxScienceSubjects");
foreach (ScienceSubject subject in sandboxSubjects.Values)
subject.Save(sandboxSubjectsNode.AddNode("subject"));
}
else
{
// save API subjects (only exists if game has RnD)
if (subjectsReceivedBuffer.Count > 0)
{
ConfigNode APISubjects = node.AddNode("APISubjects");
for (int i = 0; i < subjectsReceivedBuffer.Count; i++)
{
ConfigNode subjectNode = APISubjects.AddNode("Subject");
subjectNode.AddValue("subjectId", subjectsReceivedBuffer[i].id);
subjectNode.AddValue("science", subjectsReceivedValueBuffer[i]);
}
}
}
// save uncredited science (transmission buffer)
node.AddValue("uncreditedScience", uncreditedScience);
// save science subjects persisted data
var subjectsNode = node.AddNode("subjectData");
foreach (SubjectData subject in persistedSubjects)
{
subject.Save(subjectsNode.AddNode(DB.To_safe_key(subject.Id)));
}
}
// Use a buffer because AddScience is VERY slow
// We don't use "TransactionReasons.ScienceTransmission" because AddScience fire multiple events not meant to be fired continuously
// this avoid many side issues (ex : chatterer transmit sound playing continously, strategia "+0.0 science" popup...)
public static double uncreditedScience;
// this is for the onSubjectsReceived API event
public static List<ScienceSubject> subjectsReceivedBuffer = new List<ScienceSubject>();
public static List<double> subjectsReceivedValueBuffer = new List<double>();
private static double realTimeElapsed = 0.0;
private static double realTimeElapsedAPI = 0.0;
private static double gameTimeElapsedAPI = 0.0;
public static void CreditScienceBuffers(double elapsed_s)
{
if (!Science.GameHasRnD)
return;
if (!API.preventScienceCrediting)
{
realTimeElapsed += TimeWarp.CurrentRate > 0f ? elapsed_s / TimeWarp.CurrentRate : 0f;
if (uncreditedScience > 0.1 && realTimeElapsed > 2.5)
{
ResearchAndDevelopment.Instance.AddScience((float)uncreditedScience, TransactionReasons.None);
uncreditedScience = 0.0;
realTimeElapsed = 0.0;
}
}
if (API.subjectsReceivedEventEnabled)
{
gameTimeElapsedAPI += elapsed_s;
realTimeElapsedAPI += TimeWarp.CurrentRate > 0f ? elapsed_s / TimeWarp.CurrentRate : 0f;
if (subjectsReceivedBuffer.Count > 0 && (gameTimeElapsedAPI > API.subjectsReceivedEventGameTimeInterval || realTimeElapsedAPI > API.subjectsReceivedEventRealTimeInterval))
{
API.onSubjectsReceived.Fire(subjectsReceivedBuffer, subjectsReceivedValueBuffer);
subjectsReceivedBuffer.Clear();
subjectsReceivedValueBuffer.Clear();
gameTimeElapsedAPI = 0.0;
realTimeElapsedAPI = 0.0;
}
}
}
public static ExperimentInfo GetExperimentInfo(string experimentId)
{
ExperimentInfo expInfo;
if (!experiments.TryGetValue(experimentId, out expInfo))
return null;
return expInfo;
}
/// <summary> return the subject information for the given experiment and situation, or null if the situation isn't available. </summary>
public static SubjectData GetSubjectData(ExperimentInfo expInfo, Situation situation)
{
int situationId;
if (!situation.ScienceSituation.IsBiomesRelevantForExperiment(expInfo))
situationId = situation.GetBiomeAgnosticId();
else
situationId = situation.Id;
SubjectData subjectData;
if (!subjectByExpThenSituationId[expInfo].TryGetValue(situationId, out subjectData))
return null;
return subjectData;
}
/// <summary> return the subject information for the given experiment and situation, or null if the situation isn't available. </summary>
public static SubjectData GetSubjectData(ExperimentInfo expInfo, Situation situation, out int situationId)
{
if (!situation.ScienceSituation.IsBiomesRelevantForExperiment(expInfo))
situationId = situation.GetBiomeAgnosticId();
else
situationId = situation.Id;
SubjectData subjectData;
if (!subjectByExpThenSituationId[expInfo].TryGetValue(situationId, out subjectData))
return null;
return subjectData;
}
/// <summary> return the subject information for the given experiment and situation id, or null if the situation isn't available. </summary>
public static SubjectData GetSubjectData(ExperimentInfo expInfo, int situationId)
{
SubjectData subjectData;
if (!subjectByExpThenSituationId[expInfo].TryGetValue(situationId, out subjectData))
return null;
return subjectData;
}
/// <summary> return the subject information for the given experiment and situation, or null if the situation isn't available. </summary>
public static SubjectData GetSubjectData(string integerSubjectId)
{
string[] expAndSit = integerSubjectId.Split('@');
if (expAndSit.Length != 2)
{
Lib.Log("Could not get the SubjectData from subject '" + integerSubjectId + "' : bad format");
return null;
}
ExperimentInfo expInfo = GetExperimentInfo(expAndSit[0]);
if (expInfo == null)
{
Lib.Log("Could not get the SubjectData from subject '" + integerSubjectId + "' : the experiment id '" + expAndSit[0] + "' doesn't exists");
return null;
}
int situationId;
if (!int.TryParse(expAndSit[1], out situationId))
{
Lib.Log("Could not get the SubjectData from subject '" + integerSubjectId + "' : the situation id '" + expAndSit[1] + "' isn't a valid integer");
return null;
}
SubjectData subjectData;
if (!subjectByExpThenSituationId[expInfo].TryGetValue(situationId, out subjectData))
{
Lib.Log("Could not get the SubjectData from subject '" + integerSubjectId + "' : the situation id '" + expAndSit[1] + "' isn't valid");
return null;
}
return subjectData;
}
/// <summary>
/// Create our SubjectData by parsing the stock "experiment@situation" subject id string.
/// Used for asteroid samples, for compatibility with RnD archive data of removed mods and for converting stock ScienceData into SubjectData
/// </summary>
public static SubjectData GetSubjectDataFromStockId(string stockSubjectId, ScienceSubject RnDSubject = null, string extraSituationInfo = null)
{
SubjectData subjectData = null;
if (unknownSubjectDatas.TryGetValue(stockSubjectId, out subjectData))
return subjectData;
string[] expAndSit = stockSubjectId.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
if (expAndSit.Length != 2)
{
Lib.Log("Could not parse the SubjectData from subjectId '" + stockSubjectId + "' : bad format");
return null;
}
// the recovery experiment subject are created in ResearchAndDevelopment.reverseEngineerRecoveredVessel, called on the vessel recovery event
// it use a non-standard situation system ("body" + a situation enum "RecoverySituations"). We ignore those.
if (expAndSit[0] == "recovery")
return null;
ExperimentInfo expInfo = GetExperimentInfo(expAndSit[0]);
if (expInfo == null)
{
Lib.Log("Could not parse the SubjectData from subjectId '" + stockSubjectId + "' : the experiment id '" + expAndSit[0] + "' doesn't exists");
return null;
}
// for subject ids created with the ResearchAndDevelopment.GetExperimentSubject overload that take a "sourceUId" string,
// the sourceUId is added to the situation after a "_"
// in stock this seems to be used only for asteroids, and I don't think any mod use it.
if (expAndSit[1].Contains("_"))
{
string[] sitAndAsteroid = expAndSit[1].Split('_');
// remove
expAndSit[1] = sitAndAsteroid[0];
// asteroid are saved as "part.partInfo.name + part.flightID", and the part name always end with a randomly generated "AAA-000" string
if (extraSituationInfo == null)
{
extraSituationInfo = Regex.Match(sitAndAsteroid[1], ".*?-[0-9][0-9][0-9]").Value;
// if no match, just use the unmodified string
if (extraSituationInfo == string.Empty)
extraSituationInfo = sitAndAsteroid[1];
}
}
string[] bodyAndBiome = expAndSit[1].Split(ScienceSituationUtils.validSituationsStrings, StringSplitOptions.RemoveEmptyEntries);
string situation;
if (bodyAndBiome.Length == 1)
situation = expAndSit[1].Substring(bodyAndBiome[0].Length);
else if (bodyAndBiome.Length == 2)
situation = expAndSit[1].Substring(bodyAndBiome[0].Length, expAndSit[1].Length - bodyAndBiome[0].Length - bodyAndBiome[1].Length);
else
{
Lib.Log("Could not parse the SubjectData from subjectId '" + stockSubjectId + "' : the situation doesn't exists");
return null;
}
CelestialBody subjectBody = null;
foreach (CelestialBody body in FlightGlobals.Bodies)
{
if (body.name == bodyAndBiome[0])
{
subjectBody = body;
break;
}
}
if (subjectBody == null)
{
// TODO : DMOS asteroid experiments are doing : "magScan@AsteroidInSpaceLowCarbonaceous7051371", those subjects will be discarded entirely here
// because the body "Asteroid" doesn't exists, consequently it's impossible to create the Situation object.
// To handle that, maybe we could implement a derived class "UnknownSituation" from Situation that can handle a completely random subject format
Lib.Log("Could not parse the SubjectData from subjectId '" + stockSubjectId + "' : the body '" + bodyAndBiome[0] + "' doesn't exist");
return null;
}
ScienceSituation scienceSituation = ScienceSituationUtils.ScienceSituationDeserialize(situation);
int biomeIndex = -1;
if (bodyAndBiome.Length == 2 && ScienceSituationUtils.IsBodyBiomesRelevantForExperiment(scienceSituation, expInfo) && subjectBody.BiomeMap != null)
{
for (int i = 0; i < subjectBody.BiomeMap.Attributes.Length; i++)
{
// Note : a stock subject has its spaces in the biome name removed but prior versions of kerbalism didn't do that,
// so we try to fix it, in order not to create duplicates in the RnD archives.
// TODO : also, we need to remove the "reentry" subjects, as stock is failing to parse them, altough this is in a try/catch block and handled gracefully.
string sanitizedBiome = bodyAndBiome[1].Replace(" ", string.Empty);
if (RnDSubject != null && extraSituationInfo == null && sanitizedBiome != bodyAndBiome[1])
{
string correctedSubjectId = expAndSit[0] + "@" + bodyAndBiome[0] + situation + sanitizedBiome;
RnDSubject.id = correctedSubjectId;
Dictionary<string, ScienceSubject> stockSubjects = Lib.ReflectionValue<Dictionary<string, ScienceSubject>>(ResearchAndDevelopment.Instance, "scienceSubjects");
if (stockSubjects.Remove(stockSubjectId) && !stockSubjects.ContainsKey(correctedSubjectId))
{
stockSubjects.Add(correctedSubjectId, RnDSubject);
}
Lib.Log("RnD subject load : misformatted subject '" + stockSubjectId + "' was corrected to '" + correctedSubjectId + "'");
}
if (subjectBody.BiomeMap.Attributes[i].name.Replace(" ", string.Empty).Equals(sanitizedBiome, StringComparison.OrdinalIgnoreCase))
{
biomeIndex = i;
break;
}
}
}
int bodyIndex = subjectBody.flightGlobalsIndex;
Situation vesselSituation = new Situation(bodyIndex, scienceSituation, biomeIndex);
// if the subject is a "doable" subject, we should have it in the DB.
if (extraSituationInfo == null)
subjectData = GetSubjectData(expInfo, vesselSituation);
// else create the subjectdata. this can happen either because :
// - it's a subject using the stock "extra id" system (asteroid samples)
// - the subject was created in RnD prior to an experiment definition config change
// - it was created by a mod that does things in a non-stock way (ex : DMOS anomaly scans uses the anomaly name as biomes)
if (subjectData == null)
{
if (bodyAndBiome.Length == 2 && bodyAndBiome[1] != string.Empty && extraSituationInfo == null)
{
extraSituationInfo = bodyAndBiome[1];
}
UnknownSubjectData unknownSubjectData = new UnknownSubjectData(expInfo, vesselSituation, stockSubjectId, RnDSubject, extraSituationInfo);
subjectData = unknownSubjectData;
unknownSubjectDatas.Add(stockSubjectId, unknownSubjectData);
expBodiesSituationsBiomesSubject.AddSubject(subjectData.ExpInfo, bodyIndex, scienceSituation, biomeIndex, subjectData);
}
return subjectData;
}
public static BodiesSituationsBiomesSubject GetSubjectsForExperiment(ExperimentInfo expInfo)
{
BodiesSituationsBiomesSubject result;
expBodiesSituationsBiomesSubject.TryGetValue(expInfo, out result);
return result;
}
}
}
| |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic
{
/// <summary>
/// Enumeration values for PropulsionPlantConfiguration (der.ua.ppcfg, Propulsion Plant Configuration,
/// section 8.4.7)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public struct PropulsionPlantConfiguration
{
/// <summary>
/// Run internal simulation clock.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Run internal simulation clock.")]
public enum ConfigurationValue : uint
{
/// <summary>
/// Other
/// </summary>
Other = 0,
/// <summary>
/// Diesel/electric
/// </summary>
DieselElectric = 1,
/// <summary>
/// Diesel
/// </summary>
Diesel = 2,
/// <summary>
/// Battery
/// </summary>
Battery = 3,
/// <summary>
/// Turbine reduction
/// </summary>
TurbineReduction = 4,
/// <summary>
/// null
/// </summary>
Unknown = 5,
/// <summary>
/// Steam
/// </summary>
Steam = 6,
/// <summary>
/// Gas turbine
/// </summary>
GasTurbine = 7,
/// <summary>
/// null
/// </summary>
Unknown2 = 8
}
/// <summary>
/// Hull Mounted Masker status
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Hull Mounted Masker status")]
public enum HullMountedMaskerValue : uint
{
/// <summary>
/// Off
/// </summary>
Off = 0,
/// <summary>
/// On
/// </summary>
On = 1
}
private PropulsionPlantConfiguration.ConfigurationValue configuration;
private PropulsionPlantConfiguration.HullMountedMaskerValue hullMountedMasker;
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(PropulsionPlantConfiguration left, PropulsionPlantConfiguration right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(PropulsionPlantConfiguration left, PropulsionPlantConfiguration right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
// If parameters are null return false (cast to object to prevent recursive loop!)
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
/// <summary>
/// Performs an explicit conversion from <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> to <see cref="System.UInt32"/>.
/// </summary>
/// <param name="obj">The <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> scheme instance.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator uint(PropulsionPlantConfiguration obj)
{
return obj.ToUInt32();
}
/// <summary>
/// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/>.
/// </summary>
/// <param name="value">The uint value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator PropulsionPlantConfiguration(uint value)
{
return PropulsionPlantConfiguration.FromUInt32(value);
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> instance from the byte array.
/// </summary>
/// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/>.</param>
/// <param name="index">The starting position within value.</param>
/// <returns>The <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> instance, represented by a byte array.</returns>
/// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception>
/// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception>
public static PropulsionPlantConfiguration FromByteArray(byte[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (index < 0 ||
index > array.Length - 1 ||
index + 4 > array.Length - 1)
{
throw new IndexOutOfRangeException();
}
return FromUInt32(BitConverter.ToUInt32(array, index));
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> instance from the uint value.
/// </summary>
/// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> instance.</param>
/// <returns>The <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> instance, represented by the uint value.</returns>
public static PropulsionPlantConfiguration FromUInt32(uint value)
{
PropulsionPlantConfiguration ps = new PropulsionPlantConfiguration();
uint mask0 = 0x007f;
byte shift0 = 0;
uint newValue0 = value & mask0 >> shift0;
ps.Configuration = (PropulsionPlantConfiguration.ConfigurationValue)newValue0;
uint mask1 = 0x0080;
byte shift1 = 7;
uint newValue1 = value & mask1 >> shift1;
ps.HullMountedMasker = (PropulsionPlantConfiguration.HullMountedMaskerValue)newValue1;
return ps;
}
/// <summary>
/// Gets or sets the configuration.
/// </summary>
/// <value>The configuration.</value>
public PropulsionPlantConfiguration.ConfigurationValue Configuration
{
get { return this.configuration; }
set { this.configuration = value; }
}
/// <summary>
/// Gets or sets the hullmountedmasker.
/// </summary>
/// <value>The hullmountedmasker.</value>
public PropulsionPlantConfiguration.HullMountedMaskerValue HullMountedMasker
{
get { return this.hullMountedMasker; }
set { this.hullMountedMasker = value; }
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (!(obj is PropulsionPlantConfiguration))
{
return false;
}
return this.Equals((PropulsionPlantConfiguration)obj);
}
/// <summary>
/// Determines whether the specified <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> instance is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> instance to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(PropulsionPlantConfiguration other)
{
// If parameter is null return false (cast to object to prevent recursive loop!)
if ((object)other == null)
{
return false;
}
return
this.Configuration == other.Configuration &&
this.HullMountedMasker == other.HullMountedMasker;
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> to the byte array.
/// </summary>
/// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> instance.</returns>
public byte[] ToByteArray()
{
return BitConverter.GetBytes(this.ToUInt32());
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> to the uint value.
/// </summary>
/// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.DistributedEmission.UnderwaterAcoustic.PropulsionPlantConfiguration"/> instance.</returns>
public uint ToUInt32()
{
uint val = 0;
val |= (uint)((uint)this.Configuration << 0);
val |= (uint)((uint)this.HullMountedMasker << 7);
return val;
}
/// <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()
{
int hash = 17;
// Overflow is fine, just wrap
unchecked
{
hash = (hash * 29) + this.Configuration.GetHashCode();
hash = (hash * 29) + this.HullMountedMasker.GetHashCode();
}
return hash;
}
}
}
| |
/*
Copyright 2018 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 ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Internal.CIM;
using Geometry = ArcGIS.Core.Geometry.Geometry;
using ArcGIS.Desktop.Framework;
using System.Windows.Input;
using System.IO;
using System.Threading;
namespace Snippets
{
internal class ProSnippet
{
#region ProSnippet Group: Maps
#endregion
#region Get the active map's name
public string GetActiveMapName()
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return null;
//Return the name of the map currently displayed in the active map view.
return mapView.Map.Name;
}
#endregion
#region Test if the view is 3D
public bool IsView3D()
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return false;
//Return whether the viewing mode is SceneLocal or SceneGlobal
return mapView.ViewingMode == ArcGIS.Core.CIM.MapViewingMode.SceneLocal ||
mapView.ViewingMode == ArcGIS.Core.CIM.MapViewingMode.SceneGlobal;
}
#endregion
#region Rotate the map view
public void RotateView(double heading)
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return;
//Get the camera for the view, adjust the heading and zoom to the new camera position.
var camera = mapView.Camera;
camera.Heading = heading;
mapView.ZoomToAsync(camera, TimeSpan.Zero);
}
#endregion
private static void ClearSelectionMap()
{
#region Clear all selection in an Active map
QueuedTask.Run(() =>
{
if (MapView.Active.Map != null)
{
MapView.Active.Map.SetSelection(null);
}
});
#endregion
}
private static void CalculateSelectionTolerance()
{
#region Calculate Selection tolerance in map units
//Selection tolerance for the map in pixels
var selectionTolerance = SelectionEnvironment.SelectionTolerance;
QueuedTask.Run(() => {
//Get the map center
var mapExtent = MapView.Active.Map.GetDefaultExtent();
var mapPoint = mapExtent.Center;
//Map center as screen point
var screenPoint = MapView.Active.MapToScreen(mapPoint);
//Add selection tolerance pixels to get a "radius".
var radiusScreenPoint = new System.Windows.Point((screenPoint.X + selectionTolerance), screenPoint.Y);
var radiusMapPoint = MapView.Active.ScreenToMap(radiusScreenPoint);
//Calculate the selection tolerance distance in map uints.
var searchRadius = GeometryEngine.Instance.Distance(mapPoint, radiusMapPoint);
});
#endregion
}
private static async void AddMapViewOverlayControl ()
{
#region MapView Overlay Control
//Creat a Progress Bar user control
var progressBarControl = new System.Windows.Controls.ProgressBar();
//Configure the progress bar
progressBarControl.Minimum = 0;
progressBarControl.Maximum = 100;
progressBarControl.IsIndeterminate = true;
progressBarControl.Width = 300;
progressBarControl.Value = 10;
progressBarControl.Height = 25;
progressBarControl.Visibility = System.Windows.Visibility.Visible;
//Create a MapViewOverlayControl.
var mapViewOverlayControl = new MapViewOverlayControl(progressBarControl, true, true, true, OverlayControlRelativePosition.BottomCenter, .5, .8);
//Add to the active map
MapView.Active.AddOverlayControl(mapViewOverlayControl);
await QueuedTask.Run(() =>
{
//Wait 3 seconds to remove the progress bar from the map.
Thread.Sleep(3000);
});
//Remove from active map
MapView.Active.RemoveOverlayControl(mapViewOverlayControl);
#endregion
}
#region ProSnippet Group: Layers
#endregion
#region Select all feature layers in TOC
public void SelectAllFeatureLayersInTOC()
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return;
//Zoom to the selected layers in the TOC
var featureLayers = mapView.Map.Layers.OfType<FeatureLayer>();
mapView.SelectLayers(featureLayers.ToList());
}
#endregion
#region Flash selected features
public Task FlashSelectedFeaturesAsync()
{
return QueuedTask.Run(() =>
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return;
//Get the selected features from the map and filter out the standalone table selection.
var selectedFeatures = mapView.Map.GetSelection()
.Where(kvp => kvp.Key is BasicFeatureLayer)
.ToDictionary(kvp => (BasicFeatureLayer)kvp.Key, kvp => kvp.Value);
//Flash the collection of features.
mapView.FlashFeature(selectedFeatures);
});
}
#endregion
private void CheckLayerVisiblityInView()
{
#region Check if Layer is visible in the given map view
var mapView = MapView.Active;
var layer = mapView.Map.GetLayersAsFlattenedList().OfType<Layer>().FirstOrDefault();
if (mapView == null) return;
bool isLayerVisibleInView = layer.IsVisibleInView(mapView);
if (isLayerVisibleInView)
{
//Do Something
}
#endregion
}
private static void GetLayerPropertiesDialog()
{
#region Select a layer and open its layer properties page
// get the layer you want
var layer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
// select it in the TOC
List<Layer> layersToSelect = new List<Layer>();
layersToSelect.Add(layer);
MapView.Active.SelectLayers(layersToSelect);
// now execute the layer properties command
var wrapper = FrameworkApplication.GetPlugInWrapper("esri_mapping_selectedLayerPropertiesButton");
var command = wrapper as ICommand;
if (command == null)
return;
// execute the command
if (command.CanExecute(null))
command.Execute(null);
#endregion
}
private static void ClearSelection()
{
#region Clear selection for a specific layer
var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
QueuedTask.Run(() =>
{
lyr.ClearSelection();
});
#endregion
}
private static void OpenTablePane()
{
#region Display Table pane for Map Member
var mapMember = MapView.Active.Map.GetLayersAsFlattenedList().OfType<MapMember>().FirstOrDefault();
//Gets or creates the CIMMapTableView for a MapMember.
var tableView = FrameworkApplication.Panes.GetMapTableView(mapMember);
//Configure the table view
tableView.DisplaySubtypeDomainDescriptions = false;
tableView.SelectionMode = false;
tableView.ShowOnlyContingentValueFields = true;
tableView.HighlightInvalidContingentValueFields = true;
//Open the table pane using the configured tableView. If a table pane is already open it will be activated.
//You must be on the UI thread to call this function.
var tablePane = FrameworkApplication.Panes.OpenTablePane(tableView);
#endregion
}
#region ProSnippet Group: Features
#endregion
private static void Masking()
{
QueuedTask.Run(() => {
#region Mask feature
//Get the layer to be masked
var lineLyrToBeMasked = MapView.Active.Map.Layers.FirstOrDefault(lyr => lyr.Name == "TestLine") as FeatureLayer;
//Get the layer's definition
var lyrDefn = lineLyrToBeMasked.GetDefinition();
//Create an array of Masking layers (polygon only)
//Set the LayerMasks property of the Masked layer
lyrDefn.LayerMasks = new string[] { "CIMPATH=map3/testpoly.xml" };
//Re-set the Masked layer's defintion
lineLyrToBeMasked.SetDefinition(lyrDefn);
#endregion
});
}
#region Show a pop-up for a feature
public void ShowPopup(MapMember mapMember, long objectID)
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return;
mapView.ShowPopup(mapMember, objectID);
}
#endregion
#region Show a custom pop-up
public void ShowCustomPopup()
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return;
//Create custom popup content
var popups = new List<PopupContent>
{
new PopupContent("<b>This text is bold.</b>", "Custom tooltip from HTML string"),
new PopupContent(new Uri("http://www.esri.com/"), "Custom tooltip from Uri")
};
mapView.ShowCustomPopup(popups);
}
#endregion
#region Show a pop-up for a feature using pop-up window properties
public void ShowPopupWithWindowDef(MapMember mapMember, long objectID)
{
if (MapView.Active == null) return;
// Sample code: https://github.com/ArcGIS/arcgis-pro-sdk-community-samples/blob/master/Map-Exploration/CustomIdentify/CustomIdentify.cs
var topLeftCornerPoint = new System.Windows.Point(200, 200);
var popupDef = new PopupDefinition()
{
Append = true, // if true new record is appended to existing (if any)
Dockable = true, // if true popup is dockable - if false Append is not applicable
Position = topLeftCornerPoint, // Position of top left corner of the popup (in pixels)
Size = new System.Windows.Size(200, 400) // size of the popup (in pixels)
};
MapView.Active.ShowPopup(mapMember, objectID, popupDef);
}
#endregion
#region Show a custom pop-up using pop-up window properties
public void ShowCustomPopupWithWindowDef()
{
if (MapView.Active == null) return;
//Create custom popup content
var popups = new List<PopupContent>
{
new PopupContent("<b>This text is bold.</b>", "Custom tooltip from HTML string"),
new PopupContent(new Uri("http://www.esri.com/"), "Custom tooltip from Uri")
};
// Sample code: https://github.com/ArcGIS/arcgis-pro-sdk-community-samples/blob/master/Framework/DynamicMenu/DynamicFeatureSelectionMenu.cs
var topLeftCornerPoint = new System.Windows.Point(200, 200);
var popupDef = new PopupDefinition()
{
Append = true, // if true new record is appended to existing (if any)
Dockable = true, // if true popup is dockable - if false Append is not applicable
Position = topLeftCornerPoint, // Position of top left corner of the popup (in pixels)
Size = new System.Windows.Size(200, 400) // size of the popup (in pixels)
};
MapView.Active.ShowCustomPopup(popups, null, true, popupDef);
}
#endregion
#region ProSnippet Group: Zoom
#endregion
#region Zoom to an extent
public async Task<bool> ZoomToExtentAsync(double xMin, double yMin, double xMax, double yMax,
ArcGIS.Core.Geometry.SpatialReference spatialReference)
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return false;
//Create the envelope
var envelope =
await
QueuedTask.Run(
() =>
ArcGIS.Core.Geometry.EnvelopeBuilder.CreateEnvelope(xMin, yMin, xMax, yMax, spatialReference));
//Zoom the view to a given extent.
return await mapView.ZoomToAsync(envelope, TimeSpan.FromSeconds(2));
}
#endregion
private static void ZoomToGeographicCoordinates(double x, double y, double buffer_size)
{
QueuedTask.Run(() => {
#region Zoom to a specified point
//Note: Run within QueuedTask
//Create a point
var pt = MapPointBuilder.CreateMapPoint(x, y, SpatialReferenceBuilder.CreateSpatialReference(4326));
//Buffer it - for purpose of zoom
var poly = GeometryEngine.Instance.Buffer(pt, buffer_size);
//do we need to project the buffer polygon?
if (!MapView.Active.Map.SpatialReference.IsEqual(poly.SpatialReference))
{
//project the polygon
poly = GeometryEngine.Instance.Project(poly, MapView.Active.Map.SpatialReference);
}
//Zoom - add in a delay for animation effect
MapView.Active.ZoomTo(poly, new TimeSpan(0, 0, 0, 3));
#endregion
});
}
#region Zoom to visible layers
public Task<bool> ZoomToVisibleLayersAsync()
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return Task.FromResult(false);
//Zoom to all visible layers in the map.
var visibleLayers = mapView.Map.Layers.Where(l => l.IsVisible);
return mapView.ZoomToAsync(visibleLayers);
}
#endregion
#region Zoom to selected layers in TOC
public Task<bool> ZoomToTOCSelectedLayersAsync()
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return Task.FromResult(false);
//Zoom to the selected layers in the TOC
var selectedLayers = mapView.GetSelectedLayers();
return mapView.ZoomToAsync(selectedLayers);
}
#endregion
#region Zoom to previous camera
public Task<bool> ZoomToPreviousCameraAsync()
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return Task.FromResult(false);
//Zoom to the selected layers in the TOC
if (mapView.HasPreviousCamera())
return mapView.PreviousCameraAsync();
return Task.FromResult(false);
}
#endregion
#region Project camera into a new spatial reference
public Task<Camera> ProjectCamera(Camera camera, ArcGIS.Core.Geometry.SpatialReference spatialReference)
{
return QueuedTask.Run(() =>
{
var mapPoint = MapPointBuilder.CreateMapPoint(camera.X, camera.Y, camera.Z, camera.SpatialReference);
var newPoint = GeometryEngine.Instance.Project(mapPoint, spatialReference) as MapPoint;
var newCamera = new Camera()
{
X = newPoint.X,
Y = newPoint.Y,
Z = newPoint.Z,
Scale = camera.Scale,
Pitch = camera.Pitch,
Heading = camera.Heading,
Roll = camera.Roll,
Viewpoint = camera.Viewpoint,
SpatialReference = spatialReference
};
return newCamera;
});
}
#endregion
#region Zoom to a bookmark with a given name
public Task<bool> ZoomToBookmarkAsync(string bookmarkName)
{
return QueuedTask.Run(() =>
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return false;
//Get the first bookmark with the given name.
var bookmark = mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name == bookmarkName);
if (bookmark == null)
return false;
//Zoom the view to the bookmark.
return mapView.ZoomTo(bookmark);
});
}
#endregion
#region ProSnippet Group: Bookmarks
#endregion
#region Create a new bookmark using the active map view
public Task<Bookmark> AddBookmarkAsync(string name)
{
return QueuedTask.Run(() =>
{
//Get the active map view.
var mapView = MapView.Active;
if (mapView == null)
return null;
//Adding a new bookmark using the active view.
return mapView.Map.AddBookmark(mapView, name);
});
}
#endregion
#region Remove bookmark with a given name
public Task RemoveBookmarkAsync(Map map, string name)
{
return QueuedTask.Run(() =>
{
//Find the first bookmark with the name
var bookmark = map.GetBookmarks().FirstOrDefault(b => b.Name == name);
if (bookmark == null)
return;
//Remove the bookmark
map.RemoveBookmark(bookmark);
});
}
#endregion
#region Get the collection of bookmarks for the project
public Task<ReadOnlyObservableCollection<Bookmark>> GetProjectBookmarksAsync()
{
//Get the collection of bookmarks for the project.
return QueuedTask.Run(() => Project.Current.GetBookmarks());
}
#endregion
#region Change the thumbnail for a bookmark
public Task SetThumbnailAsync(Bookmark bookmark, string imagePath)
{
//Set the thumbnail to an image on disk, ie. C:\Pictures\MyPicture.png.
BitmapImage image = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));
return QueuedTask.Run(() => bookmark.SetThumbnail(image));
}
#endregion
#region ProSnippet Group: Time
#endregion
#region Step forward in time by 1 month
public void StepMapTime()
{
//Get the active view
MapView mapView = MapView.Active;
if (mapView == null)
return;
//Step current map time forward by 1 month
TimeDelta timeDelta = new TimeDelta(1, TimeUnit.Months);
mapView.Time = mapView.Time.Offset(timeDelta);
}
#endregion
public void DisableTime()
{
#region Disable time in the map.
MapView.Active.Time.Start = null;
MapView.Active.Time.End = null;
#endregion
}
#region ProSnippet Group: Graphic overlay
#endregion
#region Graphic Overlay
//Defined elsewhere
private IDisposable _graphic = null;
public async void GraphicOverlaySnippetTest()
{
// get the current mapview and point
var mapView = MapView.Active;
if (mapView == null)
return;
var myextent = mapView.Extent;
var point = myextent.Center;
// add point graphic to the overlay at the center of the mapView
_graphic = await QueuedTask.Run(() =>
{
//add these to the overlay
return mapView.AddOverlay(point,
SymbolFactory.Instance.ConstructPointSymbol(
ColorFactory.Instance.RedRGB, 30.0, SimpleMarkerStyle.Star).MakeSymbolReference());
});
// update the overlay with new point graphic symbol
MessageBox.Show("Now to update the overlay...");
await QueuedTask.Run(() =>
{
mapView.UpdateOverlay(_graphic, point, SymbolFactory.Instance.ConstructPointSymbol(
ColorFactory.Instance.BlueRGB, 20.0, SimpleMarkerStyle.Circle).MakeSymbolReference());
});
// clear the overlay display by disposing of the graphic
MessageBox.Show("Now to clear the overlay...");
_graphic.Dispose();
}
#endregion
public void CIMPictureGraphicOverlay(Geometry geometry, ArcGIS.Core.Geometry.Envelope envelope)
{
#region Graphic Overlay with CIMPictureGraphic
// get the current mapview
var mapView = MapView.Active;
if (mapView == null)
return;
//Valid formats for PictureURL are:
// e.g. local file URL:
// file:///<path>
// file:///c:/images/symbol.png
//
// e.g. network file URL:
// file://<host>/<path>
// file://server/share/symbol.png
//
// e.g. data URL:
// data:<mediatype>;base64,<data>
// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAU ...
//
// image/bmp
// image/gif
// image/jpeg
// image/png
// image/tiff
// image/x-esri-bglf
var pictureGraphic = new CIMPictureGraphic
{
PictureURL = @"file:///C:/Images/MyImage.png",
Box = envelope
};
IDisposable _graphic = mapView.AddOverlay(pictureGraphic);
#endregion
}
#region Add overlay graphic with text
internal class AddOverlayWithText : MapTool
{
private IDisposable _graphic = null;
private CIMLineSymbol _lineSymbol = null;
public AddOverlayWithText()
{
IsSketchTool = true;
SketchType = SketchGeometryType.Line;
SketchOutputMode = SketchOutputMode.Map;
}
protected override async Task<bool> OnSketchCompleteAsync(Geometry geometry)
{
//Add an overlay graphic to the map view
_graphic = await this.AddOverlayAsync(geometry, _lineSymbol.MakeSymbolReference());
//define the text symbol
var textSymbol = new CIMTextSymbol();
//define the text graphic
var textGraphic = new CIMTextGraphic();
await QueuedTask.Run(() =>
{
//Create a simple text symbol
textSymbol = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB, 8.5, "Corbel", "Regular");
//Sets the geometry of the text graphic
textGraphic.Shape = geometry;
//Sets the text string to use in the text graphic
textGraphic.Text = "This is my line";
//Sets symbol to use to draw the text graphic
textGraphic.Symbol = textSymbol.MakeSymbolReference();
//Draw the overlay text graphic
_graphic = this.ActiveMapView.AddOverlay(textGraphic);
});
return true;
}
}
#endregion
#region ProSnippet Group: Tools
#endregion
#region Change symbol for a sketch tool
internal class SketchTool_WithSymbol : MapTool
{
public SketchTool_WithSymbol()
{
IsSketchTool = true;
SketchOutputMode = SketchOutputMode.Map; //Changing the Sketch Symbol is only supported with map sketches.
SketchType = SketchGeometryType.Rectangle;
}
protected override Task OnToolActivateAsync(bool hasMapViewChanged)
{
return QueuedTask.Run(() =>
{
//Set the Sketch Symbol if it hasn't already been set.
if (SketchSymbol != null)
return;
var polygonSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.CreateRGBColor(24, 69, 59),
SimpleFillStyle.Solid,
SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 1.0, SimpleLineStyle.Dash));
SketchSymbol = polygonSymbol.MakeSymbolReference();
});
}
}
#endregion
#region Create a tool to the return coordinates of the point clicked in the map
internal class GetMapCoordinates : MapTool
{
protected override void OnToolMouseDown(MapViewMouseButtonEventArgs e)
{
if (e.ChangedButton == System.Windows.Input.MouseButton.Left)
e.Handled = true; //Handle the event args to get the call to the corresponding async method
}
protected override Task HandleMouseDownAsync(MapViewMouseButtonEventArgs e)
{
return QueuedTask.Run(() =>
{
//Convert the clicked point in client coordinates to the corresponding map coordinates.
var mapPoint = MapView.Active.ClientToMap(e.ClientPoint);
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(string.Format("X: {0} Y: {1} Z: {2}",
mapPoint.X, mapPoint.Y, mapPoint.Z), "Map Coordinates");
});
}
}
#endregion
#region Create a tool to identify the features that intersect the sketch geometry
internal class CustomIdentify : MapTool
{
public CustomIdentify()
{
IsSketchTool = true;
SketchType = SketchGeometryType.Rectangle;
//To perform a interactive selection or identify in 3D or 2D, sketch must be created in screen coordinates.
SketchOutputMode = SketchOutputMode.Screen;
}
protected override Task<bool> OnSketchCompleteAsync(Geometry geometry)
{
return QueuedTask.Run(() =>
{
var mapView = MapView.Active;
if (mapView == null)
return true;
//Get all the features that intersect the sketch geometry and flash them in the view.
var results = mapView.GetFeatures(geometry);
mapView.FlashFeature(results);
//Show a message box reporting each layer the number of the features.
MessageBox.Show(
String.Join("\n", results.Select(kvp => String.Format("{0}: {1}", kvp.Key.Name, kvp.Value.Count()))),
"Identify Result");
return true;
});
}
}
#endregion
#region Change the cursor of a Tool
internal class CustomMapTool : MapTool
{
public CustomMapTool()
{
IsSketchTool = true;
SketchType = SketchGeometryType.Rectangle;
SketchOutputMode = SketchOutputMode.Map;
//A custom cursor file as an embedded resource
var cursorEmbeddedResource = new Cursor(new MemoryStream(MapExploration.Resource1.red_cursor));
//A built in system cursor
var systemCursor = System.Windows.Input.Cursors.ArrowCD;
//Set the "CustomMapTool's" Cursor property to either one of the cursors defined above
Cursor = cursorEmbeddedResource;
//or
Cursor = systemCursor;
}
#endregion
protected override Task OnToolActivateAsync(bool active)
{
return base.OnToolActivateAsync(active);
}
protected override Task<bool> OnSketchCompleteAsync(Geometry geometry)
{
return base.OnSketchCompleteAsync(geometry);
}
}
}
}
| |
using Core.Common.MVVM;
using Core.Common.Reflect;
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Core.Common.MVVM
{
public static class Command
{
public static string GetCommandName(this MethodInfo method)
{
return GetCommandAttributeOrDefault(method).CommandName;
}
public static string DisplayType(this MethodInfo method)
{
return GetCommandAttributeOrDefault(method).DisplayType;
}
public static CommandAttribute GetCommandAttributeOrDefault(this MethodInfo method)
{
var attr = method.GetCustomAttribute<CommandAttribute>() ?? new CommandAttribute();
if (string.IsNullOrEmpty(attr.CommandName)) attr.CommandName = method.Name;
return attr;
}
public static MethodInfo GetCommandMethod(this Type type, string commandName)
{
var methods = type.MethodsWith<CommandAttribute>().ToArray();
methods = methods.Where(m => GetCommandAttributeOrDefault(m.Item1).CommandName == commandName).ToArray();
if (methods.Count() == 0)
{
methods = type.GetMethods()
.Where(m => m.Name == commandName)
.Select(m => Tuple.Create(m, new CommandAttribute(commandName)))
.ToArray();
}
if (methods.Count() == 0) return null;
if (methods.Count() > 1) return null;
var method = methods.SingleOrDefault();
return method.Item1;
}
public static DelegateCommand[] ReflectCommands(object instance)
{
if (instance == null) throw new ArgumentNullException();
var type = instance.GetType();
var methods = type.GetCommandMethods();
var commands = methods.Select(cmd => Command.Reflect(instance, cmd)).ToArray();
return commands;
}
public static MethodInfo[] GetCommandMethods(this Type type)
{
var commandMethods = type
.GetMethods()
.Where(m => m.IsPublic && m.GetParameters().Count() == 0 && m.GetCustomAttributes(typeof(CommandAttribute), true).Any())
.ToArray();
return commandMethods;
}
// needs to evaluate the arguments in calling thread.
//
public static Task ExecuteMethodLazy(object target, MethodInfo method, object[] parameters)
{
Task task = null;
try
{
var methodParameters = method.GetParameters();
var result = method.Invoke(target, parameters.ConcatOne(Enumerable.Repeat<object>(null, methodParameters.Length)).Take(methodParameters.Length).ToArray());
if (result is Task)
{
task = result as Task;
}
else
{
task = Task.Factory.StartNew(() => result, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}
}
catch (Exception e)
{
task = Task.Factory.StartNew(() => { throw e; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}
return task;
}
public static DelegateCommand Reflect(Delegate @delegate, MethodInfo canExecute)
{
Func<object, bool> canExecutePredicate = null;
if (canExecute != null)
{
if (!typeof(bool).IsAssignableFrom(canExecute.ReturnType))
{
throw new InvalidOperationException("can execute method needs to return a bool");
}
switch (canExecute.GetParameters().Count())
{
case 0:
canExecutePredicate = param => (bool)canExecute.Invoke(@delegate.Target, new object[0]);
break;
case 1:
canExecutePredicate = param => (bool)canExecute.Invoke(@delegate.Target, new object[] { param });
break;
default:
throw new NotImplementedException("multiple parameters are currently not implemented");
}
}
else
{
canExecutePredicate = o => true;
}
var result = new DelegateCommand(@delegate, canExecutePredicate);
var attribute = @delegate.Method.GetCommandAttributeOrDefault();
result.AllowConcurrentExecution = attribute.AllowConcurrentExecution;
return result;
}
public static DelegateCommand Reflect(object source, MethodInfo method)
{
var del = method.CreateDelegate(source);
return Reflect(del);
}
public static DelegateCommand Reflect(Delegate del)
{
var target = del.Target;
var method = del.Method;
var type = method.ReflectedType;
var commandName = method.Name;
var canExecuteName = commandName + "CanExecute";
var canExecute = type.GetMethod(canExecuteName);
bool isProperty = false;
if (canExecute == null)
{
var prop = type.GetProperty(canExecuteName);
if (prop != null)
{
canExecute = prop.GetAccessors().SingleOrDefault(m => m.Name.StartsWith("get_"));
if (canExecute != null) { isProperty = true; }
}
}
var result = Reflect(del, canExecute);
if (isProperty)
{
var notify = target as INotifyPropertyChanged;
if (notify != null)
{
notify.PropertyChanged += (sender, args) =>
{
if (args.PropertyName == canExecuteName)
{
result.RaiseCanExecuteChanged();
}
};
}
}
return result;
}
public static DelegateCommand Reflect(object source, string commandName)
{
if (source == null) return null;
var type = source.GetType();
var method = GetCommandMethod(type, commandName);
if (method == null) return null;
return Reflect(source, method);
}
public static DelegateCommand CreateCommand(Action del)
{
return Reflect(del.Target, del.Method);
}
public static DelegateCommand CreateCommand<T>(Func<T> del)
{
return Reflect(del.Target, del.Method);
}
public static DelegateCommand CreateCommand<T>(Action<T> del)
{
return Reflect(del.Target, del.Method);
}
public static DelegateCommand CreateCommand(object target, MethodInfo methodInfo)
{
return Command.Reflect(target, methodInfo);
}
}
}
| |
using NBitcoin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Backend.Controllers;
using WalletWasabi.Backend.Models;
using WalletWasabi.Backend.Models.Responses;
using WalletWasabi.BitcoinCore.Rpc;
using WalletWasabi.Blockchain.BlockFilters;
using WalletWasabi.Blockchain.Blocks;
using WalletWasabi.Logging;
using WalletWasabi.Tests.XunitConfiguration;
using WalletWasabi.Tor.Http;
using WalletWasabi.Tor.Http.Extensions;
using WalletWasabi.WebClients.Wasabi;
using Xunit;
namespace WalletWasabi.Tests.RegressionTests
{
[Collection("RegTest collection")]
public class BackendTests
{
public BackendTests(RegTestFixture regTestFixture)
{
RegTestFixture = regTestFixture;
BackendHttpClient = new ClearnetHttpClient(() => RegTestFixture.BackendEndPointUri);
BackendApiHttpClient = new ClearnetHttpClient(() => RegTestFixture.BackendEndPointApiUri);
}
private RegTestFixture RegTestFixture { get; }
/// <summary>Clearnet HTTP client with predefined base URI for Wasabi Backend (note: <c>/api</c> is not part of base URI).</summary>
public IHttpClient BackendHttpClient { get; }
/// <summary>Clearnet HTTP client with predefined base URI for Wasabi Backend API queries.</summary>
private IHttpClient BackendApiHttpClient { get; }
#region BackendTests
[Fact]
public async Task GetExchangeRatesAsync()
{
using var response = await BackendApiHttpClient.SendAsync(HttpMethod.Get, "btc/offchain/exchange-rates");
Assert.True(response.StatusCode == HttpStatusCode.OK);
var exchangeRates = await response.Content.ReadAsJsonAsync<List<ExchangeRate>>();
Assert.Single(exchangeRates);
var rate = exchangeRates[0];
Assert.Equal("USD", rate.Ticker);
Assert.True(rate.Rate > 0);
}
[Fact]
public async Task GetClientVersionAsync()
{
var client = new WasabiClient(BackendHttpClient);
var uptodate = await client.CheckUpdatesAsync(CancellationToken.None);
Assert.True(uptodate.BackendCompatible);
Assert.True(uptodate.ClientUpToDate);
}
[Fact]
public async Task BroadcastReplayTxAsync()
{
(_, IRPCClient rpc, _, _, _, _, _) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);
var utxos = await rpc.ListUnspentAsync();
var utxo = utxos[0];
var tx = await rpc.GetRawTransactionAsync(utxo.OutPoint.Hash);
using StringContent content = new($"'{tx.ToHex()}'", Encoding.UTF8, "application/json");
Logger.TurnOff();
using var response = await BackendApiHttpClient.SendAsync(HttpMethod.Post, "btc/blockchain/broadcast", content);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("Transaction is already in the blockchain.", await response.Content.ReadAsJsonAsync<string>());
Logger.TurnOn();
}
[Fact]
public async Task BroadcastInvalidTxAsync()
{
await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);
using StringContent content = new($"''", Encoding.UTF8, "application/json");
Logger.TurnOff();
using var response = await BackendApiHttpClient.SendAsync(HttpMethod.Post, "btc/blockchain/broadcast", content);
Assert.NotEqual(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Contains("The hex field is required.", await response.Content.ReadAsStringAsync());
Logger.TurnOn();
}
[Fact]
public async Task FilterBuilderTestAsync()
{
(_, IRPCClient rpc, _, _, _, _, Backend.Global global) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);
var indexBuilderServiceDir = Helpers.Common.GetWorkDir();
var indexFilePath = Path.Combine(indexBuilderServiceDir, $"Index{rpc.Network}.dat");
var indexBuilderService = new IndexBuilderService(rpc, global.HostedServices.FirstOrDefault<BlockNotifier>(), indexFilePath);
try
{
indexBuilderService.Synchronize();
// Test initial synchronization.
var times = 0;
uint256 firstHash = await rpc.GetBlockHashAsync(0);
while (indexBuilderService.GetFilterLinesExcluding(firstHash, 101, out _).filters.Count() != 101)
{
if (times > 500) // 30 sec
{
throw new TimeoutException($"{nameof(IndexBuilderService)} test timed out.");
}
await Task.Delay(100);
times++;
}
// Test later synchronization.
await rpc.GenerateAsync(10);
times = 0;
while (indexBuilderService.GetFilterLinesExcluding(firstHash, 111, out bool found5).filters.Count() != 111)
{
Assert.True(found5);
if (times > 500) // 30 sec
{
throw new TimeoutException($"{nameof(IndexBuilderService)} test timed out.");
}
await Task.Delay(100);
times++;
}
// Test correct number of filters is received.
var hundredthHash = await rpc.GetBlockHashAsync(100);
Assert.Equal(11, indexBuilderService.GetFilterLinesExcluding(hundredthHash, 11, out bool found).filters.Count());
Assert.True(found);
var bestHash = await rpc.GetBestBlockHashAsync();
Assert.Empty(indexBuilderService.GetFilterLinesExcluding(bestHash, 1, out bool found2).filters);
Assert.Empty(indexBuilderService.GetFilterLinesExcluding(uint256.Zero, 1, out bool found3).filters);
Assert.False(found3);
// Test filter block hashes are correct.
var filters = indexBuilderService.GetFilterLinesExcluding(firstHash, 111, out bool found4).filters.ToArray();
Assert.True(found4);
for (int i = 0; i < 111; i++)
{
var expectedHash = await rpc.GetBlockHashAsync(i + 1);
var filterModel = filters[i];
Assert.Equal(expectedHash, filterModel.Header.BlockHash);
}
}
finally
{
if (indexBuilderService is { })
{
await indexBuilderService.StopAsync();
}
}
}
[Fact]
public async Task StatusRequestTestAsync()
{
var requestUri = "btc/Blockchain/status";
(_, IRPCClient rpc, _, _, _, _, Backend.Global global) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);
var indexBuilderService = global.IndexBuilderService;
try
{
indexBuilderService.Synchronize();
// Test initial synchronization.
var times = 0;
uint256 firstHash = await rpc.GetBlockHashAsync(0);
while (indexBuilderService.GetFilterLinesExcluding(firstHash, 101, out _).filters.Count() != 101)
{
if (times > 500) // 30 sec
{
throw new TimeoutException($"{nameof(IndexBuilderService)} test timed out.");
}
await Task.Delay(100);
times++;
}
// First request.
using (HttpResponseMessage response = await BackendApiHttpClient.SendAsync(HttpMethod.Get, requestUri))
{
Assert.NotNull(response);
var resp = await response.Content.ReadAsJsonAsync<StatusResponse>();
Assert.True(resp.FilterCreationActive);
// Simulate an unintended stop
await indexBuilderService.StopAsync();
indexBuilderService = null;
await rpc.GenerateAsync(1);
}
// Second request.
using (HttpResponseMessage response = await BackendApiHttpClient.SendAsync(HttpMethod.Get, requestUri))
{
Assert.NotNull(response);
var resp = await response.Content.ReadAsJsonAsync<StatusResponse>();
Assert.True(resp.FilterCreationActive);
await rpc.GenerateAsync(1);
var blockchainController = (BlockchainController)RegTestFixture.BackendHost.Services.GetService(typeof(BlockchainController))!;
blockchainController.Cache.Remove($"{nameof(BlockchainController.GetStatusAsync)}");
// Set back the time to trigger timeout in BlockchainController.GetStatusAsync.
global.IndexBuilderService.LastFilterBuildTime = DateTimeOffset.UtcNow - BlockchainController.FilterTimeout;
}
// Third request.
using (HttpResponseMessage response = await BackendApiHttpClient.SendAsync(HttpMethod.Get, requestUri))
{
Assert.NotNull(response);
var resp = await response.Content.ReadAsJsonAsync<StatusResponse>();
Assert.False(resp.FilterCreationActive);
}
}
finally
{
if (indexBuilderService is { })
{
await indexBuilderService.StopAsync();
}
}
}
#endregion BackendTests
}
}
| |
using Content.Server.DoAfter;
using Content.Server.Kitchen.Components;
using Content.Server.Nutrition.Components;
using Content.Server.Popups;
using Content.Shared.DragDrop;
using Content.Shared.Interaction;
using Content.Shared.MobState.Components;
using Content.Shared.Nutrition.Components;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Player;
using System;
using static Content.Shared.Kitchen.Components.SharedKitchenSpikeComponent;
namespace Content.Server.Kitchen.EntitySystems
{
internal sealed class KitchenSpikeSystem : EntitySystem
{
[Dependency] private readonly PopupSystem _popupSystem = default!;
[Dependency] private readonly DoAfterSystem _doAfter = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<KitchenSpikeComponent, InteractUsingEvent>(OnInteractUsing);
SubscribeLocalEvent<KitchenSpikeComponent, InteractHandEvent>(OnInteractHand);
SubscribeLocalEvent<KitchenSpikeComponent, DragDropEvent>(OnDragDrop);
//DoAfter
SubscribeLocalEvent<KitchenSpikeComponent, SpikingFinishedEvent>(OnSpikingFinished);
SubscribeLocalEvent<KitchenSpikeComponent, SpikingFailEvent>(OnSpikingFail);
}
private void OnSpikingFail(EntityUid uid, KitchenSpikeComponent component, SpikingFailEvent args)
{
component.InUse = false;
if (EntityManager.TryGetComponent<SharedButcherableComponent>(args.VictimUid, out var butcherable))
butcherable.BeingButchered = false;
}
private void OnSpikingFinished(EntityUid uid, KitchenSpikeComponent component, SpikingFinishedEvent args)
{
component.InUse = false;
if (EntityManager.TryGetComponent<SharedButcherableComponent>(args.VictimUid, out var butcherable))
butcherable.BeingButchered = false;
if (Spikeable(uid, args.UserUid, args.VictimUid, component, butcherable))
{
Spike(uid, args.UserUid, args.VictimUid, component);
}
}
private void OnDragDrop(EntityUid uid, KitchenSpikeComponent component, DragDropEvent args)
{
if(args.Handled)
return;
if (!Spikeable(uid, args.User, args.Dragged, component))
return;
if (TrySpike(uid, args.User, args.Dragged, component))
args.Handled = true;
}
private void OnInteractHand(EntityUid uid, KitchenSpikeComponent component, InteractHandEvent args)
{
if (args.Handled)
return;
if (component.MeatParts > 0) {
_popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-knife-needed"), uid, Filter.Entities(args.User));
args.Handled = true;
}
}
private void OnInteractUsing(EntityUid uid, KitchenSpikeComponent component, InteractUsingEvent args)
{
if (args.Handled)
return;
if (TryGetPiece(uid, args.User, args.Used))
args.Handled = true;
}
private void Spike(EntityUid uid, EntityUid userUid, EntityUid victimUid,
KitchenSpikeComponent? component = null, SharedButcherableComponent? butcherable = null)
{
if (!Resolve(uid, ref component) || !Resolve(victimUid, ref butcherable))
return;
component.MeatPrototype = butcherable.SpawnedPrototype;
component.MeatParts = butcherable.Pieces;
// This feels not okay, but entity is getting deleted on "Spike", for now...
component.MeatSource1p = Loc.GetString("comp-kitchen-spike-remove-meat", ("victim", victimUid));
component.MeatSource0 = Loc.GetString("comp-kitchen-spike-remove-meat-last", ("victim", victimUid));
component.MeatName = Loc.GetString("comp-kitchen-spike-meat-name", ("victim", victimUid));
UpdateAppearance(uid, null, component);
_popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-kill", ("user", userUid), ("victim", victimUid)), uid, Filter.Pvs(userUid));
// THE WHAT?
// TODO: Need to be able to leave them on the spike to do DoT, see ss13.
EntityManager.QueueDeleteEntity(victimUid);
SoundSystem.Play(Filter.Pvs(uid), component.SpikeSound.GetSound(), uid);
}
private bool TryGetPiece(EntityUid uid, EntityUid user, EntityUid used,
KitchenSpikeComponent? component = null, UtensilComponent? utensil = null)
{
if (!Resolve(uid, ref component) || component.MeatParts == 0)
return false;
// Is using knife
if (!Resolve(used, ref utensil, false) || (utensil.Types & UtensilType.Knife) == 0)
{
return false;
}
component.MeatParts--;
if (!string.IsNullOrEmpty(component.MeatPrototype))
{
var meat = EntityManager.SpawnEntity(component.MeatPrototype, Transform(uid).Coordinates);
MetaData(meat).EntityName = component.MeatName;
}
if (component.MeatParts != 0)
{
_popupSystem.PopupEntity(component.MeatSource1p, uid, Filter.Entities(user));
}
else
{
UpdateAppearance(uid, null, component);
_popupSystem.PopupEntity(component.MeatSource0, uid, Filter.Entities(user));
}
return true;
}
private void UpdateAppearance(EntityUid uid, AppearanceComponent? appearance = null, KitchenSpikeComponent? component = null)
{
if (!Resolve(uid, ref component, ref appearance, false))
return;
appearance.SetData(KitchenSpikeVisuals.Status, (component.MeatParts > 0) ? KitchenSpikeStatus.Bloody : KitchenSpikeStatus.Empty);
}
private bool Spikeable(EntityUid uid, EntityUid userUid, EntityUid victimUid,
KitchenSpikeComponent? component = null, SharedButcherableComponent? butcherable = null)
{
if (!Resolve(uid, ref component))
return false;
if (component.MeatParts > 0)
{
_popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-deny-collect", ("this", uid)), uid, Filter.Entities(userUid));
return false;
}
if (!Resolve(victimUid, ref butcherable, false) || butcherable.SpawnedPrototype == null)
{
_popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-deny-butcher", ("victim", victimUid), ("this", uid)), victimUid, Filter.Entities(userUid));
return false;
}
return true;
}
public bool TrySpike(EntityUid uid, EntityUid userUid, EntityUid victimUid, KitchenSpikeComponent? component = null,
SharedButcherableComponent? butcherable = null, MobStateComponent? mobState = null)
{
if (!Resolve(uid, ref component) || component.InUse ||
!Resolve(victimUid, ref butcherable) || butcherable.BeingButchered)
return false;
if (butcherable.Type != ButcheringType.Spike)
return false;
// THE WHAT? (again)
// Prevent dead from being spiked TODO: Maybe remove when rounds can be played and DOT is implemented
if (Resolve(victimUid, ref mobState, false) &&
!mobState.IsDead())
{
_popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-deny-not-dead", ("victim", victimUid)),
victimUid, Filter.Entities(userUid));
return true;
}
if (userUid != victimUid)
{
_popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-begin-hook-victim", ("user", userUid), ("this", uid)), victimUid, Filter.Entities(victimUid));
}
// TODO: make it work when SuicideEvent is implemented
// else
// _popupSystem.PopupEntity(Loc.GetString("comp-kitchen-spike-begin-hook-self", ("this", uid)), victimUid, Filter.Pvs(uid)); // This is actually unreachable and should be in SuicideEvent
butcherable.BeingButchered = true;
component.InUse = true;
var doAfterArgs = new DoAfterEventArgs(userUid, component.SpikeDelay + butcherable.ButcherDelay, default, uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
BreakOnDamage = true,
BreakOnStun = true,
NeedHand = true,
TargetFinishedEvent = new SpikingFinishedEvent(userUid, victimUid),
TargetCancelledEvent = new SpikingFailEvent(victimUid)
};
_doAfter.DoAfter(doAfterArgs);
return true;
}
private sealed class SpikingFinishedEvent : EntityEventArgs
{
public EntityUid VictimUid;
public EntityUid UserUid;
public SpikingFinishedEvent(EntityUid userUid, EntityUid victimUid)
{
UserUid = userUid;
VictimUid = victimUid;
}
}
private sealed class SpikingFailEvent : EntityEventArgs
{
public EntityUid VictimUid;
public SpikingFailEvent(EntityUid victimUid)
{
VictimUid = victimUid;
}
}
}
}
| |
// Copyright (CPOL) 2011 RikTheVeggie - see http://www.codeproject.com/info/cpol10.aspx
// Tri-State Tree View http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=202435
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace RikTheVeggie
{
// <summary>
// A Tri-State TreeView designed for on-demand populating of the tree
// </summary>
// <remarks>
// 'Mixed' nodes retain their checked state, meaning they can be checked or unchecked according to their current state
// Tree can be navigated by keyboard (cursor keys & space)
// No need to do anything special in calling code
// </remarks>
public class TriStateTreeView : TreeView
{
// <remarks>
// CheckedState is an enum of all allowable nodes states
// </remarks>
public enum CheckedState : int { UnInitialised = -1, UnChecked, Checked, Mixed };
// <remarks>
// IgnoreClickAction is used to ingore messages generated by setting the node.Checked flag in code
// Do not set <c>e.Cancel = true</c> in <c>OnBeforeCheck</c> otherwise the Checked state will be lost
// </remarks>
private int IgnoreClickAction = 0;
// <remarks>
// TriStateStyles is an enum of all allowable tree styles
// All styles check children when parent is checked
// Installer automatically checks parent if all children are checked, and unchecks parent if at least one child is unchecked
// Standard never changes the checked status of a parent
// </remarks>
public enum TriStateStyles : int { Standard = 0, Installer };
// Create a private member for the tree style, and allow it to be set on the property sheer
private TriStateStyles TriStateStyle = TriStateStyles.Standard;
[Category("Tri-State Tree View")]
[DisplayName("Style")]
[Description("Style of the Tri-State Tree View")]
public TriStateStyles TriStateStyleProperty
{
get { return TriStateStyle; }
set { TriStateStyle = value; }
}
// <summary>
// Constructor. Create and populate an image list
// </summary>
public TriStateTreeView() : base()
{
StateImageList = new ImageList();
// populate the image list, using images from the System.Windows.Forms.CheckBoxRenderer class
for (var i = 0; i < 3; i++)
{
// Create a bitmap which holds the relevent check box style
// see http://msdn.microsoft.com/en-us/library/ms404307.aspx and http://msdn.microsoft.com/en-us/library/system.windows.forms.checkboxrenderer.aspx
var bmp = new Bitmap(16, 16);
var chkGraphics = Graphics.FromImage(bmp);
switch ( i )
{
// 0,1 - offset the checkbox slightly so it positions in the correct place
case 0:
CheckBoxRenderer.DrawCheckBox(chkGraphics, new Point(0, 1), CheckBoxState.UncheckedNormal);
break;
case 1:
CheckBoxRenderer.DrawCheckBox(chkGraphics, new Point(0, 1), CheckBoxState.CheckedNormal);
break;
case 2:
CheckBoxRenderer.DrawCheckBox(chkGraphics, new Point(0, 1), CheckBoxState.MixedNormal);
break;
}
StateImageList.Images.Add(bmp);
}
}
// <summary>
// Called once before window displayed. Disables default Checkbox functionality and ensures all nodes display an 'unchecked' image.
// </summary>
protected override void OnCreateControl()
{
base.OnCreateControl();
CheckBoxes = false; // Disable default CheckBox functionality if it's been enabled
// Give every node an initial 'unchecked' image
IgnoreClickAction++; // we're making changes to the tree, ignore any other change requests
UpdateChildState(this.Nodes, (int)CheckedState.UnChecked, false, true);
IgnoreClickAction--;
}
// <summary>
// Called after a node is checked. Forces all children to inherit current state, and notifies parents they may need to become 'mixed'
// </summary>
protected override void OnAfterCheck(TreeViewEventArgs e)
{
base.OnAfterCheck(e);
if (IgnoreClickAction > 0)
{
return;
}
IgnoreClickAction++; // we're making changes to the tree, ignore any other change requests
// the checked state has already been changed, we just need to update the state index
// node is either ticked or unticked. ignore mixed state, as the node is still only ticked or unticked regardless of state of children
var tn = e.Node;
tn.StateImageIndex = tn.Checked ? (int)CheckedState.Checked : (int)CheckedState.UnChecked;
// force all children to inherit the same state as the current node
UpdateChildState(e.Node.Nodes, e.Node.StateImageIndex, e.Node.Checked, false);
// populate state up the tree, possibly resulting in parents with mixed state
UpdateParentState(e.Node.Parent);
IgnoreClickAction--;
}
// <summary>
// Called after a node is expanded. Ensures any new nodes display an 'unchecked' image
// </summary>
protected override void OnAfterExpand(TreeViewEventArgs e)
{
// If any child node is new, give it the same check state as the current node
// So if current node is ticked, child nodes will also be ticked
base.OnAfterExpand(e);
IgnoreClickAction++; // we're making changes to the tree, ignore any other change requests
UpdateChildState(e.Node.Nodes, e.Node.StateImageIndex, e.Node.Checked, true);
IgnoreClickAction--;
}
// <summary>
// Helper function to replace child state with that of the parent
// </summary>
protected void UpdateChildState(TreeNodeCollection Nodes, int StateImageIndex, bool Checked, bool ChangeUninitialisedNodesOnly)
{
foreach (TreeNode tnChild in Nodes)
{
if (!ChangeUninitialisedNodesOnly || tnChild.StateImageIndex == -1)
{
tnChild.StateImageIndex = StateImageIndex;
tnChild.Checked = Checked; // override 'checked' state of child with that of parent
if (tnChild.Nodes.Count > 0)
{
UpdateChildState(tnChild.Nodes, StateImageIndex, Checked, ChangeUninitialisedNodesOnly);
}
}
}
}
// <summary>
// Helper function to notify parent it may need to use 'mixed' state
// </summary>
protected void UpdateParentState(TreeNode tn)
{
// Node needs to check all of it's children to see if any of them are ticked or mixed
if (tn == null)
return;
var OrigStateImageIndex = tn.StateImageIndex;
int UnCheckedNodes = 0, CheckedNodes = 0, MixedNodes = 0;
// The parent needs to know how many of it's children are Checked or Mixed
foreach (TreeNode tnChild in tn.Nodes)
{
if (tnChild.StateImageIndex == (int)CheckedState.Checked)
CheckedNodes++;
else if (tnChild.StateImageIndex == (int)CheckedState.Mixed)
{
MixedNodes++;
break;
}
else
UnCheckedNodes++;
}
if (TriStateStyle == TriStateStyles.Installer)
{
// In Installer mode, if all child nodes are checked then parent is checked
// If at least one child is unchecked, then parent is unchecked
if (MixedNodes == 0)
{
if (UnCheckedNodes == 0)
{
// all children are checked, so parent must be checked
tn.Checked = true;
}
else
{
// at least one child is unchecked, so parent must be unchecked
tn.Checked = false;
}
}
}
// Determine the parent's new Image State
if (MixedNodes > 0)
{
// at least one child is mixed, so parent must be mixed
tn.StateImageIndex = (int)CheckedState.Mixed;
}
else if (CheckedNodes > 0 && UnCheckedNodes == 0)
{
// all children are checked
if (tn.Checked)
tn.StateImageIndex = (int)CheckedState.Checked;
else
tn.StateImageIndex = (int)CheckedState.Mixed;
}
else if (CheckedNodes > 0)
{
// some children are checked, the rest are unchecked
tn.StateImageIndex = (int)CheckedState.Mixed;
}
else
{
// all children are unchecked
if (tn.Checked)
tn.StateImageIndex = (int)CheckedState.Mixed;
else
tn.StateImageIndex = (int)CheckedState.UnChecked;
}
if (OrigStateImageIndex != tn.StateImageIndex && tn.Parent != null)
{
// Parent's state has changed, notify the parent's parent
UpdateParentState(tn.Parent);
}
}
// <summary>
// Called on keypress. Used to change node state when Space key is pressed
// Invokes OnAfterCheck to do the real work
// </summary>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
// is the keypress a space? If not, discard it
if (e.KeyCode == Keys.Space)
{
// toggle the node's checked status. This will then fire OnAfterCheck
SelectedNode.Checked = !SelectedNode.Checked;
}
}
// <summary>
// Called when node is clicked by the mouse. Does nothing unless the image was clicked
// Invokes OnAfterCheck to do the real work
// </summary>
protected override void OnNodeMouseClick(TreeNodeMouseClickEventArgs e)
{
base.OnNodeMouseClick(e);
// is the click on the checkbox? If not, discard it
var info = HitTest(e.X, e.Y);
if (info == null || info.Location != TreeViewHitTestLocations.StateImage)
{
return;
}
// toggle the node's checked status. This will then fire OnAfterCheck
var tn = e.Node;
tn.Checked = !tn.Checked;
}
}
}
| |
using J2N.Threading.Atomic;
using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
namespace Lucene.Net.Index
{
/*
* 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 BinaryDocValuesField = BinaryDocValuesField;
using BytesRef = Lucene.Net.Util.BytesRef;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using DocValuesConsumer = Lucene.Net.Codecs.DocValuesConsumer;
using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat;
using IBits = Lucene.Net.Util.IBits;
using IMutableBits = Lucene.Net.Util.IMutableBits;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using LiveDocsFormat = Lucene.Net.Codecs.LiveDocsFormat;
using NumericDocValuesField = NumericDocValuesField;
using TrackingDirectoryWrapper = Lucene.Net.Store.TrackingDirectoryWrapper;
/// <summary>
/// Used by <see cref="IndexWriter"/> to hold open <see cref="SegmentReader"/>s (for
/// searching or merging), plus pending deletes and updates,
/// for a given segment
/// </summary>
internal class ReadersAndUpdates
{
// Not final because we replace (clone) when we need to
// change it and it's been shared:
public SegmentCommitInfo Info { get; private set; }
// Tracks how many consumers are using this instance:
private readonly AtomicInt32 refCount = new AtomicInt32(1);
private readonly IndexWriter writer;
// Set once (null, and then maybe set, and never set again):
private SegmentReader reader;
// TODO: it's sometimes wasteful that we hold open two
// separate SRs (one for merging one for
// reading)... maybe just use a single SR? The gains of
// not loading the terms index (for merging in the
// non-NRT case) are far less now... and if the app has
// any deletes it'll open real readers anyway.
// Set once (null, and then maybe set, and never set again):
private SegmentReader mergeReader;
// Holds the current shared (readable and writable)
// liveDocs. this is null when there are no deleted
// docs, and it's copy-on-write (cloned whenever we need
// to change it but it's been shared to an external NRT
// reader).
private IBits liveDocs;
// How many further deletions we've done against
// liveDocs vs when we loaded it or last wrote it:
private int pendingDeleteCount;
// True if the current liveDocs is referenced by an
// external NRT reader:
private bool liveDocsShared;
// Indicates whether this segment is currently being merged. While a segment
// is merging, all field updates are also registered in the
// mergingNumericUpdates map. Also, calls to writeFieldUpdates merge the
// updates with mergingNumericUpdates.
// That way, when the segment is done merging, IndexWriter can apply the
// updates on the merged segment too.
private bool isMerging = false;
private readonly IDictionary<string, DocValuesFieldUpdates> mergingDVUpdates = new Dictionary<string, DocValuesFieldUpdates>();
public ReadersAndUpdates(IndexWriter writer, SegmentCommitInfo info)
{
this.Info = info;
this.writer = writer;
liveDocsShared = true;
}
public virtual void IncRef()
{
int rc = refCount.IncrementAndGet();
if (Debugging.AssertsEnabled) Debugging.Assert(rc > 1);
}
public virtual void DecRef()
{
int rc = refCount.DecrementAndGet();
if (Debugging.AssertsEnabled) Debugging.Assert(rc >= 0);
}
public virtual int RefCount()
{
int rc = refCount;
if (Debugging.AssertsEnabled) Debugging.Assert(rc >= 0);
return rc;
}
public virtual int PendingDeleteCount
{
get
{
lock (this)
{
return pendingDeleteCount;
}
}
}
// Call only from assert!
public virtual bool VerifyDocCounts()
{
lock (this)
{
int count;
if (liveDocs != null)
{
count = 0;
for (int docID = 0; docID < Info.Info.DocCount; docID++)
{
if (liveDocs.Get(docID))
{
count++;
}
}
}
else
{
count = Info.Info.DocCount;
}
if (Debugging.AssertsEnabled) Debugging.Assert(Info.Info.DocCount - Info.DelCount - pendingDeleteCount == count, () => "info.docCount=" + Info.Info.DocCount + " info.DelCount=" + Info.DelCount + " pendingDeleteCount=" + pendingDeleteCount + " count=" + count);
return true;
}
}
/// <summary>
/// Returns a <see cref="SegmentReader"/>. </summary>
public virtual SegmentReader GetReader(IOContext context)
{
if (reader == null)
{
// We steal returned ref:
reader = new SegmentReader(Info, writer.Config.ReaderTermsIndexDivisor, context);
if (liveDocs == null)
{
liveDocs = reader.LiveDocs;
}
}
// Ref for caller
reader.IncRef();
return reader;
}
// Get reader for merging (does not load the terms
// index):
public virtual SegmentReader GetMergeReader(IOContext context)
{
lock (this)
{
//System.out.println(" livedocs=" + rld.liveDocs);
if (mergeReader == null)
{
if (reader != null)
{
// Just use the already opened non-merge reader
// for merging. In the NRT case this saves us
// pointless double-open:
//System.out.println("PROMOTE non-merge reader seg=" + rld.info);
// Ref for us:
reader.IncRef();
mergeReader = reader;
//System.out.println(Thread.currentThread().getName() + ": getMergeReader share seg=" + info.name);
}
else
{
//System.out.println(Thread.currentThread().getName() + ": getMergeReader seg=" + info.name);
// We steal returned ref:
mergeReader = new SegmentReader(Info, -1, context);
if (liveDocs == null)
{
liveDocs = mergeReader.LiveDocs;
}
}
}
// Ref for caller
mergeReader.IncRef();
return mergeReader;
}
}
public virtual void Release(SegmentReader sr)
{
lock (this)
{
if (Debugging.AssertsEnabled) Debugging.Assert(Info == sr.SegmentInfo);
sr.DecRef();
}
}
public virtual bool Delete(int docID)
{
lock (this)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(liveDocs != null);
Debugging.Assert(Monitor.IsEntered(writer));
Debugging.Assert(docID >= 0 && docID < liveDocs.Length, () => "out of bounds: docid=" + docID + " liveDocsLength=" + liveDocs.Length + " seg=" + Info.Info.Name + " docCount=" + Info.Info.DocCount);
Debugging.Assert(!liveDocsShared);
}
bool didDelete = liveDocs.Get(docID);
if (didDelete)
{
((IMutableBits)liveDocs).Clear(docID);
pendingDeleteCount++;
//System.out.println(" new del seg=" + info + " docID=" + docID + " pendingDelCount=" + pendingDeleteCount + " totDelCount=" + (info.docCount-liveDocs.count()));
}
return didDelete;
}
}
// NOTE: removes callers ref
public virtual void DropReaders()
{
lock (this)
{
// TODO: can we somehow use IOUtils here...? problem is
// we are calling .decRef not .close)...
try
{
if (reader != null)
{
//System.out.println(" pool.drop info=" + info + " rc=" + reader.getRefCount());
try
{
reader.DecRef();
}
finally
{
reader = null;
}
}
}
finally
{
if (mergeReader != null)
{
//System.out.println(" pool.drop info=" + info + " merge rc=" + mergeReader.getRefCount());
try
{
mergeReader.DecRef();
}
finally
{
mergeReader = null;
}
}
}
DecRef();
}
}
/// <summary>
/// Returns a ref to a clone. NOTE: you should <see cref="DecRef()"/> the reader when you're
/// done (ie do not call <see cref="IndexReader.Dispose()"/>).
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public virtual SegmentReader GetReadOnlyClone(IOContext context)
{
lock (this)
{
if (reader == null)
{
GetReader(context).DecRef();
if (Debugging.AssertsEnabled) Debugging.Assert(reader != null);
}
liveDocsShared = true;
if (liveDocs != null)
{
return new SegmentReader(reader.SegmentInfo, reader, liveDocs, Info.Info.DocCount - Info.DelCount - pendingDeleteCount);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(reader.LiveDocs == liveDocs);
reader.IncRef();
return reader;
}
}
}
public virtual void InitWritableLiveDocs()
{
lock (this)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(Monitor.IsEntered(writer));
Debugging.Assert(Info.Info.DocCount > 0);
}
//System.out.println("initWritableLivedocs seg=" + info + " liveDocs=" + liveDocs + " shared=" + shared);
if (liveDocsShared)
{
// Copy on write: this means we've cloned a
// SegmentReader sharing the current liveDocs
// instance; must now make a private clone so we can
// change it:
LiveDocsFormat liveDocsFormat = Info.Info.Codec.LiveDocsFormat;
if (liveDocs == null)
{
//System.out.println("create BV seg=" + info);
liveDocs = liveDocsFormat.NewLiveDocs(Info.Info.DocCount);
}
else
{
liveDocs = liveDocsFormat.NewLiveDocs(liveDocs);
}
liveDocsShared = false;
}
}
}
public virtual IBits LiveDocs
{
get
{
lock (this)
{
if (Debugging.AssertsEnabled) Debugging.Assert(Monitor.IsEntered(writer));
return liveDocs;
}
}
}
public virtual IBits GetReadOnlyLiveDocs()
{
lock (this)
{
//System.out.println("getROLiveDocs seg=" + info);
if (Debugging.AssertsEnabled) Debugging.Assert(Monitor.IsEntered(writer));
liveDocsShared = true;
//if (liveDocs != null) {
//System.out.println(" liveCount=" + liveDocs.count());
//}
return liveDocs;
}
}
public virtual void DropChanges()
{
lock (this)
{
// Discard (don't save) changes when we are dropping
// the reader; this is used only on the sub-readers
// after a successful merge. If deletes had
// accumulated on those sub-readers while the merge
// is running, by now we have carried forward those
// deletes onto the newly merged segment, so we can
// discard them on the sub-readers:
pendingDeleteCount = 0;
DropMergingUpdates();
}
}
// Commit live docs (writes new _X_N.del files) and field updates (writes new
// _X_N updates files) to the directory; returns true if it wrote any file
// and false if there were no new deletes or updates to write:
// TODO (DVU_RENAME) to writeDeletesAndUpdates
[MethodImpl(MethodImplOptions.NoInlining)]
public virtual bool WriteLiveDocs(Directory dir)
{
lock (this)
{
if (Debugging.AssertsEnabled) Debugging.Assert(Monitor.IsEntered(writer));
//System.out.println("rld.writeLiveDocs seg=" + info + " pendingDelCount=" + pendingDeleteCount + " numericUpdates=" + numericUpdates);
if (pendingDeleteCount == 0)
{
return false;
}
// We have new deletes
if (Debugging.AssertsEnabled) Debugging.Assert(liveDocs.Length == Info.Info.DocCount);
// Do this so we can delete any created files on
// exception; this saves all codecs from having to do
// it:
TrackingDirectoryWrapper trackingDir = new TrackingDirectoryWrapper(dir);
// We can write directly to the actual name (vs to a
// .tmp & renaming it) because the file is not live
// until segments file is written:
bool success = false;
try
{
Codec codec = Info.Info.Codec;
codec.LiveDocsFormat.WriteLiveDocs((IMutableBits)liveDocs, trackingDir, Info, pendingDeleteCount, IOContext.DEFAULT);
success = true;
}
finally
{
if (!success)
{
// Advance only the nextWriteDelGen so that a 2nd
// attempt to write will write to a new file
Info.AdvanceNextWriteDelGen();
// Delete any partially created file(s):
foreach (string fileName in trackingDir.CreatedFiles)
{
try
{
dir.DeleteFile(fileName);
}
catch (Exception)
{
// Ignore so we throw only the first exc
}
}
}
}
// If we hit an exc in the line above (eg disk full)
// then info's delGen remains pointing to the previous
// (successfully written) del docs:
Info.AdvanceDelGen();
Info.DelCount = Info.DelCount + pendingDeleteCount;
pendingDeleteCount = 0;
return true;
}
}
// Writes field updates (new _X_N updates files) to the directory
[MethodImpl(MethodImplOptions.NoInlining)]
public virtual void WriteFieldUpdates(Directory dir, DocValuesFieldUpdates.Container dvUpdates)
{
lock (this)
{
if (Debugging.AssertsEnabled) Debugging.Assert(Monitor.IsEntered(writer));
//System.out.println("rld.writeFieldUpdates: seg=" + info + " numericFieldUpdates=" + numericFieldUpdates);
if (Debugging.AssertsEnabled) Debugging.Assert(dvUpdates.Any());
// Do this so we can delete any created files on
// exception; this saves all codecs from having to do
// it:
TrackingDirectoryWrapper trackingDir = new TrackingDirectoryWrapper(dir);
FieldInfos fieldInfos = null;
bool success = false;
try
{
Codec codec = Info.Info.Codec;
// reader could be null e.g. for a just merged segment (from
// IndexWriter.commitMergedDeletes).
SegmentReader reader = this.reader == null ? new SegmentReader(Info, writer.Config.ReaderTermsIndexDivisor, IOContext.READ_ONCE) : this.reader;
try
{
// clone FieldInfos so that we can update their dvGen separately from
// the reader's infos and write them to a new fieldInfos_gen file
FieldInfos.Builder builder = new FieldInfos.Builder(writer.globalFieldNumberMap);
// cannot use builder.add(reader.getFieldInfos()) because it does not
// clone FI.attributes as well FI.dvGen
foreach (FieldInfo fi in reader.FieldInfos)
{
FieldInfo clone = builder.Add(fi);
// copy the stuff FieldInfos.Builder doesn't copy
if (fi.Attributes != null)
{
foreach (KeyValuePair<string, string> e in fi.Attributes)
{
clone.PutAttribute(e.Key, e.Value);
}
}
clone.DocValuesGen = fi.DocValuesGen;
}
// create new fields or update existing ones to have NumericDV type
foreach (string f in dvUpdates.numericDVUpdates.Keys)
{
builder.AddOrUpdate(f, NumericDocValuesField.TYPE);
}
// create new fields or update existing ones to have BinaryDV type
foreach (string f in dvUpdates.binaryDVUpdates.Keys)
{
builder.AddOrUpdate(f, BinaryDocValuesField.fType);
}
fieldInfos = builder.Finish();
long nextFieldInfosGen = Info.NextFieldInfosGen;
string segmentSuffix = nextFieldInfosGen.ToString(CultureInfo.InvariantCulture);//Convert.ToString(nextFieldInfosGen, Character.MAX_RADIX));
SegmentWriteState state = new SegmentWriteState(null, trackingDir, Info.Info, fieldInfos, writer.Config.TermIndexInterval, null, IOContext.DEFAULT, segmentSuffix);
DocValuesFormat docValuesFormat = codec.DocValuesFormat;
DocValuesConsumer fieldsConsumer = docValuesFormat.FieldsConsumer(state);
bool fieldsConsumerSuccess = false;
try
{
// System.out.println("[" + Thread.currentThread().getName() + "] RLD.writeFieldUpdates: applying numeric updates; seg=" + info + " updates=" + numericFieldUpdates);
foreach (KeyValuePair<string, NumericDocValuesFieldUpdates> e in dvUpdates.numericDVUpdates)
{
string field = e.Key;
NumericDocValuesFieldUpdates fieldUpdates = e.Value;
FieldInfo fieldInfo = fieldInfos.FieldInfo(field);
if (Debugging.AssertsEnabled) Debugging.Assert(fieldInfo != null);
fieldInfo.DocValuesGen = nextFieldInfosGen;
// write the numeric updates to a new gen'd docvalues file
fieldsConsumer.AddNumericField(fieldInfo, GetInt64Enumerable(reader, field, fieldUpdates));
}
// System.out.println("[" + Thread.currentThread().getName() + "] RAU.writeFieldUpdates: applying binary updates; seg=" + info + " updates=" + dvUpdates.binaryDVUpdates);
foreach (KeyValuePair<string, BinaryDocValuesFieldUpdates> e in dvUpdates.binaryDVUpdates)
{
string field = e.Key;
BinaryDocValuesFieldUpdates dvFieldUpdates = e.Value;
FieldInfo fieldInfo = fieldInfos.FieldInfo(field);
if (Debugging.AssertsEnabled) Debugging.Assert(fieldInfo != null);
// System.out.println("[" + Thread.currentThread().getName() + "] RAU.writeFieldUpdates: applying binary updates; seg=" + info + " f=" + dvFieldUpdates + ", updates=" + dvFieldUpdates);
fieldInfo.DocValuesGen = nextFieldInfosGen;
// write the numeric updates to a new gen'd docvalues file
fieldsConsumer.AddBinaryField(fieldInfo, GetBytesRefEnumerable(reader, field, dvFieldUpdates));
}
codec.FieldInfosFormat.FieldInfosWriter.Write(trackingDir, Info.Info.Name, segmentSuffix, fieldInfos, IOContext.DEFAULT);
fieldsConsumerSuccess = true;
}
finally
{
if (fieldsConsumerSuccess)
{
fieldsConsumer.Dispose();
}
else
{
IOUtils.DisposeWhileHandlingException(fieldsConsumer);
}
}
}
finally
{
if (reader != this.reader)
{
// System.out.println("[" + Thread.currentThread().getName() + "] RLD.writeLiveDocs: closeReader " + reader);
reader.Dispose();
}
}
success = true;
}
finally
{
if (!success)
{
// Advance only the nextWriteDocValuesGen so that a 2nd
// attempt to write will write to a new file
Info.AdvanceNextWriteFieldInfosGen();
// Delete any partially created file(s):
foreach (string fileName in trackingDir.CreatedFiles)
{
try
{
dir.DeleteFile(fileName);
}
catch (Exception)
{
// Ignore so we throw only the first exc
}
}
}
}
Info.AdvanceFieldInfosGen();
// copy all the updates to mergingUpdates, so they can later be applied to the merged segment
if (isMerging)
{
foreach (KeyValuePair<string, NumericDocValuesFieldUpdates> e in dvUpdates.numericDVUpdates)
{
DocValuesFieldUpdates updates;
if (!mergingDVUpdates.TryGetValue(e.Key, out updates))
{
mergingDVUpdates[e.Key] = e.Value;
}
else
{
updates.Merge(e.Value);
}
}
foreach (KeyValuePair<string, BinaryDocValuesFieldUpdates> e in dvUpdates.binaryDVUpdates)
{
DocValuesFieldUpdates updates;
if (!mergingDVUpdates.TryGetValue(e.Key, out updates))
{
mergingDVUpdates[e.Key] = e.Value;
}
else
{
updates.Merge(e.Value);
}
}
}
// create a new map, keeping only the gens that are in use
IDictionary<long, ISet<string>> genUpdatesFiles = Info.UpdatesFiles;
IDictionary<long, ISet<string>> newGenUpdatesFiles = new Dictionary<long, ISet<string>>();
long fieldInfosGen = Info.FieldInfosGen;
foreach (FieldInfo fi in fieldInfos)
{
long dvGen = fi.DocValuesGen;
if (dvGen != -1 && !newGenUpdatesFiles.ContainsKey(dvGen))
{
if (dvGen == fieldInfosGen)
{
newGenUpdatesFiles[fieldInfosGen] = trackingDir.CreatedFiles;
}
else
{
newGenUpdatesFiles[dvGen] = genUpdatesFiles[dvGen];
}
}
}
Info.SetGenUpdatesFiles(newGenUpdatesFiles);
// wrote new files, should checkpoint()
writer.Checkpoint();
// if there is a reader open, reopen it to reflect the updates
if (reader != null)
{
SegmentReader newReader = new SegmentReader(Info, reader, liveDocs, Info.Info.DocCount - Info.DelCount - pendingDeleteCount);
bool reopened = false;
try
{
reader.DecRef();
reader = newReader;
reopened = true;
}
finally
{
if (!reopened)
{
newReader.DecRef();
}
}
}
}
}
/// <summary>
/// NOTE: This was getLongEnumerable() in Lucene
/// </summary>
private IEnumerable<long?> GetInt64Enumerable(SegmentReader reader, string field, NumericDocValuesFieldUpdates fieldUpdates)
{
int maxDoc = reader.MaxDoc;
IBits DocsWithField = reader.GetDocsWithField(field);
NumericDocValues currentValues = reader.GetNumericDocValues(field);
NumericDocValuesFieldUpdates.Iterator iter = (NumericDocValuesFieldUpdates.Iterator)fieldUpdates.GetIterator();
int updateDoc = iter.NextDoc();
for (int curDoc = 0; curDoc < maxDoc; ++curDoc)
{
if (curDoc == updateDoc) //document has an updated value
{
long? value = (long?)iter.Value; // either null or updated
updateDoc = iter.NextDoc(); //prepare for next round
yield return value;
}
else
{ // no update for this document
if (Debugging.AssertsEnabled) Debugging.Assert(curDoc < updateDoc);
if (currentValues != null && DocsWithField.Get(curDoc))
{
// only read the current value if the document had a value before
yield return currentValues.Get(curDoc);
}
else
{
yield return null;
}
}
}
}
private IEnumerable<BytesRef> GetBytesRefEnumerable(SegmentReader reader, string field, BinaryDocValuesFieldUpdates fieldUpdates)
{
BinaryDocValues currentValues = reader.GetBinaryDocValues(field);
IBits DocsWithField = reader.GetDocsWithField(field);
int maxDoc = reader.MaxDoc;
var iter = (BinaryDocValuesFieldUpdates.Iterator)fieldUpdates.GetIterator();
int updateDoc = iter.NextDoc();
var scratch = new BytesRef();
for (int curDoc = 0; curDoc < maxDoc; ++curDoc)
{
if (curDoc == updateDoc) //document has an updated value
{
BytesRef value = (BytesRef)iter.Value; // either null or updated
updateDoc = iter.NextDoc(); //prepare for next round
yield return value;
}
else
{ // no update for this document
if (Debugging.AssertsEnabled) Debugging.Assert(curDoc < updateDoc);
if (currentValues != null && DocsWithField.Get(curDoc))
{
// only read the current value if the document had a value before
currentValues.Get(curDoc, scratch);
yield return scratch;
}
else
{
yield return null;
}
}
}
}
/// <summary>
/// Returns a reader for merge. this method applies field updates if there are
/// any and marks that this segment is currently merging.
/// </summary>
internal virtual SegmentReader GetReaderForMerge(IOContext context)
{
lock (this)
{
if (Debugging.AssertsEnabled) Debugging.Assert(Monitor.IsEntered(writer));
// must execute these two statements as atomic operation, otherwise we
// could lose updates if e.g. another thread calls writeFieldUpdates in
// between, or the updates are applied to the obtained reader, but then
// re-applied in IW.commitMergedDeletes (unnecessary work and potential
// bugs).
isMerging = true;
return GetReader(context);
}
}
/// <summary>
/// Drops all merging updates. Called from IndexWriter after this segment
/// finished merging (whether successfully or not).
/// </summary>
public virtual void DropMergingUpdates()
{
lock (this)
{
mergingDVUpdates.Clear();
isMerging = false;
}
}
/// <summary>
/// Returns updates that came in while this segment was merging. </summary>
public virtual IDictionary<string, DocValuesFieldUpdates> MergingFieldUpdates
{
get
{
lock (this)
{
return mergingDVUpdates;
}
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("ReadersAndLiveDocs(seg=").Append(Info);
sb.Append(" pendingDeleteCount=").Append(pendingDeleteCount);
sb.Append(" liveDocsShared=").Append(liveDocsShared);
return sb.ToString();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MenuItemBinding.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web;
/// <devdoc>
/// Provides a data mapping definition for a Menu
/// </devdoc>
[DefaultProperty("TextField")]
public sealed class MenuItemBinding : IStateManager, ICloneable, IDataSourceViewSchemaAccessor {
private bool _isTrackingViewState;
private StateBag _viewState;
/// <devdoc>
/// The data member to use in the mapping
/// </devdoc>
[
DefaultValue(""),
WebCategory("Data"),
WebSysDescription(SR.Binding_DataMember),
]
public string DataMember {
get {
object s = ViewState["DataMember"];
if (s == null) {
return String.Empty;
}
else {
return (string)s;
}
}
set {
ViewState["DataMember"] = value;
}
}
/// <devdoc>
/// The depth of the level for which this MenuItemBinding is defining a data mapping
/// </devdoc>
[
DefaultValue(-1),
TypeConverter("System.Web.UI.Design.WebControls.TreeNodeBindingDepthConverter, " + AssemblyRef.SystemDesign),
WebCategory("Data"),
WebSysDescription(SR.MenuItemBinding_Depth),
]
public int Depth {
get {
object o = ViewState["Depth"];
if (o == null) {
return -1;
}
return (int)o;
}
set {
ViewState["Depth"] = value;
}
}
[DefaultValue(true)]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_Enabled)]
public bool Enabled {
get {
object o = ViewState["Enabled"];
return (o == null ? true : (bool)o);
}
set {
ViewState["Enabled"] = value;
}
}
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_EnabledField),
]
public string EnabledField {
get {
object s = ViewState["EnabledField"];
return (s == null ? String.Empty : (string)s);
}
set {
ViewState["EnabledField"] = value;
}
}
/// <devdoc>
/// Gets and sets the format string used to render the bound data for this node
/// </devdoc>
[DefaultValue("")]
[Localizable(true)]
[WebCategory("Databindings")]
[WebSysDescription(SR.MenuItemBinding_FormatString)]
public string FormatString {
get {
object s = ViewState["FormatString"];
if (s == null) {
return String.Empty;
}
return (string)s;
}
set {
ViewState["FormatString"] = value;
}
}
/// <devdoc>
/// Gets and sets the image URl to be rendered for this node
/// </devdoc>
[DefaultValue("")]
[Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))]
[UrlProperty()]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_ImageUrl)]
public string ImageUrl {
get {
object s = ViewState["ImageUrl"];
if (s == null) {
return String.Empty;
}
return (string)s;
}
set {
ViewState["ImageUrl"] = value;
}
}
/// <devdoc>
/// Get and sets the fieldname to use for the ImageUrl property in a MenuItem
/// </devdoc>
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_ImageUrlField),
]
public string ImageUrlField {
get {
object s = ViewState["ImageUrlField"];
if (s == null) {
return String.Empty;
}
else {
return (string)s;
}
}
set {
ViewState["ImageUrlField"] = value;
}
}
[DefaultValue("")]
[Editor("System.Web.UI.Design.UrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))]
[UrlProperty()]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_NavigateUrl)]
public string NavigateUrl {
get {
object s = ViewState["NavigateUrl"];
if (s == null) {
return String.Empty;
}
return (string)s;
}
set {
ViewState["NavigateUrl"] = value;
}
}
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_NavigateUrlField),
]
public string NavigateUrlField {
get {
object s = ViewState["NavigateUrlField"];
if (s == null) {
return String.Empty;
}
else {
return (string)s;
}
}
set {
ViewState["NavigateUrlField"] = value;
}
}
[DefaultValue("")]
[Editor("System.Web.UI.Design.UrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))]
[UrlProperty()]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_PopOutImageUrl)]
public string PopOutImageUrl {
get {
object s = ViewState["PopOutImageUrl"];
if (s == null) {
return String.Empty;
}
return (string)s;
}
set {
ViewState["PopOutImageUrl"] = value;
}
}
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_PopOutImageUrlField),
]
public string PopOutImageUrlField {
get {
object s = ViewState["PopOutImageUrlField"];
if (s == null) {
return String.Empty;
}
else {
return (string)s;
}
}
set {
ViewState["PopOutImageUrlField"] = value;
}
}
[DefaultValue(true)]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_Selectable)]
public bool Selectable {
get {
object o = ViewState["Selectable"];
return (o == null ? true : (bool)o);
}
set {
ViewState["Selectable"] = value;
}
}
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_SelectableField),
]
public string SelectableField {
get {
object s = ViewState["SelectableField"];
return (s == null ? String.Empty : (string)s);
}
set {
ViewState["SelectableField"] = value;
}
}
[DefaultValue("")]
[Editor("System.Web.UI.Design.UrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))]
[UrlProperty()]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_SeparatorImageUrl)]
public string SeparatorImageUrl {
get {
object s = ViewState["SeparatorImageUrl"];
if (s == null) {
return String.Empty;
}
return (string)s;
}
set {
ViewState["SeparatorImageUrl"] = value;
}
}
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_SeparatorImageUrlField),
]
public string SeparatorImageUrlField {
get {
object s = ViewState["SeparatorImageUrlField"];
if (s == null) {
return String.Empty;
}
else {
return (string)s;
}
}
set {
ViewState["SeparatorImageUrlField"] = value;
}
}
/// <devdoc>
/// Gets and sets the target window that the MenuItemBinding will browse to if selected
/// </devdoc>
[DefaultValue("")]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_Target)]
public string Target {
get {
object s = ViewState["Target"];
if (s == null) {
return String.Empty;
}
return (string)s;
}
set {
ViewState["Target"] = value;
}
}
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_TargetField),
]
public string TargetField {
get {
string s = (string)ViewState["TargetField"];
if (s == null) {
return String.Empty;
}
else {
return s;
}
}
set {
ViewState["TargetField"] = value;
}
}
/// <devdoc>
/// Gets and sets the display text
/// </devdoc>
[DefaultValue("")]
[Localizable(true)]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_Text)]
public string Text {
get {
object s = ViewState["Text"];
if (s == null) {
s = ViewState["Value"];
if (s == null) {
return String.Empty;
}
}
return (string)s;
}
set {
ViewState["Text"] = value;
}
}
/// <devdoc>
/// Get and sets the fieldname to use for the Text property in a MenuItem
/// </devdoc>
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_TextField),
]
public string TextField {
get {
object s = ViewState["TextField"];
if (s == null) {
return String.Empty;
}
return (string)s;
}
set {
ViewState["TextField"] = value;
}
}
/// <devdoc>
/// Gets and sets the MenuItemBinding tooltip
/// </devdoc>
[DefaultValue("")]
[Localizable(true)]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_ToolTip)]
public string ToolTip {
get {
object s = ViewState["ToolTip"];
if (s == null) {
return String.Empty;
}
return (string)s;
}
set {
ViewState["ToolTip"] = value;
}
}
/// <devdoc>
/// Get and sets the fieldname to use for the ToolTip property in a MenuItem
/// </devdoc>
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_ToolTipField),
]
public string ToolTipField {
get {
object s = ViewState["ToolTipField"];
if (s == null) {
return String.Empty;
}
else {
return (string)s;
}
}
set {
ViewState["ToolTipField"] = value;
}
}
/// <devdoc>
/// Gets and sets the value
/// </devdoc>
[DefaultValue("")]
[Localizable(true)]
[WebCategory("DefaultProperties")]
[WebSysDescription(SR.MenuItemBinding_Value)]
public string Value {
get {
object s = ViewState["Value"];
if (s == null) {
s = ViewState["Text"];
if (s == null) {
return String.Empty;
}
}
return (string)s;
}
set {
ViewState["Value"] = value;
}
}
/// <devdoc>
/// Get and sets the fieldname to use for the Value property in a MenuItem
/// </devdoc>
[
DefaultValue(""),
TypeConverter("System.Web.UI.Design.DataSourceViewSchemaConverter, " + AssemblyRef.SystemDesign),
WebCategory("Databindings"),
WebSysDescription(SR.MenuItemBinding_ValueField),
]
public string ValueField {
get {
object s = ViewState["ValueField"];
if (s == null) {
return String.Empty;
}
return (string)s;
}
set {
ViewState["ValueField"] = value;
}
}
/// <devdoc>
/// The state for this MenuItemBinding
/// </devdoc>
private StateBag ViewState {
get {
if (_viewState == null) {
_viewState = new StateBag();
if (_isTrackingViewState) {
((IStateManager)_viewState).TrackViewState();
}
}
return _viewState;
}
}
internal void SetDirty() {
ViewState.SetDirty(true);
}
public override string ToString() {
return (String.IsNullOrEmpty(DataMember) ?
SR.GetString(SR.TreeNodeBinding_EmptyBindingText) :
DataMember);
}
#region ICloneable implemention
/// <internalonly/>
/// <devdoc>
/// Creates a clone of the MenuItemBinding.
/// </devdoc>
object ICloneable.Clone() {
MenuItemBinding clone = new MenuItemBinding();
clone.DataMember = DataMember;
clone.Depth = Depth;
clone.Enabled = Enabled;
clone.EnabledField = EnabledField;
clone.FormatString = FormatString;
clone.ImageUrl = ImageUrl;
clone.ImageUrlField = ImageUrlField;
clone.NavigateUrl = NavigateUrl;
clone.NavigateUrlField = NavigateUrlField;
clone.PopOutImageUrl = PopOutImageUrl;
clone.PopOutImageUrlField = PopOutImageUrlField;
clone.Selectable = Selectable;
clone.SelectableField = SelectableField;
clone.SeparatorImageUrl = SeparatorImageUrl;
clone.SeparatorImageUrlField = SeparatorImageUrlField;
clone.Target = Target;
clone.TargetField = TargetField;
clone.Text = Text;
clone.TextField = TextField;
clone.ToolTip = ToolTip;
clone.ToolTipField = ToolTipField;
clone.Value = Value;
clone.ValueField = ValueField;
return clone;
}
#endregion
#region IStateManager implementation
/// <internalonly/>
bool IStateManager.IsTrackingViewState {
get {
return _isTrackingViewState;
}
}
/// <internalonly/>
void IStateManager.LoadViewState(object state) {
if (state != null) {
((IStateManager)ViewState).LoadViewState(state);
}
}
/// <internalonly/>
object IStateManager.SaveViewState() {
if (_viewState != null) {
return ((IStateManager)_viewState).SaveViewState();
}
return null;
}
/// <internalonly/>
void IStateManager.TrackViewState() {
_isTrackingViewState = true;
if (_viewState != null) {
((IStateManager)_viewState).TrackViewState();
}
}
#endregion
#region IDataSourceViewSchemaAccessor implementation
/// <internalonly/>
object IDataSourceViewSchemaAccessor.DataSourceViewSchema {
get {
return ViewState["IDataSourceViewSchemaAccessor.DataSourceViewSchema"];
}
set {
ViewState["IDataSourceViewSchemaAccessor.DataSourceViewSchema"] = value;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Caching;
using umbraco.cms.businesslogic.web;
using umbraco.DataLayer;
using umbraco.BusinessLogic;
using System.IO;
using System.Text.RegularExpressions;
using System.ComponentModel;
using Umbraco.Core.IO;
using System.Collections;
using umbraco.cms.businesslogic.task;
using umbraco.cms.businesslogic.workflow;
using umbraco.cms.businesslogic.Tags;
using File = System.IO.File;
using Media = umbraco.cms.businesslogic.media.Media;
using Tag = umbraco.cms.businesslogic.Tags.Tag;
using Notification = umbraco.cms.businesslogic.workflow.Notification;
using Task = umbraco.cms.businesslogic.task.Task;
namespace umbraco.cms.businesslogic
{
/// <summary>
/// CMSNode class serves as the base class for many of the other components in the cms.businesslogic.xx namespaces.
/// Providing the basic hierarchical data structure and properties Text (name), Creator, Createdate, updatedate etc.
/// which are shared by most umbraco objects.
///
/// The child classes are required to implement an identifier (Guid) which is used as the objecttype identifier, for
/// distinguishing the different types of CMSNodes (ex. Documents/Medias/Stylesheets/documenttypes and so forth).
/// </summary>
[Obsolete("Obsolete, This class will eventually be phased out", false)]
public class CMSNode : BusinessLogic.console.IconI
{
#region Private Members
private string _text;
private int _id = 0;
private Guid _uniqueID;
private int _parentid;
private Guid _nodeObjectType;
private int _level;
private string _path;
private bool _hasChildren;
private int _sortOrder;
private int _userId;
private DateTime _createDate;
private bool _hasChildrenInitialized;
private string m_image = "default.png";
private bool? _isTrashed = null;
private IUmbracoEntity _entity;
#endregion
#region Private static
private static readonly string DefaultIconCssFile = IOHelper.MapPath(SystemDirectories.UmbracoClient + "/Tree/treeIcons.css");
private static readonly List<string> InternalDefaultIconClasses = new List<string>();
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
private static void InitializeIconClasses()
{
StreamReader re = File.OpenText(DefaultIconCssFile);
string content = string.Empty;
string input = null;
while ((input = re.ReadLine()) != null)
{
content += input.Replace("\n", "") + "\n";
}
re.Close();
// parse the classes
var m = Regex.Matches(content, "([^{]*){([^}]*)}", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match match in m)
{
var groups = match.Groups;
var cssClass = groups[1].Value.Replace("\n", "").Replace("\r", "").Trim().Trim(Environment.NewLine.ToCharArray());
if (string.IsNullOrEmpty(cssClass) == false)
{
InternalDefaultIconClasses.Add(cssClass);
}
}
}
private const string SqlSingle = "SELECT id, createDate, trashed, parentId, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text FROM umbracoNode WHERE id = @id";
private const string SqlDescendants = @"
SELECT id, createDate, trashed, parentId, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text
FROM umbracoNode
WHERE path LIKE '%,{0},%'";
#endregion
#region Public static
/// <summary>
/// Get a count on all CMSNodes given the objecttype
/// </summary>
/// <param name="objectType">The objecttype identifier</param>
/// <returns>
/// The number of CMSNodes of the given objecttype
/// </returns>
public static int CountByObjectType(Guid objectType)
{
return SqlHelper.ExecuteScalar<int>("SELECT COUNT(*) from umbracoNode WHERE nodeObjectType = @type", SqlHelper.CreateParameter("@type", objectType));
}
/// <summary>
/// Number of ancestors of the current CMSNode
/// </summary>
/// <param name="Id">The CMSNode Id</param>
/// <returns>
/// The number of ancestors from the given CMSNode
/// </returns>
public static int CountSubs(int Id)
{
return SqlHelper.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoNode WHERE ','+path+',' LIKE '%," + Id.ToString() + ",%'");
}
/// <summary>
/// Returns the number of leaf nodes from the newParent id for a given object type
/// </summary>
/// <param name="parentId"></param>
/// <param name="objectType"></param>
/// <returns></returns>
public static int CountLeafNodes(int parentId, Guid objectType)
{
return SqlHelper.ExecuteScalar<int>("Select count(uniqueID) from umbracoNode where nodeObjectType = @type And parentId = @parentId",
SqlHelper.CreateParameter("@type", objectType),
SqlHelper.CreateParameter("@parentId", parentId));
}
/// <summary>
/// Gets the default icon classes.
/// </summary>
/// <value>The default icon classes.</value>
public static List<string> DefaultIconClasses
{
get
{
using (var l = new UpgradeableReadLock(Locker))
{
if (InternalDefaultIconClasses.Count == 0)
{
l.UpgradeToWriteLock();
InitializeIconClasses();
}
return InternalDefaultIconClasses;
}
}
}
/// <summary>
/// Method for checking if a CMSNode exits with the given Guid
/// </summary>
/// <param name="uniqueID">Identifier</param>
/// <returns>True if there is a CMSNode with the given Guid</returns>
public static bool IsNode(Guid uniqueID)
{
return (SqlHelper.ExecuteScalar<int>("select count(id) from umbracoNode where uniqueID = @uniqueID", SqlHelper.CreateParameter("@uniqueId", uniqueID)) > 0);
}
/// <summary>
/// Method for checking if a CMSNode exits with the given id
/// </summary>
/// <param name="Id">Identifier</param>
/// <returns>True if there is a CMSNode with the given id</returns>
public static bool IsNode(int Id)
{
return (SqlHelper.ExecuteScalar<int>("select count(id) from umbracoNode where id = @id", SqlHelper.CreateParameter("@id", Id)) > 0);
}
/// <summary>
/// Retrieve a list of the unique id's of all CMSNodes given the objecttype
/// </summary>
/// <param name="objectType">The objecttype identifier</param>
/// <returns>
/// A list of all unique identifiers which each are associated to a CMSNode
/// </returns>
public static Guid[] getAllUniquesFromObjectType(Guid objectType)
{
IRecordsReader dr = SqlHelper.ExecuteReader("Select uniqueID from umbracoNode where nodeObjectType = @type",
SqlHelper.CreateParameter("@type", objectType));
System.Collections.ArrayList tmp = new System.Collections.ArrayList();
while (dr.Read()) tmp.Add(dr.GetGuid("uniqueID"));
dr.Close();
Guid[] retval = new Guid[tmp.Count];
for (int i = 0; i < tmp.Count; i++) retval[i] = (Guid)tmp[i];
return retval;
}
/// <summary>
/// Retrieve a list of the node id's of all CMSNodes given the objecttype
/// </summary>
/// <param name="objectType">The objecttype identifier</param>
/// <returns>
/// A list of all node ids which each are associated to a CMSNode
/// </returns>
public static int[] getAllUniqueNodeIdsFromObjectType(Guid objectType)
{
IRecordsReader dr = SqlHelper.ExecuteReader("Select id from umbracoNode where nodeObjectType = @type",
SqlHelper.CreateParameter("@type", objectType));
System.Collections.ArrayList tmp = new System.Collections.ArrayList();
while (dr.Read()) tmp.Add(dr.GetInt("id"));
dr.Close();
return (int[])tmp.ToArray(typeof(int));
}
/// <summary>
/// Retrieves the top level nodes in the hierarchy
/// </summary>
/// <param name="ObjectType">The Guid identifier of the type of objects</param>
/// <returns>
/// A list of all top level nodes given the objecttype
/// </returns>
public static Guid[] TopMostNodeIds(Guid ObjectType)
{
IRecordsReader dr = SqlHelper.ExecuteReader("Select uniqueID from umbracoNode where nodeObjectType = @type And parentId = -1 order by sortOrder",
SqlHelper.CreateParameter("@type", ObjectType));
System.Collections.ArrayList tmp = new System.Collections.ArrayList();
while (dr.Read()) tmp.Add(dr.GetGuid("uniqueID"));
dr.Close();
Guid[] retval = new Guid[tmp.Count];
for (int i = 0; i < tmp.Count; i++) retval[i] = (Guid)tmp[i];
return retval;
}
#endregion
#region Protected static
/// <summary>
/// Given the protected modifier the CMSNode.MakeNew method can only be accessed by
/// derived classes > who by definition knows of its own objectType.
/// </summary>
/// <param name="parentId">The newParent CMSNode id</param>
/// <param name="objectType">The objecttype identifier</param>
/// <param name="userId">Creator</param>
/// <param name="level">The level in the tree hieararchy</param>
/// <param name="text">The name of the CMSNode</param>
/// <param name="uniqueID">The unique identifier</param>
/// <returns></returns>
protected static CMSNode MakeNew(int parentId, Guid objectType, int userId, int level, string text, Guid uniqueID)
{
CMSNode parent = null;
string path = "";
int sortOrder = 0;
if (level > 0)
{
parent = new CMSNode(parentId);
sortOrder = GetNewDocumentSortOrder(parentId);
path = parent.Path;
}
else
path = "-1";
// Ruben 8/1/2007: I replace this with a parameterized version.
// But does anyone know what the 'level++' is supposed to be doing there?
// Nothing obviously, since it's a postfix.
SqlHelper.ExecuteNonQuery("INSERT INTO umbracoNode(trashed, parentID, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text, createDate) VALUES(@trashed, @parentID, @nodeObjectType, @nodeUser, @level, @path, @sortOrder, @uniqueID, @text, @createDate)",
SqlHelper.CreateParameter("@trashed", 0),
SqlHelper.CreateParameter("@parentID", parentId),
SqlHelper.CreateParameter("@nodeObjectType", objectType),
SqlHelper.CreateParameter("@nodeUser", userId),
SqlHelper.CreateParameter("@level", level++),
SqlHelper.CreateParameter("@path", path),
SqlHelper.CreateParameter("@sortOrder", sortOrder),
SqlHelper.CreateParameter("@uniqueID", uniqueID),
SqlHelper.CreateParameter("@text", text),
SqlHelper.CreateParameter("@createDate", DateTime.Now));
CMSNode retVal = new CMSNode(uniqueID);
retVal.Path = path + "," + retVal.Id.ToString();
// NH 4.7.1 duplicate permissions because of refactor
if (parent != null)
{
IEnumerable<Permission> permissions = Permission.GetNodePermissions(parent);
foreach (Permission p in permissions)
{
Permission.MakeNew(User.GetUser(p.UserId), retVal, p.PermissionId);
}
}
//event
NewEventArgs e = new NewEventArgs();
retVal.FireAfterNew(e);
return retVal;
}
private static int GetNewDocumentSortOrder(int parentId)
{
var sortOrder = 0;
using (IRecordsReader dr = SqlHelper.ExecuteReader(
"SELECT MAX(sortOrder) AS sortOrder FROM umbracoNode WHERE parentID = @parentID AND nodeObjectType = @GuidForNodesOfTypeDocument",
SqlHelper.CreateParameter("@parentID", parentId),
SqlHelper.CreateParameter("@GuidForNodesOfTypeDocument", Document._objectType)
))
{
while (dr.Read())
sortOrder = dr.GetInt("sortOrder") + 1;
}
return sortOrder;
}
/// <summary>
/// Retrieve a list of the id's of all CMSNodes given the objecttype and the first letter of the name.
/// </summary>
/// <param name="objectType">The objecttype identifier</param>
/// <param name="letter">Firstletter</param>
/// <returns>
/// A list of all CMSNodes which has the objecttype and a name that starts with the given letter
/// </returns>
protected static int[] getUniquesFromObjectTypeAndFirstLetter(Guid objectType, char letter)
{
using (IRecordsReader dr = SqlHelper.ExecuteReader("Select id from umbracoNode where nodeObjectType = @objectType AND text like @letter", SqlHelper.CreateParameter("@objectType", objectType), SqlHelper.CreateParameter("@letter", letter.ToString() + "%")))
{
List<int> tmp = new List<int>();
while (dr.Read()) tmp.Add(dr.GetInt("id"));
return tmp.ToArray();
}
}
/// <summary>
/// Gets the SQL helper.
/// </summary>
/// <value>The SQL helper.</value>
[Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)]
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
internal static UmbracoDatabase Database
{
get { return ApplicationContext.Current.DatabaseContext.Database; }
}
#endregion
#region Constructors
/// <summary>
/// Empty constructor that is not suported
/// ...why is it here?
/// </summary>
public CMSNode()
{
throw new NotSupportedException();
}
/// <summary>
/// Initializes a new instance of the <see cref="CMSNode"/> class.
/// </summary>
/// <param name="Id">The id.</param>
public CMSNode(int Id)
{
_id = Id;
setupNode();
}
/// <summary>
/// This is purely for a hackity hack hack hack in order to make the new Document(id, version) constructor work because
/// the Version property needs to be set on the object before setupNode is called, otherwise it never works! this allows
/// inheritors to set default data before setupNode() is called.
/// </summary>
/// <param name="id"></param>
/// <param name="ctorArgs"></param>
internal CMSNode(int id, object[] ctorArgs)
{
_id = id;
PreSetupNode(ctorArgs);
}
/// <summary>
/// Initializes a new instance of the <see cref="CMSNode"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="noSetup">if set to <c>true</c> [no setup].</param>
public CMSNode(int id, bool noSetup)
{
_id = id;
if (!noSetup)
setupNode();
}
/// <summary>
/// Initializes a new instance of the <see cref="CMSNode"/> class.
/// </summary>
/// <param name="uniqueID">The unique ID.</param>
public CMSNode(Guid uniqueID)
{
_id = SqlHelper.ExecuteScalar<int>("SELECT id FROM umbracoNode WHERE uniqueID = @uniqueId", SqlHelper.CreateParameter("@uniqueId", uniqueID));
setupNode();
}
public CMSNode(Guid uniqueID, bool noSetup)
{
_id = SqlHelper.ExecuteScalar<int>("SELECT id FROM umbracoNode WHERE uniqueID = @uniqueId", SqlHelper.CreateParameter("@uniqueId", uniqueID));
if (!noSetup)
setupNode();
}
protected internal CMSNode(IRecordsReader reader)
{
_id = reader.GetInt("id");
PopulateCMSNodeFromReader(reader);
}
protected internal CMSNode(IUmbracoEntity entity)
{
_id = entity.Id;
_entity = entity;
}
protected internal CMSNode(IEntity entity)
{
_id = entity.Id;
}
#endregion
#region Public Methods
/// <summary>
/// Ensures uniqueness by id
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
var l = obj as CMSNode;
if (l != null)
{
return this._id.Equals(l._id);
}
return false;
}
/// <summary>
/// Ensures uniqueness by id
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return _id.GetHashCode();
}
/// <summary>
/// An xml representation of the CMSNOde
/// </summary>
/// <param name="xd">Xmldocument context</param>
/// <param name="Deep">If true the xml will append the CMSNodes child xml</param>
/// <returns>The CMSNode Xmlrepresentation</returns>
public virtual XmlNode ToXml(XmlDocument xd, bool Deep)
{
XmlNode x = xd.CreateNode(XmlNodeType.Element, "node", "");
XmlPopulate(xd, x, Deep);
return x;
}
public virtual XmlNode ToPreviewXml(XmlDocument xd)
{
// If xml already exists
if (!PreviewExists(UniqueId))
{
SavePreviewXml(ToXml(xd, false), UniqueId);
}
return GetPreviewXml(xd, UniqueId);
}
public virtual List<CMSPreviewNode> GetNodesForPreview(bool childrenOnly)
{
List<CMSPreviewNode> nodes = new List<CMSPreviewNode>();
string sql = @"
select umbracoNode.id, umbracoNode.parentId, umbracoNode.level, umbracoNode.sortOrder, cmsPreviewXml.xml
from umbracoNode
inner join cmsPreviewXml on cmsPreviewXml.nodeId = umbracoNode.id
where trashed = 0 and path like '{0}'
order by level,sortOrder";
string pathExp = childrenOnly ? Path + ",%" : Path;
IRecordsReader dr = SqlHelper.ExecuteReader(String.Format(sql, pathExp));
while (dr.Read())
nodes.Add(new CMSPreviewNode(dr.GetInt("id"), dr.GetGuid("uniqueID"), dr.GetInt("parentId"), dr.GetShort("level"), dr.GetInt("sortOrder"), dr.GetString("xml"), false));
dr.Close();
return nodes;
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public virtual void Save()
{
SaveEventArgs e = new SaveEventArgs();
this.FireBeforeSave(e);
if (!e.Cancel)
{
//In the future there will be SQL stuff happening here...
this.FireAfterSave(e);
}
}
public override string ToString()
{
if (Id != int.MinValue || !string.IsNullOrEmpty(Text))
{
return string.Format("{{ Id: {0}, Text: {1}, ParentId: {2} }}",
Id,
Text,
_parentid
);
}
return base.ToString();
}
private void Move(CMSNode newParent)
{
MoveEventArgs e = new MoveEventArgs();
FireBeforeMove(e);
if (!e.Cancel)
{
//first we need to establish if the node already exists under the newParent node
//var isNewParentInPath = (Path.Contains("," + newParent.Id + ","));
//if it's the same newParent, we can save some SQL calls since we know these wont change.
//level and path might change even if it's the same newParent because the newParent could be moving somewhere.
if (ParentId != newParent.Id)
{
int maxSortOrder = SqlHelper.ExecuteScalar<int>("select coalesce(max(sortOrder),0) from umbracoNode where parentid = @parentId",
SqlHelper.CreateParameter("@parentId", newParent.Id));
this.Parent = newParent;
this.sortOrder = maxSortOrder + 1;
}
//detect if we have moved, then update the level and path
// issue: http://issues.umbraco.org/issue/U4-1579
if (this.Path != newParent.Path + "," + this.Id.ToString())
{
this.Level = newParent.Level + 1;
this.Path = newParent.Path + "," + this.Id.ToString();
}
//this code block should not be here but since the class structure is very poor and doesn't use
//overrides (instead using shadows/new) for the Children property, when iterating over the children
//and calling Move(), the super classes overridden OnMove or Move methods never get fired, so
//we now need to hard code this here :(
if (Path.Contains("," + ((int)RecycleBin.RecycleBinType.Content).ToString() + ",")
|| Path.Contains("," + ((int)RecycleBin.RecycleBinType.Media).ToString() + ","))
{
//if we've moved this to the recyle bin, we need to update the trashed property
if (!IsTrashed) IsTrashed = true; //don't update if it's not necessary
}
else
{
if (IsTrashed) IsTrashed = false; //don't update if it's not necessary
}
//make sure the node type is a document/media, if it is a recycle bin then this will not be equal
if (!IsTrashed && newParent.nodeObjectType == Document._objectType)
{
// regenerate the xml of the current document
var movedDocument = new Document(this.Id);
movedDocument.XmlGenerate(new XmlDocument());
//regenerate the xml for the newParent node
var parentDocument = new Document(newParent.Id);
parentDocument.XmlGenerate(new XmlDocument());
}
else if (!IsTrashed && newParent.nodeObjectType == Media._objectType)
{
//regenerate the xml for the newParent node
var m = new Media(newParent.Id);
m.XmlGenerate(new XmlDocument());
}
var children = this.Children;
foreach (CMSNode c in children)
{
c.Move(this);
}
//TODO: Properly refactor this, we're just clearing the cache so the changes will also be visible in the backoffice
InMemoryCacheProvider.Current.Clear();
FireAfterMove(e);
}
}
/// <summary>
/// Moves the CMSNode from the current position in the hierarchy to the target
/// </summary>
/// <param name="NewParentId">Target CMSNode id</param>
[Obsolete("Obsolete, Use Umbraco.Core.Services.ContentService.Move() or Umbraco.Core.Services.MediaService.Move()", false)]
public virtual void Move(int newParentId)
{
CMSNode parent = new CMSNode(newParentId);
Move(parent);
}
/// <summary>
/// Deletes this instance.
/// </summary>
public virtual void delete()
{
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
// remove relations
var rels = Relations;
foreach (relation.Relation rel in rels)
{
rel.Delete();
}
//removes tasks
foreach (Task t in Tasks)
{
t.Delete();
}
//remove notifications
Notification.DeleteNotifications(this);
//remove permissions
Permission.DeletePermissions(this);
//removes tag associations (i know the key is set to cascade but do it anyways)
Tag.RemoveTagsFromNode(this.Id);
SqlHelper.ExecuteNonQuery("DELETE FROM umbracoNode WHERE uniqueID= @uniqueId", SqlHelper.CreateParameter("@uniqueId", _uniqueID));
FireAfterDelete(e);
}
}
/// <summary>
/// Does the current CMSNode have any child nodes.
/// </summary>
/// <value>
/// <c>true</c> if this instance has children; otherwise, <c>false</c>.
/// </value>
public virtual bool HasChildren
{
get
{
if (!_hasChildrenInitialized)
{
int tmpChildrenCount = SqlHelper.ExecuteScalar<int>("select count(id) from umbracoNode where ParentId = @id",
SqlHelper.CreateParameter("@id", Id));
HasChildren = (tmpChildrenCount > 0);
}
return _hasChildren;
}
set
{
_hasChildrenInitialized = true;
_hasChildren = value;
}
}
/// <summary>
/// Returns all descendant nodes from this node.
/// </summary>
/// <returns></returns>
/// <remarks>
/// This doesn't return a strongly typed IEnumerable object so that we can override in in super clases
/// and since this class isn't a generic (thought it should be) this is not strongly typed.
/// </remarks>
public virtual IEnumerable GetDescendants()
{
var descendants = new List<CMSNode>();
using (IRecordsReader dr = SqlHelper.ExecuteReader(string.Format(SqlDescendants, Id)))
{
while (dr.Read())
{
var node = new CMSNode(dr.GetInt("id"), true);
node.PopulateCMSNodeFromReader(dr);
descendants.Add(node);
}
}
return descendants;
}
#endregion
#region Public properties
/// <summary>
/// Determines if the node is in the recycle bin.
/// This is only relavent for node types that support a recyle bin (such as Document/Media)
/// </summary>
public virtual bool IsTrashed
{
get
{
if (!_isTrashed.HasValue)
{
_isTrashed = Convert.ToBoolean(SqlHelper.ExecuteScalar<object>("SELECT trashed FROM umbracoNode where id=@id",
SqlHelper.CreateParameter("@id", this.Id)));
}
return _isTrashed.Value;
}
set
{
_isTrashed = value;
SqlHelper.ExecuteNonQuery("update umbracoNode set trashed = @trashed where id = @id",
SqlHelper.CreateParameter("@trashed", value),
SqlHelper.CreateParameter("@id", this.Id));
}
}
/// <summary>
/// Gets or sets the sort order.
/// </summary>
/// <value>The sort order.</value>
public virtual int sortOrder
{
get { return _sortOrder; }
set
{
_sortOrder = value;
SqlHelper.ExecuteNonQuery("update umbracoNode set sortOrder = '" + value + "' where id = " + this.Id.ToString());
if (_entity != null)
_entity.SortOrder = value;
}
}
/// <summary>
/// Gets or sets the create date time.
/// </summary>
/// <value>The create date time.</value>
public virtual DateTime CreateDateTime
{
get { return _createDate; }
set
{
_createDate = value;
SqlHelper.ExecuteNonQuery("update umbracoNode set createDate = @createDate where id = " + this.Id.ToString(), SqlHelper.CreateParameter("@createDate", _createDate));
}
}
/// <summary>
/// Gets the creator
/// </summary>
/// <value>The user.</value>
public BusinessLogic.User User
{
get
{
return BusinessLogic.User.GetUser(_userId);
}
}
/// <summary>
/// Gets the id.
/// </summary>
/// <value>The id.</value>
public int Id
{
get { return _id; }
}
/// <summary>
/// Get the newParent id of the node
/// </summary>
public virtual int ParentId
{
get { return _parentid; }
internal set { _parentid = value; }
}
/// <summary>
/// Given the hierarchical tree structure a CMSNode has only one newParent but can have many children
/// </summary>
/// <value>The newParent.</value>
public CMSNode Parent
{
get
{
if (Level == 1) throw new ArgumentException("No newParent node");
return new CMSNode(_parentid);
}
set
{
_parentid = value.Id;
SqlHelper.ExecuteNonQuery("update umbracoNode set parentId = " + value.Id.ToString() + " where id = " + this.Id.ToString());
if (_entity != null)
_entity.ParentId = value.Id;
}
}
/// <summary>
/// An comma separated string consisting of integer node id's
/// that indicates the path from the topmost node to the given node
/// </summary>
/// <value>The path.</value>
public virtual string Path
{
get { return _path; }
set
{
_path = value;
SqlHelper.ExecuteNonQuery("update umbracoNode set path = '" + _path + "' where id = " + this.Id.ToString());
if (_entity != null)
_entity.Path = value;
}
}
/// <summary>
/// Returns an integer value that indicates in which level of the
/// tree structure the given node is
/// </summary>
/// <value>The level.</value>
public virtual int Level
{
get { return _level; }
set
{
_level = value;
SqlHelper.ExecuteNonQuery("update umbracoNode set level = " + _level.ToString() + " where id = " + this.Id.ToString());
if (_entity != null)
_entity.Level = value;
}
}
/// <summary>
/// All CMSNodes has an objecttype ie. Webpage, StyleSheet etc., used to distinguish between the different
/// object types for for fast loading children to the tree.
/// </summary>
/// <value>The type of the node object.</value>
public Guid nodeObjectType
{
get { return _nodeObjectType; }
}
/// <summary>
/// Besides the hierarchy it's possible to relate one CMSNode to another, use this for alternative
/// non-strict hierarchy
/// </summary>
/// <value>The relations.</value>
public relation.Relation[] Relations
{
get { return relation.Relation.GetRelations(this.Id); }
}
/// <summary>
/// Returns all tasks associated with this node
/// </summary>
public Tasks Tasks
{
get { return Task.GetTasks(this.Id); }
}
public virtual int ChildCount
{
get
{
return SqlHelper.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoNode where ParentID = @parentId",
SqlHelper.CreateParameter("@parentId", this.Id));
}
}
/// <summary>
/// The basic recursive tree pattern
/// </summary>
/// <value>The children.</value>
public virtual BusinessLogic.console.IconI[] Children
{
get
{
System.Collections.ArrayList tmp = new System.Collections.ArrayList();
using (IRecordsReader dr = SqlHelper.ExecuteReader("SELECT id, createDate, trashed, parentId, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text FROM umbracoNode WHERE ParentID = @ParentID AND nodeObjectType = @type order by sortOrder",
SqlHelper.CreateParameter("@type", this.nodeObjectType),
SqlHelper.CreateParameter("ParentID", this.Id)))
{
while (dr.Read())
{
tmp.Add(new CMSNode(dr));
}
}
CMSNode[] retval = new CMSNode[tmp.Count];
for (int i = 0; i < tmp.Count; i++)
{
retval[i] = (CMSNode)tmp[i];
}
return retval;
}
}
/// <summary>
/// Retrieve all CMSNodes in the umbraco installation
/// Use with care.
/// </summary>
/// <value>The children of all object types.</value>
public BusinessLogic.console.IconI[] ChildrenOfAllObjectTypes
{
get
{
System.Collections.ArrayList tmp = new System.Collections.ArrayList();
IRecordsReader dr = SqlHelper.ExecuteReader("select id from umbracoNode where ParentID = " + this.Id + " order by sortOrder");
while (dr.Read())
tmp.Add(dr.GetInt("Id"));
dr.Close();
CMSNode[] retval = new CMSNode[tmp.Count];
for (int i = 0; i < tmp.Count; i++)
retval[i] = new CMSNode((int)tmp[i]);
return retval;
}
}
#region IconI members
// Unique identifier of the given node
/// <summary>
/// Unique identifier of the CMSNode, used when locating data.
/// </summary>
public Guid UniqueId
{
get { return _uniqueID; }
}
/// <summary>
/// Human readable name/label
/// </summary>
public virtual string Text
{
get { return _text; }
set
{
_text = value;
SqlHelper.ExecuteNonQuery("UPDATE umbracoNode SET text = @text WHERE id = @id",
SqlHelper.CreateParameter("@text", value.Trim()),
SqlHelper.CreateParameter("@id", this.Id));
if (_entity != null)
_entity.Name = value;
}
}
/// <summary>
/// The menu items used in the tree view
/// </summary>
[Obsolete("this is not used anywhere")]
public virtual BusinessLogic.console.MenuItemI[] MenuItems
{
get { return new BusinessLogic.console.MenuItemI[0]; }
}
/// <summary>
/// Not implemented, always returns "about:blank"
/// </summary>
public virtual string DefaultEditorURL
{
get { return "about:blank"; }
}
/// <summary>
/// The icon in the tree
/// </summary>
public virtual string Image
{
get { return m_image; }
set { m_image = value; }
}
/// <summary>
/// The "open/active" icon in the tree
/// </summary>
public virtual string OpenImage
{
get { return ""; }
}
#endregion
#endregion
#region Protected methods
/// <summary>
/// This allows inheritors to set the underlying text property without persisting the change to the database.
/// </summary>
/// <param name="txt"></param>
protected void SetText(string txt)
{
_text = txt;
if (_entity != null)
_entity.Name = txt;
}
/// <summary>
/// This is purely for a hackity hack hack hack in order to make the new Document(id, version) constructor work because
/// the Version property needs to be set on the object before setupNode is called, otherwise it never works!
/// </summary>
/// <param name="ctorArgs"></param>
internal virtual void PreSetupNode(params object[] ctorArgs)
{
//if people want to override then awesome but then we call setupNode so they need to ensure
// to call base.PreSetupNode
setupNode();
}
/// <summary>
/// Sets up the internal data of the CMSNode, used by the various constructors
/// </summary>
protected virtual void setupNode()
{
using (IRecordsReader dr = SqlHelper.ExecuteReader(SqlSingle,
SqlHelper.CreateParameter("@id", this.Id)))
{
if (dr.Read())
{
PopulateCMSNodeFromReader(dr);
}
else
{
throw new ArgumentException(string.Format("No node exists with id '{0}'", Id));
}
}
}
/// <summary>
/// Sets up the node for the content tree, this makes no database calls, just sets the underlying properties
/// </summary>
/// <param name="uniqueID">The unique ID.</param>
/// <param name="nodeObjectType">Type of the node object.</param>
/// <param name="Level">The level.</param>
/// <param name="ParentId">The newParent id.</param>
/// <param name="UserId">The user id.</param>
/// <param name="Path">The path.</param>
/// <param name="Text">The text.</param>
/// <param name="CreateDate">The create date.</param>
/// <param name="hasChildren">if set to <c>true</c> [has children].</param>
protected void SetupNodeForTree(Guid uniqueID, Guid nodeObjectType, int leve, int parentId, int userId, string path, string text,
DateTime createDate, bool hasChildren)
{
_uniqueID = uniqueID;
_nodeObjectType = nodeObjectType;
_level = leve;
_parentid = parentId;
_userId = userId;
_path = path;
_text = text;
_createDate = createDate;
HasChildren = hasChildren;
}
/// <summary>
/// Updates the temp path for the content tree.
/// </summary>
/// <param name="Path">The path.</param>
protected void UpdateTempPathForTree(string Path)
{
this._path = Path;
}
protected virtual XmlNode GetPreviewXml(XmlDocument xd, Guid version)
{
XmlDocument xmlDoc = new XmlDocument();
using (XmlReader xmlRdr = SqlHelper.ExecuteXmlReader(
"select xml from cmsPreviewXml where nodeID = @nodeId and versionId = @versionId",
SqlHelper.CreateParameter("@nodeId", Id),
SqlHelper.CreateParameter("@versionId", version)))
{
xmlDoc.Load(xmlRdr);
}
return xd.ImportNode(xmlDoc.FirstChild, true);
}
protected internal virtual bool PreviewExists(Guid versionId)
{
return (SqlHelper.ExecuteScalar<int>("SELECT COUNT(nodeId) FROM cmsPreviewXml WHERE nodeId=@nodeId and versionId = @versionId",
SqlHelper.CreateParameter("@nodeId", Id), SqlHelper.CreateParameter("@versionId", versionId)) != 0);
}
/// <summary>
/// This needs to be synchronized since we are doing multiple sql operations in one method
/// </summary>
/// <param name="x"></param>
/// <param name="versionId"></param>
[MethodImpl(MethodImplOptions.Synchronized)]
protected void SavePreviewXml(XmlNode x, Guid versionId)
{
string sql = PreviewExists(versionId) ? "UPDATE cmsPreviewXml SET xml = @xml, timestamp = @timestamp WHERE nodeId=@nodeId AND versionId = @versionId"
: "INSERT INTO cmsPreviewXml(nodeId, versionId, timestamp, xml) VALUES (@nodeId, @versionId, @timestamp, @xml)";
SqlHelper.ExecuteNonQuery(sql,
SqlHelper.CreateParameter("@nodeId", Id),
SqlHelper.CreateParameter("@versionId", versionId),
SqlHelper.CreateParameter("@timestamp", DateTime.Now),
SqlHelper.CreateParameter("@xml", x.OuterXml));
}
protected void PopulateCMSNodeFromReader(IRecordsReader dr)
{
// testing purposes only > original umbraco data hasn't any unique values ;)
// And we need to have a newParent in order to create a new node ..
// Should automatically add an unique value if no exists (or throw a decent exception)
if (dr.IsNull("uniqueID")) _uniqueID = Guid.NewGuid();
else _uniqueID = dr.GetGuid("uniqueID");
_nodeObjectType = dr.GetGuid("nodeObjectType");
_level = dr.GetShort("level");
_path = dr.GetString("path");
_parentid = dr.GetInt("parentId");
_text = dr.GetString("text");
_sortOrder = dr.GetInt("sortOrder");
_userId = dr.GetInt("nodeUser");
_createDate = dr.GetDateTime("createDate");
_isTrashed = dr.GetBoolean("trashed");
}
internal protected void PopulateCMSNodeFromUmbracoEntity(IUmbracoEntity content, Guid objectType)
{
_uniqueID = content.Key;
_nodeObjectType = objectType;
_level = content.Level;
_path = content.Path;
_parentid = content.ParentId;
_text = content.Name;
_sortOrder = content.SortOrder;
_userId = content.CreatorId;
_createDate = content.CreateDate;
_isTrashed = content.Trashed;
_entity = content;
}
internal protected void PopulateCMSNodeFromUmbracoEntity(IAggregateRoot content, Guid objectType)
{
_uniqueID = content.Key;
_nodeObjectType = objectType;
_createDate = content.CreateDate;
}
#endregion
#region Private Methods
private void XmlPopulate(XmlDocument xd, XmlNode x, bool Deep)
{
// attributes
x.Attributes.Append(xmlHelper.addAttribute(xd, "id", this.Id.ToString()));
if (this.Level > 1)
x.Attributes.Append(xmlHelper.addAttribute(xd, "parentID", this.Parent.Id.ToString()));
else
x.Attributes.Append(xmlHelper.addAttribute(xd, "parentID", "-1"));
x.Attributes.Append(xmlHelper.addAttribute(xd, "level", this.Level.ToString()));
x.Attributes.Append(xmlHelper.addAttribute(xd, "writerID", this.User.Id.ToString()));
x.Attributes.Append(xmlHelper.addAttribute(xd, "sortOrder", this.sortOrder.ToString()));
x.Attributes.Append(xmlHelper.addAttribute(xd, "createDate", this.CreateDateTime.ToString("s")));
x.Attributes.Append(xmlHelper.addAttribute(xd, "nodeName", this.Text));
x.Attributes.Append(xmlHelper.addAttribute(xd, "path", this.Path));
if (Deep)
{
//store children array here because iterating over an Array property object is very inneficient.
var children = this.Children;
foreach (Content c in children)
x.AppendChild(c.ToXml(xd, true));
}
}
#endregion
#region Events
/// <summary>
/// Calls the subscribers of a cancelable event handler,
/// stopping at the event handler which cancels the event (if any).
/// </summary>
/// <typeparam name="T">Type of the event arguments.</typeparam>
/// <param name="cancelableEvent">The event to fire.</param>
/// <param name="sender">Sender of the event.</param>
/// <param name="eventArgs">Event arguments.</param>
protected virtual void FireCancelableEvent<T>(EventHandler<T> cancelableEvent, object sender, T eventArgs) where T : CancelEventArgs
{
if (cancelableEvent != null)
{
foreach (Delegate invocation in cancelableEvent.GetInvocationList())
{
invocation.DynamicInvoke(sender, eventArgs);
if (eventArgs.Cancel)
break;
}
}
}
/// <summary>
/// Occurs before a node is saved.
/// </summary>
public static event EventHandler<SaveEventArgs> BeforeSave;
/// <summary>
/// Raises the <see cref="E:BeforeSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeSave(SaveEventArgs e)
{
FireCancelableEvent(BeforeSave, this, e);
}
/// <summary>
/// Occurs after a node is saved.
/// </summary>
public static event EventHandler<SaveEventArgs> AfterSave;
/// <summary>
/// Raises the <see cref="E:AfterSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
AfterSave(this, e);
}
/// <summary>
/// Occurs after a new node is created.
/// </summary>
public static event EventHandler<NewEventArgs> AfterNew;
/// <summary>
/// Raises the <see cref="E:AfterNew"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterNew(NewEventArgs e)
{
if (AfterNew != null)
AfterNew(this, e);
}
/// <summary>
/// Occurs before a node is deleted.
/// </summary>
public static event EventHandler<DeleteEventArgs> BeforeDelete;
/// <summary>
/// Raises the <see cref="E:BeforeDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeDelete(DeleteEventArgs e)
{
FireCancelableEvent(BeforeDelete, this, e);
}
/// <summary>
/// Occurs after a node is deleted.
/// </summary>
public static event EventHandler<DeleteEventArgs> AfterDelete;
/// <summary>
/// Raises the <see cref="E:AfterDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
/// <summary>
/// Occurs before a node is moved.
/// </summary>
public static event EventHandler<MoveEventArgs> BeforeMove;
/// <summary>
/// Raises the <see cref="E:BeforeMove"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeMove(MoveEventArgs e)
{
FireCancelableEvent(BeforeMove, this, e);
}
/// <summary>
/// Occurs after a node is moved.
/// </summary>
public static event EventHandler<MoveEventArgs> AfterMove;
/// <summary>
/// Raises the <see cref="E:AfterMove"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterMove(MoveEventArgs e)
{
if (AfterMove != null)
AfterMove(this, e);
}
#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.
/*============================================================
**
**
**
** Purpose: Your favorite String class. Native methods
** are implemented in StringNative.cpp
**
**
===========================================================*/
namespace System {
using System.Text;
using System;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Globalization;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
//
// For Information on these methods, please see COMString.cpp
//
// The String class represents a static string of characters. Many of
// the String methods perform some type of transformation on the current
// instance and return the result as a new String. All comparison methods are
// implemented as a part of String. As with arrays, character positions
// (indices) are zero-based.
[ComVisible(true)]
[Serializable]
public sealed partial class String : IComparable, ICloneable, IConvertible, IEnumerable
, IComparable<String>, IEnumerable<char>, IEquatable<String>
{
//
//NOTE NOTE NOTE NOTE
//These fields map directly onto the fields in an EE StringObject. See object.h for the layout.
//
[NonSerialized] private int m_stringLength;
// For empty strings, this will be '\0' since
// strings are both null-terminated and length prefixed
[NonSerialized] private char m_firstChar;
// The Empty constant holds the empty string value. It is initialized by the EE during startup.
// It is treated as intrinsic by the JIT as so the static constructor would never run.
// Leaving it uninitialized would confuse debuggers.
//
//We need to call the String constructor so that the compiler doesn't mark this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field which we can access
//from native.
public static readonly String Empty;
internal char FirstChar { get { return m_firstChar; } }
//
// This is a helper method for the security team. They need to uppercase some strings (guaranteed to be less
// than 0x80) before security is fully initialized. Without security initialized, we can't grab resources (the nlp's)
// from the assembly. This provides a workaround for that problem and should NOT be used anywhere else.
//
internal unsafe static string SmallCharToUpper(string strIn) {
Contract.Requires(strIn != null);
Contract.EndContractBlock();
//
// Get the length and pointers to each of the buffers. Walk the length
// of the string and copy the characters from the inBuffer to the outBuffer,
// capitalizing it if necessary. We assert that all of our characters are
// less than 0x80.
//
int length = strIn.Length;
String strOut = FastAllocateString(length);
fixed (char * inBuff = &strIn.m_firstChar, outBuff = &strOut.m_firstChar) {
for(int i = 0; i < length; i++) {
int c = inBuff[i];
Debug.Assert(c <= 0x7F, "string has to be ASCII");
// uppercase - notice that we need just one compare
if ((uint)(c - 'a') <= (uint)('z' - 'a')) c -= 0x20;
outBuff[i] = (char)c;
}
Debug.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'");
}
return strOut;
}
// Gets the character at a specified position.
//
// Spec#: Apply the precondition here using a contract assembly. Potential perf issue.
[System.Runtime.CompilerServices.IndexerName("Chars")]
public extern char this[int index] {
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
// Converts a substring of this string to an array of characters. Copies the
// characters of this string beginning at position sourceIndex and ending at
// sourceIndex + count - 1 to the character array buffer, beginning
// at destinationIndex.
//
unsafe public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count > Length - sourceIndex)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
if (destinationIndex > destination.Length - count || destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
Contract.EndContractBlock();
// Note: fixed does not like empty arrays
if (count > 0)
{
fixed (char* src = &this.m_firstChar)
fixed (char* dest = destination)
wstrcpy(dest + destinationIndex, src + sourceIndex, count);
}
}
// Returns the entire string as an array of characters.
unsafe public char[] ToCharArray() {
int length = Length;
if (length > 0)
{
char[] chars = new char[length];
fixed (char* src = &this.m_firstChar) fixed (char* dest = chars)
{
wstrcpy(dest, src, length);
}
return chars;
}
return Array.Empty<char>();
}
// Returns a substring of this string as an array of characters.
//
unsafe public char[] ToCharArray(int startIndex, int length)
{
// Range check everything.
if (startIndex < 0 || startIndex > Length || startIndex > Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
if (length > 0)
{
char[] chars = new char[length];
fixed (char* src = &this.m_firstChar) fixed (char* dest = chars)
{
wstrcpy(dest, src + startIndex, length);
}
return chars;
}
return Array.Empty<char>();
}
[Pure]
public static bool IsNullOrEmpty(String value) {
return (value == null || value.Length == 0);
}
[Pure]
public static bool IsNullOrWhiteSpace(String value) {
if (value == null) return true;
for(int i = 0; i < value.Length; i++) {
if(!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
// Gets the length of this string
//
/// This is a EE implemented function so that the JIT can recognise is specially
/// and eliminate checks on character fetchs in a loop like:
/// for(int i = 0; i < str.Length; i++) str[i]
/// The actually code generated for this will be one instruction and will be inlined.
//
// Spec#: Add postcondition in a contract assembly. Potential perf problem.
public extern int Length {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// Creates a new string with the characters copied in from ptr. If
// ptr is null, a 0-length string (like String.Empty) is returned.
//
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(char *value);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(char *value, int startIndex, int length);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte *value);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte *value, int startIndex, int length);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte *value, int startIndex, int length, Encoding enc);
unsafe static private String CreateString(sbyte *value, int startIndex, int length, Encoding enc) {
if (enc == null)
return new String(value, startIndex, length); // default to ANSI
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
if ((value + startIndex) < value) {
// overflow check
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
byte [] b = new byte[length];
try {
Buffer.Memcpy(b, 0, (byte*)value, startIndex, length);
}
catch(NullReferenceException) {
// If we got a NullReferencException. It means the pointer or
// the index is out of range
throw new ArgumentOutOfRangeException(nameof(value),
Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
return enc.GetString(b);
}
// Helper for encodings so they can talk to our buffer directly
// stringLength must be the exact size we'll expect
unsafe static internal String CreateStringFromEncoding(
byte* bytes, int byteLength, Encoding encoding)
{
Contract.Requires(bytes != null);
Contract.Requires(byteLength >= 0);
// Get our string length
int stringLength = encoding.GetCharCount(bytes, byteLength, null);
Debug.Assert(stringLength >= 0, "stringLength >= 0");
// They gave us an empty string if they needed one
// 0 bytelength might be possible if there's something in an encoder
if (stringLength == 0)
return String.Empty;
String s = FastAllocateString(stringLength);
fixed(char* pTempChars = &s.m_firstChar)
{
int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
Debug.Assert(stringLength == doubleCheck,
"Expected encoding.GetChars to return same length as encoding.GetCharCount");
}
return s;
}
// This is only intended to be used by char.ToString.
// It is necessary to put the code in this class instead of Char, since m_firstChar is a private member.
// Making m_firstChar internal would be dangerous since it would make it much easier to break String's immutability.
internal static string CreateFromChar(char c)
{
string result = FastAllocateString(1);
result.m_firstChar = c;
return result;
}
unsafe internal int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer,Encoding encoding)
{
// encoding == Encoding.UTF8
fixed (char* pwzChar = &this.m_firstChar)
{
return encoding.GetBytes(pwzChar, m_stringLength, pbNativeBuffer, cbNativeBuffer);
}
}
unsafe internal int ConvertToAnsi(byte *pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar)
{
Debug.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
const uint CP_ACP = 0;
int nb;
const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
uint flgs = (fBestFit ? 0 : WC_NO_BEST_FIT_CHARS);
uint DefaultCharUsed = 0;
fixed (char* pwzChar = &this.m_firstChar)
{
nb = Win32Native.WideCharToMultiByte(
CP_ACP,
flgs,
pwzChar,
this.Length,
pbNativeBuffer,
cbNativeBuffer,
IntPtr.Zero,
(fThrowOnUnmappableChar ? new IntPtr(&DefaultCharUsed) : IntPtr.Zero));
}
if (0 != DefaultCharUsed)
{
throw new ArgumentException(Environment.GetResourceString("Interop_Marshal_Unmappable_Char"));
}
pbNativeBuffer[nb] = 0;
return nb;
}
// Normalization Methods
// These just wrap calls to Normalization class
public bool IsNormalized()
{
// Default to Form C
return IsNormalized(NormalizationForm.FormC);
}
public bool IsNormalized(NormalizationForm normalizationForm)
{
if (this.IsFastSort())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if( normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD )
return true;
}
return Normalization.IsNormalized(this, normalizationForm);
}
public String Normalize()
{
// Default to Form C
return Normalize(NormalizationForm.FormC);
}
public String Normalize(NormalizationForm normalizationForm)
{
if (this.IsAscii())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if( normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD )
return this;
}
return Normalization.Normalize(this, normalizationForm);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static String FastAllocateString(int length);
// Creates a new string from the characters in a subarray. The new string will
// be created from the characters in value between startIndex and
// startIndex + length - 1.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char [] value, int startIndex, int length);
// Creates a new string from the characters in a subarray. The new string will be
// created from the characters in value.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char [] value);
internal static unsafe void wstrcpy(char *dmem, char *smem, int charCount)
{
Buffer.Memcpy((byte*)dmem, (byte*)smem, charCount * 2); // 2 used everywhere instead of sizeof(char)
}
private String CtorCharArray(char [] value)
{
if (value != null && value.Length != 0) {
String result = FastAllocateString(value.Length);
unsafe {
fixed (char* dest = &result.m_firstChar, source = value) {
wstrcpy(dest, source, value.Length);
}
}
return result;
}
else
return String.Empty;
}
private String CtorCharArrayStartLength(char [] value, int startIndex, int length)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
if (startIndex > value.Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
if (length > 0) {
String result = FastAllocateString(length);
unsafe {
fixed (char* dest = &result.m_firstChar, source = value) {
wstrcpy(dest, source + startIndex, length);
}
}
return result;
}
else
return String.Empty;
}
private String CtorCharCount(char c, int count)
{
if (count > 0) {
String result = FastAllocateString(count);
if (c != 0)
{
unsafe {
fixed (char* dest = &result.m_firstChar) {
char *dmem = dest;
while (((uint)dmem & 3) != 0 && count > 0) {
*dmem++ = c;
count--;
}
uint cc = (uint)((c << 16) | c);
if (count >= 4) {
count -= 4;
do{
((uint *)dmem)[0] = cc;
((uint *)dmem)[1] = cc;
dmem += 4;
count -= 4;
} while (count >= 0);
}
if ((count & 2) != 0) {
((uint *)dmem)[0] = cc;
dmem += 2;
}
if ((count & 1) != 0)
dmem[0] = c;
}
}
}
return result;
}
else if (count == 0)
return String.Empty;
else
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(count)));
}
private static unsafe int wcslen(char *ptr)
{
char *end = ptr;
// First make sure our pointer is aligned on a word boundary
int alignment = IntPtr.Size - 1;
// If ptr is at an odd address (e.g. 0x5), this loop will simply iterate all the way
while (((uint)end & (uint)alignment) != 0)
{
if (*end == 0) goto FoundZero;
end++;
}
#if !BIT64
// The following code is (somewhat surprisingly!) significantly faster than a naive loop,
// at least on x86 and the current jit.
// The loop condition below works because if "end[0] & end[1]" is non-zero, that means
// neither operand can have been zero. If is zero, we have to look at the operands individually,
// but we hope this going to fairly rare.
// In general, it would be incorrect to access end[1] if we haven't made sure
// end[0] is non-zero. However, we know the ptr has been aligned by the loop above
// so end[0] and end[1] must be in the same word (and therefore page), so they're either both accessible, or both not.
while ((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0)) {
end += 2;
}
Debug.Assert(end[0] == 0 || end[1] == 0);
if (end[0] != 0) end++;
#else // !BIT64
// Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
// 64-bit implementation: process 1 ulong (word) at a time
// What we do here is add 0x7fff from each of the
// 4 individual chars within the ulong, using MagicMask.
// If the char > 0 and < 0x8001, it will have its high bit set.
// We then OR with MagicMask, to set all the other bits.
// This will result in all bits set (ulong.MaxValue) for any
// char that fits the above criteria, and something else otherwise.
// Note that for any char > 0x8000, this will be a false
// positive and we will fallback to the slow path and
// check each char individually. This is OK though, since
// we optimize for the common case (ASCII chars, which are < 0x80).
// NOTE: We can access a ulong a time since the ptr is aligned,
// and therefore we're only accessing the same word/page. (See notes
// for the 32-bit version above.)
const ulong MagicMask = 0x7fff7fff7fff7fff;
while (true)
{
ulong word = *(ulong*)end;
word += MagicMask; // cause high bit to be set if not zero, and <= 0x8000
word |= MagicMask; // set everything besides the high bits
if (word == ulong.MaxValue) // 0xffff...
{
// all of the chars have their bits set (and therefore none can be 0)
end += 4;
continue;
}
// at least one of them didn't have their high bit set!
// go through each char and check for 0.
if (end[0] == 0) goto EndAt0;
if (end[1] == 0) goto EndAt1;
if (end[2] == 0) goto EndAt2;
if (end[3] == 0) goto EndAt3;
// if we reached here, it was a false positive-- just continue
end += 4;
}
EndAt3: end++;
EndAt2: end++;
EndAt1: end++;
EndAt0:
#endif // !BIT64
FoundZero:
Debug.Assert(*end == 0);
int count = (int)(end - ptr);
return count;
}
private unsafe String CtorCharPtr(char *ptr)
{
if (ptr == null)
return String.Empty;
#if !FEATURE_PAL
if (ptr < (char*)64000)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStringPtrNotAtom"));
#endif // FEATURE_PAL
Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
try {
int count = wcslen(ptr);
if (count == 0)
return String.Empty;
String result = FastAllocateString(count);
fixed (char* dest = &result.m_firstChar)
wstrcpy(dest, ptr, count);
return result;
}
catch (NullReferenceException) {
throw new ArgumentOutOfRangeException(nameof(ptr), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
}
private unsafe String CtorCharPtrStartLength(char *ptr, int startIndex, int length)
{
if (length < 0) {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (startIndex < 0) {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
Contract.EndContractBlock();
Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
char *pFrom = ptr + startIndex;
if (pFrom < ptr) {
// This means that the pointer operation has had an overflow
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
if (length == 0)
return String.Empty;
String result = FastAllocateString(length);
try {
fixed (char* dest = &result.m_firstChar)
wstrcpy(dest, pFrom, length);
return result;
}
catch (NullReferenceException) {
throw new ArgumentOutOfRangeException(nameof(ptr), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char c, int count);
// Returns this string.
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this;
}
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this;
}
// Method required for the ICloneable interface.
// There's no point in cloning a string since they're immutable, so we simply return this.
public Object Clone() {
Contract.Ensures(Contract.Result<Object>() != null);
Contract.EndContractBlock();
return this;
}
unsafe public static String Copy (String str) {
if (str==null) {
throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
int length = str.Length;
String result = FastAllocateString(length);
fixed(char* dest = &result.m_firstChar)
fixed(char* src = &str.m_firstChar) {
wstrcpy(dest, src, length);
}
return result;
}
public static String Intern(String str) {
if (str==null) {
throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>().Length == str.Length);
Contract.Ensures(str.Equals(Contract.Result<String>()));
Contract.EndContractBlock();
return Thread.GetDomain().GetOrInternString(str);
}
[Pure]
public static String IsInterned(String str) {
if (str==null) {
throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>() == null || Contract.Result<String>().Length == str.Length);
Contract.EndContractBlock();
return Thread.GetDomain().IsStringInterned(str);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode() {
return TypeCode.String;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(this, provider);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
return Convert.ToChar(this, provider);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(this, provider);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(this, provider);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(this, provider);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(this, provider);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return Convert.ToInt32(this, provider);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(this, provider);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(this, provider);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(this, provider);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
return Convert.ToSingle(this, provider);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
return Convert.ToDouble(this, provider);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
return Convert.ToDecimal(this, provider);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
return Convert.ToDateTime(this, provider);
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
// Is this a string that can be compared quickly (that is it has only characters > 0x80
// and not a - or '
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsFastSort();
// Is this a string that only contains characters < 0x80.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsAscii();
// Set extra byte for odd-sized strings that came from interop as BSTR.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetTrailByte(byte data);
// Try to retrieve the extra byte - returns false if not present.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool TryGetTrailByte(out byte data);
public CharEnumerator GetEnumerator() {
Contract.Ensures(Contract.Result<CharEnumerator>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
IEnumerator<char> IEnumerable<char>.GetEnumerator() {
Contract.Ensures(Contract.Result<IEnumerator<char>>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
/// <internalonly/>
IEnumerator IEnumerable.GetEnumerator() {
Contract.Ensures(Contract.Result<IEnumerator>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
// Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes.
internal unsafe static void InternalCopy(String src, IntPtr dest,int len)
{
if (len == 0)
return;
fixed(char* charPtr = &src.m_firstChar) {
byte* srcPtr = (byte*) charPtr;
byte* dstPtr = (byte*) dest;
Buffer.Memcpy(dstPtr, srcPtr, len);
}
}
internal ref char GetFirstCharRef() {
return ref m_firstChar;
}
}
}
| |
#region License Header
// /*******************************************************************************
// * Open Behavioral Health Information Technology Architecture (OBHITA.org)
// *
// * Redistribution and use in source and binary forms, with or without
// * modification, are permitted provided that the following conditions are met:
// * * Redistributions of source code must retain the above copyright
// * notice, this list of conditions and the following disclaimer.
// * * Redistributions in binary form must reproduce the above copyright
// * notice, this list of conditions and the following disclaimer in the
// * documentation and/or other materials provided with the distribution.
// * * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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
namespace ProCenter.Common
{
#region Using Statements
using System;
using System.Security.Claims;
using System.Threading;
using Extension;
using Pillar.Common.Utility;
#endregion
/// <summary>The user context class.</summary>
public class UserContext
{
#region Fields
private readonly ClaimsPrincipal _claimsPrincipal;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="UserContext" /> class.
/// </summary>
/// <param name="claimsPrincipal">The claims principal.</param>
public UserContext ( ClaimsPrincipal claimsPrincipal)
{
Check.IsNotNull ( claimsPrincipal, "Claims Principal is not defined." );
_claimsPrincipal = claimsPrincipal;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the current.
/// </summary>
/// <value>
/// The current.
/// </value>
public static UserContext Current
{
get
{
return new UserContext(Thread.CurrentPrincipal as ClaimsPrincipal);
}
}
/// <summary>
/// Gets the name of the organization.
/// </summary>
/// <value>
/// The name of the organization.
/// </value>
public string OrganizationName
{
get
{
return _claimsPrincipal.GetClaim<string> ( ProCenterClaimType.OrganizationNameClaimType );
}
}
/// <summary>
/// Gets the display name.
/// </summary>
/// <value>
/// The display name.
/// </value>
public string DisplayName
{
get
{
return string.Format ( "{0} {1}",
_claimsPrincipal.GetClaim<string> ( ProCenterClaimType.UserFirstNameClaimType ),
_claimsPrincipal.GetClaim<string> ( ProCenterClaimType.UserLastNameClaimType ) );
}
}
/// <summary>
/// Gets the organization key.
/// </summary>
/// <value>
/// The organization key.
/// </value>
public Guid? OrganizationKey
{
get { return _claimsPrincipal.GetClaim<Guid?> ( ProCenterClaimType.OrganizationKeyClaimType ); }
}
/// <summary>
/// Gets the patient key.
/// </summary>
/// <value>
/// The patient key.
/// </value>
public Guid? PatientKey
{
get { return _claimsPrincipal.GetClaim<Guid?> ( ProCenterClaimType.PatientKeyClaimType ); }
}
/// <summary>
/// Gets the staff key.
/// </summary>
/// <value>
/// The staff key.
/// </value>
public Guid? StaffKey
{
get { return _claimsPrincipal.GetClaim<Guid?> ( ProCenterClaimType.StaffKeyClaimType ); }
}
/// <summary>
/// Gets the system account key.
/// </summary>
/// <value>
/// The system account key.
/// </value>
public Guid? SystemAccountKey
{
get { return _claimsPrincipal.GetClaim<Guid?> ( ProCenterClaimType.AccountKeyClaimType ); }
}
/// <summary>
/// Gets a value indicating whether [validated].
/// </summary>
/// <value>
/// <c>true</c> if [validated]; otherwise, <c>false</c>.
/// </value>
public bool Validated
{
get { return StaffKey != null || _claimsPrincipal.GetClaim<bool?> ( ProCenterClaimType.ValidatedClaimType ) == true; }
}
/// <summary>
/// Gets the validation attempts.
/// </summary>
/// <value>
/// The validation attempts.
/// </value>
public int ValidationAttempts
{
get { return _claimsPrincipal.GetClaim<int> ( ProCenterClaimType.ValidationAttemptsClaimType ); }
}
#endregion
#region Public Methods and Operators
/// <summary>Adds afailed validation attempt to claims identity.</summary>
public void FailedValidationAttempt ()
{
var claimsIdentity = _claimsPrincipal.Identity as ClaimsIdentity;
var claim = claimsIdentity.FindFirst ( ProCenterClaimType.ValidationAttemptsClaimType );
var attempts = 0;
if ( claim != null )
{
claimsIdentity.RemoveClaim ( claim );
attempts = int.Parse ( claim.Value );
}
attempts++;
claimsIdentity.AddClaim ( new Claim ( ProCenterClaimType.ValidationAttemptsClaimType, attempts.ToString () ) );
}
/// <summary>Refreshes the validation attempts.</summary>
public void RefreshValidationAttempts ()
{
var claimsIdentity = _claimsPrincipal.Identity as ClaimsIdentity;
var claim = claimsIdentity.FindFirst ( ProCenterClaimType.ValidationAttemptsClaimType );
if ( claim != null )
{
claimsIdentity.RemoveClaim ( claim );
}
claimsIdentity.AddClaim ( new Claim ( ProCenterClaimType.ValidationAttemptsClaimType, "0" ) );
}
#endregion
}
}
| |
using Loon.Core.Geom;
using Loon.Core.Graphics.Opengl;
using Loon.Core.Input;
using Loon.Utils;
using System.Collections.Generic;
namespace Loon.Core.Graphics.Component {
public class LGesture : LComponent {
private float mX;
private float mY;
private float curveEndX;
private float curveEndY;
private bool resetGesture;
private bool autoClear;
private Path goalPath;
private LColor color = LColor.orange;
private int lineWidth;
public LGesture(int x, int y, int w, int h, bool c):base(x, y, w, h){
this.autoClear = c;
this.lineWidth = 5;
}
public LGesture(int x, int y, int w, int h) :this(x, y, w, h, true){
}
public LGesture():this(0, 0, LSystem.screenRect.width, LSystem.screenRect.height, true) {
}
public LGesture(bool flag): this(0, 0, LSystem.screenRect.width, LSystem.screenRect.height, flag) {
}
public override void CreateUI(GLEx g, int x, int y, LComponent component,
LTexture[] buttonImage) {
if (visible && goalPath != null) {
g.SetLineWidth(lineWidth);
g.SetColor(color);
g.Draw(goalPath);
g.ResetLineWidth();
g.ResetColor();
}
}
protected internal override void ProcessTouchPressed() {
int x = Touch.X();
int y = Touch.Y();
if (GetCollisionBox().Contains(x, y)) {
mX = x;
mY = y;
if (resetGesture) {
resetGesture = false;
if (goalPath != null) {
goalPath.Clear();
}
}
if (goalPath == null) {
goalPath = new Path(x, y);
} else {
goalPath.Set(x, y);
}
curveEndX = x;
curveEndY = y;
DownClick();
}
}
protected internal override void ProcessTouchReleased() {
if (autoClear) {
Clear();
}
UpClick();
}
protected internal override void ProcessTouchDragged() {
if (input.IsMoving()) {
int x = Touch.X();
int y = Touch.Y();
if (GetCollisionBox().Contains(x, y)) {
float previousX = mX;
float previousY = mY;
float dx = MathUtils.Abs(x - previousX);
float dy = MathUtils.Abs(y - previousY);
if (dx >= 3 || dy >= 3) {
float cX = curveEndX = (x + previousX) / 2;
float cY = curveEndY = (y + previousY) / 2;
if (goalPath != null) {
goalPath.QuadTo(previousX, previousY, cX, cY);
}
mX = x;
mY = y;
}
DragClick();
}
}
}
public float[] GetPoints() {
if (goalPath != null) {
return goalPath.GetPoints();
}
return null;
}
public List<Vector2f> GetList() {
if (goalPath != null) {
float[] points = goalPath.GetPoints();
int size = points.Length;
List<Vector2f> result = new List<Vector2f>(size);
for (int i = 0; i < size; i++) {
result.Add(new Vector2f(points[i], points[i + 1]));
}
return result;
}
return null;
}
private static float Distance(float x1, float y1, float x2, float y2) {
float deltaX = x1 - x2;
float deltaY = y1 - y2;
return MathUtils.Sqrt(deltaX * deltaX + deltaY * deltaY);
}
public float GetLength() {
if (goalPath != null) {
float length = 0;
float[] points = goalPath.GetPoints();
int size = points.Length;
for (int i = 0; i < size;) {
if (i < size - 3) {
length += Distance(points[0 + i], points[1 + i],
points[2 + i], points[3 + i]);
}
i += 4;
}
return length;
}
return 0;
}
public virtual float[] GetCenter()
{
if (goalPath != null) {
return goalPath.GetCenter();
}
return new float[] { 0, 0 };
}
public virtual void DragClick()
{
if (Click != null) {
Click.DragClick(this, input.GetTouchX(), input.GetTouchY());
}
}
public virtual void DownClick()
{
if (Click != null) {
Click.DownClick(this, input.GetTouchX(), input.GetTouchY());
}
}
public virtual void UpClick()
{
if (Click != null) {
Click.UpClick(this, input.GetTouchX(), input.GetTouchY());
}
}
public virtual void Clear()
{
if (goalPath != null) {
goalPath.Clear();
}
}
public virtual float GetCurveEndX()
{
return curveEndX;
}
public virtual void SetCurveEndX(float curveEndX)
{
this.curveEndX = curveEndX;
}
public virtual float GetCurveEndY()
{
return curveEndY;
}
public virtual void SetCurveEndY(float curveEndY)
{
this.curveEndY = curveEndY;
}
public virtual Path GetPath()
{
return goalPath;
}
public virtual LColor GetColor()
{
return color;
}
public virtual void SetColor(LColor color)
{
this.color = color;
}
public virtual int GetLineWidth()
{
return lineWidth;
}
public virtual void SetLineWidth(int lineWidth)
{
this.lineWidth = lineWidth;
}
public virtual bool IsAutoClear()
{
return autoClear;
}
public virtual void SetAutoClear(bool autoClear)
{
this.autoClear = autoClear;
}
public override string GetUIName() {
return "Gesture";
}
}
}
| |
// Copyright (c) 2013, Luminary Productions Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 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.
//
// Use also subject to the terms of the Leap Motion SDK Agreement available at
// https://developer.leapmotion.com/sdk_agreement
using UnityEngine;
using System.Collections;
using Leap;
using System;
using Object = UnityEngine.Object;
using Screen = UnityEngine.Screen;
public class PuzzleManager : MonoBehaviour
{
public enum SelectionMethod
{
Hover,
Tap,
Pinch
}
public float pointableScale = 0.01f;
public Material pointableMaterial = null;
public Font font = null;
public Texture2D logo = null;
public float hoverTime = 1.5f;
public float pinchRadius = 0.02f;
[HideInInspector]
public GameObject[] pointables = null;
private SelectionMethod selectionMethod = SelectionMethod.Hover;
private string[] selectionMethods = System.Enum.GetNames(typeof(SelectionMethod));
private string[] selectionDescriptions = new string[] {
"Hover over a piece to select; Drag to a new location and hover over to de-select",
"Tap on a piece once it is highlighted to select; Tap anywhere to de-select",
"Pinch a piece once it is highlighted to select; Pinch anywhere to de-select",
};
private GameObject selected = null;
private Piece selectedPiece = null;
private Vector3 pieceTargetOffset = Vector3.zero;
private Vector3 pieceTargetPosition = Vector3.zero;
private Rect selectedRect = Rect.MinMaxRect(0f, 0f, 0f, 0f);
private float pinchDistance = 0f;
private float pinchCoolOff = 0.5f;
private float nextPinch = 0f;
private float selectedTime = 0f;
private int[] pointableIDs = null;
private WebCamPictures webCamPics = null;
private GUISkin skin = null;
private Texture2D whiteTex = null;
private bool showInstructions = true;
private float snapshotCountdown = -1f;
private float snapshotWaitTime = 5f;
private void Start()
{
whiteTex = new Texture2D(1, 1, TextureFormat.RGB24, false);
whiteTex.SetPixels(new Color[] { Color.white });
whiteTex.Apply();
// Set defaults and fix incorrect scaling issue w/ distributed Unity project (units are in mm, not cm)
Leap.UnityVectorExtension.InputOffset = Vector3.zero;
Leap.UnityVectorExtension.InputScale = Vector3.one * 0.001f;
LeapInputEx.Controller.EnableGesture(Gesture.GestureType.TYPECIRCLE);
LeapInputEx.Controller.EnableGesture(Gesture.GestureType.TYPEKEYTAP);
// Not sure if these are working; Experimenting with these to improve the key tap
// Debug.Log(LeapInputEx.Controller.Config.SetFloat("Gesture.KeyTap.MinDownVelocity", 0f));
// Debug.Log(LeapInputEx.Controller.Config.SetFloat("Gesture.KeyTap.MinDistance", 0f));
// Debug.Log(LeapInputEx.Controller.Config.Save());
LeapInputEx.Controller.EnableGesture(Gesture.GestureType.TYPESWIPE);
LeapInputEx.GestureDetected += OnGestureDetected;
pointables = new GameObject[10];
pointableIDs = new int[pointables.Length];
for( int i = 0; i < pointables.Length; i++ )
{
pointableIDs[i] = -1;
pointables[i] = CreatePointable(transform, i);
}
LeapInputEx.PointableFound += OnPointableFound;
LeapInputEx.PointableLost += OnPointableLost;
LeapInputEx.PointableUpdated += OnPointableUpdated;
foreach (GameObject pointable in pointables)
{
updatePointable(Leap.Pointable.Invalid, pointable);
}
webCamPics = GetComponentInChildren<WebCamPictures>();
}
private void Update ()
{
LeapInputEx.Update();
if (webCamPics.Ready)
{
snapshotCountdown -= Time.deltaTime;
if (!webCamPics.snapshotTaken && snapshotCountdown < 0f)
{
webCamPics.TakeSnapshot();
}
}
if (selectedPiece)
{
Vector3 position = Vector3.zero;
int activePointables = 0;
foreach (GameObject pointable in pointables)
{
if (pointable.active)
{
position += pointable.transform.position;
activePointables++;
}
}
if (activePointables > 0)
{
position = position * 1f / activePointables;
position.y = selectedPiece.transform.position.y;
position += pieceTargetOffset;
if (!collider.bounds.Contains(position))
{
position = collider.ClosestPointOnBounds(position);
}
pieceTargetPosition = position;
}
selectedPiece.transform.position = Vector3.Lerp(selectedPiece.transform.position, pieceTargetPosition, Time.deltaTime);
if (selected)
{
// If the object is also selected, then we need to update the outline rect
GenerateSelectedRect();
}
}
if (selected)
{
// The switch is a special case where we only want to handle a tap
if (selected.GetComponent<Switch>())
{
selectedTime = hoverTime;
}
else
{
switch (selectionMethod)
{
case SelectionMethod.Hover:
selectedTime = Mathf.Clamp(selectedTime + Time.deltaTime, 0f, hoverTime);
if (selectedTime >= hoverTime)
{
TriggerSelected();
}
break;
default:
selectedTime = hoverTime;
break;
}
}
}
// Pinch is handled separately as a piece can be de-selected even when the pointables are not inside the volume
if (selectionMethod == SelectionMethod.Pinch)
{
selectedTime = hoverTime;
GameObject firstPointable = null;
if (Time.time >= nextPinch)
{
foreach (GameObject p in pointables)
{
if (!p.active)
continue;
if (firstPointable)
{
pinchDistance = Vector3.Distance(firstPointable.transform.position, p.transform.position);
if (pinchDistance <= pinchRadius)
{
if (selected)
{
TriggerSelected();
}
else if (selectedPiece)
{
// Allow for a selected piece to be de-selected even if we are not inside the collision volume
selectedPiece = null;
}
nextPinch = Time.time + pinchCoolOff;
}
break;
}
else
{
firstPointable = p;
}
}
}
}
}
private void TriggerSelected()
{
// De-select the selected piece if this new selection is the same one
if (selectedPiece && selectedPiece.gameObject == selected)
{
selectedPiece = null;
}
else
{
selectedPiece = selected.GetComponent<Piece>();
if (selectedPiece)
{
// All pointables are averaged, since we don't know which pointable is necessarily the "right" one to
// track in the case of multiple fingers
int activePointables = 0;
Vector3 position = Vector3.zero;
foreach (GameObject pointable in pointables)
{
if (pointable.active)
{
position += pointable.transform.position;
activePointables++;
}
}
if (activePointables > 0)
{
position = position * 1f / activePointables;
position.y = selectedPiece.transform.position.y;
}
// Calculate an offset from the lower-left corner of the piece, so that the offset is preserved when
// tracking the finger; Otherwise it will snap to the lower-left corner
if (selectedPiece.collider.bounds.Contains(position))
{
pieceTargetOffset = selectedPiece.transform.position - position;
}
}
else
{
selected.SendMessage("OnSelected");
}
}
selected = null;
}
private void EnteredTriggerVolume(GameObject go)
{
// Only allow selection after the image has been scattered
if (!webCamPics.scattered)
return;
// Only set a selection if we don't have a piece selected (i.e. switch) or if this object is the same
// as the piece that is already selected (necessary for de-selection)
if (!selectedPiece || selectedPiece.gameObject == go)
{
selected = go;
selectedTime = 0f;
GenerateSelectedRect();
}
}
private void ExitedTriggerVolume(GameObject go)
{
if (selected == go)
{
selected = null;
}
}
private void OnGestureDetected(GestureList gestures)
{
foreach (Gesture g in gestures)
{
switch (g.Type)
{
case Gesture.GestureType.TYPECIRCLE:
if (g.State == Gesture.GestureState.STATESTOP)
{
if (showInstructions)
{
StartCoroutine(webCamPics.StartPlayback());
snapshotCountdown = snapshotWaitTime;
LeapInputEx.Controller.EnableGesture(Gesture.GestureType.TYPECIRCLE, false);
showInstructions = false;
}
}
break;
case Gesture.GestureType.TYPESWIPE:
if (g.State == Gesture.GestureState.STATESTOP)
{
if (webCamPics.snapshotTaken && !webCamPics.scattered)
{
StartCoroutine(webCamPics.Scatter());
}
}
break;
case Gesture.GestureType.TYPEKEYTAP:
if ((selected && selected.GetComponent<Switch>())
|| (selectionMethod == SelectionMethod.Tap && g.State == Gesture.GestureState.STATESTOP))
{
if (selected)
{
TriggerSelected();
}
else if (selectedPiece)
{
// Allow for a selected piece to be de-selected even if we are not inside the collision volume
selectedPiece = null;
}
}
break;
}
}
}
private GameObject CreatePointable(Transform parent, int index)
{
GameObject pointable = GameObject.CreatePrimitive(PrimitiveType.Sphere);
pointable.AddComponent<Rigidbody>();
pointable.rigidbody.useGravity = false;
pointable.rigidbody.isKinematic = true;
pointable.transform.localScale = Vector3.one * pointableScale;
pointable.transform.parent = parent;
pointable.renderer.sharedMaterial = pointableMaterial;
pointable.name = "Pointable " + index;
return pointable;
}
void OnPointableUpdated(Pointable p)
{
int index = Array.FindIndex(pointableIDs, id => id == p.Id);
if( index != -1 )
{
updatePointable( p, pointables[index] );
}
}
void OnPointableFound( Pointable p )
{
int index = Array.FindIndex(pointableIDs, id => id == -1);
if( index != -1 )
{
pointableIDs[index] = p.Id;
updatePointable( p, pointables[index] );
}
}
void OnPointableLost( int lostID )
{
int index = Array.FindIndex(pointableIDs, id => id == lostID);
if( index != -1 )
{
updatePointable( Pointable.Invalid, pointables[index] );
pointableIDs[index] = -1;
}
}
private void updatePointable( Leap.Pointable pointable, GameObject pointableObject )
{
pointableObject.active = pointable.IsValid;
if ( pointable.IsValid )
{
Vector3 vPointableDir = pointable.Direction.ToUnity();
Vector3 vPointablePos = pointable.TipPosition.ToUnityTranslated();
Debug.DrawRay(vPointablePos, vPointableDir * 0.1f, Color.red);
pointableObject.transform.position = vPointablePos;
pointableObject.transform.localRotation = Quaternion.FromToRotation( Vector3.forward, vPointableDir );
}
}
private void DrawOutline(Rect selectedRect, float t, float borderWidth, Color color)
{
GUI.color = color;
// Calculate the lerp value for each section using the actual circumference traversed in a period of time
float circumference = 2f * (selectedRect.width + selectedRect.height);
float tCircumference = t * circumference;
float traceSum = selectedRect.width;
float section = Mathf.Min(tCircumference, traceSum) / selectedRect.width;
GUI.DrawTexture(new Rect(selectedRect.xMin, selectedRect.yMin,
Mathf.Lerp(0f, selectedRect.width, section), borderWidth), whiteTex);
float tracePrev = traceSum;
traceSum += selectedRect.height;
section = (Mathf.Min(tCircumference, traceSum) - tracePrev) / selectedRect.height;
GUI.DrawTexture(new Rect(selectedRect.xMax - borderWidth, selectedRect.yMin, borderWidth,
Mathf.Lerp(0f, selectedRect.height, section)), whiteTex);
tracePrev = traceSum;
traceSum += selectedRect.width;
section = (Mathf.Min(tCircumference, traceSum) - tracePrev) / selectedRect.width;
GUI.DrawTexture(new Rect(selectedRect.xMax, selectedRect.yMax - borderWidth,
-Mathf.Lerp(0f, selectedRect.width, section), borderWidth), whiteTex);
tracePrev = traceSum;
traceSum += selectedRect.height;
section = (Mathf.Min(tCircumference, traceSum) - tracePrev) / selectedRect.height;
GUI.DrawTexture(new Rect(selectedRect.xMin, selectedRect.yMax, borderWidth,
-Mathf.Lerp(0f, selectedRect.height, section)), whiteTex);
GUI.color = Color.white;
}
private void OnGUI()
{
if (skin == null)
{
skin = Object.Instantiate(GUI.skin) as GUISkin;
skin.font = font;
skin.toggle.fontSize = 10;
}
GUI.skin = skin;
if (selected)
{
DrawOutline(selectedRect, selectedTime / hoverTime, 4f, Color.yellow);
}
Rect fullScreenRect = new Rect(0, 0, Screen.width, Screen.height);
GUILayout.FlexibleSpace();
Rect backgroundRect = fullScreenRect;
backgroundRect.y = Screen.height - 50f;
GUI.color = new Color(1f, 1f, 1f, 0.25f);
GUI.DrawTexture(backgroundRect, whiteTex);
GUI.color = Color.white;
GUILayout.BeginArea(fullScreenRect);
selectionMethod = (SelectionMethod)GUILayout.Toolbar((int)selectionMethod, selectionMethods);
GUILayout.Label(selectionDescriptions[(int)selectionMethod]);
// GUILayout.Label(pinchDistance.ToString());
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.Space(10f);
GUILayout.Label("Experiment #4: Basic Selections");
GUILayout.FlexibleSpace();
GUILayout.Label(logo, GUIStyle.none);
GUILayout.Space(10f);
GUILayout.EndHorizontal();
GUILayout.Space(10f);
GUILayout.EndArea();
if (snapshotCountdown > 0f)
{
GUIStyle s = new GUIStyle();
s.fontSize = 50;
GUILayout.BeginArea(fullScreenRect);
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(Mathf.CeilToInt(snapshotCountdown).ToString(), s);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.FlexibleSpace();
GUILayout.EndArea();
}
if (showInstructions)
{
GUI.color = new Color(0f, 0f, 0f, 0.5f);
GUI.DrawTexture(fullScreenRect, whiteTex);
GUI.color = Color.white;
GUILayout.BeginArea(fullScreenRect);
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Draw a circle to take a picture\nAfterwards, swipe to scatter");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.FlexibleSpace();
GUILayout.EndArea();
}
}
private void GenerateSelectedRect()
{
if (selected)
{
Bounds? selectedBounds = null;
// Collect the bounds of all of the meshes for this object in local space as an optimization,
// since we can then transform that bounding box by the selected object's position and orientation.
Renderer[] renderers = selected.GetComponentsInChildren<Renderer>();
foreach (Renderer r in renderers)
{
MeshFilter mf = r.GetComponent<MeshFilter>();
if (mf.sharedMesh)
{
if (!selectedBounds.HasValue)
selectedBounds = mf.sharedMesh.bounds;
else
selectedBounds.Value.Encapsulate(mf.sharedMesh.bounds);
}
}
// Collect all corners of the AABB
Vector3[] corners = new Vector3[8];
Vector3 min = selectedBounds.Value.min;
Vector3 size = selectedBounds.Value.size;
corners[0] = min;
corners[1] = min + Vector3.right * size.x;
corners[2] = min + Vector3.forward * size.z;
corners[3] = min + Vector3.right * size.x + Vector3.forward * size.z;
corners[4] = min + Vector3.up * size.y;
corners[5] = min + Vector3.right * size.x + Vector3.up * size.y;
corners[6] = min + Vector3.forward * size.z + Vector3.up * size.y;
corners[7] = min + size;
// Find the min and max coords in screen space by projecting each of the corners
selectedRect.xMin = Screen.width;
selectedRect.xMax = 0;
selectedRect.yMin = Screen.height;
selectedRect.yMax = 0;
selectedRect.xMin = float.MaxValue;
selectedRect.xMax = float.MinValue;
selectedRect.yMin = float.MaxValue;
selectedRect.yMax = float.MinValue;
Vector3[] screenPts = new Vector3[8];
for (int i = 0; i < corners.Length; i++)
{
Vector3 screenPt = Camera.main.WorldToScreenPoint(selected.transform.TransformPoint(corners[i]));
screenPts[i] = screenPt;
if (screenPt.x < selectedRect.xMin)
{
selectedRect.xMin = screenPt.x;
//Debug.Log("xMin " + i.ToString());
}
if (screenPt.y < selectedRect.yMin)
{
selectedRect.yMin = screenPt.y;
//Debug.Log("yMin " + i.ToString());
}
if (screenPt.x > selectedRect.xMax)
{
selectedRect.xMax = screenPt.x;
//Debug.Log("xMax " + i.ToString());
}
if (screenPt.y > selectedRect.yMax)
{
selectedRect.yMax = screenPt.y;
//Debug.Log("yMax " + i.ToString());
}
}
// Flip for GUI coords
selectedRect.yMin = Screen.height - selectedRect.yMin;
selectedRect.yMax = Screen.height - selectedRect.yMax;
float swap = selectedRect.yMin;
selectedRect.yMin = selectedRect.yMax;
selectedRect.yMax = swap;
}
}
}
| |
// CqlSharp.Linq - CqlSharp.Linq
// Copyright (c) 2014 Joost Reuzel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Linq;
namespace CqlSharp.Linq.Mutations
{
/// <summary>
/// Tracks changes for a specific table
/// </summary>
/// <typeparam name="TEntity"> The type of the entity. </typeparam>
internal class TableChangeTracker<TEntity> : ITableChangeTracker where TEntity : class, new()
{
private readonly object _syncLock = new object();
/// <summary>
/// the table for which changes are tracked
/// </summary>
private readonly CqlTable<TEntity> _table;
private readonly Dictionary<TEntity, EntityEntry<TEntity>> _trackedEntities;
/// <summary>
/// The tracked objects stored by reference and by key
/// </summary>
private readonly Dictionary<EntityKey<TEntity>, EntityEntry<TEntity>> _trackedEntitiesByKey;
/// <summary>
/// Initializes a new instance of the <see cref="CqlChangeTracker" /> class.
/// </summary>
public TableChangeTracker(CqlTable<TEntity> table)
{
_table = table;
_trackedEntities =
new Dictionary<TEntity, EntityEntry<TEntity>>(ObjectReferenceEqualityComparer<TEntity>.Instance);
_trackedEntitiesByKey = new Dictionary<EntityKey<TEntity>, EntityEntry<TEntity>>();
}
#region ITableChangeTracker Members
/// <summary>
/// Gets a value indicating whether this table has any changes.
/// </summary>
/// <value> <c>true</c> if [has changes]; otherwise, <c>false</c> . </value>
public bool HasChanges()
{
lock (_syncLock)
{
return _trackedEntities.Values.Any(te => te.State != EntityState.Unchanged);
}
}
/// <summary>
/// Detects all changes in the tracked entities.
/// </summary>
/// <returns> </returns>
public bool DetectChanges()
{
bool hasChanges = false;
// ReSharper disable LoopCanBeConvertedToQuery
foreach (var trackedObject in Entries())
{
hasChanges |= trackedObject.DetectChanges();
}
// ReSharper restore LoopCanBeConvertedToQuery
return hasChanges;
}
/// <summary>
/// enlists the changes to a transaction
/// </summary>
/// <param name="transaction"> transaction the changes is enlisted on </param>
/// <param name="consistency"> The consistency. </param>
/// <param name="connection"> connection to execute command on </param>
public void EnlistChanges(CqlConnection connection, CqlBatchTransaction transaction, CqlConsistency consistency)
{
foreach (var trackedObject in _trackedEntities.Values)
{
if (trackedObject.State != EntityState.Unchanged)
{
var cql = trackedObject.GetDmlStatement();
_table.Context.Database.LogQuery(cql);
var command = new CqlCommand(connection, cql, consistency) { Transaction = transaction };
command.ExecuteNonQuery();
}
}
}
public void AcceptAllChanges()
{
foreach (var trackedObject in _trackedEntities.Values)
{
switch (trackedObject.State)
{
case EntityState.Deleted:
trackedObject.State = EntityState.Detached;
break;
case EntityState.Added:
case EntityState.Modified:
trackedObject.SetOriginalValues(trackedObject.Entity);
trackedObject.State = EntityState.Unchanged;
break;
}
}
}
IEnumerable<IEntityEntry> ITableChangeTracker.Entries()
{
return Entries();
}
#endregion
/// <summary>
/// Adds the entity in an Added state.
/// </summary>
/// <param name="entity"> The entity. </param>
/// <returns> </returns>
public bool Add(TEntity entity)
{
lock (_syncLock)
{
//check if entity already tracked
if (_trackedEntities.ContainsKey(entity))
return false;
//create a new key from object
var key = EntityKey<TEntity>.Create(entity);
//check if key already tracked
if (_trackedEntitiesByKey.ContainsKey(key))
return false;
//create new entry
var entry = new EntityEntry<TEntity>(_table, key, entity, default(TEntity), EntityState.Added);
//add the entry
_trackedEntities.Add(entity, entry);
_trackedEntitiesByKey.Add(key, entry);
//okidoki
return true;
}
}
/// <summary>
/// Attaches the specified entity.
/// </summary>
/// <param name="entity"> The entity. </param>
/// <returns> </returns>
public bool Attach(TEntity entity)
{
lock (_syncLock)
{
//check if entity already tracked
if (_trackedEntities.ContainsKey(entity))
return false;
//create a new key from object
var key = EntityKey<TEntity>.Create(entity);
//check if key already tracked
if (_trackedEntitiesByKey.ContainsKey(key))
return false;
//create new entry
var original = EntityHelper<TEntity>.Instance.Clone(entity);
var entry = new EntityEntry<TEntity>(_table, key, entity, original, EntityState.Unchanged);
//add the entry
_trackedEntities.Add(entity, entry);
_trackedEntitiesByKey.Add(key, entry);
//okidoki
return true;
}
}
/// <summary>
/// Detaches the specified entity.
/// </summary>
/// <returns> </returns>
public bool Detach(TEntity entity)
{
lock (_syncLock)
{
EntityEntry<TEntity> entry;
if (!_trackedEntities.TryGetValue(entity, out entry))
return false;
//entry found, remove it
_trackedEntities.Remove(entity);
_trackedEntitiesByKey.Remove(entry.Key);
//okidoki
return true;
}
}
/// <summary>
/// Deletes the specified entity.
/// </summary>
/// <param name="entity"> The entity. </param>
public void Delete(TEntity entity)
{
lock (_syncLock)
{
EntityEntry<TEntity> entry;
if (!_trackedEntities.TryGetValue(entity, out entry))
{
//entity not tracked yet. Create entry.
var key = EntityKey<TEntity>.Create(entity);
entry = new EntityEntry<TEntity>(_table, key, entity,
default(TEntity), EntityState.Deleted);
//add the entry
_trackedEntities.Add(entity, entry);
_trackedEntitiesByKey.Add(key, entry);
}
entry.State = EntityState.Deleted;
}
}
/// <summary>
/// Gets or adds the row as described by the entity. If an entity with an identical key
/// already is tracked, this already tracked entity is returned
/// </summary>
/// <param name="entity"> The entity. </param>
/// <returns> </returns>
public TEntity GetOrAttach(TEntity entity)
{
lock (_syncLock)
{
//check if entity contained in entity reference list
if (_trackedEntities.ContainsKey(entity))
return entity;
//check if entity with same key is already tracked
EntityEntry<TEntity> entry;
if (_trackedEntitiesByKey.TryGetValue(new EntityKey<TEntity>(entity), out entry))
{
return entry.Entity;
}
//entry not existing yet, attach it.
Attach(entity);
//return entity
return entity;
}
}
/// <summary>
/// Tries the get entity by key.
/// </summary>
/// <param name="key"> The key. </param>
/// <param name="entity"> The entity. </param>
/// <returns> </returns>
public bool TryGetEntityByKey(EntityKey<TEntity> key, out TEntity entity)
{
lock (_syncLock)
{
EntityEntry<TEntity> entry;
if (_trackedEntitiesByKey.TryGetValue(key, out entry))
{
entity = entry.Entity;
return true;
}
entity = default(TEntity);
return false;
}
}
public IEnumerable<TEntity> Entities()
{
return _trackedEntities.Keys;
}
public IEnumerable<EntityEntry<TEntity>> Entries()
{
return _trackedEntities.Values;
}
/// <summary>
/// Tries to get the tracked entry related to the provided entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="entry">The entry.</param>
/// <returns></returns>
public bool TryGetEntry(TEntity entity, out EntityEntry<TEntity> entry)
{
lock (_syncLock)
{
return _trackedEntities.TryGetValue(entity, out entry);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using FlatRedBall.Instructions.Reflection;
namespace FlatRedBall.Gui
{
#region Struct
#region XML Docs
/// <summary>
/// Settings which can be used to set the visibility of member elements
/// depending on the value of another member.
/// </summary>
/// <remarks>
/// This enum is used by MemberVisibleCondition which is used in the
/// PropertyGrid's SetConditionalMemberVisibility method to set how the
/// state of one property can impact the visibility of another property.
/// </remarks>
#endregion
public enum VisibilitySetting
{
IncludeOnTrue = 1,
IncludeOnFalse = 2,
ExcludeOnTrue = 4,
ExcludeOnFalse = 8
}
struct MemberVisibleCondition
{
public MemberCondition MemberCondition;
public VisibilitySetting VisibilitySettings;
public string MemberToAffect;
public MemberVisibleCondition(MemberCondition memberCondition,
VisibilitySetting visibilitySetting,
string memberToAffect)
{
MemberCondition = memberCondition;
VisibilitySettings = visibilitySetting;
MemberToAffect = memberToAffect;
}
}
#endregion
#region XML Docs
/// <summary>
/// Base non-generic class for the generic PropertyWindowAssociation class.
/// </summary>
/// <remarks>
/// Contains information about an element in the PropertyGrid. Information includes the
/// UI element displaying the property, its associated Label, the member name, read/write
/// permissions, and category.
/// </remarks>
#endregion
public class PropertyWindowAssociation
{
#region Fields
#region XML Docs
/// <summary>
/// The window that allows for editing of the property.
/// </summary>
/// <remarks>
/// Fore example, a bool property would have a ComboBox.
/// </remarks>
#endregion
internal IWindow Window;
#if !SILVERLIGHT
internal TextDisplay Label;
#endif
internal Type Type;
internal string MemberName;
internal bool CanRead;
internal bool CanWrite;
internal MemberTypes ReferencedMemberType;
internal List<MemberVisibleCondition> mMemberVisibleConditions =
new List<MemberVisibleCondition>();
#region XML Docs
/// <summary>
/// When a property is not a base type understood by
/// the PropertyGrid it is represented by a button. These
/// properties can then be viewed in their own PropertyGrid.
/// Even if CanWrite is false on these properties the user should
/// still be able to view them. If CanWrite is false but this is
/// true then the UI (button) representing this property will be enabled.
/// </summary>
#endregion
internal bool IsViewable;
internal string Category = "";
#region XML Docs
/// <summary>
/// Raised whenever a property is changed through the PropertyGrid.
/// </summary>
#endregion
internal event FlatRedBall.Gui.GuiMessage ChangeEvent;
internal bool IsStatic = false;
#region XML Docs
/// <summary>
/// The window that allows for more detailed editing of an object.
/// This window will appear if the user clicks on an "Edit Property" button.
/// </summary>
/// <remarks>
/// Some types like ints and floats have natural representations, but other custom
/// types do not. Therefore if a member that the PropertyGrid does not how to display
/// is included, then the PropertyGrid will show a button that says "Edit Property". Pressing
/// this button will bring up a new window which will show the details of an object in a new PropertyGrid
/// or ListBox. This will hold the reference to the window.
///
/// Holding the reference not only eliminates some garbage collection and memory allocation, but it also allows
/// the user to get a reference to it to add events for custom behavior.
/// </remarks>
#endregion
internal Window ChildFloatingWindow;
#endregion
#region Properties
internal virtual bool IsTypedPropertyWindowAssociation
{
get { return false; }
}
#endregion
#region Event Methods
#if !SILVERLIGHT
// This is made internal so that the PropertyGrid can raise this continually so that
// window visiblity is purely reactive
internal void IncludeAndExcludeAccordingToValue(PropertyGrid propertyGrid)
{
for (int i = 0; i < mMemberVisibleConditions.Count; i++)
{
MemberVisibleCondition mvc = mMemberVisibleConditions[i];
// Update the SelectedObject
mvc.MemberCondition.SelectedObjectAsObject = propertyGrid.GetSelectedObject();
bool result = mvc.MemberCondition.Result;
#region If the member condition is true
if (result)
{
if ((mvc.VisibilitySettings & VisibilitySetting.ExcludeOnTrue) ==
VisibilitySetting.ExcludeOnTrue)
{
propertyGrid.ExcludeMember(mvc.MemberToAffect);
}
if ((mvc.VisibilitySettings & VisibilitySetting.IncludeOnTrue) ==
VisibilitySetting.IncludeOnTrue)
{
if (string.IsNullOrEmpty(this.Category))
{
propertyGrid.IncludeMember(mvc.MemberToAffect);
}
else
{
propertyGrid.IncludeMember(mvc.MemberToAffect, Category);
}
}
}
#endregion
#region Else if the member condition is false
else // result == false
{
if ((mvc.VisibilitySettings & VisibilitySetting.ExcludeOnFalse) ==
VisibilitySetting.ExcludeOnFalse)
{
propertyGrid.ExcludeMember(mvc.MemberToAffect);
}
if ((mvc.VisibilitySettings & VisibilitySetting.IncludeOnFalse) ==
VisibilitySetting.IncludeOnFalse)
{
if (string.IsNullOrEmpty(this.Category))
{
propertyGrid.IncludeMember(mvc.MemberToAffect);
}
else
{
propertyGrid.IncludeMember(mvc.MemberToAffect, Category);
}
}
}
#endregion
}
}
#endif
#endregion
#region Methods
#if !SILVERLIGHT
internal PropertyWindowAssociation(IWindow window, TextDisplay label,
Type type, string memberName, bool canRead, bool canWrite, MemberTypes memberType, bool isStatic)
{
Window = window; Label = label; Type = type; MemberName = memberName;
CanRead = canRead;
CanWrite = canWrite;
ReferencedMemberType = memberType;
IsStatic = isStatic;
}
#endif
internal void ClearChangeEvent()
{
ChangeEvent = null;
}
public virtual void SetPropertyFor(PropertyGrid propertyGrid, object objectToSet)
{
}
#if !SILVERLIGHT
public void OnMemberChanged(IWindow callingWindow, PropertyGrid parentPropertyGrid)
{
if (ChangeEvent != null)
{
ChangeEvent((Window)callingWindow);
}
IncludeAndExcludeAccordingToValue(parentPropertyGrid);
}
#endif
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Name: ").AppendLine(MemberName + " ");
stringBuilder.Append("Category: ").AppendLine(Category);
return stringBuilder.ToString();
}
#endregion
}
#region XML Docs
/// <summary>
/// Generic class storing associations between UI elements and settings for the member
/// in the PropertyGrid.
/// </summary>
/// <remarks>
/// <seealso cref="FlatRedBall.Gui.PropertyWindowAssociation"/>
/// </remarks>
/// <typeparam name="T">The type of the member being shown.</typeparam>
#endregion
public class PropertyWindowAssociation<T> : PropertyWindowAssociation
{
#region Properties
internal override bool IsTypedPropertyWindowAssociation
{
get
{
return true ;
}
}
#endregion
#region Methods
#if !SILVERLIGHT
public PropertyWindowAssociation(Window window, TextDisplay label,
Type type, string memberName, bool canRead, bool canWrite,
MemberTypes memberType, bool isStatic) :
base(window, label, type, memberName, canRead,
canWrite, memberType, isStatic)
{
}
public override void SetPropertyFor(PropertyGrid propertyGrid, object objectToSet)
{
PropertyGrid<T> typedGrid = propertyGrid as PropertyGrid<T>;
T typedObject = (T)objectToSet;
if (typedGrid != null)
{
typedGrid.SelectedObject = typedObject;
}
else
{
throw new Exception("PropertyGrid type and object type do not match");
}
}
#endif
#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.Linq;
using System.Text;
using System.Collections.Generic;
using Xunit;
using Test.Cryptography;
namespace System.Tests
{
public partial class ConvertTests
{
[Theory]
[InlineData(new byte[0], "")]
[InlineData(new byte[] { 5, 6, 7, 8 }, "BQYHCA==")]
public void ToBase64String_Span_ProducesExpectedOutput(byte[] input, string expected)
{
Assert.Equal(expected, Convert.ToBase64String(input.AsSpan()));
Assert.Equal(expected, Convert.ToBase64String(input.AsSpan(), Base64FormattingOptions.None));
Assert.Equal(expected, Convert.ToBase64String(input.AsSpan(), Base64FormattingOptions.InsertLineBreaks));
}
[Fact]
public void ToBase64String_Span_LongWithOptions_ProducesExpectedOutput()
{
byte[] input = Enumerable.Range(0, 120).Select(i => (byte)i).ToArray();
Assert.Equal(
"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4" +
"OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3Bx" +
"cnN0dXZ3",
Convert.ToBase64String(input));
Assert.Equal(
"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4" +
"OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3Bx" +
"cnN0dXZ3",
Convert.ToBase64String(input, Base64FormattingOptions.None));
Assert.Equal(
"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4\r\n" +
"OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3Bx\r\n" +
"cnN0dXZ3",
Convert.ToBase64String(input, Base64FormattingOptions.InsertLineBreaks));
}
[Theory]
[InlineData((Base64FormattingOptions)(-1))]
[InlineData((Base64FormattingOptions)(2))]
public void ToBase64String_Span_InvalidOptions_Throws(Base64FormattingOptions invalidOption)
{
AssertExtensions.Throws<ArgumentException>("options", () => Convert.ToBase64String(new byte[0].AsSpan(), invalidOption));
}
[Theory]
[InlineData(new byte[0], "")]
[InlineData(new byte[] { 5, 6, 7, 8 }, "BQYHCA==")]
public void TryToBase64Chars_ProducesExpectedOutput(byte[] input, string expected)
{
Span<char> dest;
// Just right
dest = new char[expected.Length];
Assert.True(Convert.TryToBase64Chars(input.AsSpan(), dest, out int charsWritten));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal<char>(expected.ToCharArray(), dest.ToArray());
// Too short
if (expected.Length > 0)
{
dest = new char[expected.Length - 1];
Assert.False(Convert.TryToBase64Chars(input.AsSpan(), dest, out charsWritten));
Assert.Equal(0, charsWritten);
}
// Longer than needed
dest = new char[expected.Length + 1];
Assert.True(Convert.TryToBase64Chars(input.AsSpan(), dest, out charsWritten));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal<char>(expected.ToCharArray(), dest.Slice(0, expected.Length).ToArray());
Assert.Equal(0, dest[dest.Length - 1]);
}
[Theory]
[InlineData((Base64FormattingOptions)(-1))]
[InlineData((Base64FormattingOptions)(2))]
public void TryToBase64Chars_InvalidOptions_Throws(Base64FormattingOptions invalidOption)
{
AssertExtensions.Throws<ArgumentException>("options",
() => Convert.TryToBase64Chars(new byte[0].AsSpan(), new char[0].AsSpan(), out int charsWritten, invalidOption));
}
[Theory]
[MemberData(nameof(Base64TestData))]
public static void TryFromBase64String(string encoded, byte[] expected)
{
if (expected == null)
{
Span<byte> actual = new byte[1000];
bool success = Convert.TryFromBase64String(encoded, actual, out int bytesWritten);
Assert.False(success);
Assert.Equal(0, bytesWritten);
}
else
{
// Exact-sized buffer
{
byte[] actual = new byte[expected.Length];
bool success = Convert.TryFromBase64String(encoded, actual, out int bytesWritten);
Assert.True(success);
Assert.Equal<byte>(expected, actual);
Assert.Equal(expected.Length, bytesWritten);
}
// Buffer too short
if (expected.Length != 0)
{
byte[] actual = new byte[expected.Length - 1];
bool success = Convert.TryFromBase64String(encoded, actual, out int bytesWritten);
Assert.False(success);
Assert.Equal(0, bytesWritten);
}
// Buffer larger than needed
{
byte[] actual = new byte[expected.Length + 1];
actual[expected.Length] = 99;
bool success = Convert.TryFromBase64String(encoded, actual, out int bytesWritten);
Assert.True(success);
Assert.Equal(99, actual[expected.Length]);
Assert.Equal<byte>(expected, actual.Take(expected.Length));
Assert.Equal(expected.Length, bytesWritten);
}
}
}
[Theory]
[MemberData(nameof(Base64TestData))]
public static void TryFromBase64Chars(string encodedAsString, byte[] expected)
{
ReadOnlySpan<char> encoded = encodedAsString; // Executing the conversion to ROS here so people debugging don't have to step through it at the api callsite.
if (expected == null)
{
Span<byte> actual = new byte[1000];
bool success = Convert.TryFromBase64Chars(encoded, actual, out int bytesWritten);
Assert.False(success);
Assert.Equal(0, bytesWritten);
}
else
{
// Exact-sized buffer
{
byte[] actual = new byte[expected.Length];
bool success = Convert.TryFromBase64Chars(encoded, actual, out int bytesWritten);
Assert.True(success);
Assert.Equal<byte>(expected, actual);
Assert.Equal(expected.Length, bytesWritten);
}
// Buffer too short
if (expected.Length != 0)
{
byte[] actual = new byte[expected.Length - 1];
bool success = Convert.TryFromBase64Chars(encoded, actual, out int bytesWritten);
Assert.False(success);
Assert.Equal(0, bytesWritten);
}
// Buffer larger than needed
{
byte[] actual = new byte[expected.Length + 1];
actual[expected.Length] = 99;
bool success = Convert.TryFromBase64Chars(encoded, actual, out int bytesWritten);
Assert.True(success);
Assert.Equal(99, actual[expected.Length]);
Assert.Equal<byte>(expected, actual.Take(expected.Length));
Assert.Equal(expected.Length, bytesWritten);
}
}
}
public static IEnumerable<object[]> Base64TestData
{
get
{
foreach (Tuple<string, byte[]> tuple in Base64TestDataSeed)
{
yield return new object[] { tuple.Item1, tuple.Item2 };
yield return new object[] { InsertSpaces(tuple.Item1, 1), tuple.Item2 };
yield return new object[] { InsertSpaces(tuple.Item1, 4), tuple.Item2 };
}
}
}
public static IEnumerable<Tuple<string, byte[]>> Base64TestDataSeed
{
get
{
// Empty
yield return Tuple.Create<string, byte[]>("", Array.Empty<byte>());
// All whitespace characters.
yield return Tuple.Create<string, byte[]>(" \t\r\n", Array.Empty<byte>());
// Pad characters
yield return Tuple.Create<string, byte[]>("BQYHCAZ=", "0506070806".HexToByteArray());
yield return Tuple.Create<string, byte[]>("BQYHCA==", "05060708".HexToByteArray());
// Typical
yield return Tuple.Create<string, byte[]>(
"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0" +
"BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3",
("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E" +
"3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F7071727374757677").HexToByteArray()
);
// Input length not multiple of 4
yield return Tuple.Create<string, byte[]>("A", null);
yield return Tuple.Create<string, byte[]>("AA", null);
yield return Tuple.Create<string, byte[]>("AAA", null);
yield return Tuple.Create<string, byte[]>("AAAAA", null);
yield return Tuple.Create<string, byte[]>("AAAAAA", null);
yield return Tuple.Create<string, byte[]>("AAAAAAA", null);
// Cannot continue past end pad
yield return Tuple.Create<string, byte[]>("AAA=BBBB", null);
yield return Tuple.Create<string, byte[]>("AA==BBBB", null);
// Cannot have more than two end pads
yield return Tuple.Create<string, byte[]>("A===", null);
yield return Tuple.Create<string, byte[]>("====", null);
// Verify negative entries of charmap.
for (int i = 0; i < 256; i++)
{
char c = (char)i;
if (!IsValidBase64Char(c))
{
string text = new string(c, 1) + "AAA";
yield return Tuple.Create<string, byte[]>(text, null);
}
}
// Verify >255 character handling.
string largerThanByte = new string((char)256, 1);
yield return Tuple.Create<string, byte[]>(largerThanByte + "AAA", null);
yield return Tuple.Create<string, byte[]>("A" + largerThanByte + "AA", null);
yield return Tuple.Create<string, byte[]>("AA" + largerThanByte + "A", null);
yield return Tuple.Create<string, byte[]>("AAA" + largerThanByte, null);
yield return Tuple.Create<string, byte[]>("AAAA" + largerThanByte + "AAA", null);
yield return Tuple.Create<string, byte[]>("AAAA" + "A" + largerThanByte + "AA", null);
yield return Tuple.Create<string, byte[]>("AAAA" + "AA" + largerThanByte + "A", null);
yield return Tuple.Create<string, byte[]>("AAAA" + "AAA" + largerThanByte, null);
// Verify positive entries of charmap.
yield return Tuple.Create<string, byte[]>("+A==", new byte[] { 0xf8 });
yield return Tuple.Create<string, byte[]>("/A==", new byte[] { 0xfc });
yield return Tuple.Create<string, byte[]>("0A==", new byte[] { 0xd0 });
yield return Tuple.Create<string, byte[]>("1A==", new byte[] { 0xd4 });
yield return Tuple.Create<string, byte[]>("2A==", new byte[] { 0xd8 });
yield return Tuple.Create<string, byte[]>("3A==", new byte[] { 0xdc });
yield return Tuple.Create<string, byte[]>("4A==", new byte[] { 0xe0 });
yield return Tuple.Create<string, byte[]>("5A==", new byte[] { 0xe4 });
yield return Tuple.Create<string, byte[]>("6A==", new byte[] { 0xe8 });
yield return Tuple.Create<string, byte[]>("7A==", new byte[] { 0xec });
yield return Tuple.Create<string, byte[]>("8A==", new byte[] { 0xf0 });
yield return Tuple.Create<string, byte[]>("9A==", new byte[] { 0xf4 });
yield return Tuple.Create<string, byte[]>("AA==", new byte[] { 0x00 });
yield return Tuple.Create<string, byte[]>("BA==", new byte[] { 0x04 });
yield return Tuple.Create<string, byte[]>("CA==", new byte[] { 0x08 });
yield return Tuple.Create<string, byte[]>("DA==", new byte[] { 0x0c });
yield return Tuple.Create<string, byte[]>("EA==", new byte[] { 0x10 });
yield return Tuple.Create<string, byte[]>("FA==", new byte[] { 0x14 });
yield return Tuple.Create<string, byte[]>("GA==", new byte[] { 0x18 });
yield return Tuple.Create<string, byte[]>("HA==", new byte[] { 0x1c });
yield return Tuple.Create<string, byte[]>("IA==", new byte[] { 0x20 });
yield return Tuple.Create<string, byte[]>("JA==", new byte[] { 0x24 });
yield return Tuple.Create<string, byte[]>("KA==", new byte[] { 0x28 });
yield return Tuple.Create<string, byte[]>("LA==", new byte[] { 0x2c });
yield return Tuple.Create<string, byte[]>("MA==", new byte[] { 0x30 });
yield return Tuple.Create<string, byte[]>("NA==", new byte[] { 0x34 });
yield return Tuple.Create<string, byte[]>("OA==", new byte[] { 0x38 });
yield return Tuple.Create<string, byte[]>("PA==", new byte[] { 0x3c });
yield return Tuple.Create<string, byte[]>("QA==", new byte[] { 0x40 });
yield return Tuple.Create<string, byte[]>("RA==", new byte[] { 0x44 });
yield return Tuple.Create<string, byte[]>("SA==", new byte[] { 0x48 });
yield return Tuple.Create<string, byte[]>("TA==", new byte[] { 0x4c });
yield return Tuple.Create<string, byte[]>("UA==", new byte[] { 0x50 });
yield return Tuple.Create<string, byte[]>("VA==", new byte[] { 0x54 });
yield return Tuple.Create<string, byte[]>("WA==", new byte[] { 0x58 });
yield return Tuple.Create<string, byte[]>("XA==", new byte[] { 0x5c });
yield return Tuple.Create<string, byte[]>("YA==", new byte[] { 0x60 });
yield return Tuple.Create<string, byte[]>("ZA==", new byte[] { 0x64 });
yield return Tuple.Create<string, byte[]>("aA==", new byte[] { 0x68 });
yield return Tuple.Create<string, byte[]>("bA==", new byte[] { 0x6c });
yield return Tuple.Create<string, byte[]>("cA==", new byte[] { 0x70 });
yield return Tuple.Create<string, byte[]>("dA==", new byte[] { 0x74 });
yield return Tuple.Create<string, byte[]>("eA==", new byte[] { 0x78 });
yield return Tuple.Create<string, byte[]>("fA==", new byte[] { 0x7c });
yield return Tuple.Create<string, byte[]>("gA==", new byte[] { 0x80 });
yield return Tuple.Create<string, byte[]>("hA==", new byte[] { 0x84 });
yield return Tuple.Create<string, byte[]>("iA==", new byte[] { 0x88 });
yield return Tuple.Create<string, byte[]>("jA==", new byte[] { 0x8c });
yield return Tuple.Create<string, byte[]>("kA==", new byte[] { 0x90 });
yield return Tuple.Create<string, byte[]>("lA==", new byte[] { 0x94 });
yield return Tuple.Create<string, byte[]>("mA==", new byte[] { 0x98 });
yield return Tuple.Create<string, byte[]>("nA==", new byte[] { 0x9c });
yield return Tuple.Create<string, byte[]>("oA==", new byte[] { 0xa0 });
yield return Tuple.Create<string, byte[]>("pA==", new byte[] { 0xa4 });
yield return Tuple.Create<string, byte[]>("qA==", new byte[] { 0xa8 });
yield return Tuple.Create<string, byte[]>("rA==", new byte[] { 0xac });
yield return Tuple.Create<string, byte[]>("sA==", new byte[] { 0xb0 });
yield return Tuple.Create<string, byte[]>("tA==", new byte[] { 0xb4 });
yield return Tuple.Create<string, byte[]>("uA==", new byte[] { 0xb8 });
yield return Tuple.Create<string, byte[]>("vA==", new byte[] { 0xbc });
yield return Tuple.Create<string, byte[]>("wA==", new byte[] { 0xc0 });
yield return Tuple.Create<string, byte[]>("xA==", new byte[] { 0xc4 });
yield return Tuple.Create<string, byte[]>("yA==", new byte[] { 0xc8 });
yield return Tuple.Create<string, byte[]>("zA==", new byte[] { 0xcc });
}
}
private static string InsertSpaces(string text, int period)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
if ((i % period) == 0)
{
sb.Append(" ");
}
sb.Append(text[i]);
}
sb.Append(" ");
return sb.ToString();
}
private static bool IsValidBase64Char(char c)
{
return c >= 'A' && c <= 'Z'
|| c >= 'a' && c <= 'z'
|| c >= '0' && c <= '9'
|| c == '+'
|| c == '/';
}
}
}
| |
//The MIT License (MIT)
//Copyright (c) 2013-2014 Omar Khudeira (http://omar.io)
//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;
// ReSharper disable CSharpWarnings::CS1591
namespace Humanizer.Bytes
{
/// <summary>
/// Represents a byte size value.
/// </summary>
public struct ByteSize : IComparable<ByteSize>, IEquatable<ByteSize>
{
public static readonly ByteSize MinValue = FromBits(long.MinValue);
public static readonly ByteSize MaxValue = FromBits(long.MaxValue);
public const long BitsInByte = 8;
public const long BytesInKilobyte = 1024;
public const long BytesInMegabyte = 1048576;
public const long BytesInGigabyte = 1073741824;
public const long BytesInTerabyte = 1099511627776;
public const string BitSymbol = "b";
public const string ByteSymbol = "B";
public const string KilobyteSymbol = "KB";
public const string MegabyteSymbol = "MB";
public const string GigabyteSymbol = "GB";
public const string TerabyteSymbol = "TB";
public long Bits { get; private set; }
public double Bytes { get; private set; }
public double Kilobytes { get; private set; }
public double Megabytes { get; private set; }
public double Gigabytes { get; private set; }
public double Terabytes { get; private set; }
public string LargestWholeNumberSymbol
{
get
{
// Absolute value is used to deal with negative values
if (Math.Abs(Terabytes) >= 1)
return TerabyteSymbol;
if (Math.Abs(Gigabytes) >= 1)
return GigabyteSymbol;
if (Math.Abs(Megabytes) >= 1)
return MegabyteSymbol;
if (Math.Abs(Kilobytes) >= 1)
return KilobyteSymbol;
if (Math.Abs(Bytes) >= 1)
return ByteSymbol;
return BitSymbol;
}
}
public double LargestWholeNumberValue
{
get
{
// Absolute value is used to deal with negative values
if (Math.Abs(Terabytes) >= 1)
return Terabytes;
if (Math.Abs(Gigabytes) >= 1)
return Gigabytes;
if (Math.Abs(Megabytes) >= 1)
return Megabytes;
if (Math.Abs(Kilobytes) >= 1)
return Kilobytes;
if (Math.Abs(Bytes) >= 1)
return Bytes;
return Bits;
}
}
public ByteSize(double byteSize)
: this()
{
// Get ceiling because bis are whole units
Bits = (long)Math.Ceiling(byteSize * BitsInByte);
Bytes = byteSize;
Kilobytes = byteSize / BytesInKilobyte;
Megabytes = byteSize / BytesInMegabyte;
Gigabytes = byteSize / BytesInGigabyte;
Terabytes = byteSize / BytesInTerabyte;
}
public static ByteSize FromBits(long value)
{
return new ByteSize(value / (double)BitsInByte);
}
public static ByteSize FromBytes(double value)
{
return new ByteSize(value);
}
public static ByteSize FromKilobytes(double value)
{
return new ByteSize(value * BytesInKilobyte);
}
public static ByteSize FromMegabytes(double value)
{
return new ByteSize(value * BytesInMegabyte);
}
public static ByteSize FromGigabytes(double value)
{
return new ByteSize(value * BytesInGigabyte);
}
public static ByteSize FromTerabytes(double value)
{
return new ByteSize(value * BytesInTerabyte);
}
/// <summary>
/// Converts the value of the current ByteSize object to a string.
/// The metric prefix symbol (bit, byte, kilo, mega, giga, tera) used is
/// the largest metric prefix such that the corresponding value is greater
/// than or equal to one.
/// </summary>
public override string ToString()
{
return string.Format("{0} {1}", LargestWholeNumberValue, LargestWholeNumberSymbol);
}
public string ToString(string format)
{
if (!format.Contains("#") && !format.Contains("0"))
format = "#.## " + format;
Func<string, bool> has = s => format.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) != -1;
Func<double, string> output = n => n.ToString(format);
if (has(TerabyteSymbol))
return output(Terabytes);
if (has(GigabyteSymbol))
return output(Gigabytes);
if (has(MegabyteSymbol))
return output(Megabytes);
if (has(KilobyteSymbol))
return output(Kilobytes);
// Byte and Bit symbol look must be case-sensitive
if (format.IndexOf(ByteSymbol, StringComparison.Ordinal) != -1)
return output(Bytes);
if (format.IndexOf(BitSymbol, StringComparison.Ordinal) != -1)
return output(Bits);
return string.Format("{0} {1}", LargestWholeNumberValue.ToString(format), LargestWholeNumberSymbol);
}
public override bool Equals(object value)
{
if (value == null)
return false;
ByteSize other;
if (value is ByteSize)
other = (ByteSize)value;
else
return false;
return Equals(other);
}
public bool Equals(ByteSize value)
{
return Bits == value.Bits;
}
public override int GetHashCode()
{
return Bits.GetHashCode();
}
public int CompareTo(ByteSize other)
{
return Bits.CompareTo(other.Bits);
}
public ByteSize Add(ByteSize bs)
{
return new ByteSize(Bits + bs.Bits);
}
public ByteSize AddBits(long value)
{
return new ByteSize(Bits + value);
}
public ByteSize AddBytes(double value)
{
return this + FromBytes(value);
}
public ByteSize AddKilobytes(double value)
{
return this + FromKilobytes(value);
}
public ByteSize AddMegabytes(double value)
{
return this + FromMegabytes(value);
}
public ByteSize AddGigabytes(double value)
{
return this + FromGigabytes(value);
}
public ByteSize AddTerabytes(double value)
{
return this + FromTerabytes(value);
}
public ByteSize Subtract(ByteSize bs)
{
return new ByteSize(Bits - bs.Bits);
}
public static ByteSize operator +(ByteSize b1, ByteSize b2)
{
return new ByteSize(b1.Bits + b2.Bits);
}
public static ByteSize operator ++(ByteSize b)
{
return new ByteSize(b.Bits++);
}
public static ByteSize operator -(ByteSize b)
{
return new ByteSize(-b.Bits);
}
public static ByteSize operator --(ByteSize b)
{
return new ByteSize(b.Bits--);
}
public static bool operator ==(ByteSize b1, ByteSize b2)
{
return b1.Bits == b2.Bits;
}
public static bool operator !=(ByteSize b1, ByteSize b2)
{
return b1.Bits != b2.Bits;
}
public static bool operator <(ByteSize b1, ByteSize b2)
{
return b1.Bits < b2.Bits;
}
public static bool operator <=(ByteSize b1, ByteSize b2)
{
return b1.Bits <= b2.Bits;
}
public static bool operator >(ByteSize b1, ByteSize b2)
{
return b1.Bits > b2.Bits;
}
public static bool operator >=(ByteSize b1, ByteSize b2)
{
return b1.Bits >= b2.Bits;
}
public static bool TryParse(string s, out ByteSize result)
{
// Arg checking
if (string.IsNullOrWhiteSpace(s))
throw new ArgumentNullException("s", "String is null or whitespace");
// Setup the result
result = new ByteSize();
// Get the index of the first non-digit character
s = s.TrimStart(); // Protect against leading spaces
int num;
var found = false;
// Pick first non-digit number
for (num = 0; num < s.Length; num++)
if (!(char.IsDigit(s[num]) || s[num] == '.'))
{
found = true;
break;
}
if (found == false)
return false;
int lastNumber = num;
// Cut the input string in half
string numberPart = s.Substring(0, lastNumber).Trim();
string sizePart = s.Substring(lastNumber, s.Length - lastNumber).Trim();
// Get the numeric part
double number;
if (!double.TryParse(numberPart, out number))
return false;
// Get the magnitude part
switch (sizePart.ToUpper())
{
case ByteSymbol:
if (sizePart == BitSymbol)
{ // Bits
if (number % 1 != 0) // Can't have partial bits
return false;
result = FromBits((long)number);
}
else
{ // Bytes
result = FromBytes(number);
}
break;
case KilobyteSymbol:
result = FromKilobytes(number);
break;
case MegabyteSymbol:
result = FromMegabytes(number);
break;
case GigabyteSymbol:
result = FromGigabytes(number);
break;
case TerabyteSymbol:
result = FromTerabytes(number);
break;
}
return true;
}
public static ByteSize Parse(string s)
{
ByteSize result;
if (TryParse(s, out result))
return result;
throw new FormatException("Value is not in the correct format");
}
}
}
// ReSharper restore CSharpWarnings::CS1591
| |
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Lucene.Net.Index
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
internal sealed class StandardDirectoryReader : DirectoryReader
{
private readonly IndexWriter writer;
private readonly SegmentInfos segmentInfos;
private readonly int termInfosIndexDivisor;
private readonly bool applyAllDeletes;
/// <summary>
/// called only from static <c>Open()</c> methods </summary>
internal StandardDirectoryReader(Directory directory, AtomicReader[] readers, IndexWriter writer, SegmentInfos sis, int termInfosIndexDivisor, bool applyAllDeletes)
: base(directory, readers)
{
this.writer = writer;
this.segmentInfos = sis;
this.termInfosIndexDivisor = termInfosIndexDivisor;
this.applyAllDeletes = applyAllDeletes;
}
/// <summary>
/// called from <c>DirectoryReader.Open(...)</c> methods </summary>
internal static DirectoryReader Open(Directory directory, IndexCommit commit, int termInfosIndexDivisor)
{
return (DirectoryReader)new FindSegmentsFileAnonymousInnerClassHelper(directory, termInfosIndexDivisor).Run(commit);
}
private class FindSegmentsFileAnonymousInnerClassHelper : SegmentInfos.FindSegmentsFile
{
private readonly int termInfosIndexDivisor;
public FindSegmentsFileAnonymousInnerClassHelper(Directory directory, int termInfosIndexDivisor)
: base(directory)
{
this.termInfosIndexDivisor = termInfosIndexDivisor;
}
protected internal override object DoBody(string segmentFileName)
{
var sis = new SegmentInfos();
sis.Read(directory, segmentFileName);
var readers = new SegmentReader[sis.Count];
for (int i = sis.Count - 1; i >= 0; i--)
{
IOException prior = null;
bool success = false;
try
{
readers[i] = new SegmentReader(sis.Info(i), termInfosIndexDivisor, IOContext.READ);
success = true;
}
catch (IOException ex)
{
prior = ex;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(prior, readers);
}
}
}
return new StandardDirectoryReader(directory, readers, null, sis, termInfosIndexDivisor, false);
}
}
/// <summary>
/// Used by near real-time search </summary>
internal static DirectoryReader Open(IndexWriter writer, SegmentInfos infos, bool applyAllDeletes)
{
// IndexWriter synchronizes externally before calling
// us, which ensures infos will not change; so there's
// no need to process segments in reverse order
int numSegments = infos.Count;
IList<SegmentReader> readers = new List<SegmentReader>();
Directory dir = writer.Directory;
SegmentInfos segmentInfos = (SegmentInfos)infos.Clone();
int infosUpto = 0;
bool success = false;
try
{
for (int i = 0; i < numSegments; i++)
{
// NOTE: important that we use infos not
// segmentInfos here, so that we are passing the
// actual instance of SegmentInfoPerCommit in
// IndexWriter's segmentInfos:
SegmentCommitInfo info = infos.Info(i);
if (Debugging.AssertsEnabled) Debugging.Assert(info.Info.Dir == dir);
ReadersAndUpdates rld = writer.readerPool.Get(info, true);
try
{
SegmentReader reader = rld.GetReadOnlyClone(IOContext.READ);
if (reader.NumDocs > 0 || writer.KeepFullyDeletedSegments)
{
// Steal the ref:
readers.Add(reader);
infosUpto++;
}
else
{
reader.DecRef();
segmentInfos.Remove(infosUpto);
}
}
finally
{
writer.readerPool.Release(rld);
}
}
writer.IncRefDeleter(segmentInfos);
StandardDirectoryReader result = new StandardDirectoryReader(dir, readers.ToArray(), writer, segmentInfos, writer.Config.ReaderTermsIndexDivisor, applyAllDeletes);
success = true;
return result;
}
finally
{
if (!success)
{
foreach (SegmentReader r in readers)
{
try
{
r.DecRef();
}
#pragma warning disable 168
catch (Exception th)
#pragma warning restore 168
{
// ignore any exception that is thrown here to not mask any original
// exception.
}
}
}
}
}
/// <summary>
/// This constructor is only used for <see cref="DoOpenIfChanged(SegmentInfos)"/> </summary>
private static DirectoryReader Open(Directory directory, SegmentInfos infos, IList<IndexReader> oldReaders, int termInfosIndexDivisor) // LUCENENET: Changed from AtomicReader to IndexReader to eliminate casting from the 1 place this is called from
{
// we put the old SegmentReaders in a map, that allows us
// to lookup a reader using its segment name
IDictionary<string, int?> segmentReaders = new Dictionary<string, int?>();
if (oldReaders != null)
{
// create a Map SegmentName->SegmentReader
for (int i = 0, c = oldReaders.Count; i < c; i++)
{
SegmentReader sr = (SegmentReader)oldReaders[i];
segmentReaders[sr.SegmentName] = i;
}
}
SegmentReader[] newReaders = new SegmentReader[infos.Count];
// remember which readers are shared between the old and the re-opened
// DirectoryReader - we have to incRef those readers
bool[] readerShared = new bool[infos.Count];
for (int i = infos.Count - 1; i >= 0; i--)
{
// find SegmentReader for this segment
int? oldReaderIndex;
segmentReaders.TryGetValue(infos.Info(i).Info.Name, out oldReaderIndex);
if (oldReaderIndex == null)
{
// this is a new segment, no old SegmentReader can be reused
newReaders[i] = null;
}
else
{
// there is an old reader for this segment - we'll try to reopen it
newReaders[i] = (SegmentReader)oldReaders[(int)oldReaderIndex];
}
bool success = false;
Exception prior = null;
try
{
SegmentReader newReader;
if (newReaders[i] == null || infos.Info(i).Info.UseCompoundFile != newReaders[i].SegmentInfo.Info.UseCompoundFile)
{
// this is a new reader; in case we hit an exception we can close it safely
newReader = new SegmentReader(infos.Info(i), termInfosIndexDivisor, IOContext.READ);
readerShared[i] = false;
newReaders[i] = newReader;
}
else
{
if (newReaders[i].SegmentInfo.DelGen == infos.Info(i).DelGen && newReaders[i].SegmentInfo.FieldInfosGen == infos.Info(i).FieldInfosGen)
{
// No change; this reader will be shared between
// the old and the new one, so we must incRef
// it:
readerShared[i] = true;
newReaders[i].IncRef();
}
else
{
// there are changes to the reader, either liveDocs or DV updates
readerShared[i] = false;
// Steal the ref returned by SegmentReader ctor:
if (Debugging.AssertsEnabled)
{
Debugging.Assert(infos.Info(i).Info.Dir == newReaders[i].SegmentInfo.Info.Dir);
Debugging.Assert(infos.Info(i).HasDeletions || infos.Info(i).HasFieldUpdates);
}
if (newReaders[i].SegmentInfo.DelGen == infos.Info(i).DelGen)
{
// only DV updates
newReaders[i] = new SegmentReader(infos.Info(i), newReaders[i], newReaders[i].LiveDocs, newReaders[i].NumDocs);
}
else
{
// both DV and liveDocs have changed
newReaders[i] = new SegmentReader(infos.Info(i), newReaders[i]);
}
}
}
success = true;
}
catch (Exception ex)
{
prior = ex;
}
finally
{
if (!success)
{
for (i++; i < infos.Count; i++)
{
if (newReaders[i] != null)
{
try
{
if (!readerShared[i])
{
// this is a new subReader that is not used by the old one,
// we can close it
newReaders[i].Dispose();
}
else
{
// this subReader is also used by the old reader, so instead
// closing we must decRef it
newReaders[i].DecRef();
}
}
catch (Exception t)
{
if (prior == null)
{
prior = t;
}
}
}
}
}
// throw the first exception
IOUtils.ReThrow(prior);
}
}
return new StandardDirectoryReader(directory, newReaders, null, infos, termInfosIndexDivisor, false);
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append(this.GetType().Name);
buffer.Append('(');
string segmentsFile = segmentInfos.GetSegmentsFileName();
if (segmentsFile != null)
{
buffer.Append(segmentsFile).Append(":").Append(segmentInfos.Version);
}
if (writer != null)
{
buffer.Append(":nrt");
}
foreach (AtomicReader r in GetSequentialSubReaders())
{
buffer.Append(' ');
buffer.Append(r);
}
buffer.Append(')');
return buffer.ToString();
}
protected internal override DirectoryReader DoOpenIfChanged()
{
return DoOpenIfChanged((IndexCommit)null);
}
protected internal override DirectoryReader DoOpenIfChanged(IndexCommit commit)
{
EnsureOpen();
// If we were obtained by writer.getReader(), re-ask the
// writer to get a new reader.
if (writer != null)
{
return DoOpenFromWriter(commit);
}
else
{
return DoOpenNoWriter(commit);
}
}
protected internal override DirectoryReader DoOpenIfChanged(IndexWriter writer, bool applyAllDeletes)
{
EnsureOpen();
if (writer == this.writer && applyAllDeletes == this.applyAllDeletes)
{
return DoOpenFromWriter(null);
}
else
{
return writer.GetReader(applyAllDeletes);
}
}
private DirectoryReader DoOpenFromWriter(IndexCommit commit)
{
if (commit != null)
{
return DoOpenFromCommit(commit);
}
if (writer.NrtIsCurrent(segmentInfos))
{
return null;
}
DirectoryReader reader = writer.GetReader(applyAllDeletes);
// If in fact no changes took place, return null:
if (reader.Version == segmentInfos.Version)
{
reader.DecRef();
return null;
}
return reader;
}
private DirectoryReader DoOpenNoWriter(IndexCommit commit)
{
if (commit == null)
{
if (IsCurrent())
{
return null;
}
}
else
{
if (m_directory != commit.Directory)
{
throw new IOException("the specified commit does not match the specified Directory");
}
if (segmentInfos != null && commit.SegmentsFileName.Equals(segmentInfos.GetSegmentsFileName(), StringComparison.Ordinal))
{
return null;
}
}
return DoOpenFromCommit(commit);
}
private DirectoryReader DoOpenFromCommit(IndexCommit commit)
{
return (DirectoryReader)new FindSegmentsFileAnonymousInnerClassHelper2(this, m_directory).Run(commit);
}
private class FindSegmentsFileAnonymousInnerClassHelper2 : SegmentInfos.FindSegmentsFile
{
private readonly StandardDirectoryReader outerInstance;
public FindSegmentsFileAnonymousInnerClassHelper2(StandardDirectoryReader outerInstance, Directory directory)
: base(directory)
{
this.outerInstance = outerInstance;
}
protected internal override object DoBody(string segmentFileName)
{
SegmentInfos infos = new SegmentInfos();
infos.Read(outerInstance.m_directory, segmentFileName);
return outerInstance.DoOpenIfChanged(infos);
}
}
internal DirectoryReader DoOpenIfChanged(SegmentInfos infos)
{
return StandardDirectoryReader.Open(m_directory, infos, GetSequentialSubReaders(), termInfosIndexDivisor);
}
public override long Version
{
get
{
EnsureOpen();
return segmentInfos.Version;
}
}
public override bool IsCurrent()
{
EnsureOpen();
if (writer == null || writer.IsClosed)
{
// Fully read the segments file: this ensures that it's
// completely written so that if
// IndexWriter.prepareCommit has been called (but not
// yet commit), then the reader will still see itself as
// current:
SegmentInfos sis = new SegmentInfos();
sis.Read(m_directory);
// we loaded SegmentInfos from the directory
return sis.Version == segmentInfos.Version;
}
else
{
return writer.NrtIsCurrent(segmentInfos);
}
}
protected internal override void DoClose()
{
Exception firstExc = null;
foreach (AtomicReader r in GetSequentialSubReaders())
{
// try to close each reader, even if an exception is thrown
try
{
r.DecRef();
}
catch (Exception t)
{
if (firstExc == null)
{
firstExc = t;
}
}
}
if (writer != null)
{
try
{
writer.DecRefDeleter(segmentInfos);
}
#pragma warning disable 168
catch (ObjectDisposedException ex)
#pragma warning restore 168
{
// this is OK, it just means our original writer was
// closed before we were, and this may leave some
// un-referenced files in the index, which is
// harmless. The next time IW is opened on the
// index, it will delete them.
}
}
// throw the first exception
IOUtils.ReThrow(firstExc);
}
public override IndexCommit IndexCommit
{
get
{
EnsureOpen();
return new ReaderCommit(segmentInfos, m_directory);
}
}
internal sealed class ReaderCommit : IndexCommit
{
internal string segmentsFileName;
internal ICollection<string> files;
internal Directory dir;
internal long generation;
internal readonly IDictionary<string, string> userData;
internal readonly int segmentCount;
internal ReaderCommit(SegmentInfos infos, Directory dir)
{
segmentsFileName = infos.GetSegmentsFileName();
this.dir = dir;
userData = infos.UserData;
files = infos.GetFiles(dir, true);
generation = infos.Generation;
segmentCount = infos.Count;
}
public override string ToString()
{
return "DirectoryReader.ReaderCommit(" + segmentsFileName + ")";
}
public override int SegmentCount => segmentCount;
public override string SegmentsFileName => segmentsFileName;
public override ICollection<string> FileNames => files;
public override Directory Directory => dir;
public override long Generation => generation;
public override bool IsDeleted => false;
public override IDictionary<string, string> UserData => userData;
public override void Delete()
{
throw new NotSupportedException("this IndexCommit does not support deletions");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CSharp.RuntimeBinder;
using Xunit;
using static Dynamic.Operator.Tests.LiftCommon;
namespace Dynamic.Operator.Tests
{
public class PlusEqualLiftTests
{
[Fact]
public static void Bool()
{
dynamic d = true;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
Assert.Throws<RuntimeBinderException>(() => d += s_byte);
Assert.Throws<RuntimeBinderException>(() => d += s_char);
Assert.Throws<RuntimeBinderException>(() => d += s_decimal);
Assert.Throws<RuntimeBinderException>(() => d += s_double);
Assert.Throws<RuntimeBinderException>(() => d += s_float);
Assert.Throws<RuntimeBinderException>(() => d += s_int);
Assert.Throws<RuntimeBinderException>(() => d += s_long);
Assert.Throws<RuntimeBinderException>(() => d += s_object);
Assert.Throws<RuntimeBinderException>(() => d += s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d += s_short);
d = true;
d += s_string;
d = true;
Assert.Throws<RuntimeBinderException>(() => d += s_uint);
Assert.Throws<RuntimeBinderException>(() => d += s_ulong);
Assert.Throws<RuntimeBinderException>(() => d += s_ushort);
}
[Fact]
public static void Byte()
{
dynamic d = (byte)1;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = (byte)1;
d += s_byte;
d = (byte)1;
d += s_char;
d = (byte)1;
d += s_decimal;
d = (byte)1;
d += s_double;
d = (byte)1;
d += s_float;
d = (byte)1;
d += s_int;
d = (byte)1;
d += s_long;
d = (byte)1;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = (byte)1;
d += s_sbyte;
d = (byte)1;
d += s_short;
d = (byte)1;
d += s_string;
d = (byte)1;
d += s_uint;
d = (byte)1;
d += s_ulong;
d = (byte)1;
d += s_ushort;
}
[Fact]
public static void Char()
{
dynamic d = 'a';
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = 'a';
d += s_byte;
d = 'a';
d += s_char;
d = 'a';
d += s_decimal;
d = 'a';
d += s_double;
d = 'a';
d += s_float;
d = 'a';
d += s_int;
d = 'a';
d += s_long;
d = 'a';
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = 'a';
d += s_sbyte;
d = 'a';
d += s_short;
d = 'a';
d += s_string;
d = 'a';
d += s_uint;
d = 'a';
d += s_ulong;
d = 'a';
d += s_ushort;
}
[Fact]
public static void Decimal()
{
dynamic d = 10m;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = 10m;
d += s_byte;
d = 10m;
d += s_char;
d = 10m;
d += s_decimal;
d = 10m;
Assert.Throws<RuntimeBinderException>(() => d += s_double);
Assert.Throws<RuntimeBinderException>(() => d += s_float);
d = 10m;
d += s_int;
d = 10m;
d += s_long;
d = 10m;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = 10m;
d += s_sbyte;
d = 10m;
d += s_short;
d = 10m;
d += s_string;
d = 10m;
d += s_uint;
d = 10m;
d += s_ulong;
d = 10m;
d += s_ushort;
}
[Fact]
public static void Double()
{
dynamic d = 10d;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = 10d;
d += s_byte;
d = 10d;
d += s_char;
d = 10d;
Assert.Throws<RuntimeBinderException>(() => d += s_decimal);
d = 10d;
d += s_double;
d = 10d;
d += s_float;
d = 10d;
d += s_int;
d = 10d;
d += s_long;
d = 10d;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = 10d;
d += s_sbyte;
d = 10d;
d += s_short;
d = 10d;
d += s_string;
d = 10d;
d += s_uint;
d = 10d;
d += s_ulong;
d = 10d;
d += s_ushort;
}
[Fact]
public static void Float()
{
dynamic d = 10f;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = 10f;
d += s_byte;
d = 10f;
d += s_char;
d = 10f;
Assert.Throws<RuntimeBinderException>(() => d += s_decimal);
d = 10f;
d += s_double;
d = 10f;
d += s_float;
d = 10f;
d += s_int;
d = 10f;
d += s_long;
d = 10f;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = 10f;
d += s_sbyte;
d = 10f;
d += s_short;
d = 10f;
d += s_string;
d = 10f;
d += s_uint;
d = 10f;
d += s_ulong;
d = 10f;
d += s_ushort;
}
[Fact]
public static void Int()
{
dynamic d = 10;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = 10;
d += s_byte;
d = 10;
d += s_char;
d = 10;
d += s_decimal;
d = 10;
d += s_double;
d = 10;
d += s_float;
d = 10;
d += s_int;
d = 10;
d += s_long;
d = 10;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = 10;
d += s_sbyte;
d = 10;
d += s_short;
d = 10;
d += s_string;
d = 10;
d += s_uint;
d = 10;
Assert.Throws<RuntimeBinderException>(() => d += s_ulong);
d = 10;
d += s_ushort;
}
[Fact]
public static void Long()
{
dynamic d = 10L;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = 10L;
d += s_byte;
d = 10L;
d += s_char;
d = 10L;
d += s_decimal;
d = 10L;
d += s_double;
d = 10L;
d += s_float;
d = 10L;
d += s_int;
d = 10L;
d += s_long;
d = 10L;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = 10L;
d += s_sbyte;
d = 10L;
d += s_short;
d = 10L;
d += s_string;
d = 10L;
d += s_uint;
d = 10L;
Assert.Throws<RuntimeBinderException>(() => d += s_ulong);
d = 10L;
d += s_ushort;
}
[Fact]
public static void Object()
{
dynamic d = new object();
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
Assert.Throws<RuntimeBinderException>(() => d += s_byte);
Assert.Throws<RuntimeBinderException>(() => d += s_char);
Assert.Throws<RuntimeBinderException>(() => d += s_decimal);
Assert.Throws<RuntimeBinderException>(() => d += s_double);
Assert.Throws<RuntimeBinderException>(() => d += s_float);
Assert.Throws<RuntimeBinderException>(() => d += s_int);
Assert.Throws<RuntimeBinderException>(() => d += s_long);
Assert.Throws<RuntimeBinderException>(() => d += s_object);
Assert.Throws<RuntimeBinderException>(() => d += s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d += s_short);
d = new object();
d += s_string;
d = new object();
Assert.Throws<RuntimeBinderException>(() => d += s_uint);
Assert.Throws<RuntimeBinderException>(() => d += s_ulong);
Assert.Throws<RuntimeBinderException>(() => d += s_ushort);
}
[Fact]
public static void SByte()
{
dynamic d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = (sbyte)10;
d += s_byte;
d = (sbyte)10;
d += s_char;
d = (sbyte)10;
d += s_decimal;
d = (sbyte)10;
d += s_double;
d = (sbyte)10;
d += s_float;
d = (sbyte)10;
d += s_int;
d = (sbyte)10;
d += s_long;
d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = (sbyte)10;
d += s_sbyte;
d = (sbyte)10;
d += s_short;
d = (sbyte)10;
d += s_string;
d = (sbyte)10;
d += s_uint;
d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d += s_ulong);
d = (sbyte)10;
d += s_ushort;
}
[Fact]
public static void Short()
{
dynamic d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = (short)10;
d += s_byte;
d = (short)10;
d += s_char;
d = (short)10;
d += s_decimal;
d = (short)10;
d += s_double;
d = (short)10;
d += s_float;
d = (short)10;
d += s_int;
d = (short)10;
d += s_long;
d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = (short)10;
d += s_sbyte;
d = (short)10;
d += s_short;
d = (short)10;
d += s_string;
d = (short)10;
d += s_uint;
d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d += s_ulong);
d = (short)10;
d += s_ushort;
}
[Fact]
public static void String()
{
dynamic d = "a";
d += s_bool;
d = "a";
d += s_byte;
d = "a";
d += s_char;
d = "a";
d += s_decimal;
d = "a";
d += s_double;
d = "a";
d += s_float;
d = "a";
d += s_int;
d = "a";
d += s_long;
d = "a";
d += s_object;
d = "a";
d += s_sbyte;
d = "a";
d += s_short;
d = "a";
d += s_string;
d = "a";
d += s_uint;
d = "a";
d += s_ulong;
d = "a";
d += s_ushort;
}
[Fact]
public static void UInt()
{
dynamic d = (uint)10;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = (uint)10;
d += s_byte;
d = (uint)10;
d += s_char;
d = (uint)10;
d += s_decimal;
d = (uint)10;
d += s_double;
d = (uint)10;
d += s_float;
d = (uint)10;
d += s_int;
d = (uint)10;
d += s_long;
d = (uint)10;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = (uint)10;
d += s_sbyte;
d = (uint)10;
d += s_short;
d = (uint)10;
d += s_string;
d = (uint)10;
d += s_uint;
d = (uint)10;
d += s_ulong;
d = (uint)10;
d += s_ushort;
}
[Fact]
public static void ULong()
{
dynamic d = (ulong)10;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = (ulong)10;
d += s_byte;
d = (ulong)10;
d += s_char;
d = (ulong)10;
d += s_decimal;
d = (ulong)10;
d += s_double;
d = (ulong)10;
d += s_float;
d = (ulong)10;
Assert.Throws<RuntimeBinderException>(() => d += s_int);
Assert.Throws<RuntimeBinderException>(() => d += s_long);
Assert.Throws<RuntimeBinderException>(() => d += s_object);
Assert.Throws<RuntimeBinderException>(() => d += s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d += s_short);
d = (ulong)10;
d += s_string;
d = (ulong)10;
d += s_uint;
d = (ulong)10;
d += s_ulong;
d = (ulong)10;
d += s_ushort;
}
[Fact]
public static void UShort()
{
dynamic d = (ushort)10;
Assert.Throws<RuntimeBinderException>(() => d += s_bool);
d = (ushort)10;
d += s_byte;
d = (ushort)10;
d += s_char;
d = (ushort)10;
d += s_decimal;
d = (ushort)10;
d += s_double;
d = (ushort)10;
d += s_float;
d = (ushort)10;
d += s_int;
d = (ushort)10;
d += s_long;
d = (ushort)10;
Assert.Throws<RuntimeBinderException>(() => d += s_object);
d = (ushort)10;
d += s_sbyte;
d = (ushort)10;
d += s_short;
d = (ushort)10;
d += s_string;
d = (ushort)10;
d += s_uint;
d = (ushort)10;
d += s_ulong;
d = (ushort)10;
d += s_ushort;
}
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Data.Core;
using Avalonia.Utilities;
#nullable enable
namespace Avalonia.Markup.Parsers
{
#if !BUILDTASK
public
#endif
class PropertyPathGrammar
{
private enum State
{
Start,
Next,
AfterProperty,
End
}
public static IEnumerable<ISyntax> Parse(string s)
{
var r = new CharacterReader(s.AsSpan());
return Parse(ref r);
}
private static IEnumerable<ISyntax> Parse(ref CharacterReader r)
{
var state = State.Start;
var parsed = new List<ISyntax>();
while (state != State.End)
{
ISyntax? syntax = null;
if (state == State.Start)
(state, syntax) = ParseStart(ref r);
else if (state == State.Next)
(state, syntax) = ParseNext(ref r);
else if (state == State.AfterProperty)
(state, syntax) = ParseAfterProperty(ref r);
if (syntax != null)
{
parsed.Add(syntax);
}
}
if (state != State.End && r.End)
{
throw new ExpressionParseException(r.Position, "Unexpected end of property path");
}
return parsed;
}
private static (State, ISyntax?) ParseNext(ref CharacterReader r)
{
r.SkipWhitespace();
if (r.End)
return (State.End, null);
return ParseStart(ref r);
}
private static (State, ISyntax) ParseStart(ref CharacterReader r)
{
if (TryParseCasts(ref r, out var rv))
return rv;
r.SkipWhitespace();
if (r.TakeIf('('))
return ParseTypeQualifiedProperty(ref r);
return ParseProperty(ref r);
}
private static (State, ISyntax) ParseTypeQualifiedProperty(ref CharacterReader r)
{
r.SkipWhitespace();
const string error =
"Unable to parse qualified property name, expected `(ns:TypeName.PropertyName)` or `(TypeName.PropertyName)` after `(`";
var typeName = ParseXamlIdentifier(ref r);
if (!r.TakeIf('.'))
throw new ExpressionParseException(r.Position, error);
var propertyName = r.ParseIdentifier();
if (propertyName.IsEmpty)
throw new ExpressionParseException(r.Position, error);
r.SkipWhitespace();
if (!r.TakeIf(')'))
throw new ExpressionParseException(r.Position,
"Expected ')' after qualified property name "
+ typeName.ns + ':' + typeName.name +
"." + propertyName.ToString());
return (State.AfterProperty,
new TypeQualifiedPropertySyntax
{
Name = propertyName.ToString(),
TypeName = typeName.name,
TypeNamespace = typeName.ns
});
}
static (string? ns, string name) ParseXamlIdentifier(ref CharacterReader r)
{
var ident = r.ParseIdentifier();
if (ident.IsEmpty)
throw new ExpressionParseException(r.Position, "Expected identifier");
if (r.TakeIf(':'))
{
var part2 = r.ParseIdentifier();
if (part2.IsEmpty)
throw new ExpressionParseException(r.Position,
"Expected the rest of the identifier after " + ident.ToString() + ":");
return (ident.ToString(), part2.ToString());
}
return (null, ident.ToString());
}
private static (State, ISyntax) ParseProperty(ref CharacterReader r)
{
r.SkipWhitespace();
var prop = r.ParseIdentifier();
if (prop.IsEmpty)
throw new ExpressionParseException(r.Position, "Unable to parse property name");
return (State.AfterProperty, new PropertySyntax {Name = prop.ToString()});
}
private static bool TryParseCasts(ref CharacterReader r, out (State, ISyntax) rv)
{
if (r.TakeIfKeyword(":="))
rv = ParseEnsureType(ref r);
else if (r.TakeIfKeyword(":>") || r.TakeIfKeyword("as "))
rv = ParseCastType(ref r);
else
{
rv = default;
return false;
}
return true;
}
private static (State, ISyntax?) ParseAfterProperty(ref CharacterReader r)
{
if (TryParseCasts(ref r, out var rv))
return rv;
r.SkipWhitespace();
if (r.End)
return (State.End, null);
if (r.TakeIf('.'))
return (State.Next, ChildTraversalSyntax.Instance);
throw new ExpressionParseException(r.Position, "Unexpected character " + r.Peek + " after property name");
}
private static (State, ISyntax) ParseEnsureType(ref CharacterReader r)
{
r.SkipWhitespace();
var type = ParseXamlIdentifier(ref r);
return (State.AfterProperty, new EnsureTypeSyntax {TypeName = type.name, TypeNamespace = type.ns});
}
private static (State, ISyntax) ParseCastType(ref CharacterReader r)
{
r.SkipWhitespace();
var type = ParseXamlIdentifier(ref r);
return (State.AfterProperty, new CastTypeSyntax {TypeName = type.name, TypeNamespace = type.ns});
}
public interface ISyntax
{
}
// Don't need to override GetHashCode as the ISyntax objects will not be stored in a hash; the
// only reason they have overridden Equals methods is for unit testing.
#pragma warning disable CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
public class PropertySyntax : ISyntax
{
public string Name { get; set; } = string.Empty;
public override bool Equals(object? obj)
=> obj is PropertySyntax other
&& other.Name == Name;
}
public class TypeQualifiedPropertySyntax : ISyntax
{
public string Name { get; set; } = string.Empty;
public string TypeName { get; set; } = string.Empty;
public string? TypeNamespace { get; set; }
public override bool Equals(object? obj)
=> obj is TypeQualifiedPropertySyntax other
&& other.Name == Name
&& other.TypeName == TypeName
&& other.TypeNamespace == TypeNamespace;
}
public class ChildTraversalSyntax : ISyntax
{
public static ChildTraversalSyntax Instance { get; } = new ChildTraversalSyntax();
public override bool Equals(object? obj) => obj is ChildTraversalSyntax;
}
public class EnsureTypeSyntax : ISyntax
{
public string TypeName { get; set; } = string.Empty;
public string? TypeNamespace { get; set; }
public override bool Equals(object? obj)
=> obj is EnsureTypeSyntax other
&& other.TypeName == TypeName
&& other.TypeNamespace == TypeNamespace;
}
public class CastTypeSyntax : ISyntax
{
public string TypeName { get; set; } = string.Empty;
public string? TypeNamespace { get; set; }
public override bool Equals(object? obj)
=> obj is CastTypeSyntax other
&& other.TypeName == TypeName
&& other.TypeNamespace == TypeNamespace;
}
#pragma warning restore CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
}
}
| |
#region Code Header
/*
* Copyright Luminary Solutions Limited
*
*/
/*
* Description : Provides logic for SCPWrappers to make calls to SCPs
*
* Class : Base class for all SCPWrappers. A wrapper is generated for each SCP
* and uses this logic to call SCPs and raise errors as exceptions if the
* call causes and error in the OpenROAD server.
*
* Class Name : SCPWrapperBase
*
* System Name : ProxyGen
*
* Sub-System Name : C# Template Code
*
* File Name : SCPWrapperBase.cs
*
* Version History
*
* Version Date Who Description
* ------- ---------- --- --------------
* 1.0 01/05/2008 LUM Original Version
*/
#endregion
#region Namespaces Used
using System;
using ORRSOLib;
#endregion
namespace Luminary.ProxyGen.Util
{
/// <summary>
/// Base class implementation for the SCPWrapper
/// </summary>
public abstract class SCPWrapperBase
{
#region Delegate Declarations
#endregion
#region Class Fields
private ORASOSessionClass orSession;
private ORPDOClass orByValParameter;
private ORPDOClass orByRefParameter;
#endregion
#region Class Properties
/// <summary>
/// The SCP name.
/// </summary>
protected virtual string SCPName
{
get
{
return String.Empty;
}
}
/// <summary>
/// The OpenROAD ASO session.
/// </summary>
public ORASOSessionClass ORSession
{
get
{
return orSession;
}
set
{
orSession = value;
}
}
/// <summary>
/// The OpenROAD ASO by value parameter object.
/// </summary>
protected ORPDOClass ORByValParameter
{
get
{
return orByValParameter;
}
set
{
orByValParameter = value;
}
}
/// <summary>
/// The OpenROAD aso by reference parameter object.
/// </summary>
protected ORPDOClass ORByRefParameter
{
get
{
return orByRefParameter;
}
set
{
orByRefParameter = value;
}
}
/// <summary>
/// Gets the contents of the ByVal parameter descriptions in an array.
/// </summary>
protected Array ByValParametersDesc
{
get
{
if (ORByValParameter != null)
{
Object paramDesc;
Object paramVal;
ORByValParameter.GetParameters(out paramDesc, out paramVal);
return paramDesc as Array;
}
else
{
return null;
}
}
}
/// <summary>
/// Gets the contents of the ByVal parameter values in an array.
/// </summary>
protected Array ByValParametersVal
{
get
{
if (ORByValParameter != null)
{
Object paramDesc;
Object paramVal;
ORByValParameter.GetParameters(out paramDesc, out paramVal);
return paramVal as Array;
}
else
{
return null;
}
}
}
/// <summary>
/// Gets the contents of the ByRef parameter descriptions in an array.
/// </summary>
protected Array ByRefParametersDesc
{
get
{
if (ORByRefParameter != null)
{
Object paramDesc;
Object paramVal;
ORByRefParameter.GetParameters(out paramDesc, out paramVal);
return paramDesc as Array;
}
else
{
return null;
}
}
}
/// <summary>
/// Gets the contents of the ByRef parameter values in an array.
/// </summary>
protected Array ByRefParametersVal
{
get
{
if (ORByRefParameter != null)
{
Object paramDesc;
Object paramVal;
ORByRefParameter.GetParameters(out paramDesc, out paramVal);
return paramVal as Array;
}
else
{
return null;
}
}
}
/// <summary>
/// Gets the contents of the SCP error number
/// </summary>
protected virtual int SCPErrorNumber
{
get
{
return ORSession.i_error_no;
}
}
/// <summary>
/// Gets the contents of the SCP error type
/// </summary>
protected virtual int SCPErrorType
{
get
{
return ORSession.i_error_type;
}
}
/// <summary>
/// Gets the contents of the SCP error text
/// </summary>
protected virtual string SCPErrorText
{
get
{
return ORSession.v_msg_txt;
}
}
#endregion
#region Class Constructors
/// <summary>
/// Default Constructor
/// </summary>
internal SCPWrapperBase()
{
InitialiseClass();
}
/// <summary>
/// Connected OpenROAD ASO session parameter constructor.
/// </summary>
/// <param name="orSession">Connected OpenROAD ASO session.</param>
public SCPWrapperBase(ORASOSessionClass orSession) :base()
{
InitialiseClass();
// set the OR Session
ORSession = orSession;
}
#endregion
#region Class Methods
/// <summary>
/// Default base class initialiser
/// </summary>
protected virtual void InitialiseClass()
{
}
#endregion
#region Protected Methods
/// <summary>
/// Call the SCP.
/// </summary>
/// <returns>The result of the SCP.</returns>
protected virtual void CallSCP()
{
try
{
// Validate we have everything we need
Validate();
// Declare the ByVal and ByRef parameter objects
DeclareAttributes();
// Populate the parameter values.
PopulateAttributes();
// Call the SCP.
Object ORByValParameterParam = ORByValParameter;
Object ORByRefParameterParam = ORByRefParameter;
CallSCPProcedure(SCPName, ref ORByValParameterParam, ref ORByRefParameterParam);
}
catch (SCPInvalidArgumentException)
{
// Throw it on.
throw;
}
catch (SCPCallException)
{
//rethrow SCPCall Exception
throw;
}
catch (Exception ex)
{
//Something went wrong in the call of the SCP - throw it on.
throw new SCPCallException(ex.Message);
}
}
/// <summary>
/// Calls the SCP procedure
/// </summary>
/// <param name="scpName">SCP Name</param>
/// <param name="byValObj">By value attributes</param>
/// <param name="byRefObj">By Ref attributes</param>
/// <returns>populated SCP response</returns>
protected virtual void CallSCPProcedure(string scpName, ref Object byValObj, ref Object byRefObj)
{
try
{
//DePopulate OSCA and add it set the RSO ByRef (but only if it has been set)
if (!OSCA.IsEmpty)
DePopulateOSCAIntoByRefPDO();
//Cast the RSO as its interface (ORRSO) not (ORRSOClass)
ORRSO orRSO = (ORRSO)ORSession.RSO;
//CallProc using RSO.
orRSO.CallProc(scpName, ref byValObj, ref byRefObj);
//Always populate OSCA with OSCA from app server.
OSCA.PopulateSelfFromByRef((ORPDOClass)byRefObj);
//Check OSCA for error
if (OSCA.ErrorNumber > 0)
{
throw new SCPCallException(OSCA.MessageText, OSCA.ErrorType, OSCA.ErrorNumber);
}
}
catch (SCPCallException)
{
throw;
}
catch (Exception ex)
{
throw new SCPCallException(ex.Message, ex);
}
}
/// <summary>
/// Depopulate static OSCA properties into the ByRef
/// </summary>
private void DePopulateOSCAIntoByRefPDO()
{
SetAttribute("b_osca.i_context_id", OSCA.ContextId);
SetAttribute("b_osca.i_error_no", OSCA.ErrorNumber);
SetAttribute("b_osca.i_error_type", OSCA.ErrorType);
SetAttribute("b_osca.v_msg_txt", OSCA.MessageText);
}
/// <summary>
/// Evaluate if a parameter is null.
/// </summary>
/// <param name="attributeName">The attribute to evaluate.</param>
/// <returns>Wheteher the attribute parameter is null or not.</returns>
protected bool IsParameterNull( string attributeName)
{
return ORByRefParameter.IsNull(attributeName) == 1;
}
/// <summary>
/// Set the attribute.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <param name="val">The value to set.</param>
protected virtual void SetAttribute(string attributeName, Object val)
{
object objVal = val;
if (val is DateTime)
{
// Convert Date & Time to UTC format as OpenROAD expects them in this format
objVal = ((DateTime)val).ToUniversalTime();
}
ORByRefParameter.SetAttribute(attributeName, ref val);
}
/// <summary>
/// Declare an individual userclass attribute.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
protected void DeclareUserClassAttribute(string attributeName)
{
// Call underlying private method
DeclareAttribute(attributeName, Constants.OR_ASA_DATATYPE_USERCLASS);
}
/// <summary>
/// Declare an individual array attribute.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
protected void DeclareArrayAttribute(string attributeName)
{
// Call underlying private method
DeclareAttribute(attributeName, Constants.OR_ASA_DATATYPE_UCARRAY);
}
/// <summary>
/// Declare an individual string attribute.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
protected void DeclareStringAttribute(string attributeName)
{
// Call underlying private method
DeclareAttribute(attributeName, Constants.OR_ASA_DATATYPE_STRING);
}
/// <summary>
/// Declare an individual small integer attribute.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
protected void DeclareSmallIntegerAttribute(string attributeName)
{
// Call underlying private method
DeclareAttribute(attributeName, Constants.OR_ASA_DATATYPE_SMALL_INTEGER);
}
/// <summary>
/// Declare an boolean attribute
/// </summary>
/// <param name="attributeName">The attribute name.</param>
protected void DeclareBooleanAttribute(string attributeName)
{
// Call underlying private method - a boolean is internally represented by a small integer
DeclareAttribute(attributeName, Constants.OR_ASA_DATATYPE_SMALL_INTEGER);
}
/// <summary>
/// Declare an individual integer attribute.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
protected void DeclareIntegerAttribute(string attributeName)
{
// Call underlying private method
DeclareAttribute(attributeName, Constants.OR_ASA_DATATYPE_INTEGER);
}
/// <summary>
/// Declare an individual float attribute.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
protected void DeclareFloatAttribute(string attributeName)
{
// Call underlying private method
DeclareAttribute(attributeName, Constants.OR_ASA_DATATYPE_FLOAT);
}
/// <summary>
/// Declare and individial money attribute.
/// </summary>
/// <param name="attributeName"></param>
protected void DeclareMoneyAttribute(string attributeName)
{
// Call underlying private method
DeclareAttribute(attributeName, Constants.OR_ASA_DATATYPE_MONEY);
}
/// <summary>
/// Declare an individual date attribute.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
protected void DeclareDateAttribute(string attributeName)
{
// call delegate
DeclareAttribute(attributeName, Constants.OR_ASA_DATATYPE_DATE);
}
/// <summary>
/// Get small integer attribute out of the ByRef parameter object.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <returns>The value from the openroad parameter.</returns>
protected short GetSmallIntegerAttribute(string attributeName)
{
// Call underlying private method
return (short) GetAttribute(attributeName);
}
/// <summary>
/// Get integer attribute out of the ByRef parameter object with default if null.
/// </summary>
/// <param name="useByValParameter">Flag to indicate which PDO to use.</param>
/// <param name="attributeName">The attribute name.</param>
/// <param name="defaultIfNull">The value to return if null encountered.</param>
/// <returns>The value from the OpenROAD parameter; default value if null.</returns>
protected short GetSmallIntegerAttribute(string attributeName, short defaultIfNull)
{
// Call underlying private method
object obj = GetAttribute(attributeName);
//If the value returned is null then return the amount specified.
return obj is System.DBNull || obj == null ? defaultIfNull : (short) obj;
}
/// <summary>
/// Get integer attribute out of the ByRef parameter object.
/// </summary>
/// <param name="useByValParameter">Flag to indicate which PDO to use.</param>
/// <param name="attributeName">The attribute name.</param>
/// <returns>The value from the OpenROAD parameter.</returns>
protected int GetIntegerAttribute(string attributeName)
{
// Call underlying private method
return (int) GetAttribute(attributeName);
}
/// <summary>
/// Get integer attribute out of the ByRef parameter object with default if null.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <param name="defaultIfNull">The value to return if null encountered.</param>
/// <returns>The value from the OpenROAD parameter; default value if null.</returns>
protected int GetIntegerAttribute(bool useByValParameter, string attributeName, int defaultIfNull)
{
// Call underlying private method
object obj = GetAttribute(attributeName);
//If the value returned is null then return the amount specified.
return obj is System.DBNull || obj == null ? defaultIfNull : (int) obj;
}
/// <summary>
/// Get string attribute out of the ByRef parameter object.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <returns>The value from the OpenROAD parameter.</returns>
protected string GetStringAttribute(string attributeName)
{
// Call underlying private method
return (string) GetAttribute(attributeName);
}
/// <summary>
/// Get string attribute out of the ByRef parameter object with default if null.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <param name="defaultIfNull">The value to return if null encountered.</param>
/// <returns>The value from the OpenROAD parameter; default value if null.</returns>
protected string GetStringAttribute(string attributeName, string defaultIfNull)
{
// Call underlying private method
object obj = GetAttribute(attributeName);
//If the value returned is null then return the amount specified.
return obj is System.DBNull || obj == null ? defaultIfNull : (string) obj;
}
/// <summary>
/// Get boolean attribute out of the ByRef parameter object.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <returns>The value from the OpenROAD parameter.</returns>
protected bool GetBooleanAttribute(string attributeName)
{
return Convert.ToInt16(GetAttribute(attributeName)) == 1;
}
/// <summary>
/// Get boolean attribute out of the ByRef parameter object with default if null.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <param name="defaultIfNull">The value to return if null encountered.</param>
/// <returns>The value from the OpenROAD parameter; default value if null.</returns>
protected bool GetBooleanAttribute(string attributeName, bool defaultIfNull)
{
// Call underlying private method
object obj = GetAttribute(attributeName);
//If the value returned is null then return the amount specified.
return obj is System.DBNull || obj == null ? defaultIfNull : Convert.ToInt16(obj) == 1;
}
/// <summary>
/// Gets decimal attribute out of the ByRef parameter object.
/// </summary>
/// <param name="attributeName"></param>
/// <returns></returns>
protected decimal GetDecimalAttribute(string attributeName)
{
// Call underlying private method
return (decimal)GetAttribute(attributeName);
}
/// <summary>
/// Get decimal attribute out of the ByRef parameter object.
/// </summary>
/// <param name="attributeName"></param>
/// <param name="defaultIfNull"></param>
/// <returns></returns>
protected decimal GetDecimalAttribute(string attributeName, decimal defaultIfNull)
{
// Call underlying private method
object obj = GetAttribute(attributeName);
//If the value returned is null then return the amount specified.
return obj is System.DBNull || obj == null ? defaultIfNull : (decimal)obj;
}
/// <summary>
/// Get double attribute out of the ByRef parameter object.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <returns>The value from the OpenROAD parameter.</returns>
protected double GetDoubleAttribute(string attributeName)
{
// Call underlying private method
return (double) GetAttribute(attributeName);
}
/// <summary>
/// Get double attribute out of the ByRef parameter object with default if null.
/// </summary>
/// <param name="attributeName">The Attribute Name.</param>
/// <param name="defaultIfNull">The value to return if null encountered.</param>
/// <returns>The value from the OpenROAD parameter; default value if null.</returns>
protected double GetDoubleAttribute(string attributeName, double defaultIfNull)
{
// Call underlying private method
object obj = GetAttribute(attributeName);
//If the value returned is null then return the amount specified.
return obj is System.DBNull || obj == null ? defaultIfNull : (double) obj;
}
/// <summary>
/// Get date attribute out of the ByRef parameter object.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <returns>The date value from the OpenROAD parameter.</returns>
protected DateTime GetDateAttribute(string attributeName)
{
// Call underlying private method
// DateTime dtm = (DateTime) ;
object oDtm = GetAttribute(attributeName);
DateTime dtm = Constants.OR_MIN_DATE_VALUE.Date;
//If the attribute is of type DateTime, do a direct cast.
if (oDtm is DateTime)
{
dtm = (DateTime) oDtm;
}
else
{
//otherwise, get the string representation and use TryParse.
DateTime.TryParse((string)GetAttribute(attributeName), out dtm);
}
// Convert the time to co-ordinated local time
dtm = dtm.ToLocalTime();
// Perform the magic on the date conversion to prevent problems moving between OpenROAD and .NET
// they have difference min value dates;
if (dtm.Date == Constants.OR_MIN_DATE_VALUE.Date)
{
dtm = DateTime.MinValue;
}
return dtm;
}
/// <summary>
/// Get date attribute out of the ByRef parameter object with default if null.
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <param name="defaultIfNull">The value to return if null encountered.</param>
/// <returns>The value from the OpenROAD parameter; default value if null.</returns>
protected DateTime GetDateAttribute(string attributeName, DateTime defaultIfNull)
{
// Call underlying private method
object obj = GetAttribute(attributeName);
// If the value returned is null then return the amount specified.
if (obj == null || obj is System.DBNull)
{
return defaultIfNull;
}
// Can get empty string back as a date so check for this.
string emptyDateTest = obj as string;
if (emptyDateTest != null && emptyDateTest == String.Empty)
{
return defaultIfNull;
}
// Convert the time to co-ordinated local time
DateTime dtm = ((DateTime)obj).ToLocalTime();
// Perform the magic on the date conversion to prevent problems moving between OpenROAD and .NET
// they have difference min value dates;
if (dtm.Date == Constants.OR_MIN_DATE_VALUE.Date)
{
dtm = DateTime.MinValue;
}
return dtm;
}
/// <summary>
/// Convert date to OpenROAD string format (dd.mm.ccyy 00:00:00).
/// </summary>
/// <param name="dateToConvert">The date to convert.</param>
/// <returns>The string representation of the date.</returns>
protected string ToOpenROADString(DateTime dateToConvert)
{
return dateToConvert.ToString("dd.MM.yyyy HHmmss");
}
#endregion
#region Virtual Overridable methods
/// <summary>
/// Validate parameters.
/// </summary>
protected virtual void Validate()
{
// By this stage the ASO Session must be instantiated and connected.
if (ORSession == null)
{
throw new SCPInvalidArgumentException(Constants.OR_SESSION_UNAVAILABLE_EXCEPTION_MESSAGE);
}
if (ORSession.IsConnected == 0)
{
throw new SCPInvalidArgumentException(Constants.OR_SESSION_NOT_CONNECTED_EXCEPTION_MESSAGE);
}
// The SCP Name must be provided.
if (SCPName == null || SCPName == String.Empty)
{
throw new SCPInvalidArgumentException(Constants.INVALID_SCP_NAME_EXCEPTION_MESSAGE);
}
}
/// <summary>
/// Declare attribute parameters.
/// </summary>
protected virtual void DeclareAttributes()
{
// Declare the PDO's
orByValParameter = new ORPDOClass();
orByRefParameter = new ORPDOClass();
//Declare OSCA
orByRefParameter.DeclareAttribute("b_osca", Constants.OR_ASA_DATATYPE_USERCLASS);
orByRefParameter.DeclareAttribute("b_osca.i_context_id", Constants.OR_ASA_DATATYPE_INTEGER);
orByRefParameter.DeclareAttribute("b_osca.i_error_no", Constants.OR_ASA_DATATYPE_INTEGER);
orByRefParameter.DeclareAttribute("b_osca.i_error_type", Constants.OR_ASA_DATATYPE_INTEGER);
orByRefParameter.DeclareAttribute("b_osca.v_msg_txt", Constants.OR_ASA_DATATYPE_STRING);
}
/// <summary>
/// Populate the attributes.
/// </summary>
protected virtual void PopulateAttributes()
{
}
#endregion
#region Helper Methods
#region Private Member methods
/// <summary>
/// The underlying delegate method to declare an individual attribute.
/// </summary>
/// <param name="attributeName">The Attribute Name.</param>
/// <param name="attributeType">The Attribute Type.</param>
protected virtual void DeclareAttribute(string attributeName, string attributeType)
{
AttributeManager.DeclareAttribute(orByRefParameter, attributeName, attributeType);
}
/// <summary>
/// The underlying delegate method to get attribute value
/// </summary>
/// <param name="attributeName">The attribute name.</param>
/// <returns>The attribute value.</returns>
protected virtual object GetAttribute(string attributeName)
{
object rtn;
rtn = AttributeManager.GetAttribute(orByRefParameter, attributeName);
return rtn;
}
/// <summary>
/// Return the number of rows in an OpenROAD byref parameter object array.
/// </summary>
/// <param name="arrayName">The fully qualified name of the array in the PDO.</param>
/// <returns>The number of rows (not zero based).</returns>
protected virtual int GetLastRow(string arrayName)
{
return ORByRefParameter.LastRow(arrayName);
}
#endregion
#endregion
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Helper.ApplyCustomTemplate
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Moq;
using Ritter.Domain;
using Ritter.Infra.Crosscutting.Specifications;
using Ritter.Infra.Data.Tests.Extensions;
using Ritter.Infra.Data.Tests.Mocks;
using Xunit;
namespace Ritter.Infra.Data.Tests.Repositories
{
public class Repository_Remove
{
[Fact]
public void CallSaveChangesSuccessfullyGivenOneEntity()
{
var mockedTests = new List<Test>();
Mock<DbSet<Test>> mockDbSet = mockedTests
.AsQueryable()
.BuildMockDbSet();
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object);
mockUnitOfWork.Setup(p => p.SaveChanges());
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
var test = new Test();
testRepository.Remove(test);
mockUnitOfWork.Verify(x => x.Set<Test>().Remove(It.IsAny<Test>()), Times.Once);
mockUnitOfWork.Verify(x => x.SaveChanges(), Times.Once);
}
[Fact]
public void CallSaveChangesSuccessfullyGivenOneEntityAsync()
{
var mockedTests = new List<Test>();
Mock<DbSet<Test>> mockDbSet = mockedTests
.AsQueryable()
.BuildMockDbSet();
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object);
mockUnitOfWork.Setup(p => p.SaveChangesAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(It.IsAny<int>()));
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
var test = new Test();
testRepository.RemoveAsync(test).GetAwaiter().GetResult();
mockUnitOfWork.Verify(x => x.Set<Test>().Remove(It.IsAny<Test>()), Times.Once);
mockUnitOfWork.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public void ThrowsArgumentNullExceptionGivenNullEntity()
{
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
Action act = () =>
{
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
testRepository.Remove((Test)null);
};
act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("entity");
}
[Fact]
public void ThrowsArgumentNullExceptionGivenNullEntityAsync()
{
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
Action act = () =>
{
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
testRepository.RemoveAsync((Test)null).GetAwaiter().GetResult();
};
act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("entity");
}
[Fact]
public void CallSaveChangesSuccessfullyGivenManyEntities()
{
var mockedTests = new List<Test>();
Mock<DbSet<Test>> mockDbSet = mockedTests
.AsQueryable()
.BuildMockDbSet();
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object);
mockUnitOfWork.Setup(p => p.SaveChanges());
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
List<Test> tests = MockTests();
testRepository.Remove(tests);
mockUnitOfWork.Verify(x => x.Set<Test>().RemoveRange(It.IsAny<IEnumerable<Test>>()), Times.Once);
mockUnitOfWork.Verify(x => x.SaveChanges(), Times.Once);
}
[Fact]
public void CallSaveChangesSuccessfullyGivenManyEntitiesAsync()
{
var mockedTests = new List<Test>();
Mock<DbSet<Test>> mockDbSet = mockedTests
.AsQueryable()
.BuildMockDbSet();
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object);
mockUnitOfWork.Setup(p => p.SaveChangesAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(It.IsAny<int>()));
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
List<Test> tests = MockTests();
testRepository.RemoveAsync(tests).GetAwaiter().GetResult();
mockUnitOfWork.Verify(x => x.Set<Test>().RemoveRange(It.IsAny<IEnumerable<Test>>()), Times.Once);
mockUnitOfWork.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public void ThrowsArgumentNullExceptionGivenNullEntityEnumerable()
{
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
Action act = () =>
{
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
testRepository.Remove((IEnumerable<Test>)null);
};
act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("entities");
}
[Fact]
public void ThrowsArgumentNullExceptionGivenNullEntityEnumerableAsync()
{
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
Action act = () =>
{
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
testRepository.RemoveAsync((IEnumerable<Test>)null).GetAwaiter().GetResult();
};
act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("entities");
}
[Fact]
public void CallSaveChangesSuccessfullyGivenSpecification()
{
List<Test> mockedTests = MockTests();
Mock<DbSet<Test>> mockDbSet = mockedTests
.AsQueryable()
.BuildMockDbSet();
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object);
mockUnitOfWork.Setup(p => p.SaveChanges());
ISpecification<Test> spec = new DirectSpecification<Test>(p => p.Id == 1);
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
testRepository.Remove(spec);
mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Exactly(2));
mockUnitOfWork.Verify(x => x.Set<Test>().RemoveRange(It.IsAny<IEnumerable<Test>>()), Times.Once);
mockUnitOfWork.Verify(x => x.SaveChanges(), Times.Once);
}
[Fact]
public void CallSaveChangesSuccessfullyGivenSpecificationAsync()
{
List<Test> mockedTests = MockTests();
Mock<DbSet<Test>> mockDbSet = mockedTests
.AsQueryable()
.BuildMockDbSet();
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object);
mockUnitOfWork.Setup(p => p.SaveChangesAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(It.IsAny<int>()));
ISpecification<Test> spec = new DirectSpecification<Test>(p => p.Id == 1);
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
testRepository.RemoveAsync(spec).GetAwaiter().GetResult();
mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Exactly(2));
mockUnitOfWork.Verify(x => x.Set<Test>().RemoveRange(It.IsAny<IEnumerable<Test>>()), Times.Once);
mockUnitOfWork.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public void ThrowsArgumentNullExceptionGivenNullSpecification()
{
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
Action act = () =>
{
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
testRepository.Remove((ISpecification<Test>)null);
};
act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("specification");
}
[Fact]
public void ThrowsArgumentNullExceptionGivenNullSpecificationAsync()
{
var mockUnitOfWork = new Mock<IEFUnitOfWork>();
Action act = () =>
{
ISqlRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object);
testRepository.RemoveAsync((ISpecification<Test>)null).GetAwaiter().GetResult();
};
act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("specification");
}
private static List<Test> MockTests(int count)
{
var tests = new List<Test>();
for (int i = 1; i <= count; i++)
{
tests.Add(new Test(i));
}
return tests;
}
private static List<Test> MockTests() => MockTests(5);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Messaging;
using Orleans.Runtime;
using Xunit;
namespace NonSilo.Tests
{
public class NoOpGatewaylistProvider : IGatewayListProvider
{
public TimeSpan MaxStaleness => throw new NotImplementedException();
public bool IsUpdatable => throw new NotImplementedException();
public Task<IList<Uri>> GetGateways()
{
throw new NotImplementedException();
}
public Task InitializeGatewayListProvider()
{
throw new NotImplementedException();
}
}
/// <summary>
/// Tests for <see cref="ClientBuilder"/>.
/// </summary>
[TestCategory("BVT")]
[TestCategory("ClientBuilder")]
public class ClientBuilderTests
{
/// <summary>
/// Tests that a client cannot be created without specifying a ClusterId and a ServiceId.
/// </summary>
[Fact]
public void ClientBuilder_ClusterOptionsTest()
{
Assert.Throws<OrleansConfigurationException>(() =>
{
var host = new HostBuilder()
.UseOrleansClient(clientBuilder =>
{
clientBuilder.Configure<ClusterOptions>(options =>
{
options.ClusterId = null;
options.ServiceId = null;
});
clientBuilder.ConfigureServices(services =>
services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>());
})
.Build();
_ = host.Services.GetRequiredService<IClusterClient>();
});
Assert.Throws<OrleansConfigurationException>(() =>
{
var host = new HostBuilder()
.UseOrleansClient(clientBuilder =>
{
clientBuilder.Configure<ClusterOptions>(options =>
{
options.ClusterId = "someClusterId";
options.ServiceId = null;
});
clientBuilder.ConfigureServices(services =>
services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>());
})
.Build();
_ = host.Services.GetRequiredService<IClusterClient>();
});
Assert.Throws<OrleansConfigurationException>(() =>
{
var host = new HostBuilder()
.UseOrleansClient(clientBuilder =>
{
clientBuilder.Configure<ClusterOptions>(options =>
{
options.ClusterId = null;
options.ServiceId = "someServiceId";
});
clientBuilder.ConfigureServices(services =>
services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>());
})
.Build();
_ = host.Services.GetRequiredService<IClusterClient>();
});
var host = new HostBuilder()
.UseOrleansClient(clientBuilder =>
{
clientBuilder.Configure<ClusterOptions>(options =>
{
options.ClusterId = "someClusterId";
options.ServiceId = "someServiceId";
});
clientBuilder.ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>());
})
.Build();
var client = host.Services.GetRequiredService<IClusterClient>();
Assert.NotNull(client);
}
/// <summary>
/// Tests that a client can be created without specifying configuration.
/// </summary>
[Fact]
public void ClientBuilder_NoSpecifiedConfigurationTest()
{
var hostBuilder = new HostBuilder()
.UseOrleansClient(clientBuilder =>
{
clientBuilder.ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>());
})
.ConfigureServices(RemoveConfigValidators);
var host = hostBuilder.Build();
var client = host.Services.GetRequiredService<IClusterClient>();
Assert.NotNull(client);
}
[Fact]
public void ClientBuilder_ThrowsDuringStartupIfNoGrainInterfacesAdded()
{
// Add only an assembly with generated serializers but no grain interfaces
var hostBuilder = new HostBuilder()
.UseOrleansClient(clientBuilder =>
{
clientBuilder
.UseLocalhostClustering()
.Configure<GrainTypeOptions>(options =>
{
options.Interfaces.Clear();
});
})
.ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>());
var host = hostBuilder.Build();
Assert.Throws<OrleansConfigurationException>(() => _ = host.Services.GetRequiredService<IClusterClient>());
}
/// <summary>
/// Tests that the <see cref="IClientBuilder.ConfigureServices"/> delegate works as expected.
/// </summary>
[Fact]
public void ClientBuilder_ServiceProviderTest()
{
var hostBuilder = new HostBuilder()
.UseOrleansClient(clientBuilder =>
{
clientBuilder.ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>());
})
.ConfigureServices(RemoveConfigValidators);
Assert.Throws<ArgumentNullException>(() => hostBuilder.ConfigureServices(null));
var registeredFirst = new int[1];
var one = new MyService { Id = 1 };
hostBuilder.ConfigureServices(
services =>
{
Interlocked.CompareExchange(ref registeredFirst[0], 1, 0);
services.AddSingleton(one);
});
var two = new MyService { Id = 2 };
hostBuilder.ConfigureServices(
services =>
{
Interlocked.CompareExchange(ref registeredFirst[0], 2, 0);
services.AddSingleton(two);
});
var host = hostBuilder.Build();
var client = host.Services.GetRequiredService<IClusterClient>();
var services = client.ServiceProvider.GetServices<MyService>()?.ToList();
Assert.NotNull(services);
// Both services should be registered.
Assert.Equal(2, services.Count);
Assert.NotNull(services.FirstOrDefault(svc => svc.Id == 1));
Assert.NotNull(services.FirstOrDefault(svc => svc.Id == 2));
// Service 1 should have been registered first - the pipeline order should be preserved.
Assert.Equal(1, registeredFirst[0]);
// The last registered service should be provided by default.
Assert.Equal(2, client.ServiceProvider.GetRequiredService<MyService>().Id);
}
[Fact]
public void ClientBuilderThrowsDuringStartupIfSiloBuildersAdded()
{
Assert.Throws<OrleansConfigurationException>(() =>
{
_ = new HostBuilder()
.UseOrleans(siloBuilder =>
{
siloBuilder.UseLocalhostClustering();
})
.UseOrleansClient(clientBuilder =>
{
clientBuilder.UseLocalhostClustering();
});
});
}
private static void RemoveConfigValidators(IServiceCollection services)
{
var validators = services.Where(descriptor => descriptor.ServiceType == typeof(IConfigurationValidator)).ToList();
foreach (var validator in validators) services.Remove(validator);
}
private class MyService
{
public int Id { get; set; }
}
}
}
| |
//
// ComboBoxEntryBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using AppKit;
using Foundation;
using Xwt.Backends;
namespace Xwt.Mac
{
public class ComboBoxEntryBackend: ViewBackend<NSComboBox,IComboBoxEventSink>, IComboBoxEntryBackend
{
ComboDataSource tsource;
TextEntryBackend entryBackend;
int textColumn;
public ComboBoxEntryBackend ()
{
}
public override void Initialize ()
{
base.Initialize ();
ViewObject = new MacComboBox (EventSink, ApplicationContext);
}
protected override Size GetNaturalSize ()
{
var s = base.GetNaturalSize ();
return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height);
}
#region IComboBoxEntryBackend implementation
public ITextEntryBackend TextEntryBackend {
get {
if (entryBackend == null)
entryBackend = new Xwt.Mac.TextEntryBackend ((MacComboBox)ViewObject);
return entryBackend;
}
}
#endregion
#region IComboBoxBackend implementation
public void SetViews (CellViewCollection views)
{
}
public void SetSource (IListDataSource source, IBackend sourceBackend)
{
tsource = new ComboDataSource (source);
tsource.TextColumn = textColumn;
Widget.UsesDataSource = true;
Widget.DataSource = tsource;
}
public int SelectedRow {
get {
return (int) Widget.SelectedIndex;
}
set {
Widget.SelectItem (value);
}
}
public void SetTextColumn (int column)
{
textColumn = column;
if (tsource != null)
tsource.TextColumn = column;
}
#endregion
}
class MacComboBox : NSComboBox, IViewObject, INSComboBoxDelegate
{
IComboBoxEventSink eventSink;
ITextBoxEventSink entryEventSink;
ApplicationContext context;
int cacheSelectionStart, cacheSelectionLength;
bool checkMouseMovement;
public MacComboBox (IComboBoxEventSink eventSink, ApplicationContext context)
{
this.context = context;
this.eventSink = eventSink;
Delegate = this;
}
public void SetEntryEventSink (ITextBoxEventSink entryEventSink)
{
this.entryEventSink = entryEventSink;
}
public NSView View {
get {
return this;
}
}
public ViewBackend Backend { get; set; }
[Export ("comboBoxSelectionDidChange:")]
public new void SelectionChanged (NSNotification notification)
{
if (entryEventSink != null) {
context.InvokeUserCode (delegate {
entryEventSink.OnChanged ();
eventSink.OnSelectionChanged ();
});
}
}
public override void DidChange (NSNotification notification)
{
base.DidChange (notification);
if (entryEventSink != null) {
context.InvokeUserCode (delegate {
entryEventSink.OnChanged ();
entryEventSink.OnSelectionChanged ();
});
}
}
public override void KeyUp (NSEvent theEvent)
{
base.KeyUp (theEvent);
HandleSelectionChanged ();
}
NSTrackingArea trackingArea;
public override void UpdateTrackingAreas ()
{
if (trackingArea != null) {
RemoveTrackingArea (trackingArea);
trackingArea.Dispose ();
}
var viewBounds = this.Bounds;
var options = NSTrackingAreaOptions.MouseMoved | NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseEnteredAndExited;
trackingArea = new NSTrackingArea (viewBounds, options, this, null);
AddTrackingArea (trackingArea);
}
public override void RightMouseDown (NSEvent theEvent)
{
base.RightMouseDown (theEvent);
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
ButtonEventArgs args = new ButtonEventArgs ();
args.X = p.X;
args.Y = p.Y;
args.Button = PointerButton.Right;
args.IsContextMenuTrigger = theEvent.TriggersContextMenu ();
context.InvokeUserCode (delegate {
eventSink.OnButtonPressed (args);
});
}
public override void RightMouseUp (NSEvent theEvent)
{
base.RightMouseUp (theEvent);
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
ButtonEventArgs args = new ButtonEventArgs ();
args.X = p.X;
args.Y = p.Y;
args.Button = PointerButton.Right;
context.InvokeUserCode (delegate {
eventSink.OnButtonReleased (args);
});
}
public override void MouseDown (NSEvent theEvent)
{
base.MouseDown (theEvent);
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
ButtonEventArgs args = new ButtonEventArgs ();
args.X = p.X;
args.Y = p.Y;
args.Button = PointerButton.Left;
args.IsContextMenuTrigger = theEvent.TriggersContextMenu ();
context.InvokeUserCode (delegate {
eventSink.OnButtonPressed (args);
});
}
public override void MouseUp (NSEvent theEvent)
{
base.MouseUp (theEvent);
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
ButtonEventArgs args = new ButtonEventArgs ();
args.X = p.X;
args.Y = p.Y;
args.Button = (PointerButton) (int)theEvent.ButtonNumber + 1;
context.InvokeUserCode (delegate {
eventSink.OnButtonReleased (args);
});
}
public override void MouseEntered (NSEvent theEvent)
{
base.MouseEntered (theEvent);
checkMouseMovement = true;
context.InvokeUserCode (eventSink.OnMouseEntered);
}
public override void MouseExited (NSEvent theEvent)
{
base.MouseExited (theEvent);
context.InvokeUserCode (eventSink.OnMouseExited);
checkMouseMovement = false;
HandleSelectionChanged ();
}
public override void MouseMoved (NSEvent theEvent)
{
base.MouseMoved (theEvent);
if (!checkMouseMovement)
return;
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
MouseMovedEventArgs args = new MouseMovedEventArgs ((long) TimeSpan.FromSeconds (theEvent.Timestamp).TotalMilliseconds, p.X, p.Y);
context.InvokeUserCode (delegate {
eventSink.OnMouseMoved (args);
});
if (checkMouseMovement)
HandleSelectionChanged ();
}
void HandleSelectionChanged ()
{
if (entryEventSink == null || CurrentEditor == null)
return;
if (cacheSelectionStart != CurrentEditor.SelectedRange.Location ||
cacheSelectionLength != CurrentEditor.SelectedRange.Length) {
cacheSelectionStart = (int)CurrentEditor.SelectedRange.Location;
cacheSelectionLength = (int)CurrentEditor.SelectedRange.Length;
context.InvokeUserCode (entryEventSink.OnSelectionChanged);
}
}
}
class ComboDataSource: NSComboBoxDataSource
{
NSComboBox comboBox;
IListDataSource source;
public int TextColumn;
public ComboDataSource (IListDataSource source)
{
this.source = source;
source.RowChanged += SourceChanged;
source.RowDeleted += SourceChanged;
source.RowInserted += SourceChanged;
source.RowsReordered += SourceChanged;
}
void SourceChanged (object sender, ListRowEventArgs e)
{
// FIXME: we need to find a more efficient way
comboBox?.ReloadData ();
}
public override NSObject ObjectValueForItem (NSComboBox comboBox, nint index)
{
SetComboBox (comboBox);
return NSObject.FromObject (source.GetValue ((int) index, TextColumn));
}
public override nint ItemCount (NSComboBox comboBox)
{
SetComboBox (comboBox);
return source.RowCount;
}
void SetComboBox (NSComboBox comboBox)
{
if (this.comboBox == null) {
this.comboBox = comboBox;
source.RowChanged += SourceChanged;
source.RowDeleted += SourceChanged;
source.RowInserted += SourceChanged;
source.RowsReordered += SourceChanged;
}
if (this.comboBox != comboBox)
throw new InvalidOperationException ("This ComboDataSource is already bound to an other ComboBox");
}
protected override void Dispose (bool disposing)
{
if (source != null) {
source.RowChanged -= SourceChanged;
source.RowDeleted -= SourceChanged;
source.RowInserted -= SourceChanged;
source.RowsReordered -= SourceChanged;
source = null;
}
base.Dispose (disposing);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected override void AddedControl(Control control, int index)
{
// This is necessary because Safari and Chrome browsers don't display the Menu control correctly.
// Add this to the code in your master page.
if (Request.ServerVariables["http_user_agent"].IndexOf("Safari", StringComparison.CurrentCultureIgnoreCase) != -1)
this.Page.ClientTarget = "uplevel";
base.AddedControl(control, index);
}
protected void Page_Load(object sender, EventArgs e)
{
string pageName = this.ContentPlaceHolder1.Page.GetType().FullName;
string queryString = "";
string TieneSubmenu01 = "N";
string TieneSubmenu02 = "N";
string TieneSubmenu03 = "N";
string TieneSubmenu04 = "N";
string TieneSubmenu05 = "N";
string TieneSubmenu06 = "N";
string TieneSubmenu07 = "N";
string TieneSubmenu08 = "N";
string TieneSubmenu09 = "N";
string TieneSubmenu10 = "N";
string TieneSubmenu11 = "N";
string TieneSubmenu12 = "N";
string TieneSubmenu13 = "N";
string TieneSubmenu14 = "N";
string TieneSubmenu15 = "N";
string TieneSubmenu16 = "N";
string TieneSubmenu17 = "N";
string TieneSubmenu18 = "N";
string TieneSubmenu19 = "N";
string TieneSubmenu20 = "N";
if (pageName == "ASP.login_aspx")
{
FormsAuthentication.SignOut();
queryString = "SELECT IdHead FROM Menu_Items WHERE 1=2 ";
}
else
{
/* nuevo para saber si tiene submenues */
queryString = "SELECT I.IdHead PadreId,count(*) " +
"FROM Menu_Items I " +
"inner join Menu_Tipos T on T.IdItemMenu=I.IdItemMenu " +
"inner join Usuarios U on U.IdMenu = T.IdMenu " +
"WHERE U.Usuario='" + HttpContext.Current.User.Identity.Name + "' " +
"GROUP BY I.IdHead";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConSql"].ConnectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader[0].ToString() == "1" && reader[1].ToString() != "1") { TieneSubmenu01 = "S"; }
if (reader[0].ToString() == "2" && reader[1].ToString() != "1") { TieneSubmenu02 = "S"; }
if (reader[0].ToString() == "3" && reader[1].ToString() != "1") { TieneSubmenu03 = "S"; }
if (reader[0].ToString() == "4" && reader[1].ToString() != "1") { TieneSubmenu04 = "S"; }
if (reader[0].ToString() == "5" && reader[1].ToString() != "1") { TieneSubmenu05 = "S"; }
if (reader[0].ToString() == "6" && reader[1].ToString() != "1") { TieneSubmenu06 = "S"; }
if (reader[0].ToString() == "7" && reader[1].ToString() != "1") { TieneSubmenu07 = "S"; }
if (reader[0].ToString() == "8" && reader[1].ToString() != "1") { TieneSubmenu08 = "S"; }
if (reader[0].ToString() == "9" && reader[1].ToString() != "1") { TieneSubmenu09 = "S"; }
if (reader[0].ToString() == "10" && reader[1].ToString() != "1") { TieneSubmenu10 = "S"; }
if (reader[0].ToString() == "11" && reader[1].ToString() != "1") { TieneSubmenu11 = "S"; }
if (reader[0].ToString() == "12" && reader[1].ToString() != "1") { TieneSubmenu12 = "S"; }
if (reader[0].ToString() == "13" && reader[1].ToString() != "1") { TieneSubmenu13 = "S"; }
if (reader[0].ToString() == "14" && reader[1].ToString() != "1") { TieneSubmenu14 = "S"; }
if (reader[0].ToString() == "15" && reader[1].ToString() != "1") { TieneSubmenu15 = "S"; }
if (reader[0].ToString() == "16" && reader[1].ToString() != "1") { TieneSubmenu16 = "S"; }
if (reader[0].ToString() == "17" && reader[1].ToString() != "1") { TieneSubmenu17 = "S"; }
if (reader[0].ToString() == "18" && reader[1].ToString() != "1") { TieneSubmenu18 = "S"; }
if (reader[0].ToString() == "19" && reader[1].ToString() != "1") { TieneSubmenu19 = "S"; }
if (reader[0].ToString() == "20" && reader[1].ToString() != "1") { TieneSubmenu20 = "S"; }
}
connection.Close();
}
/* FIN - nuevo para saber si tiene submenues */
queryString = "SELECT I.IdItemMenu, I.Descripcion, I.Posicion, I.IdHead, I.Icono, I.Url " +
"FROM Menu_Items I " +
"inner join Menu_Tipos T on T.IdItemMenu=I.IdItemMenu " +
"inner join Usuarios U on U.IdMenu = T.IdMenu " +
"WHERE U.Usuario='" + HttpContext.Current.User.Identity.Name + "' " +
"ORDER BY I.IdHead,I.Posicion";
}
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConSql"].ConnectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
MenuItem mnuMenuItem = new MenuItem();
int NumeroItem = 0;
HtmlGenericControl li2 = new HtmlGenericControl("li");
HtmlGenericControl submen = new HtmlGenericControl("ul");
string menuConSubmenu = "@";
while (reader.Read())
{
if (reader[2].ToString() == reader[3].ToString())
{
NumeroItem += 1;
menuConSubmenu = "@";
HtmlGenericControl anchor = new HtmlGenericControl("a");
string ClaseMenu = "dropdown";
if (reader[5].ToString() != "")
{ anchor.Attributes.Add("href", reader[5].ToString()); }
else
{ anchor.Attributes.Add("href", "#"); }
if (reader[3].ToString() == "1" && TieneSubmenu01 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "2" && TieneSubmenu02 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "3" && TieneSubmenu03 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "4" && TieneSubmenu04 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "5" && TieneSubmenu05 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "6" && TieneSubmenu06 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "7" && TieneSubmenu07 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "8" && TieneSubmenu08 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "9" && TieneSubmenu09 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "10" && TieneSubmenu10 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "11" && TieneSubmenu11 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "12" && TieneSubmenu12 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "13" && TieneSubmenu13 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "14" && TieneSubmenu14 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "15" && TieneSubmenu15 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "16" && TieneSubmenu16 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "17" && TieneSubmenu17 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "18" && TieneSubmenu18 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "19" && TieneSubmenu19 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
if (reader[3].ToString() == "20" && TieneSubmenu20 == "S") { anchor.Attributes.Add("class", "dropdown-toggle"); ClaseMenu = "dropdown"; }
anchor.InnerText = reader[1].ToString();
if (NumeroItem == 1) { Li1.Controls.Add(anchor); Li1.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 2) { Li2.Controls.Add(anchor); Li2.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 3) { Li3.Controls.Add(anchor); Li3.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 4) { Li4.Controls.Add(anchor); Li4.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 5) { Li5.Controls.Add(anchor); Li5.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 6) { Li6.Controls.Add(anchor); Li6.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 7) { Li7.Controls.Add(anchor); Li7.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 8) { Li8.Controls.Add(anchor); Li8.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 9) { Li9.Controls.Add(anchor); Li9.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 10) { Li10.Controls.Add(anchor); Li10.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 11) { Li11.Controls.Add(anchor); Li11.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 12) { Li12.Controls.Add(anchor); Li12.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 13) { Li13.Controls.Add(anchor); Li13.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 14) { Li14.Controls.Add(anchor); Li14.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 15) { Li15.Controls.Add(anchor); Li15.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 16) { Li16.Controls.Add(anchor); Li16.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 17) { Li17.Controls.Add(anchor); Li17.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 18) { Li18.Controls.Add(anchor); Li18.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 19) { Li19.Controls.Add(anchor); Li19.Attributes.Add("class", ClaseMenu); }
if (NumeroItem == 20) { Li20.Controls.Add(anchor); Li20.Attributes.Add("class", ClaseMenu); }
}
else
{
if (menuConSubmenu == "@")
{
submen = new HtmlGenericControl("ul");
submen.Attributes.Add("class", "dropdown-menu");
if (NumeroItem == 1) { Li1.Controls.Add(submen); }
if (NumeroItem == 2) { Li2.Controls.Add(submen); }
if (NumeroItem == 3) { Li3.Controls.Add(submen); }
if (NumeroItem == 4) { Li4.Controls.Add(submen); }
if (NumeroItem == 5) { Li5.Controls.Add(submen); }
if (NumeroItem == 6) { Li6.Controls.Add(submen); }
if (NumeroItem == 7) { Li7.Controls.Add(submen); }
if (NumeroItem == 8) { Li8.Controls.Add(submen); }
if (NumeroItem == 9) { Li9.Controls.Add(submen); }
if (NumeroItem == 10) { Li10.Controls.Add(submen); }
if (NumeroItem == 11) { Li11.Controls.Add(submen); }
if (NumeroItem == 12) { Li12.Controls.Add(submen); }
if (NumeroItem == 13) { Li13.Controls.Add(submen); }
if (NumeroItem == 14) { Li14.Controls.Add(submen); }
if (NumeroItem == 15) { Li15.Controls.Add(submen); }
if (NumeroItem == 16) { Li16.Controls.Add(submen); }
if (NumeroItem == 17) { Li17.Controls.Add(submen); }
if (NumeroItem == 18) { Li18.Controls.Add(submen); }
if (NumeroItem == 19) { Li19.Controls.Add(submen); }
if (NumeroItem == 20) { Li20.Controls.Add(submen); }
menuConSubmenu = NumeroItem.ToString();
}
HtmlGenericControl linea2 = new HtmlGenericControl("li");
submen.Controls.Add(linea2);
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", reader[5].ToString());
anchor.InnerText = reader[1].ToString();
linea2.Controls.Add(anchor);
}
}
reader.Close();
if (NumeroItem < 1)
{
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "login.aspx");
anchor.InnerText = "Ingresar";
Li1.Controls.Add(anchor); Li1.Attributes.Add("class", "dropdown");
}
if (NumeroItem < 2) { Li2.Visible = false; }
if (NumeroItem < 3) { Li3.Visible = false; }
if (NumeroItem < 4) { Li4.Visible = false; }
if (NumeroItem < 5) { Li5.Visible = false; }
if (NumeroItem < 6) { Li6.Visible = false; }
if (NumeroItem < 7) { Li7.Visible = false; }
if (NumeroItem < 8) { Li8.Visible = false; }
if (NumeroItem < 9) { Li9.Visible = false; }
if (NumeroItem < 10) { Li10.Visible=false; }
if (NumeroItem < 11) { Li11.Visible = false; }
if (NumeroItem < 12) { Li12.Visible = false; }
if (NumeroItem < 13) { Li13.Visible = false; }
if (NumeroItem < 14) { Li14.Visible = false; }
if (NumeroItem < 15) { Li15.Visible = false; }
if (NumeroItem < 16) { Li16.Visible = false; }
if (NumeroItem < 17) { Li17.Visible = false; }
if (NumeroItem < 18) { Li18.Visible = false; }
if (NumeroItem < 19) { Li19.Visible = false; }
if (NumeroItem < 20) { Li20.Visible = false; }
}
if (!Page.IsPostBack)
{
// Label2.Text += "Not postback";
}
else
{
// Label2.Text += "Postback";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Channels.Tests
{
public abstract partial class ChannelTestBase : TestBase
{
protected Channel<int> CreateChannel() => CreateChannel<int>();
protected abstract Channel<T> CreateChannel<T>();
protected Channel<int> CreateFullChannel() => CreateFullChannel<int>();
protected abstract Channel<T> CreateFullChannel<T>();
protected virtual bool AllowSynchronousContinuations => false;
protected virtual bool RequiresSingleReader => false;
protected virtual bool RequiresSingleWriter => false;
protected virtual bool BuffersItems => true;
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Requires internal reflection on framework types.")]
[Fact]
public void ValidateDebuggerAttributes()
{
Channel<int> c = CreateChannel();
for (int i = 1; i <= 10; i++)
{
c.Writer.WriteAsync(i);
}
DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
DebuggerAttributes.InvokeDebuggerTypeProxyProperties(c);
}
[Fact]
public void Cast_MatchesInOut()
{
Channel<int> c = CreateChannel();
ChannelReader<int> rc = c;
ChannelWriter<int> wc = c;
Assert.Same(rc, c.Reader);
Assert.Same(wc, c.Writer);
}
[Fact]
public void Completion_Idempotent()
{
Channel<int> c = CreateChannel();
Task completion = c.Reader.Completion;
Assert.Equal(TaskStatus.WaitingForActivation, completion.Status);
Assert.Same(completion, c.Reader.Completion);
c.Writer.Complete();
Assert.Same(completion, c.Reader.Completion);
Assert.Equal(TaskStatus.RanToCompletion, completion.Status);
}
[Fact]
public async Task Complete_AfterEmpty_NoWaiters_TriggersCompletion()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await c.Reader.Completion;
}
[Fact]
public async Task Complete_AfterEmpty_WaitingReader_TriggersCompletion()
{
Channel<int> c = CreateChannel();
Task<int> r = c.Reader.ReadAsync().AsTask();
c.Writer.Complete();
await c.Reader.Completion;
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => r);
}
[Fact]
public async Task Complete_BeforeEmpty_WaitingReaders_TriggersCompletion()
{
Channel<int> c = CreateChannel();
ValueTask<int> read = c.Reader.ReadAsync();
c.Writer.Complete();
await c.Reader.Completion;
await Assert.ThrowsAnyAsync<InvalidOperationException>(async () => await read);
}
[Fact]
public void Complete_Twice_ThrowsInvalidOperationException()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.ThrowsAny<InvalidOperationException>(() => c.Writer.Complete());
}
[Fact]
public void TryComplete_Twice_ReturnsTrueThenFalse()
{
Channel<int> c = CreateChannel();
Assert.True(c.Writer.TryComplete());
Assert.False(c.Writer.TryComplete());
Assert.False(c.Writer.TryComplete());
}
[Fact]
public async Task TryComplete_ErrorsPropage()
{
Channel<int> c;
// Success
c = CreateChannel();
Assert.True(c.Writer.TryComplete());
await c.Reader.Completion;
// Error
c = CreateChannel();
Assert.True(c.Writer.TryComplete(new FormatException()));
await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion);
// Canceled
c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
Assert.True(c.Writer.TryComplete(new OperationCanceledException(cts.Token)));
await AssertCanceled(c.Reader.Completion, cts.Token);
}
[Fact]
public void SingleProducerConsumer_ConcurrentReadWrite_Success()
{
Channel<int> c = CreateChannel();
const int NumItems = 100000;
Task.WaitAll(
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
await c.Writer.WriteAsync(i);
}
}),
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
Assert.Equal(i, await c.Reader.ReadAsync());
}
}));
}
[Fact]
public void SingleProducerConsumer_PingPong_Success()
{
Channel<int> c1 = CreateChannel();
Channel<int> c2 = CreateChannel();
const int NumItems = 100000;
Task.WaitAll(
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
Assert.Equal(i, await c1.Reader.ReadAsync());
await c2.Writer.WriteAsync(i);
}
}),
Task.Run(async () =>
{
for (int i = 0; i < NumItems; i++)
{
await c1.Writer.WriteAsync(i);
Assert.Equal(i, await c2.Reader.ReadAsync());
}
}));
}
[Theory]
[InlineData(1, 1)]
[InlineData(1, 10)]
[InlineData(10, 1)]
[InlineData(10, 10)]
public void ManyProducerConsumer_ConcurrentReadWrite_Success(int numReaders, int numWriters)
{
if (RequiresSingleReader && numReaders > 1)
{
return;
}
if (RequiresSingleWriter && numWriters > 1)
{
return;
}
Channel<int> c = CreateChannel();
const int NumItems = 10000;
long readTotal = 0;
int remainingWriters = numWriters;
int remainingItems = NumItems;
Task[] tasks = new Task[numWriters + numReaders];
for (int i = 0; i < numReaders; i++)
{
tasks[i] = Task.Run(async () =>
{
try
{
while (await c.Reader.WaitToReadAsync())
{
if (c.Reader.TryRead(out int value))
{
Interlocked.Add(ref readTotal, value);
}
}
}
catch (ChannelClosedException) { }
});
}
for (int i = 0; i < numWriters; i++)
{
tasks[numReaders + i] = Task.Run(async () =>
{
while (true)
{
int value = Interlocked.Decrement(ref remainingItems);
if (value < 0)
{
break;
}
await c.Writer.WriteAsync(value + 1);
}
if (Interlocked.Decrement(ref remainingWriters) == 0)
{
c.Writer.Complete();
}
});
}
Task.WaitAll(tasks);
Assert.Equal((NumItems * (NumItems + 1L)) / 2, readTotal);
}
[Fact]
public void WaitToReadAsync_DataAvailableBefore_CompletesSynchronously()
{
Channel<int> c = CreateChannel();
ValueTask write = c.Writer.WriteAsync(42);
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.True(read.IsCompletedSuccessfully);
}
[Fact]
public void WaitToReadAsync_DataAvailableAfter_CompletesAsynchronously()
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.False(read.IsCompleted);
ValueTask write = c.Writer.WriteAsync(42);
Assert.True(read.Result);
}
[Fact]
public void WaitToReadAsync_AfterComplete_SynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.True(read.IsCompletedSuccessfully);
Assert.False(read.Result);
}
[Fact]
public void WaitToReadAsync_BeforeComplete_AsynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.False(read.IsCompleted);
c.Writer.Complete();
Assert.False(read.Result);
}
[Fact]
public void WaitToWriteAsync_AfterComplete_SynchronouslyCompletes()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
Assert.True(write.IsCompletedSuccessfully);
Assert.False(write.Result);
}
[Fact]
public void WaitToWriteAsync_EmptyChannel_SynchronouslyCompletes()
{
if (!BuffersItems)
{
return;
}
Channel<int> c = CreateChannel();
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
Assert.True(write.IsCompletedSuccessfully);
Assert.True(write.Result);
}
[Fact]
public async Task WaitToWriteAsync_ManyConcurrent_SatisifedByReaders()
{
if (RequiresSingleReader || RequiresSingleWriter)
{
return;
}
Channel<int> c = CreateChannel();
Task[] writers = Enumerable.Range(0, 100).Select(_ => c.Writer.WaitToWriteAsync().AsTask()).ToArray();
Task[] readers = Enumerable.Range(0, 100).Select(_ => c.Reader.ReadAsync().AsTask()).ToArray();
await Task.WhenAll(writers);
}
[Fact]
public void WaitToWriteAsync_BlockedReader_ReturnsTrue()
{
Channel<int> c = CreateChannel();
ValueTask<int> reader = c.Reader.ReadAsync();
AssertSynchronousSuccess(c.Writer.WaitToWriteAsync());
}
[Fact]
public void TryRead_DataAvailable_Success()
{
Channel<int> c = CreateChannel();
ValueTask write = c.Writer.WriteAsync(42);
Assert.True(c.Reader.TryRead(out int result));
Assert.Equal(42, result);
}
[Fact]
public void TryRead_AfterComplete_ReturnsFalse()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.False(c.Reader.TryRead(out int result));
}
[Fact]
public void TryWrite_AfterComplete_ReturnsFalse()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
Assert.False(c.Writer.TryWrite(42));
}
[Fact]
public async Task WriteAsync_AfterComplete_ThrowsException()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await Assert.ThrowsAnyAsync<InvalidOperationException>(async () => await c.Writer.WriteAsync(42));
}
[Fact]
public async Task Complete_WithException_PropagatesToCompletion()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
Assert.Same(exc, await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion));
}
[Fact]
public async Task Complete_WithCancellationException_PropagatesToCompletion()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
cts.Cancel();
Exception exc = null;
try { cts.Token.ThrowIfCancellationRequested(); }
catch (Exception e) { exc = e; }
c.Writer.Complete(exc);
await AssertCanceled(c.Reader.Completion, cts.Token);
}
[Fact]
public async Task Complete_WithException_PropagatesToExistingWriter()
{
Channel<int> c = CreateFullChannel();
if (c != null)
{
ValueTask write = c.Writer.WriteAsync(42);
var exc = new FormatException();
c.Writer.Complete(exc);
Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(async () => await write)).InnerException);
}
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWriter()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
ValueTask write = c.Writer.WriteAsync(42);
Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(async () => await write)).InnerException);
}
[Fact]
public async Task Complete_WithException_PropagatesToExistingWaitingReader()
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
var exc = new FormatException();
c.Writer.Complete(exc);
await Assert.ThrowsAsync<FormatException>(async () => await read);
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWaitingReader()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
ValueTask<bool> read = c.Reader.WaitToReadAsync();
await Assert.ThrowsAsync<FormatException>(async () => await read);
}
[Fact]
public async Task Complete_WithException_PropagatesToNewWaitingWriter()
{
Channel<int> c = CreateChannel();
var exc = new FormatException();
c.Writer.Complete(exc);
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
await Assert.ThrowsAsync<FormatException>(async () => await write);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void ManyWriteAsync_ThenManyTryRead_Success(int readMode)
{
if (RequiresSingleReader || RequiresSingleWriter)
{
return;
}
Channel<int> c = CreateChannel();
const int NumItems = 2000;
ValueTask[] writers = new ValueTask[NumItems];
for (int i = 0; i < writers.Length; i++)
{
writers[i] = c.Writer.WriteAsync(i);
}
Task<int>[] readers = new Task<int>[NumItems];
for (int i = 0; i < readers.Length; i++)
{
int result;
Assert.True(c.Reader.TryRead(out result));
Assert.Equal(i, result);
}
Assert.All(writers, w => Assert.True(w.IsCompleted));
}
[Fact]
public void Precancellation_Writing_ReturnsImmediately()
{
Channel<int> c = CreateChannel();
ValueTask writeTask = c.Writer.WriteAsync(42, new CancellationToken(true));
Assert.True(writeTask.IsCanceled);
ValueTask<bool> waitTask = c.Writer.WaitToWriteAsync(new CancellationToken(true));
Assert.True(writeTask.IsCanceled);
}
[Fact]
public void Write_WaitToReadAsync_CompletesSynchronously()
{
Channel<int> c = CreateChannel();
c.Writer.WriteAsync(42);
AssertSynchronousTrue(c.Reader.WaitToReadAsync());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Precancellation_WaitToReadAsync_ReturnsImmediately(bool dataAvailable)
{
Channel<int> c = CreateChannel();
if (dataAvailable)
{
Assert.True(c.Writer.TryWrite(42));
}
ValueTask<bool> waitTask = c.Reader.WaitToReadAsync(new CancellationToken(true));
Assert.True(waitTask.IsCanceled);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task WaitToReadAsync_DataWritten_CompletesSuccessfully(bool cancelable)
{
Channel<int> c = CreateChannel();
CancellationToken token = cancelable ? new CancellationTokenSource().Token : default;
ValueTask<bool> read = c.Reader.WaitToReadAsync(token);
Assert.False(read.IsCompleted);
ValueTask write = c.Writer.WriteAsync(42, token);
Assert.True(await read);
}
[Fact]
public async Task WaitToReadAsync_NoDataWritten_Canceled_CompletesAsCanceled()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
ValueTask<bool> read = c.Reader.WaitToReadAsync(cts.Token);
Assert.False(read.IsCompleted);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await read);
}
[Fact]
public async Task ReadAsync_ThenWriteAsync_Succeeds()
{
Channel<int> c = CreateChannel();
ValueTask<int> r = c.Reader.ReadAsync();
Assert.False(r.IsCompleted);
ValueTask w = c.Writer.WriteAsync(42);
AssertSynchronousSuccess(w);
Assert.Equal(42, await r);
}
[Fact]
public async Task WriteAsync_ReadAsync_Succeeds()
{
Channel<int> c = CreateChannel();
ValueTask w = c.Writer.WriteAsync(42);
ValueTask<int> r = c.Reader.ReadAsync();
await Task.WhenAll(w.AsTask(), r.AsTask());
Assert.Equal(42, await r);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Precancellation_ReadAsync_ReturnsImmediately(bool dataAvailable)
{
Channel<int> c = CreateChannel();
if (dataAvailable)
{
Assert.True(c.Writer.TryWrite(42));
}
ValueTask<int> readTask = c.Reader.ReadAsync(new CancellationToken(true));
Assert.True(readTask.IsCanceled);
}
[Fact]
public async Task ReadAsync_Canceled_CanceledAsynchronously()
{
Channel<int> c = CreateChannel();
var cts = new CancellationTokenSource();
ValueTask<int> r = c.Reader.ReadAsync(cts.Token);
Assert.False(r.IsCompleted);
cts.Cancel();
await AssertCanceled(r.AsTask(), cts.Token);
if (c.Writer.TryWrite(42))
{
Assert.Equal(42, await c.Reader.ReadAsync());
}
}
[Fact]
public async Task ReadAsync_WriteAsync_ManyConcurrentReaders_SerializedWriters_Success()
{
if (RequiresSingleReader)
{
return;
}
Channel<int> c = CreateChannel();
const int Items = 100;
ValueTask<int>[] readers = (from i in Enumerable.Range(0, Items) select c.Reader.ReadAsync()).ToArray();
for (int i = 0; i < Items; i++)
{
await c.Writer.WriteAsync(i);
}
Assert.Equal((Items * (Items - 1)) / 2, Enumerable.Sum(await Task.WhenAll(readers.Select(r => r.AsTask()))));
}
[Fact]
public async Task ReadAsync_TryWrite_ManyConcurrentReaders_SerializedWriters_Success()
{
if (RequiresSingleReader)
{
return;
}
Channel<int> c = CreateChannel();
const int Items = 100;
Task<int>[] readers = (from i in Enumerable.Range(0, Items) select c.Reader.ReadAsync().AsTask()).ToArray();
var remainingReaders = new List<Task<int>>(readers);
for (int i = 0; i < Items; i++)
{
Assert.True(c.Writer.TryWrite(i), $"Failed to write at {i}");
Task<int> r = await Task.WhenAny(remainingReaders);
await r;
remainingReaders.Remove(r);
}
Assert.Equal((Items * (Items - 1)) / 2, Enumerable.Sum(await Task.WhenAll(readers)));
}
[Fact]
public async Task ReadAsync_AlreadyCompleted_Throws()
{
Channel<int> c = CreateChannel();
c.Writer.Complete();
await Assert.ThrowsAsync<ChannelClosedException>(() => c.Reader.ReadAsync().AsTask());
}
[Fact]
public async Task ReadAsync_SubsequentlyCompleted_Throws()
{
Channel<int> c = CreateChannel();
Task<int> r = c.Reader.ReadAsync().AsTask();
Assert.False(r.IsCompleted);
c.Writer.Complete();
await Assert.ThrowsAsync<ChannelClosedException>(() => r);
}
[Fact]
public async Task ReadAsync_AfterFaultedChannel_Throws()
{
Channel<int> c = CreateChannel();
var e = new FormatException();
c.Writer.Complete(e);
Assert.True(c.Reader.Completion.IsFaulted);
ChannelClosedException cce = await Assert.ThrowsAsync<ChannelClosedException>(() => c.Reader.ReadAsync().AsTask());
Assert.Same(e, cce.InnerException);
}
[Fact]
public async Task ReadAsync_AfterCanceledChannel_Throws()
{
Channel<int> c = CreateChannel();
var e = new OperationCanceledException();
c.Writer.Complete(e);
Assert.True(c.Reader.Completion.IsCanceled);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => c.Reader.ReadAsync().AsTask());
}
[Fact]
public async Task ReadAsync_Canceled_WriteAsyncCompletesNextReader()
{
Channel<int> c = CreateChannel();
for (int i = 0; i < 5; i++)
{
var cts = new CancellationTokenSource();
ValueTask<int> r = c.Reader.ReadAsync(cts.Token);
cts.Cancel();
await AssertCanceled(r.AsTask(), cts.Token);
}
for (int i = 0; i < 7; i++)
{
ValueTask<int> r = c.Reader.ReadAsync();
await c.Writer.WriteAsync(i);
Assert.Equal(i, await r);
}
}
[Fact]
public async Task ReadAsync_ConsecutiveReadsSucceed()
{
Channel<int> c = CreateChannel();
for (int i = 0; i < 5; i++)
{
ValueTask<int> r = c.Reader.ReadAsync();
await c.Writer.WriteAsync(i);
Assert.Equal(i, await r);
}
}
[Fact]
public async Task WaitToReadAsync_ConsecutiveReadsSucceed()
{
Channel<int> c = CreateChannel();
for (int i = 0; i < 5; i++)
{
ValueTask<bool> r = c.Reader.WaitToReadAsync();
await c.Writer.WriteAsync(i);
Assert.True(await r);
Assert.True(c.Reader.TryRead(out int item));
Assert.Equal(i, item);
}
}
[Theory]
[InlineData(false, null)]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, null)]
[InlineData(true, false)]
[InlineData(true, true)]
public void WaitToReadAsync_MultipleContinuations_Throws(bool onCompleted, bool? continueOnCapturedContext)
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
switch (continueOnCapturedContext)
{
case null:
if (onCompleted)
{
read.GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
}
else
{
read.GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
default:
if (onCompleted)
{
read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { }));
}
else
{
read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
}
}
[Theory]
[InlineData(false, null)]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, null)]
[InlineData(true, false)]
[InlineData(true, true)]
public void ReadAsync_MultipleContinuations_Throws(bool onCompleted, bool? continueOnCapturedContext)
{
Channel<int> c = CreateChannel();
ValueTask<int> read = c.Reader.ReadAsync();
switch (continueOnCapturedContext)
{
case null:
if (onCompleted)
{
read.GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
}
else
{
read.GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
default:
if (onCompleted)
{
read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { }));
}
else
{
read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => read.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
}
}
[Fact]
public async Task WaitToReadAsync_AwaitThenGetResult_Throws()
{
Channel<int> c = CreateChannel();
ValueTask<bool> read = c.Reader.WaitToReadAsync();
Assert.True(c.Writer.TryWrite(42));
Assert.True(await read);
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().IsCompleted);
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().GetResult());
}
[Fact]
public async Task ReadAsync_AwaitThenGetResult_Throws()
{
Channel<int> c = CreateChannel();
ValueTask<int> read = c.Reader.ReadAsync();
Assert.True(c.Writer.TryWrite(42));
Assert.Equal(42, await read);
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().IsCompleted);
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().OnCompleted(() => { }));
Assert.Throws<InvalidOperationException>(() => read.GetAwaiter().GetResult());
}
[Fact]
public async Task WaitToWriteAsync_AwaitThenGetResult_Throws()
{
Channel<int> c = CreateFullChannel();
if (c == null)
{
return;
}
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
await c.Reader.ReadAsync();
Assert.True(await write);
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().IsCompleted);
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().OnCompleted(() => { }));
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().GetResult());
}
[Fact]
public async Task WriteAsync_AwaitThenGetResult_Throws()
{
Channel<int> c = CreateFullChannel();
if (c == null)
{
return;
}
ValueTask write = c.Writer.WriteAsync(42);
await c.Reader.ReadAsync();
await write;
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().IsCompleted);
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().OnCompleted(() => { }));
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().GetResult());
}
[Theory]
[InlineData(false, null)]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, null)]
[InlineData(true, false)]
[InlineData(true, true)]
public void WaitToWriteAsync_MultipleContinuations_Throws(bool onCompleted, bool? continueOnCapturedContext)
{
Channel<int> c = CreateFullChannel();
if (c == null)
{
return;
}
ValueTask<bool> write = c.Writer.WaitToWriteAsync();
switch (continueOnCapturedContext)
{
case null:
if (onCompleted)
{
write.GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().OnCompleted(() => { }));
}
else
{
write.GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
default:
if (onCompleted)
{
write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { }));
}
else
{
write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
}
}
[Theory]
[InlineData(false, null)]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, null)]
[InlineData(true, false)]
[InlineData(true, true)]
public void WriteAsync_MultipleContinuations_Throws(bool onCompleted, bool? continueOnCapturedContext)
{
Channel<int> c = CreateFullChannel();
if (c == null)
{
return;
}
ValueTask write = c.Writer.WriteAsync(42);
switch (continueOnCapturedContext)
{
case null:
if (onCompleted)
{
write.GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().OnCompleted(() => { }));
}
else
{
write.GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
default:
if (onCompleted)
{
write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(() => { }));
}
else
{
write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => write.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(() => { }));
}
break;
}
}
public static IEnumerable<object[]> Reader_ContinuesOnCurrentContextIfDesired_MemberData() =>
from readOrWait in new[] { true, false }
from completeBeforeOnCompleted in new[] { true, false }
from flowExecutionContext in new[] { true, false }
from continueOnCapturedContext in new bool?[] { null, false, true }
from setNonDefaultTaskScheduler in new[] { true, false }
select new object[] { readOrWait, completeBeforeOnCompleted, flowExecutionContext, continueOnCapturedContext, setNonDefaultTaskScheduler };
[Theory]
[MemberData(nameof(Reader_ContinuesOnCurrentContextIfDesired_MemberData))]
public async Task Reader_ContinuesOnCurrentSynchronizationContextIfDesired(
bool readOrWait, bool completeBeforeOnCompleted, bool flowExecutionContext, bool? continueOnCapturedContext, bool setNonDefaultTaskScheduler)
{
if (AllowSynchronousContinuations)
{
return;
}
await Task.Factory.StartNew(async () =>
{
Assert.Null(SynchronizationContext.Current);
Channel<bool> c = CreateChannel<bool>();
ValueTask<bool> vt = readOrWait ?
c.Reader.ReadAsync() :
c.Reader.WaitToReadAsync();
var continuationRan = new TaskCompletionSource<bool>();
var asyncLocal = new AsyncLocal<int>();
bool schedulerWasFlowed = false;
bool executionContextWasFlowed = false;
Action continuation = () =>
{
schedulerWasFlowed = SynchronizationContext.Current is CustomSynchronizationContext;
executionContextWasFlowed = 42 == asyncLocal.Value;
continuationRan.SetResult(true);
};
if (completeBeforeOnCompleted)
{
Assert.False(vt.IsCompleted);
Assert.False(vt.IsCompletedSuccessfully);
c.Writer.TryWrite(true);
}
SynchronizationContext.SetSynchronizationContext(new CustomSynchronizationContext());
asyncLocal.Value = 42;
switch (continueOnCapturedContext)
{
case null:
if (flowExecutionContext)
{
vt.GetAwaiter().OnCompleted(continuation);
}
else
{
vt.GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
default:
if (flowExecutionContext)
{
vt.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(continuation);
}
else
{
vt.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
}
asyncLocal.Value = 0;
SynchronizationContext.SetSynchronizationContext(null);
if (!completeBeforeOnCompleted)
{
Assert.False(vt.IsCompleted);
Assert.False(vt.IsCompletedSuccessfully);
c.Writer.TryWrite(true);
}
await continuationRan.Task;
Assert.True(vt.IsCompleted);
Assert.True(vt.IsCompletedSuccessfully);
Assert.Equal(continueOnCapturedContext != false, schedulerWasFlowed);
if (completeBeforeOnCompleted) // OnCompleted will simply queue using a mechanism that happens to flow
{
Assert.True(executionContextWasFlowed);
}
else
{
Assert.Equal(flowExecutionContext, executionContextWasFlowed);
}
}, CancellationToken.None, TaskCreationOptions.None, setNonDefaultTaskScheduler ? new CustomTaskScheduler() : TaskScheduler.Default);
}
public static IEnumerable<object[]> Reader_ContinuesOnCurrentSchedulerIfDesired_MemberData() =>
from readOrWait in new[] { true, false }
from completeBeforeOnCompleted in new[] { true, false }
from flowExecutionContext in new[] { true, false }
from continueOnCapturedContext in new bool?[] { null, false, true }
from setDefaultSyncContext in new[] { true, false }
select new object[] { readOrWait, completeBeforeOnCompleted, flowExecutionContext, continueOnCapturedContext, setDefaultSyncContext };
[Theory]
[MemberData(nameof(Reader_ContinuesOnCurrentSchedulerIfDesired_MemberData))]
public async Task Reader_ContinuesOnCurrentTaskSchedulerIfDesired(
bool readOrWait, bool completeBeforeOnCompleted, bool flowExecutionContext, bool? continueOnCapturedContext, bool setDefaultSyncContext)
{
if (AllowSynchronousContinuations)
{
return;
}
await Task.Run(async () =>
{
Assert.Null(SynchronizationContext.Current);
Channel<bool> c = CreateChannel<bool>();
ValueTask<bool> vt = readOrWait ?
c.Reader.ReadAsync() :
c.Reader.WaitToReadAsync();
var continuationRan = new TaskCompletionSource<bool>();
var asyncLocal = new AsyncLocal<int>();
bool schedulerWasFlowed = false;
bool executionContextWasFlowed = false;
Action continuation = () =>
{
schedulerWasFlowed = TaskScheduler.Current is CustomTaskScheduler;
executionContextWasFlowed = 42 == asyncLocal.Value;
continuationRan.SetResult(true);
};
if (completeBeforeOnCompleted)
{
Assert.False(vt.IsCompleted);
Assert.False(vt.IsCompletedSuccessfully);
c.Writer.TryWrite(true);
}
await Task.Factory.StartNew(() =>
{
if (setDefaultSyncContext)
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}
Assert.IsType<CustomTaskScheduler>(TaskScheduler.Current);
asyncLocal.Value = 42;
switch (continueOnCapturedContext)
{
case null:
if (flowExecutionContext)
{
vt.GetAwaiter().OnCompleted(continuation);
}
else
{
vt.GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
default:
if (flowExecutionContext)
{
vt.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(continuation);
}
else
{
vt.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
}
asyncLocal.Value = 0;
}, CancellationToken.None, TaskCreationOptions.None, new CustomTaskScheduler());
if (!completeBeforeOnCompleted)
{
Assert.False(vt.IsCompleted);
Assert.False(vt.IsCompletedSuccessfully);
c.Writer.TryWrite(true);
}
await continuationRan.Task;
Assert.True(vt.IsCompleted);
Assert.True(vt.IsCompletedSuccessfully);
Assert.Equal(continueOnCapturedContext != false, schedulerWasFlowed);
if (completeBeforeOnCompleted) // OnCompleted will simply queue using a mechanism that happens to flow
{
Assert.True(executionContextWasFlowed);
}
else
{
Assert.Equal(flowExecutionContext, executionContextWasFlowed);
}
});
}
[Fact]
public void ValueTask_GetResultWhenNotCompleted_Throws()
{
ValueTaskAwaiter<int> readVt = CreateChannel().Reader.ReadAsync().GetAwaiter();
Assert.Throws<InvalidOperationException>(() => readVt.GetResult());
ValueTaskAwaiter<bool> waitReadVt = CreateChannel().Reader.WaitToReadAsync().GetAwaiter();
Assert.Throws<InvalidOperationException>(() => waitReadVt.GetResult());
if (CreateFullChannel() != null)
{
ValueTaskAwaiter writeVt = CreateFullChannel().Writer.WriteAsync(42).GetAwaiter();
Assert.Throws<InvalidOperationException>(() => writeVt.GetResult());
ValueTaskAwaiter<bool> waitWriteVt = CreateFullChannel().Writer.WaitToWriteAsync().GetAwaiter();
Assert.Throws<InvalidOperationException>(() => waitWriteVt.GetResult());
}
}
[Fact]
public void ValueTask_MultipleContinuations_Throws()
{
ValueTaskAwaiter<int> readVt = CreateChannel().Reader.ReadAsync().GetAwaiter();
readVt.OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => readVt.OnCompleted(() => { }));
ValueTaskAwaiter<bool> waitReadVt = CreateChannel().Reader.WaitToReadAsync().GetAwaiter();
waitReadVt.OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => waitReadVt.OnCompleted(() => { }));
if (CreateFullChannel() != null)
{
ValueTaskAwaiter writeVt = CreateFullChannel().Writer.WriteAsync(42).GetAwaiter();
writeVt.OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => writeVt.OnCompleted(() => { }));
ValueTaskAwaiter<bool> waitWriteVt = CreateFullChannel().Writer.WaitToWriteAsync().GetAwaiter();
waitWriteVt.OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => waitWriteVt.OnCompleted(() => { }));
}
}
private sealed class CustomSynchronizationContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object state)
{
ThreadPool.QueueUserWorkItem(delegate
{
SetSynchronizationContext(this);
try
{
d(state);
}
finally
{
SetSynchronizationContext(null);
}
}, null);
}
}
private sealed class CustomTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task) => ThreadPool.QueueUserWorkItem(_ => TryExecuteTask(task));
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => false;
protected override IEnumerable<Task> GetScheduledTasks() => null;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using ASC.Api.Impl;
using ASC.Core;
using ASC.Core.Users;
using ASC.Specific;
using ASC.Web.Core.Users;
namespace ASC.Api.Employee
{
[DataContract(Name = "person", Namespace = "")]
public class EmployeeWraperFull : EmployeeWraper
{
[DataMember(Order = 10)]
public string FirstName { get; set; }
[DataMember(Order = 10)]
public string LastName { get; set; }
[DataMember(Order = 2)]
public string UserName { get; set; }
[DataMember(Order = 10)]
public string Email { get; set; }
[DataMember(Order = 12, EmitDefaultValue = false)]
protected List<Contact> Contacts { get; set; }
[DataMember(Order = 10, EmitDefaultValue = false)]
public ApiDateTime Birthday { get; set; }
[DataMember(Order = 10, EmitDefaultValue = false)]
public string Sex { get; set; }
[DataMember(Order = 10)]
public EmployeeStatus Status { get; set; }
[DataMember(Order = 10)]
public EmployeeActivationStatus ActivationStatus { get; set; }
[DataMember(Order = 10)]
public ApiDateTime Terminated { get; set; }
[DataMember(Order = 10, EmitDefaultValue = false)]
public string Department { get; set; }
[DataMember(Order = 10, EmitDefaultValue = false)]
public ApiDateTime WorkFrom { get; set; }
[DataMember(Order = 20, EmitDefaultValue = false)]
public List<GroupWrapperSummary> Groups { get; set; }
[DataMember(Order = 10, EmitDefaultValue = false)]
public string Location { get; set; }
[DataMember(Order = 10, EmitDefaultValue = false)]
public string Notes { get; set; }
[DataMember(Order = 20)]
public string AvatarMedium { get; set; }
[DataMember(Order = 20)]
public string Avatar { get; set; }
[DataMember(Order = 20)]
public bool IsAdmin { get; set; }
[DataMember(Order = 20)]
public bool IsLDAP { get; set; }
[DataMember(Order = 20, EmitDefaultValue = false)]
public List<string> ListAdminModules { get; set; }
[DataMember(Order = 20)]
public bool IsOwner { get; set; }
[DataMember(Order = 2)]
public bool IsVisitor { get; set; }
[DataMember(Order = 20, EmitDefaultValue = false)]
public string CultureName { get; set; }
[DataMember(Order = 11, EmitDefaultValue = false)]
protected String MobilePhone { get; set; }
[DataMember(Order = 11, EmitDefaultValue = false)]
protected MobilePhoneActivationStatus MobilePhoneActivationStatus { get; set; }
[DataMember(Order = 20)]
public bool IsSSO { get; set; }
public EmployeeWraperFull()
{
}
public EmployeeWraperFull(UserInfo userInfo)
: this(userInfo, null)
{
}
public EmployeeWraperFull(UserInfo userInfo, ApiContext context)
: base(userInfo, context)
{
UserName = userInfo.UserName;
IsVisitor = userInfo.IsVisitor();
FirstName = userInfo.FirstName;
LastName = userInfo.LastName;
Birthday = (ApiDateTime)userInfo.BirthDate;
if (userInfo.Sex.HasValue)
Sex = userInfo.Sex.Value ? "male" : "female";
Status = userInfo.Status;
ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated;
Terminated = (ApiDateTime)userInfo.TerminatedDate;
WorkFrom = (ApiDateTime)userInfo.WorkFromDate;
Email = userInfo.Email;
if (!string.IsNullOrEmpty(userInfo.Location))
{
Location = userInfo.Location;
}
if (!string.IsNullOrEmpty(userInfo.Notes))
{
Notes = userInfo.Notes;
}
if (!string.IsNullOrEmpty(userInfo.MobilePhone))
{
MobilePhone = userInfo.MobilePhone;
}
MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus;
if (!string.IsNullOrEmpty(userInfo.CultureName))
{
CultureName = userInfo.CultureName;
}
FillConacts(userInfo);
if (CheckContext(context, "groups") || CheckContext(context, "department"))
{
var groups = CoreContext.UserManager.GetUserGroups(userInfo.ID).Select(x => new GroupWrapperSummary(x)).ToList();
if (groups.Any())
{
Groups = groups;
Department = string.Join(", ", Groups.Select(d => d.Name.HtmlEncode()));
}
else
{
Department = "";
}
}
if (CheckContext(context, "avatarMedium"))
{
AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID) + "?_=" + userInfo.LastModified.GetHashCode();
}
if (CheckContext(context, "avatar"))
{
Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID) + "?_=" + userInfo.LastModified.GetHashCode();
}
IsAdmin = userInfo.IsAdmin();
if (CheckContext(context, "listAdminModules"))
{
var listAdminModules = userInfo.GetListAdminModules();
if (listAdminModules.Any())
ListAdminModules = listAdminModules;
}
IsOwner = userInfo.IsOwner();
IsLDAP = userInfo.IsLDAP();
IsSSO = userInfo.IsSSO();
}
private void FillConacts(UserInfo userInfo)
{
var contacts = new List<Contact>();
for (var i = 0; i < userInfo.Contacts.Count; i += 2)
{
if (i + 1 < userInfo.Contacts.Count)
{
contacts.Add(new Contact(userInfo.Contacts[i], userInfo.Contacts[i + 1]));
}
}
if (contacts.Any())
{
Contacts = contacts;
}
}
public static bool CheckContext(ApiContext context, string field)
{
return context == null || context.Fields == null ||
(context.Fields != null && context.Fields.Contains(field));
}
public static EmployeeWraperFull GetFull(Guid userId)
{
try
{
return GetFull(CoreContext.UserManager.GetUsers(userId));
}
catch (Exception)
{
return GetFull(Core.Users.Constants.LostUser);
}
}
public static EmployeeWraperFull GetFull(UserInfo userInfo)
{
return new EmployeeWraperFull(userInfo);
}
public new static EmployeeWraperFull GetSample()
{
return new EmployeeWraperFull
{
Avatar = "url to big avatar",
AvatarSmall = "url to small avatar",
Contacts = new List<Contact> { Contact.GetSample() },
Email = "my@domain.com",
FirstName = "Mike",
Id = Guid.Empty,
IsAdmin = false,
ListAdminModules = new List<string> { "projects", "crm" },
UserName = "Mike.Zanyatski",
LastName = "Zanyatski",
Title = "Manager",
Groups = new List<GroupWrapperSummary> { GroupWrapperSummary.GetSample() },
AvatarMedium = "url to medium avatar",
Birthday = ApiDateTime.GetSample(),
Department = "Marketing",
Location = "Palo Alto",
Notes = "Notes to worker",
Sex = "male",
Status = EmployeeStatus.Active,
WorkFrom = ApiDateTime.GetSample(),
//Terminated = ApiDateTime.GetSample(),
CultureName = "en-EN",
IsLDAP = false,
IsSSO = false
};
}
}
}
| |
//============================Top==========================================
// Logically, the most important thing in a video game is being able to control your character
// This guide will cover how the Torque2D engine handles input and how we can use it in our game
//============================Input Event Callbacks========================
// An input event callback is the response from the T2D engine when an input event (clicking, scrolling, or leaving the window with the cursor) has happened
// Input events are handled by the GuiControl that receives them
// The most common GuiControl that we will deal with is the SceneWindow
// This is the Gui object where our game is displayed
// When you click and drag or resize the window, those events are handled by input event callbacks within the engine
// We can also create multiple SceneWindows and handle them in different ways
// This is the syntax for using Input Event Callbacks:
// This is the same process as defining a method
// SceneWindow is the class that this method will work with
// ::onTouchDown is the name of the object method that we are defining
// %this is the variable parameter that is passed for the engine to refer to this method within itself
// %touchID is the variable parameter that defines specifically which finger is touching the screen
// This is an android/iOS function, we won't need this unless we port the game to other platforms
// %worldPosition is the point on the game screen (the world) that was clicked
// %mouseClicks keeps track of the number of times the mouse was clicked (for double-click actions, or even quintuple-click if you like)
function SceneWindow::onTouchDown(%this, %touchID, %worldPosition, %mouseClicks)
{
}
// This is a list of other callbacks you could use:
onTouchDown
onTouchUp
onTouchMoved
onTouchDragged
onTouchEnter
onTouchLeave
onMiddleMouseDown
onMiddleMouseUp
onMiddleMouseDragged
onRightMouseDown
onRightMouseUp
onRightMouseDragged
onMouseWheelUp
onMouseWheelDown
onMouseEnter
onMouseLeave
// The names should be pretty self-explanatory
// Left-click mouse functions are covered by the onTouch... functions
//============================Input Listeners==============================
// An input listener is an object that receives any input events that the SceneWindow also receives now or in the future
// You can allow any SimObject to be an input listener as follows:
// %obj is the local variable that will store the listener
// new announces to the engine that we are creating a new instance of this object
// ScriptObject is the type of object that we are creating
%obj = new ScriptObject()
{
// class is an existing field already within the engine that we are giving to this object
class="ExampleListener";
};
// This is how we call the object method
SceneWindow.addInputListener(%obj);
// This is how we can tell the engine that we want the listener to stop receiving the same inputs as SceneWindow
SceneWindow.removeInputListener(%obj);
//============================Per-Object Callbacks=========================
// While you can use input callbacks on the SceneWindow level, it is also possible to use them on a per-object basis
// This means that individual sprites or other scene objects can react to defined input events
// Touching or clicking within that object's bounding box will result in the callback being run
// To turn on SceneWindow event passing:
// Turn on input events for scene objects.
SceneWindow.setUseObjectInputEvents(true);
// As a second step, each individual object needs its ability to receive input events turned on
// This can be done with .setUseInputEvents():
// We create a new Sprite and store it in the %object variable
// We give it the class field and put it in the ButtonClass
%object = new Sprite() {class = "ButtonClass";};
// Now we tell this sprite to use input event from the SceneWindow
%object.setUseInputEvents(true);
// Note that we used a different format for defining the Sprite object because it was a one-line function
// We could have just as easily done this:
%object = new Sprite()
{
class = "ButtonClass";
};
// It means the same thing
// You can then use the same callback list as the SceneWindow to create object specific functions:
function ButtonClass::onTouchDown(%this, %touchID, %worldPosition)
{
}
function ButtonClass::onTouchUp(%this, %touchID, %worldPosition)
{
}
// Note that the onMouseEnter/onTouchEnter and onMouseLeave/onTouchLeave callbacks do not work for objects
// Consider the following example:
// Make sure that you have turned on object event passing for both the SceneWindow and each individual object
function SceneWindow::onTouchDown(%this, %touchID, %worldPosition)
{
echo("This is the SceneWindow");
}
function AreaX::onTouchDown(%this, %touchID, %worldPosition)
{
echo("This is Area X");
}
function AreaY::onTouchDown(%this, %touchID, %worldPosition)
{
echo("This is Area Y");
}
// Referencing the example above, clicking or touching anywhere in the area of the SceneWindow will call the SceneWindow::onTouchDown method
// Within the scene object "X", both the SceneWindow::onTouchDown and AreaX::onTouchDown are run
// A click or touch within the scene object "Y" will give you the echo statements in the console for SceneWindow::onTouchDown and AreaY::onTouchDown only
// If you delete the SceneWindow::onTouchDown function, you will only receive a callback if you touch or click within either the X or Y areas.
// Keep this in mind when writing response callbacks for your input events
// Torque 2D gives you complete control over how global or local those callbacks should be
//============================Action Maps==================================
// ActionMaps hold key/input binds that give you commands when certain input events happen.
// These events can be anything from pressing the space bar, up arrow, or "w" key to moving the mouse horizontally or vertically.
// At the base of all input is a GlobalActionMap where the bindings are defined which will be used throughout the program.
// The GlobalActionMap's bindings cannot be overriden by other ActionMaps
// You can "push" to enable these other ActionMaps and "pop" to disable them
// This works almost as a layer system, that way when multiple ActionMaps specify commands to be triggered on an event
// The most recently pushed one will be the event triggered
// Multiple ActionMaps can be enabled at the same time and you can "bind" input commands to an ActionMap in one of three different ways
// The process of using an ActionMap is very simple:
// Create an ActionMap
// Bind a function to a device and an event
// Write the function that uses the input
// Push the ActionMap when you want to use it, pop it when you are done with it
// Create a new ActionMap for input binding
new ActionMap(moveMap);
// There are three different ways to bind a device to an event and have it call a function.
moveMap.bind(DEVICE, EVENT, COMMAND);
// or
moveMap.bindCmd(DEVICE, EVENT, MAKECMD, BREAKCMD);
// or
moveMap.bindObj(DEVICE, EVENT, COMMAND, OBJECT);
// The code samples above are a "template". For each input, you need to replace the DEVICE, EVENT, COMMAND, etc variables with the following:
// Device: keyboard, mouse0, touchdevice
// Event: "u"(as in, the u key is pressed), xaxis, touchdown, touchmove or touchup
// Command: A string that contains the name of the function you wish to call
// MakeCmd: A string that contains the name of the function you wish to call (i.e. key pressed)
// BreakCmd: A string that contains the name of the function you wish to call (i.e. key released)
// Object: The explicit object
// When you are ready to use the action map and its bindings, you need to push it to the system.
moveMap.push();
// If you need to disable the current input scheme, you can call the "pop" function to disable the action map
// This does not delete it, but it does stop capturing input
moveMap.pop();
// When you are ready to cleanup your game for a shutdown, you can delete the action map
moveMap.delete();
//============================.bind() Command=============================
// For keyboard events:
// Here keyboard is the device, the "u" key is the event, and toggleU is the name of the function we will call
moveMap.bind(keyboard, "u", toggleU);
// Now we need to define toggleU so our previous command will actually do something:
function toggleU(%val)
{
if(%val)
{
echo("u key down");
} else
{
echo("u key up");
}
}
// One very important thing to note is that this toggleU function is set to receive a "%val" value
// This is very important, when using the .bind() command you must always set your functions up like this
// In the case of a key (like our "u" key example) the %val will only ever be
// Either a 1 (representing the key was pressed) or a 0 (representing the key was released)
// As you can see we can separate the functionality with a simple if statement
// An non-key example of using .bind() would be this:
moveMap.bind(mouse0, "xaxis", horizontalMove);
// This time we aren't binding an event from the "keyboard", instead we chose "mouse0" which represents the first mouse (since T2D can handle input from multiple mice)
// The event we're binding is "xaxis" and we simply call a "horizontalMove" function
// The "xaxis" basically represents the mouse movement in the x-axis
// We can set up the horizontalMove function like this:
function horizontalMove(%val)
{
echo("xaxis = " @ %val);
}
//============================.bindCmd() Command==========================
// The .bindCmd() function works fairly similar to the bind() function,
// Except instead of setting a single function to be called when the event is processed, you set two functions.
// One will be called when the event is activated (on key down), while the other is activated when the event is broken (on key release
// In this case you don't pass just a "function" though; you pass a string that represents script to be run when you activate that event
// That means that you can pass a single line if you want to do a single script action, though generally you will simply pass a function call in a string
// You can set up the same "u" key like this:
moveMap.bindCmd(keyboard, "u", "onUDown();", "onUUp();");
// Notice we wrapped the functions in a string as well as making it a full script call to that function
// Now we can have one function do what needs to be done when the "u" key is pressed, while the other can do what is needed when the "u" key is released
function onUDown()
{
echo("u key down");
}
function onUUp()
{
echo("u key up");
}
//============================.bindObj() Command==========================
// This function follows the format of .bind() almost exactly, except that we have an extra value for the object we are assigning the bind to
// A typical use for this is within behaviors:
function moveBehavior::onBehaviorAdd(%this)
{
if (!isObject(moveMap))
return;
moveMap.bindObj(keyboard, "up", moveUp, %this);
moveMap.bindObj(keyboard, "down", moveDown, %this);
moveMap.bindObj(keyboard, "left", moveLeft, %this);
moveMap.bindObj(keyboard, "right", moveRight, %this);
}
// Similar to .bind() is the toggle function that is required
// Again, we must pass a %val value to this function:
function moveBehavior::moveUp(%this, %val)
{
%this.up = %val;
echo(%this.up);
}
//============================Peripherals==================================
// You can use joysticks, gamepads, Xbox360 controllers, or the Leap Motion in your game by applying the same concepts as described above
// Just keep in mind there are a few small differences
// Note that the Windows implementation of gamepad support works correctly as it uses DirectInput
// Unfortunately, OSX support for gamepads is not fully implemented at this time
// During the initialization of your game code, make sure to add the following lines to your script files:
$enableDirectInput=true;
activateDirectInput();
enableJoystick();
// For the Xbox360 controller, add the following lines of script to the startup methods of your game code:
enableXinput();
$enableDirectInput=true;
activateDirectInput();
// All 4 Xinput controllers/devices are referred to in script as gamepad0, gamepad1, etc.
// When mapping axes (xaxis, yaxis, zaxis, sliders) to either a bind or bindObj function, the corresponding functions' %val will return a value between -x and +x
// x represents the maximum range of the control in either direction
// A %val of 0 means the stick is centered
// Triggers on an Xbox360 controller (or on other controllers which have "analog" triggers) are a special case.
// A %val of 0 means that both triggers are untouched.
// A %val of -x means the Left trigger is completely pressed down
// A %val of x means the Right trigger is completely pressed down
// Support for other platforms will be considered if we decide to port the game to them
// Until then, this is all you need to know
//============================End==========================================
| |
//---------------------------------------------------------------------------
// <copyright file="ClockGroup.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//---------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using SR = MS.Internal.PresentationCore.SR;
using SRID = MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media.Animation
{
/// <summary>
/// The Clock instance type that will be created based on TimelineGroup
/// objects.
/// </summary>
public class ClockGroup : Clock
{
/// <summary>
/// Creates a new empty ClockGroup to be used in a Clock tree.
/// </summary>
/// <param name="timelineGroup">The TimelineGroup used to define the new
/// ClockGroup.</param>
protected internal ClockGroup(TimelineGroup timelineGroup)
: base(timelineGroup)
{
}
/// <summary>
/// Gets the TimelineGroup object that holds the description controlling the
/// behavior of this clock.
/// </summary>
/// <value>
/// The TimelineGroup object that holds the description controlling the
/// behavior of this clock.
/// </value>
public new TimelineGroup Timeline
{
get
{
return (TimelineGroup)base.Timeline;
}
}
/// <summary>
/// Gets a collection containing the children of this clock.
/// </summary>
/// <value>
/// A collection containing the children of this clock.
/// </value>
public ClockCollection Children
{
get
{
// VerifyAccess();
Debug.Assert(!IsTimeManager);
return new ClockCollection(this);
}
}
/// <summary>
/// Unchecked internal access to the child collection of this Clock.
/// </summary>
internal List<Clock> InternalChildren
{
get
{
Debug.Assert(!IsTimeManager);
return _children;
}
}
/// <summary>
/// Uncheck internal access to the root children
/// </summary>
internal List<WeakReference> InternalRootChildren
{
get
{
Debug.Assert(IsTimeManager);
return _rootChildren;
}
}
internal override void BuildClockSubTreeFromTimeline(
Timeline timeline,
bool hasControllableRoot)
{
// This is not currently necessary
//base.BuildClockSubTreeFromTimeline(timeline);
// Only TimelineGroup has children
TimelineGroup timelineGroup = timeline as TimelineGroup;
// Only a TimelineGroup should have allocated a ClockGroup.
Debug.Assert(timelineGroup != null);
// Create a clock for each of the children of the timeline
TimelineCollection timelineChildren = timelineGroup.Children;
if (timelineChildren != null && timelineChildren.Count > 0)
{
Clock childClock;
// Create a collection for the children of the clock
_children = new List<Clock>();
// Create clocks for the children
for (int index = 0; index < timelineChildren.Count; index++)
{
childClock = AllocateClock(timelineChildren[index], hasControllableRoot);
childClock._parent = this; // We connect the child to the subtree before calling BuildClockSubtreeFromTimeline
childClock.BuildClockSubTreeFromTimeline(timelineChildren[index], hasControllableRoot);
_children.Add(childClock);
childClock._childIndex = index;
}
// If we have SlipBehavior, check if we have any childen with which to slip.
if (_timeline is ParallelTimeline &&
((ParallelTimeline)_timeline).SlipBehavior == SlipBehavior.Slip)
{
// Verify that we only use SlipBehavior in supported scenarios
if (!IsRoot ||
(_timeline.RepeatBehavior.HasDuration) ||
(_timeline.AutoReverse == true) ||
(_timeline.AccelerationRatio > 0) ||
(_timeline.DecelerationRatio > 0))
{
throw new NotSupportedException(SR.Get(SRID.Timing_SlipBehavior_SlipOnlyOnSimpleTimelines));
}
for (int index = 0; index < _children.Count; index++)
{
Clock child = _children[index];
if (child.CanSlip)
{
Duration duration = child.ResolvedDuration;
// A [....] clock with duration of zero or no begin time has no effect, so do skip it
if ((!duration.HasTimeSpan || duration.TimeSpan > TimeSpan.Zero)
&& child._timeline.BeginTime.HasValue)
{
_syncData = new SyncData(child);
child._syncData = null; // The child will no longer self-[....]
}
break; // We only want the first child with CanSlip
}
}
}
}
}
/// <summary>
/// Gets the first child of this timeline.
/// </summary>
/// <value>
/// The first child of this timeline if the collection is not empty;
/// otherwise, null.
/// </value>
internal override Clock FirstChild
{
get
{
// ROOT Debug.Assert(!IsTimeManager);
Clock firstChild = null;
List<Clock> children = _children;
if (children != null)
{
firstChild = children[0];
}
return firstChild;
}
}
// This is only to be called on the TimeManager clock. Go through our
// top level clocks and find the clock with the highest desired framerate.
// DFR has to be > 0, so starting the accumulator at 0 is fine.
internal int GetMaxDesiredFrameRate()
{
Debug.Assert(IsTimeManager);
int desiredFrameRate = 0;
// Ask all top-level clock their desired framerate
WeakRefEnumerator<Clock> enumerator = new WeakRefEnumerator<Clock>(_rootChildren);
while (enumerator.MoveNext())
{
Clock currentClock = enumerator.Current;
if (currentClock != null && currentClock.CurrentState == ClockState.Active)
{
int? currentDesiredFrameRate = currentClock.DesiredFrameRate;
if (currentDesiredFrameRate.HasValue)
{
desiredFrameRate = Math.Max(desiredFrameRate, currentDesiredFrameRate.Value);
}
}
}
return desiredFrameRate;
}
// Called on the root
internal void ComputeTreeState()
{
Debug.Assert(IsTimeManager);
// Revive all children
WeakRefEnumerator<Clock> enumerator = new WeakRefEnumerator<Clock>(_rootChildren);
while (enumerator.MoveNext())
{
PrefixSubtreeEnumerator prefixEnumerator = new PrefixSubtreeEnumerator(enumerator.Current, true);
while (prefixEnumerator.MoveNext())
{
Clock current = prefixEnumerator.Current;
// Only traverse the "ripe" subset of the Timing tree
if (CurrentGlobalTime >= current.InternalNextTickNeededTime)
{
current.ApplyDesiredFrameRateToGlobalTime();
current.ComputeLocalState(); // Compute the state of the node
current.ClipNextTickByParent(); // Perform NextTick clipping, stage 1
// Make a note to visit for stage 2, only for ClockGroups and Roots
current.NeedsPostfixTraversal = (current is ClockGroup) || (current.IsRoot);
}
else
{
prefixEnumerator.SkipSubtree();
}
}
}
// To perform a postfix walk culled by NeedsPostfixTraversal flag, we use a local recursive method
// Note that since we called for this operation, it is probably already needed by the root clock
ComputeTreeStateRoot();
}
internal void ComputeTreeStateRoot()
{
Debug.Assert(IsTimeManager);
TimeSpan? previousTickNeededTime = InternalNextTickNeededTime;
InternalNextTickNeededTime = null; // Reset the root's next tick needed time
WeakRefEnumerator<Clock> enumerator = new WeakRefEnumerator<Clock>(_rootChildren);
while (enumerator.MoveNext())
{
Clock current = enumerator.Current;
if (current.NeedsPostfixTraversal)
{
if (current is ClockGroup)
{
((ClockGroup)current).ComputeTreeStatePostfix();
}
current.ApplyDesiredFrameRateToNextTick(); // Apply the effects of DFR on each root as needed
current.NeedsPostfixTraversal = false; // Reset the flag
}
if(!InternalNextTickNeededTime.HasValue ||
(enumerator.Current.InternalNextTickNeededTime.HasValue &&
enumerator.Current.InternalNextTickNeededTime < InternalNextTickNeededTime))
{
InternalNextTickNeededTime = enumerator.Current.InternalNextTickNeededTime;
}
}
if (InternalNextTickNeededTime.HasValue &&
(!previousTickNeededTime.HasValue || previousTickNeededTime > InternalNextTickNeededTime))
{
_timeManager.NotifyNewEarliestFutureActivity();
}
}
// Recursive postfix walk, culled by NeedsPostfixTraversal flags (hence cannot use PostfixSubtreeEnumerator)
private void ComputeTreeStatePostfix()
{
if (_children != null)
{
for (int c = 0; c < _children.Count; c++)
{
if (_children[c].NeedsPostfixTraversal) // Traverse deeper if this is part of the visited tree subset
{
ClockGroup group = _children[c] as ClockGroup;
Debug.Assert(group != null); // We should only have this flag set for ClockGroups
group.ComputeTreeStatePostfix();
}
}
ClipNextTickByChildren();
}
}
// Perform Stage 2 of clipping next tick time: clip by children
// Derived class does the actual clipping
private void ClipNextTickByChildren()
{
Debug.Assert(_children != null);
for (int c = 0; c < _children.Count; c++)
{
// Clip by child's NTNT if needed
if (!InternalNextTickNeededTime.HasValue ||
(_children[c].InternalNextTickNeededTime.HasValue && _children[c].InternalNextTickNeededTime < InternalNextTickNeededTime))
{
InternalNextTickNeededTime = _children[c].InternalNextTickNeededTime;
}
}
}
/// <summary>
/// Return the current duration from a specific clock
/// </summary>
/// <returns>
/// A Duration quantity representing the current iteration's estimated duration.
/// </returns>
internal override Duration CurrentDuration
{
get
{
Duration manualDuration = _timeline.Duration; // Check if a duration is specified by the user
if (manualDuration != Duration.Automatic)
{
return manualDuration;
}
Duration currentDuration = TimeSpan.Zero;
// The container ends when all of its children have ended at least
// one of their active periods.
if (_children != null)
{
bool hasChildWithUnresolvedDuration = false;
bool bufferingSlipNode = (_syncData != null // This variable makes sure that our slip node completes as needed
&& _syncData.IsInSyncPeriod
&& !_syncData.SyncClockHasReachedEffectiveDuration);
for (int childIndex = 0; childIndex < _children.Count; childIndex++)
{
Clock current = _children[childIndex];
Duration childEndOfActivePeriod = current.EndOfActivePeriod;
if (childEndOfActivePeriod == Duration.Forever)
{
// If we have even one child with a duration of forever
// our resolved duration will also be forever. It doesn't
// matter if other _children have unresolved durations.
return Duration.Forever;
}
else if (childEndOfActivePeriod == Duration.Automatic)
{
hasChildWithUnresolvedDuration = true;
}
else
{
// Make sure that until Media completes, it is not treated as expired
if (bufferingSlipNode && _syncData.SyncClock == this)
{
childEndOfActivePeriod += TimeSpan.FromMilliseconds(50); // This compensation is roughly one frame of video
bufferingSlipNode = false;
}
if (childEndOfActivePeriod > currentDuration)
{
currentDuration = childEndOfActivePeriod;
}
}
}
// We've iterated through all our _children. We know that at this
// point none of them have a duration of Forever or we would have
// returned already. If any of them still have unresolved
// durations then our duration is also still unresolved and we
// will return automatic. Otherwise, we'll fall out of the 'if'
// block and return the currentDuration as our final resolved
// duration.
if (hasChildWithUnresolvedDuration)
{
return Duration.Automatic;
}
}
return currentDuration;
}
}
/// <summary>
/// Marks this Clock as the root of a timing tree.
/// </summary>
/// <param name="timeManager">
/// The TimeManager that controls this timing tree.
/// </param>
internal void MakeRoot(TimeManager timeManager)
{
Debug.Assert(!IsTimeManager, "Cannot associate a root with multiple timing trees");
Debug.Assert(this._timeManager == null, "Cannot use a timeline already in the timing tree as a root");
Debug.Assert(timeManager.TimeManagerClock == this, "Cannot associate more than one root per timing tree");
Debug.Assert(this._parent == null && _children == null, "Cannot use a timeline connected to other timelines as a root");
IsTimeManager = true;
_rootChildren = new List<WeakReference>();
_timeManager = timeManager;
_depth = 0;
//
InternalCurrentIteration = 1;
InternalCurrentProgress = 0;
InternalCurrentGlobalSpeed = 1;
InternalCurrentClockState = ClockState.Active;
}
// Upon a discontinuous interactive operation (begin/seek/stop), this resets children with SyncData
// (e.g. media) to track this change, specifically:
// 1) Realign their begin times evenly with the parent, discounting past slippage that may have occured
// 2) Reset their state, in case they leave their "[....]" period.
internal override void ResetNodesWithSlip()
{
Debug.Assert(IsRoot);
if (_children != null)
{
for (int c = 0; c < _children.Count; c++)
{
Clock child = _children[c];
if (child._syncData != null)
{
child._beginTime = child._timeline.BeginTime; // Realign the clock
child._syncData.IsInSyncPeriod = false;
child._syncData.UpdateClockBeginTime(); // Apply effects of realigning
}
}
}
base.ResetNodesWithSlip();
}
/// <summary>
/// Activates this root clock.
/// </summary>
internal void RootActivate()
{
Debug.Assert(IsTimeManager, "Invalid call to RootActivate for a non-root Clock");
Debug.Assert(_timeManager != null); // RootActivate should be called by our own TimeManager
// Reset the state of the timing tree
TimeIntervalCollection currentIntervals = TimeIntervalCollection.CreatePoint(_timeManager.InternalCurrentGlobalTime);
currentIntervals.AddNullPoint();
_timeManager.InternalCurrentIntervals = currentIntervals;
ComputeTreeState();
}
/// <summary>
/// Removes dead weak references from the child list of the root clock.
/// </summary>
internal void RootCleanChildren()
{
Debug.Assert(IsTimeManager, "Invalid call to RootCleanChildren for a non-root Clock");
WeakRefEnumerator<Clock> enumerator = new WeakRefEnumerator<Clock>(_rootChildren);
// Simply enumerating the children with the weak reference
// enumerator is sufficient to clean up the list. Therefore, the
// body of the loop can remain empty
while (enumerator.MoveNext())
{
}
// When the loop terminates naturally the enumerator will clean
// up the list of any dead references. Therefore, by the time we
// get here we are done.
}
/// <returns>
/// Returns true if any children are left, false if none are left
/// </returns>
internal bool RootHasChildren
{
get
{
Debug.Assert(IsTimeManager, "Invalid call to RootHasChildren for a non-root Clock");
return (_rootChildren.Count > 0);
}
}
/// <summary>
/// Deactivates and disables this root clock.
/// </summary>
internal void RootDisable()
{
Debug.Assert(IsTimeManager, "Invalid call to RootDeactivate for a non-root Clock");
// Reset the state of the timing tree
WeakRefEnumerator<Clock> enumerator = new WeakRefEnumerator<Clock>(_rootChildren);
while (enumerator.MoveNext())
{
PrefixSubtreeEnumerator subtree = new PrefixSubtreeEnumerator(enumerator.Current, true);
while (subtree.MoveNext())
{
if (subtree.Current.InternalCurrentClockState != ClockState.Stopped)
{
subtree.Current.ResetCachedStateToStopped();
subtree.Current.RaiseCurrentStateInvalidated();
subtree.Current.RaiseCurrentTimeInvalidated();
subtree.Current.RaiseCurrentGlobalSpeedInvalidated();
}
else
{
subtree.SkipSubtree();
}
}
}
}
/// <summary>
/// Check if our descendants have resolved their duration, and resets the HasDescendantsWithUnresolvedDuration
/// flag from true to false once that happens.
/// </summary>
/// <returns>Returns true when this node or one of its descendants have unresolved duration.</returns>
internal override void UpdateDescendantsWithUnresolvedDuration()
{
// If the flag was already unset, or our own node doesn't know its duration yet, the flag will not change now.
if (!HasDescendantsWithUnresolvedDuration || !HasResolvedDuration)
{
return;
}
if (_children != null)
{
for (int childIndex = 0; childIndex < _children.Count; childIndex++)
{
_children[childIndex].UpdateDescendantsWithUnresolvedDuration();
if (_children[childIndex].HasDescendantsWithUnresolvedDuration)
{
return; // If any child has unresolved descendants, we cannot unset our flag yet
}
}
}
// If we finished the loop, then every child subtree has fully resolved its duration during this method call.
HasDescendantsWithUnresolvedDuration = false;
return;
}
internal override void ClearCurrentIntervalsToNull()
{
_currentIntervals.Clear();
_currentIntervals.AddNullPoint();
}
internal override void AddNullPointToCurrentIntervals()
{
_currentIntervals.AddNullPoint();
}
internal override void ComputeCurrentIntervals(TimeIntervalCollection parentIntervalCollection,
TimeSpan beginTime, TimeSpan? endTime,
Duration fillDuration, Duration period,
double appliedSpeedRatio, double accelRatio, double decelRatio,
bool isAutoReversed)
{
_currentIntervals.Clear();
parentIntervalCollection.ProjectOntoPeriodicFunction(ref _currentIntervals,
beginTime, endTime,
fillDuration, period, appliedSpeedRatio,
accelRatio, decelRatio, isAutoReversed);
}
internal override void ComputeCurrentFillInterval(TimeIntervalCollection parentIntervalCollection,
TimeSpan beginTime, TimeSpan endTime, Duration period,
double appliedSpeedRatio, double accelRatio, double decelRatio,
bool isAutoReversed)
{
_currentIntervals.Clear();
parentIntervalCollection.ProjectPostFillZone(ref _currentIntervals,
beginTime, endTime,
period, appliedSpeedRatio,
accelRatio, decelRatio, isAutoReversed);
}
internal TimeIntervalCollection CurrentIntervals
{
get
{
return _currentIntervals;
}
}
private List<Clock> _children;
private List<WeakReference> _rootChildren;
private TimeIntervalCollection _currentIntervals;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace NFCoreEx
{
public class NFCElementManager : NFIElementManager
{
public NFCElementManager()
{
mhtObject = new Hashtable();
}
#region Instance
private static NFIElementManager _Instance = null;
public static NFIElementManager Instance
{
get
{
if (_Instance == null)
{
_Instance = new NFCElementManager();
}
return _Instance;
}
}
#endregion
public override bool Load()
{
mstrRootPath = "";
ClearInstanceElement();
Hashtable xTable = NFCLogicClassManager.Instance.GetElementList();
foreach (DictionaryEntry de in xTable)
{
NFILogicClass xLogicClass = (NFILogicClass)de.Value;
LoadInstanceElement(xLogicClass);
}
return false;
}
public override bool Clear()
{
return false;
}
public override bool ExistElement(string strConfigName)
{
if (mhtObject.ContainsKey(strConfigName))
{
return true;
}
return false;
}
public override Int64 QueryPropertyInt(string strConfigName, string strPropertyName)
{
NFIElement xElement = GetElement(strConfigName);
if (null != xElement)
{
return xElement.QueryInt(strPropertyName);
}
return 0;
}
public override float QueryPropertyFloat(string strConfigName, string strPropertyName)
{
NFIElement xElement = GetElement(strConfigName);
if (null != xElement)
{
return xElement.QueryFloat(strPropertyName);
}
return 0;
}
public override double QueryPropertyDouble(string strConfigName, string strPropertyName)
{
NFIElement xElement = GetElement(strConfigName);
if (null != xElement)
{
xElement.QueryDouble(strPropertyName);
}
return 0;
}
public override string QueryPropertyString(string strConfigName, string strPropertyName)
{
NFIElement xElement = GetElement(strConfigName);
if (null != xElement)
{
return xElement.QueryString(strPropertyName);
}
return "";
}
public override bool AddElement(string strName, NFIElement xElement)
{
if (!mhtObject.ContainsKey(strName))
{
mhtObject.Add(strName, xElement);
return true;
}
return false;
}
public override NFIElement GetElement(string strConfigName)
{
if (mhtObject.ContainsKey(strConfigName))
{
return (NFIElement)mhtObject[strConfigName];
}
return null;
}
private void ClearInstanceElement()
{
mhtObject.Clear();
}
private void LoadInstanceElement(NFILogicClass xLogicClass)
{
string strLogicPath = mstrRootPath;
strLogicPath += xLogicClass.GetInstance();
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(strLogicPath);
XmlNode xRoot = xmldoc.SelectSingleNode("XML");
XmlNodeList xNodeList = xRoot.SelectNodes("Object");
for (int i = 0; i < xNodeList.Count; ++i)
{
//NFCLog.Instance.Log("Class:" + xLogicClass.GetName());
XmlNode xNodeClass = xNodeList.Item(i);
XmlAttribute strID = xNodeClass.Attributes["ID"];
//NFCLog.Instance.Log("ClassID:" + strID.Value);
NFIElement xElement = GetElement(strID.Value);
if (null == xElement)
{
xElement = new NFCElement();
AddElement(strID.Value, xElement);
xLogicClass.AddConfigName(strID.Value);
XmlAttributeCollection xCollection = xNodeClass.Attributes;
for (int j = 0; j < xCollection.Count; ++j)
{
XmlAttribute xAttribute = xCollection[j];
NFIProperty xProperty = xLogicClass.GetPropertyManager().GetProperty(xAttribute.Name);
if (null != xProperty)
{
NFIDataList.VARIANT_TYPE eType = xProperty.GetType();
switch (eType)
{
case NFIDataList.VARIANT_TYPE.VTYPE_INT:
{
NFIDataList xValue = new NFCDataList();
xValue.AddInt(int.Parse(xAttribute.Value));
xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT:
{
NFIDataList xValue = new NFCDataList();
xValue.AddFloat(float.Parse(xAttribute.Value));
xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE:
{
NFIDataList xValue = new NFCDataList();
xValue.AddDouble(double.Parse(xAttribute.Value));
xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_STRING:
{
NFIDataList xValue = new NFCDataList();
xValue.AddString(xAttribute.Value);
NFIProperty xTestProperty = xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT:
{
NFIDataList xValue = new NFCDataList();
xValue.AddObject(new NFIDENTID(0, int.Parse(xAttribute.Value)));
xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue);
}
break;
default:
break;
}
}
}
}
}
}
/////////////////////////////////////////
private Hashtable mhtObject;
private string mstrRootPath;
}
}
| |
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System.IO;
using Microsoft.VisualStudio.Services.WebApi;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Handlers
{
public interface IHandler : IAgentService
{
List<ServiceEndpoint> Endpoints { get; set; }
Dictionary<string, string> Environment { get; set; }
IExecutionContext ExecutionContext { get; set; }
Variables RuntimeVariables { get; set; }
IStepHost StepHost { get; set; }
Dictionary<string, string> Inputs { get; set; }
List<SecureFile> SecureFiles { get; set; }
string TaskDirectory { get; set; }
Pipelines.TaskStepDefinitionReference Task { get; set; }
Task RunAsync();
}
public abstract class Handler : AgentService
{
#if OS_WINDOWS
// In windows OS the maximum supported size of a environment variable value is 32k.
// You can set environment variable greater then 32K, but that variable will not be able to read in node.exe.
private const int _environmentVariableMaximumSize = 32766;
#endif
protected IWorkerCommandManager CommandManager { get; private set; }
public List<ServiceEndpoint> Endpoints { get; set; }
public Dictionary<string, string> Environment { get; set; }
public Variables RuntimeVariables { get; set; }
public IExecutionContext ExecutionContext { get; set; }
public IStepHost StepHost { get; set; }
public Dictionary<string, string> Inputs { get; set; }
public List<SecureFile> SecureFiles { get; set; }
public string TaskDirectory { get; set; }
public Pipelines.TaskStepDefinitionReference Task { get; set; }
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
CommandManager = hostContext.GetService<IWorkerCommandManager>();
}
protected void AddEndpointsToEnvironment()
{
Trace.Entering();
ArgUtil.NotNull(Endpoints, nameof(Endpoints));
ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
ArgUtil.NotNull(ExecutionContext.Endpoints, nameof(ExecutionContext.Endpoints));
List<ServiceEndpoint> endpoints;
if ((RuntimeVariables.GetBoolean(Constants.Variables.Agent.AllowAllEndpoints) ?? false) ||
string.Equals(System.Environment.GetEnvironmentVariable("AGENT_ALLOWALLENDPOINTS") ?? string.Empty, bool.TrueString, StringComparison.OrdinalIgnoreCase))
{
endpoints = ExecutionContext.Endpoints; // todo: remove after sprint 120 or so
}
else
{
endpoints = Endpoints;
}
// Add the endpoints to the environment variable dictionary.
foreach (ServiceEndpoint endpoint in endpoints)
{
ArgUtil.NotNull(endpoint, nameof(endpoint));
string partialKey = null;
if (endpoint.Id != Guid.Empty)
{
partialKey = endpoint.Id.ToString();
}
else if (string.Equals(endpoint.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase))
{
partialKey = WellKnownServiceEndpointNames.SystemVssConnection.ToUpperInvariant();
}
else if (endpoint.Data == null ||
!endpoint.Data.TryGetValue(EndpointData.RepositoryId, out partialKey) ||
string.IsNullOrEmpty(partialKey))
{
continue; // This should never happen.
}
AddEnvironmentVariable(
key: $"ENDPOINT_URL_{partialKey}",
value: endpoint.Url?.ToString());
AddEnvironmentVariable(
key: $"ENDPOINT_AUTH_{partialKey}",
// Note, JsonUtility.ToString will not null ref if the auth object is null.
value: JsonUtility.ToString(endpoint.Authorization));
if (endpoint.Authorization != null && endpoint.Authorization.Scheme != null)
{
AddEnvironmentVariable(
key: $"ENDPOINT_AUTH_SCHEME_{partialKey}",
value: endpoint.Authorization.Scheme);
foreach (KeyValuePair<string, string> pair in endpoint.Authorization.Parameters)
{
AddEnvironmentVariable(
key: $"ENDPOINT_AUTH_PARAMETER_{partialKey}_{pair.Key?.Replace(' ', '_').ToUpperInvariant()}",
value: pair.Value);
}
}
if (endpoint.Id != Guid.Empty)
{
AddEnvironmentVariable(
key: $"ENDPOINT_DATA_{partialKey}",
// Note, JsonUtility.ToString will not null ref if the data object is null.
value: JsonUtility.ToString(endpoint.Data));
if (endpoint.Data != null)
{
foreach (KeyValuePair<string, string> pair in endpoint.Data)
{
AddEnvironmentVariable(
key: $"ENDPOINT_DATA_{partialKey}_{pair.Key?.Replace(' ', '_').ToUpperInvariant()}",
value: pair.Value);
}
}
}
}
}
protected void AddSecureFilesToEnvironment()
{
Trace.Entering();
ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
ArgUtil.NotNull(SecureFiles, nameof(SecureFiles));
List<SecureFile> secureFiles;
if ((RuntimeVariables.GetBoolean(Constants.Variables.Agent.AllowAllSecureFiles) ?? false) ||
string.Equals(System.Environment.GetEnvironmentVariable("AGENT_ALLOWALLSECUREFILES") ?? string.Empty, bool.TrueString, StringComparison.OrdinalIgnoreCase))
{
secureFiles = ExecutionContext.SecureFiles ?? new List<SecureFile>(0); // todo: remove after sprint 121 or so
}
else
{
secureFiles = SecureFiles;
}
// Add the secure files to the environment variable dictionary.
foreach (SecureFile secureFile in secureFiles)
{
if (secureFile != null && secureFile.Id != Guid.Empty)
{
string partialKey = secureFile.Id.ToString();
AddEnvironmentVariable(
key: $"SECUREFILE_NAME_{partialKey}",
value: secureFile.Name);
AddEnvironmentVariable(
key: $"SECUREFILE_TICKET_{partialKey}",
value: secureFile.Ticket);
}
}
}
protected void AddInputsToEnvironment()
{
// Validate args.
Trace.Entering();
ArgUtil.NotNull(Inputs, nameof(Inputs));
// Add the inputs to the environment variable dictionary.
foreach (KeyValuePair<string, string> pair in Inputs)
{
AddEnvironmentVariable(
key: $"INPUT_{pair.Key?.Replace(' ', '_').ToUpperInvariant()}",
value: pair.Value);
}
}
protected void AddVariablesToEnvironment(bool excludeNames = false, bool excludeSecrets = false)
{
// Validate args.
Trace.Entering();
ArgUtil.NotNull(Environment, nameof(Environment));
ArgUtil.NotNull(RuntimeVariables, nameof(RuntimeVariables));
// Add the public variables.
var names = new List<string>();
foreach (KeyValuePair<string, string> pair in RuntimeVariables.Public)
{
// Add "agent.jobstatus" using the unformatted name and formatted name.
if (string.Equals(pair.Key, Constants.Variables.Agent.JobStatus, StringComparison.OrdinalIgnoreCase))
{
AddEnvironmentVariable(pair.Key, pair.Value);
}
// Add the variable using the formatted name.
string formattedKey = (pair.Key ?? string.Empty).Replace('.', '_').Replace(' ', '_').ToUpperInvariant();
AddEnvironmentVariable(formattedKey, pair.Value);
// Store the name.
names.Add(pair.Key ?? string.Empty);
}
// Add the public variable names.
if (!excludeNames)
{
AddEnvironmentVariable("VSTS_PUBLIC_VARIABLES", JsonUtility.ToString(names));
}
if (!excludeSecrets)
{
// Add the secret variables.
var secretNames = new List<string>();
foreach (KeyValuePair<string, string> pair in RuntimeVariables.Private)
{
// Add the variable using the formatted name.
string formattedKey = (pair.Key ?? string.Empty).Replace('.', '_').Replace(' ', '_').ToUpperInvariant();
AddEnvironmentVariable($"SECRET_{formattedKey}", pair.Value);
// Store the name.
secretNames.Add(pair.Key ?? string.Empty);
}
// Add the secret variable names.
if (!excludeNames)
{
AddEnvironmentVariable("VSTS_SECRET_VARIABLES", JsonUtility.ToString(secretNames));
}
}
}
protected void AddEnvironmentVariable(string key, string value)
{
ArgUtil.NotNullOrEmpty(key, nameof(key));
Trace.Verbose($"Setting env '{key}' to '{value}'.");
Environment[key] = value ?? string.Empty;
#if OS_WINDOWS
if (Environment[key].Length > _environmentVariableMaximumSize)
{
ExecutionContext.Warning(StringUtil.Loc("EnvironmentVariableExceedsMaximumLength", key, value.Length, _environmentVariableMaximumSize));
}
#endif
}
protected void AddTaskVariablesToEnvironment()
{
// Validate args.
Trace.Entering();
ArgUtil.NotNull(ExecutionContext.TaskVariables, nameof(ExecutionContext.TaskVariables));
foreach (KeyValuePair<string, string> pair in ExecutionContext.TaskVariables.Public)
{
// Add the variable using the formatted name.
string formattedKey = (pair.Key ?? string.Empty).Replace('.', '_').Replace(' ', '_').ToUpperInvariant();
AddEnvironmentVariable($"VSTS_TASKVARIABLE_{formattedKey}", pair.Value);
}
foreach (KeyValuePair<string, string> pair in ExecutionContext.TaskVariables.Private)
{
// Add the variable using the formatted name.
string formattedKey = (pair.Key ?? string.Empty).Replace('.', '_').Replace(' ', '_').ToUpperInvariant();
AddEnvironmentVariable($"VSTS_TASKVARIABLE_{formattedKey}", pair.Value);
}
}
protected void AddPrependPathToEnvironment()
{
// Validate args.
Trace.Entering();
ArgUtil.NotNull(ExecutionContext.PrependPath, nameof(ExecutionContext.PrependPath));
if (ExecutionContext.PrependPath.Count == 0)
{
return;
}
// Prepend path.
string prepend = string.Join(Path.PathSeparator.ToString(), ExecutionContext.PrependPath.Reverse<string>());
string taskEnvPATH;
Environment.TryGetValue(Constants.PathVariable, out taskEnvPATH);
string originalPath = RuntimeVariables.Get(Constants.PathVariable) ?? // Prefer a job variable.
taskEnvPATH ?? // Then a task-environment variable.
System.Environment.GetEnvironmentVariable(Constants.PathVariable) ?? // Then an environment variable.
string.Empty;
string newPath = PathUtil.PrependPath(prepend, originalPath);
AddEnvironmentVariable(Constants.PathVariable, newPath);
}
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using System.Linq;
[TestFixture]
public class ScoreMasterTest1 {
[Test]
public void T01Bowl23 () {
int[] rolls = {2,3};
int[] frames = { 5};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T02Bowl234 () {
int[] rolls = {2,3,4};
int[] frames = { 5};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T03Bowl2345 () {
int[] rolls = {2,3,4,5};
int[] frames = { 5, 9};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T04Bowl23456 () {
int[] rolls = {2,3,4,5,6};
int[] frames = { 5, 9};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T05Bowl234561 () {
int[] rolls = {2,3,4,5,6,1};
int[] frames = { 5, 9, 7};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T06Bowl2345612 () {
int[] rolls = {2,3, 4,5, 6,1, 2};
int[] frames = { 5, 9, 7};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T07BowlX1 () {
int[] rolls = {10, 1};
int[] frames = {};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T08Bowl19 () {
int[] rolls = {1, 9};
int[] frames = {};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T09Bowl123455 () {
int[] rolls = {1,2, 3,4, 5,5};
int[] frames = { 3, 7};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T10SpareBonus () {
int[] rolls = {1,2, 3,5, 5,5, 3,3};
int[] frames = { 3, 8, 13, 6};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T11SpareBonus2 () {
int[] rolls = {1,2, 3,5, 5,5, 3,3, 7,1, 9,1, 6};
int[] frames = { 3, 8, 13, 6, 8, 16};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T12StrikeBonus () {
int[] rolls = { 10, 3,4};
int[] frames = {17, 7};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T13StrikeBonus3 () {
int[] rolls = { 1,2, 3,4, 5,4, 3,2, 10, 1,3, 3,4};
int[] frames = { 3, 7, 9, 5, 14, 4, 7};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T14MultiStrikes () {
int[] rolls = { 10, 10, 2,3};
int[] frames = {22, 15, 5};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void T15MultiStrikes3 () {
int[] rolls = { 10, 10, 2,3, 10, 5,3};
int[] frames = {22, 15, 5, 18, 8};
Assert.AreEqual (frames.ToList(), ScoreMaster.ScoreFrames (rolls.ToList()));
}
[Test]
public void C01TestGutterGame () {
int[] rolls = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int[] totalS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
[Test]
public void C02TestAllOnes () {
int[] rolls = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int[] totalS = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
[Test]
public void C03TestAllStrikes () {
int[] rolls = { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 };
int[] totalS = { 30, 60, 90, 120, 150, 180, 210, 240, 270, 300 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
[Test]
public void C04TestImmediateStrikeBonus () {
int[] rolls = { 5, 5, 3 };
int[] frames = { 13 };
Assert.AreEqual( frames.ToList(), ScoreMaster.ScoreFrames( rolls.ToList() ) );
}
[Test]
public void C05SpareInLastFrame () {
int[] rolls = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 7 };
int[] totalS = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 35 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
[Test]
public void C06StrikeInLastFrame () {
int[] rolls = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 2, 3 };
int[] totalS = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 33 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
// http://slocums.homestead.com/gamescore.html
[Test]
[Category( "Verification" )]
public void TG02GoldenCopyA () {
int[] rolls = { 10, 7, 3, 9, 0, 10, 0, 8, 8, 2, 0, 6, 10, 10, 10, 8, 1 };
int[] totalS = { 20, 39, 48, 66, 74, 84, 90, 120, 148, 167 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
//http://guttertoglory.com/wp-content/uploads/2011/11/score-2011_11_28.png
[Category( "Verification" )]
[Test]
public void TG03GoldenCopyB1of3 () {
int[] rolls = { 10, 9, 1, 9, 1, 9, 1, 9, 1, 7, 0, 9, 0, 10, 8, 2, 8, 2, 10 };
int[] totalS = { 20, 39, 58, 77, 94, 101, 110, 130, 148, 168 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
//http://guttertoglory.com/wp-content/uploads/2011/11/score-2011_11_28.png
[Category( "Verification" )]
[Test]
public void TG03GoldenCopyB2of3 () {
int[] rolls = { 8, 2, 8, 1, 9, 1, 7, 1, 8, 2, 9, 1, 9, 1, 10, 10, 7, 1 };
int[] totalS = { 18, 27, 44, 52, 71, 90, 110, 137, 155, 163 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
//http://guttertoglory.com/wp-content/uploads/2011/11/score-2011_11_28.png
[Category( "Verification" )]
[Test]
public void TG03GoldenCopyB3of3 () {
int[] rolls = { 10, 10, 9, 0, 10, 7, 3, 10, 8, 1, 6, 3, 6, 2, 9, 1, 10 };
int[] totalS = { 29, 48, 57, 77, 97, 116, 125, 134, 142, 162 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
// http://brownswick.com/wp-content/uploads/2012/06/OpenBowlingScores-6-12-12.jpg
[Category( "Verification" )]
[Test]
public void TG03GoldenCopyC1of3 () {
int[] rolls = { 7, 2, 10, 10, 10, 10, 7, 3, 10, 10, 9, 1, 10, 10, 9 };
int[] totalS = { 9, 39, 69, 96, 116, 136, 165, 185, 205, 234 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
// http://brownswick.com/wp-content/uploads/2012/06/OpenBowlingScores-6-12-12.jpg
[Category( "Verification" )]
[Test]
public void TG03GoldenCopyC2of3 () {
int[] rolls = { 10, 10, 10, 10, 9, 0, 10, 10, 10, 10, 10, 9, 1 };
int[] totalS = { 30, 60, 89, 108, 117, 147, 177, 207, 236, 256 };
Assert.AreEqual( totalS.ToList(), ScoreMaster.ScoreCumulative( rolls.ToList() ) );
}
// FormatRolls test
[Test]
public void F01Bowl1 () {
int[] rolls = { 1 };
string rollsString = "1";
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
[Test]
public void F02BowlX () {
int[] rolls = { 10 };
string rollsString = " X"; // Remember the space
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
[Test]
public void F03Bowl19 () {
int[] rolls = { 1, 9 };
string rollsString= "1/"; // Remember the space
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
[Test]
public void F04BowlStrikeInLastFrame () {
int[] rolls = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1 };
string rollsString = "111111111111111111X11"; // Remember the space
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
[Test]
public void F05Bowl0 () {
int[] rolls = { 0 };
string rollsString = "-"; // Remember the space
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
//http://guttertoglory.com/wp-content/uploads/2011/11/score-2011_11_28.png
[Category( "Verification" )]
[Test]
public void FG01GoldenCopyB1of3 () {
int[] rolls = { 10, 9, 1, 9, 1, 9, 1, 9, 1, 7, 0, 9, 0, 10, 8, 2, 8, 2, 10 };
string rollsString = " X9/9/9/9/7-9- X8/8/X";
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
//http://guttertoglory.com/wp-content/uploads/2011/11/score-2011_11_28.png
[Category( "Verification" )]
[Test]
public void FG02GoldenCopyB2of3 () {
int[] rolls = { 8, 2, 8, 1, 9, 1, 7, 1, 8, 2, 9, 1, 9, 1, 10, 10, 7, 1 };
string rollsString = "8/819/718/9/9/ X X71";
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
//http://guttertoglory.com/wp-content/uploads/2011/11/score-2011_11_28.png
[Category( "Verification" )]
[Test]
public void FG03GoldenCopyB3of3 () {
int[] rolls = { 10, 10, 9, 0, 10, 7, 3, 10, 8, 1, 6, 3, 6, 2, 9, 1, 10 };
string rollsString = " X X9- X7/ X8163629/X";
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
// http://brownswick.com/wp-content/uploads/2012/06/OpenBowlingScores-6-12-12.jpg
[Category( "Verification" )]
[Test]
public void FG04GoldenCopyC1of3 () {
int[] rolls = { 7, 2, 10, 10, 10, 10, 7, 3, 10, 10, 9, 1, 10, 10, 9 };
string rollsString = "72 X X X X7/ X X9/XX9";
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
// http://brownswick.com/wp-content/uploads/2012/06/OpenBowlingScores-6-12-12.jpg
[Category( "Verification" )]
[Test]
public void FG05GoldenCopyC2of3 () {
int[] rolls = { 10, 10, 10, 10, 9, 0, 10, 10, 10, 10, 10, 9, 1 };
string rollsString = " X X X X9- X X X XX91";
Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) );
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// Zone
/// </summary>
[DataContract]
public partial class Zone : IEquatable<Zone>
{
/// <summary>
/// Initializes a new instance of the <see cref="Zone" /> class.
/// </summary>
[JsonConstructorAttribute]
protected Zone() { }
/// <summary>
/// Initializes a new instance of the <see cref="Zone" /> class.
/// </summary>
/// <param name="WarehouseId">WarehouseId (required).</param>
/// <param name="Name">Name (required).</param>
/// <param name="Address">Address.</param>
/// <param name="IsClimateControlled">IsClimateControlled (default to false).</param>
/// <param name="IsFoodGrade">IsFoodGrade (default to false).</param>
/// <param name="IsSecure">IsSecure (default to false).</param>
/// <param name="IsFrozen">IsFrozen (default to false).</param>
/// <param name="IsRefrigerated">IsRefrigerated (default to false).</param>
public Zone(int? WarehouseId = null, string Name = null, string Address = null, bool? IsClimateControlled = null, bool? IsFoodGrade = null, bool? IsSecure = null, bool? IsFrozen = null, bool? IsRefrigerated = null)
{
// to ensure "WarehouseId" is required (not null)
if (WarehouseId == null)
{
throw new InvalidDataException("WarehouseId is a required property for Zone and cannot be null");
}
else
{
this.WarehouseId = WarehouseId;
}
// to ensure "Name" is required (not null)
if (Name == null)
{
throw new InvalidDataException("Name is a required property for Zone and cannot be null");
}
else
{
this.Name = Name;
}
this.Address = Address;
// use default value if no "IsClimateControlled" provided
if (IsClimateControlled == null)
{
this.IsClimateControlled = false;
}
else
{
this.IsClimateControlled = IsClimateControlled;
}
// use default value if no "IsFoodGrade" provided
if (IsFoodGrade == null)
{
this.IsFoodGrade = false;
}
else
{
this.IsFoodGrade = IsFoodGrade;
}
// use default value if no "IsSecure" provided
if (IsSecure == null)
{
this.IsSecure = false;
}
else
{
this.IsSecure = IsSecure;
}
// use default value if no "IsFrozen" provided
if (IsFrozen == null)
{
this.IsFrozen = false;
}
else
{
this.IsFrozen = IsFrozen;
}
// use default value if no "IsRefrigerated" provided
if (IsRefrigerated == null)
{
this.IsRefrigerated = false;
}
else
{
this.IsRefrigerated = IsRefrigerated;
}
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets WarehouseId
/// </summary>
[DataMember(Name="warehouseId", EmitDefaultValue=false)]
public int? WarehouseId { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Address
/// </summary>
[DataMember(Name="address", EmitDefaultValue=false)]
public string Address { get; set; }
/// <summary>
/// Gets or Sets IsClimateControlled
/// </summary>
[DataMember(Name="isClimateControlled", EmitDefaultValue=false)]
public bool? IsClimateControlled { get; set; }
/// <summary>
/// Gets or Sets IsFoodGrade
/// </summary>
[DataMember(Name="isFoodGrade", EmitDefaultValue=false)]
public bool? IsFoodGrade { get; set; }
/// <summary>
/// Gets or Sets IsSecure
/// </summary>
[DataMember(Name="isSecure", EmitDefaultValue=false)]
public bool? IsSecure { get; set; }
/// <summary>
/// Gets or Sets IsFrozen
/// </summary>
[DataMember(Name="isFrozen", EmitDefaultValue=false)]
public bool? IsFrozen { get; set; }
/// <summary>
/// Gets or Sets IsRefrigerated
/// </summary>
[DataMember(Name="isRefrigerated", EmitDefaultValue=false)]
public bool? IsRefrigerated { get; set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Zone {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Address: ").Append(Address).Append("\n");
sb.Append(" IsClimateControlled: ").Append(IsClimateControlled).Append("\n");
sb.Append(" IsFoodGrade: ").Append(IsFoodGrade).Append("\n");
sb.Append(" IsSecure: ").Append(IsSecure).Append("\n");
sb.Append(" IsFrozen: ").Append(IsFrozen).Append("\n");
sb.Append(" IsRefrigerated: ").Append(IsRefrigerated).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Zone);
}
/// <summary>
/// Returns true if Zone instances are equal
/// </summary>
/// <param name="other">Instance of Zone to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Zone other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.WarehouseId == other.WarehouseId ||
this.WarehouseId != null &&
this.WarehouseId.Equals(other.WarehouseId)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Address == other.Address ||
this.Address != null &&
this.Address.Equals(other.Address)
) &&
(
this.IsClimateControlled == other.IsClimateControlled ||
this.IsClimateControlled != null &&
this.IsClimateControlled.Equals(other.IsClimateControlled)
) &&
(
this.IsFoodGrade == other.IsFoodGrade ||
this.IsFoodGrade != null &&
this.IsFoodGrade.Equals(other.IsFoodGrade)
) &&
(
this.IsSecure == other.IsSecure ||
this.IsSecure != null &&
this.IsSecure.Equals(other.IsSecure)
) &&
(
this.IsFrozen == other.IsFrozen ||
this.IsFrozen != null &&
this.IsFrozen.Equals(other.IsFrozen)
) &&
(
this.IsRefrigerated == other.IsRefrigerated ||
this.IsRefrigerated != null &&
this.IsRefrigerated.Equals(other.IsRefrigerated)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.WarehouseId != null)
hash = hash * 59 + this.WarehouseId.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Address != null)
hash = hash * 59 + this.Address.GetHashCode();
if (this.IsClimateControlled != null)
hash = hash * 59 + this.IsClimateControlled.GetHashCode();
if (this.IsFoodGrade != null)
hash = hash * 59 + this.IsFoodGrade.GetHashCode();
if (this.IsSecure != null)
hash = hash * 59 + this.IsSecure.GetHashCode();
if (this.IsFrozen != null)
hash = hash * 59 + this.IsFrozen.GetHashCode();
if (this.IsRefrigerated != null)
hash = hash * 59 + this.IsRefrigerated.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
return hash;
}
}
}
}
| |
//Apache2,GitHub:mongodb-csharp
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace MongoDB
{
/// <summary>
/// Type to hold an interned string that maps to the bson symbol type.
/// </summary>
[Serializable]
public struct MongoSymbol : IEquatable<MongoSymbol>, IEquatable<String>, IComparable<MongoSymbol>, IComparable<String>, IXmlSerializable
{
/// <summary>
/// Gets or sets the empty.
/// </summary>
/// <value>The empty.</value>
public static MongoSymbol Empty { get; private set; }
/// <summary>
/// Initializes the <see cref="MongoSymbol"/> struct.
/// </summary>
static MongoSymbol(){
Empty = new MongoSymbol();
}
/// <summary>
/// Initializes a new instance of the <see cref="MongoSymbol"/> struct.
/// </summary>
/// <param name="value">The value.</param>
public MongoSymbol(string value)
: this(){
if(!string.IsNullOrEmpty(value))
Value = String.Intern(value);
}
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>The value.</value>
public string Value { get; private set; }
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(MongoSymbol other){
return Value.CompareTo(other.Value);
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(string other){
return Value.CompareTo(other);
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(MongoSymbol other){
return Equals(other.Value, Value);
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(string other){
return Value.Equals(other);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString(){
return Value;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj){
if(ReferenceEquals(null, obj))
return false;
return obj.GetType() == typeof(MongoSymbol) && Equals((MongoSymbol)obj);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(MongoSymbol a, MongoSymbol b){
return SymbolEqual(a.Value, b.Value);
}
/*
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(MongoSymbol a, string b){
return SymbolEqual(a.Value, b);
}*/
/*
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(string a, MongoSymbol b){
return SymbolEqual(a, b.Value);
}*/
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(MongoSymbol a, MongoSymbol b){
return !(a == b);
}
/*
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(MongoSymbol a, String b){
return !(a == b);
}*/
/*
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(string a, MongoSymbol b){
return !(a == b);
}*/
/// <summary>
/// Performs an implicit conversion from <see cref="MongoDB.MongoSymbol"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="s">The s.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator string(MongoSymbol s){
return s.Value;
}
/// <summary>
/// Performs an implicit conversion from <see cref="System.String"/> to <see cref="MongoDB.MongoSymbol"/>.
/// </summary>
/// <param name="s">The s.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator MongoSymbol(string s){
return new MongoSymbol(s);
}
/// <summary>
/// Determines whether the specified s is empty.
/// </summary>
/// <param name="s">The s.</param>
/// <returns>
/// <c>true</c> if the specified s is empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsEmpty(MongoSymbol s){
return s == Empty;
}
/// <summary>
/// Symbols the equal.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns></returns>
private static bool SymbolEqual(string a, string b){
return a == b;
}
/// <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 (Value != null ? Value.GetHashCode() : 0);
}
/// <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>
/// 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>
void IXmlSerializable.ReadXml(XmlReader reader)
{
if(reader.IsEmptyElement)
return;
Value = string.Intern(reader.ReadString());
}
/// <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>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if(Value != null)
writer.WriteString(Value);
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="DropboxClient.cs" company="Dropbox Inc">
// Copyright (c) Dropbox Inc. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace Dropbox.Api
{
using System;
using System.Threading.Tasks;
using Dropbox.Api.Common;
/// <summary>
/// The client which contains endpoints which perform user-level actions.
/// </summary>
public sealed partial class DropboxClient : DropboxClientBase
{
/// <summary>
/// The request handler.
/// </summary>
private readonly DropboxRequestHandler requestHandler;
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2Token">The oauth2 access token for making client requests.</param>
public DropboxClient(string oauth2Token)
: this(oauth2Token, null, null, null, new DropboxClientConfig())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2RefreshToken">The oauth2 access token for making client requests.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
public DropboxClient(string oauth2RefreshToken, string appKey)
: this(null, oauth2RefreshToken, appKey, null, new DropboxClientConfig())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2RefreshToken">The oauth2 access token for making client requests.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="config">The <see cref="DropboxClientConfig"/>.</param>
public DropboxClient(string oauth2RefreshToken, string appKey, DropboxClientConfig config)
: this(null, oauth2RefreshToken, appKey, null, config)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="appSecret">The app secret to be used for refreshing tokens.</param>
/// <param name="config">The <see cref="DropboxClientConfig"/>.</param>
public DropboxClient(string oauth2RefreshToken, string appKey, string appSecret, DropboxClientConfig config)
: this(null, oauth2RefreshToken, appKey, appSecret, config)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="appSecret">The app secret to be used for refreshing tokens.</param>
public DropboxClient(string oauth2RefreshToken, string appKey, string appSecret)
: this(null, oauth2RefreshToken, appKey, appSecret, new DropboxClientConfig())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="config">The <see cref="DropboxClientConfig"/>.</param>
public DropboxClient(string oauth2AccessToken, DropboxClientConfig config)
: this(oauth2AccessToken, null, null, null, config)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
public DropboxClient(string oauth2AccessToken, DateTime oauth2AccessTokenExpiresAt)
: this(oauth2AccessToken, null, oauth2AccessTokenExpiresAt, null, null, new DropboxClientConfig())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
/// <param name="config">The <see cref="DropboxClientConfig"/>.</param>
public DropboxClient(string oauth2AccessToken, DateTime oauth2AccessTokenExpiresAt, DropboxClientConfig config)
: this(oauth2AccessToken, null, oauth2AccessTokenExpiresAt, null, null, config)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="appSecret">The app secret to be used for refreshing tokens.</param>
public DropboxClient(string oauth2AccessToken, string oauth2RefreshToken, DateTime oauth2AccessTokenExpiresAt, string appKey, string appSecret)
: this(oauth2AccessToken, oauth2RefreshToken, oauth2AccessTokenExpiresAt, appKey, appSecret, new DropboxClientConfig())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="config">The <see cref="DropboxClientConfig"/>.</param>
public DropboxClient(string oauth2AccessToken, string oauth2RefreshToken, DateTime oauth2AccessTokenExpiresAt, string appKey, DropboxClientConfig config)
: this(new DropboxRequestHandlerOptions(config, oauth2AccessToken, oauth2RefreshToken, oauth2AccessTokenExpiresAt, appKey, null))
{
if (oauth2AccessToken == null && oauth2RefreshToken == null)
{
throw new ArgumentException("Cannot pass in both null access and refresh token");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
public DropboxClient(string oauth2AccessToken, string oauth2RefreshToken, DateTime oauth2AccessTokenExpiresAt, string appKey)
: this(oauth2AccessToken, oauth2RefreshToken, oauth2AccessTokenExpiresAt, appKey, null, new DropboxClientConfig())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="appSecret">The app secret to be used for refreshing tokens.</param>
/// <param name="config">The <see cref="DropboxClientConfig"/>.</param>
public DropboxClient(string oauth2AccessToken, string oauth2RefreshToken, DateTime oauth2AccessTokenExpiresAt, string appKey, string appSecret, DropboxClientConfig config)
: this(new DropboxRequestHandlerOptions(config, oauth2AccessToken, oauth2RefreshToken, oauth2AccessTokenExpiresAt, appKey, appSecret))
{
if (oauth2AccessToken == null && oauth2RefreshToken == null)
{
throw new ArgumentException("Cannot pass in both null access and refresh token");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="appSecret">The app secret to be used for refreshing tokens.</param>
/// <param name="config">The <see cref="DropboxClientConfig"/>.</param>
public DropboxClient(string oauth2AccessToken, string oauth2RefreshToken, string appKey, string appSecret, DropboxClientConfig config)
: this(new DropboxRequestHandlerOptions(config, oauth2AccessToken, oauth2RefreshToken, null, appKey, appSecret))
{
if (oauth2AccessToken == null && oauth2RefreshToken == null)
{
throw new ArgumentException("Cannot pass in both null access and refresh token");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="options">The request handler options.</param>
/// <param name="selectUser">The member id of the selected user. If provided together with
/// a team access token, actions will be performed on this this user's Dropbox.</param>
/// <param name="selectAdmin">The member id of the selected admin. If provided together with
/// a team access token, access is allowed for all team owned contents.</param>
/// <param name="pathRoot">The path root value used as Dropbox-Api-Path-Root header.</param>
internal DropboxClient(
DropboxRequestHandlerOptions options,
string selectUser = null,
string selectAdmin = null,
PathRoot pathRoot = null)
: this(new DropboxRequestHandler(options, selectUser: selectUser, selectAdmin: selectAdmin, pathRoot: pathRoot))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxClient"/> class.
/// </summary>
/// <param name="requestHandler">The request handler.</param>
private DropboxClient(DropboxRequestHandler requestHandler)
: base(requestHandler)
{
this.requestHandler = requestHandler;
}
/// <summary>
/// Set the value for Dropbox-Api-Path-Root header. This allows accessing content outside of user's
/// home namespace. Below is sample code of accessing content inside team space. See
/// <a href="https://www.dropbox.com/developers/reference/namespace-guide">Namespace Guide</a> for details
/// about user space vs team space.
/// <code>
/// // Fetch root namespace info from user's account info.
/// var account = await client.Users.GetCurrentAccountAsync();
///
/// if (!account.RootInfo.IsTeam)
/// {
/// Console.WriteLine("This user doesn't belong to a team with shared space.");
/// }
/// else
/// {
/// try
/// {
/// // Point path root to namespace id of team space.
/// client = client.WithPathRoot(new PathRoot.Root(account.RootInfo.RootNamespaceId));
/// await client.Files.ListFolderAsync(path);
/// }
/// catch (PathRootException ex)
/// {
/// // Handle race condition when user switched team.
/// Console.WriteLine(
/// "The user's root namespace ID has changed to {0}",
/// ex.ErrorResponse.AsInvalidRoot.Value);
/// }
/// }
/// </code>
/// </summary>
/// <param name="pathRoot">The path root object.</param>
/// <returns>A <see cref="DropboxClient"/> instance with Dropbox-Api-Path-Root header set.</returns>
public DropboxClient WithPathRoot(PathRoot pathRoot)
{
if (pathRoot == null)
{
throw new ArgumentNullException("pathRoot");
}
return new DropboxClient(this.requestHandler.WithPathRoot(pathRoot));
}
/// <summary>
/// Refreshes access token regardless of if existing token is expired.
/// </summary>
/// <param name="scopeList">subset of scopes to refresh token with, or null to refresh with all scopes.</param>
/// <returns>true if token is successfully refreshed, false otherwise.</returns>
public Task<bool> RefreshAccessToken(string[] scopeList)
{
return this.requestHandler.RefreshAccessToken(scopeList);
}
}
}
| |
using NUnit.Framework;
namespace Lucene.Net.Codecs.Lucene45
{
/*
* 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 BaseCompressingDocValuesFormatTestCase = Lucene.Net.Index.BaseCompressingDocValuesFormatTestCase;
using TestUtil = Lucene.Net.Util.TestUtil;
/// <summary>
/// Tests Lucene45DocValuesFormat
/// </summary>
public class TestLucene45DocValuesFormat : BaseCompressingDocValuesFormatTestCase
{
private readonly Codec Codec_Renamed = TestUtil.AlwaysDocValuesFormat(new Lucene45DocValuesFormat());
protected override Codec Codec
{
get
{
return Codec_Renamed;
}
}
#region BaseCompressingDocValuesFormatTestCase
// LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct
// context in Visual Studio. This fixes that with the minimum amount of code necessary
// to run them in the correct context without duplicating all of the tests.
[Test]
public override void TestUniqueValuesCompression()
{
base.TestUniqueValuesCompression();
}
[Test]
public override void TestDateCompression()
{
base.TestDateCompression();
}
[Test]
public override void TestSingleBigValueCompression()
{
base.TestSingleBigValueCompression();
}
#endregion
#region BaseDocValuesFormatTestCase
// LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct
// context in Visual Studio. This fixes that with the minimum amount of code necessary
// to run them in the correct context without duplicating all of the tests.
[Test]
public override void TestOneNumber()
{
base.TestOneNumber();
}
[Test]
public override void TestOneFloat()
{
base.TestOneFloat();
}
[Test]
public override void TestTwoNumbers()
{
base.TestTwoNumbers();
}
[Test]
public override void TestTwoBinaryValues()
{
base.TestTwoBinaryValues();
}
[Test]
public override void TestTwoFieldsMixed()
{
base.TestTwoFieldsMixed();
}
[Test]
public override void TestThreeFieldsMixed()
{
base.TestThreeFieldsMixed();
}
[Test]
public override void TestThreeFieldsMixed2()
{
base.TestThreeFieldsMixed2();
}
[Test]
public override void TestTwoDocumentsNumeric()
{
base.TestTwoDocumentsNumeric();
}
[Test]
public override void TestTwoDocumentsMerged()
{
base.TestTwoDocumentsMerged();
}
[Test]
public override void TestBigNumericRange()
{
base.TestBigNumericRange();
}
[Test]
public override void TestBigNumericRange2()
{
base.TestBigNumericRange2();
}
[Test]
public override void TestBytes()
{
base.TestBytes();
}
[Test]
public override void TestBytesTwoDocumentsMerged()
{
base.TestBytesTwoDocumentsMerged();
}
[Test]
public override void TestSortedBytes()
{
base.TestSortedBytes();
}
[Test]
public override void TestSortedBytesTwoDocuments()
{
base.TestSortedBytesTwoDocuments();
}
[Test]
public override void TestSortedBytesThreeDocuments()
{
base.TestSortedBytesThreeDocuments();
}
[Test]
public override void TestSortedBytesTwoDocumentsMerged()
{
base.TestSortedBytesTwoDocumentsMerged();
}
[Test]
public override void TestSortedMergeAwayAllValues()
{
base.TestSortedMergeAwayAllValues();
}
[Test]
public override void TestBytesWithNewline()
{
base.TestBytesWithNewline();
}
[Test]
public override void TestMissingSortedBytes()
{
base.TestMissingSortedBytes();
}
[Test]
public override void TestSortedTermsEnum()
{
base.TestSortedTermsEnum();
}
[Test]
public override void TestEmptySortedBytes()
{
base.TestEmptySortedBytes();
}
[Test]
public override void TestEmptyBytes()
{
base.TestEmptyBytes();
}
[Test]
public override void TestVeryLargeButLegalBytes()
{
base.TestVeryLargeButLegalBytes();
}
[Test]
public override void TestVeryLargeButLegalSortedBytes()
{
base.TestVeryLargeButLegalSortedBytes();
}
[Test]
public override void TestCodecUsesOwnBytes()
{
base.TestCodecUsesOwnBytes();
}
[Test]
public override void TestCodecUsesOwnSortedBytes()
{
base.TestCodecUsesOwnSortedBytes();
}
[Test]
public override void TestCodecUsesOwnBytesEachTime()
{
base.TestCodecUsesOwnBytesEachTime();
}
[Test]
public override void TestCodecUsesOwnSortedBytesEachTime()
{
base.TestCodecUsesOwnSortedBytesEachTime();
}
/*
* Simple test case to show how to use the API
*/
[Test]
public override void TestDocValuesSimple()
{
base.TestDocValuesSimple();
}
[Test]
public override void TestRandomSortedBytes()
{
base.TestRandomSortedBytes();
}
[Test]
public override void TestBooleanNumericsVsStoredFields()
{
base.TestBooleanNumericsVsStoredFields();
}
[Test]
public override void TestByteNumericsVsStoredFields()
{
base.TestByteNumericsVsStoredFields();
}
[Test]
public override void TestByteMissingVsFieldCache()
{
base.TestByteMissingVsFieldCache();
}
[Test]
public override void TestShortNumericsVsStoredFields()
{
base.TestShortNumericsVsStoredFields();
}
[Test]
public override void TestShortMissingVsFieldCache()
{
base.TestShortMissingVsFieldCache();
}
[Test]
public override void TestIntNumericsVsStoredFields()
{
base.TestIntNumericsVsStoredFields();
}
[Test]
public override void TestIntMissingVsFieldCache()
{
base.TestIntMissingVsFieldCache();
}
[Test]
public override void TestLongNumericsVsStoredFields()
{
base.TestLongNumericsVsStoredFields();
}
[Test]
public override void TestLongMissingVsFieldCache()
{
base.TestLongMissingVsFieldCache();
}
[Test]
public override void TestBinaryFixedLengthVsStoredFields()
{
base.TestBinaryFixedLengthVsStoredFields();
}
[Test]
public override void TestBinaryVariableLengthVsStoredFields()
{
base.TestBinaryVariableLengthVsStoredFields();
}
[Test]
public override void TestSortedFixedLengthVsStoredFields()
{
base.TestSortedFixedLengthVsStoredFields();
}
[Test]
public override void TestSortedFixedLengthVsFieldCache()
{
base.TestSortedFixedLengthVsFieldCache();
}
[Test]
public override void TestSortedVariableLengthVsFieldCache()
{
base.TestSortedVariableLengthVsFieldCache();
}
[Test]
public override void TestSortedVariableLengthVsStoredFields()
{
base.TestSortedVariableLengthVsStoredFields();
}
[Test]
public override void TestSortedSetOneValue()
{
base.TestSortedSetOneValue();
}
[Test]
public override void TestSortedSetTwoFields()
{
base.TestSortedSetTwoFields();
}
[Test]
public override void TestSortedSetTwoDocumentsMerged()
{
base.TestSortedSetTwoDocumentsMerged();
}
[Test]
public override void TestSortedSetTwoValues()
{
base.TestSortedSetTwoValues();
}
[Test]
public override void TestSortedSetTwoValuesUnordered()
{
base.TestSortedSetTwoValuesUnordered();
}
[Test]
public override void TestSortedSetThreeValuesTwoDocs()
{
base.TestSortedSetThreeValuesTwoDocs();
}
[Test]
public override void TestSortedSetTwoDocumentsLastMissing()
{
base.TestSortedSetTwoDocumentsLastMissing();
}
[Test]
public override void TestSortedSetTwoDocumentsLastMissingMerge()
{
base.TestSortedSetTwoDocumentsLastMissingMerge();
}
[Test]
public override void TestSortedSetTwoDocumentsFirstMissing()
{
base.TestSortedSetTwoDocumentsFirstMissing();
}
[Test]
public override void TestSortedSetTwoDocumentsFirstMissingMerge()
{
base.TestSortedSetTwoDocumentsFirstMissingMerge();
}
[Test]
public override void TestSortedSetMergeAwayAllValues()
{
base.TestSortedSetMergeAwayAllValues();
}
[Test]
public override void TestSortedSetTermsEnum()
{
base.TestSortedSetTermsEnum();
}
[Test]
public override void TestSortedSetFixedLengthVsStoredFields()
{
base.TestSortedSetFixedLengthVsStoredFields();
}
[Test]
public override void TestSortedSetVariableLengthVsStoredFields()
{
base.TestSortedSetVariableLengthVsStoredFields();
}
[Test]
public override void TestSortedSetFixedLengthSingleValuedVsStoredFields()
{
base.TestSortedSetFixedLengthSingleValuedVsStoredFields();
}
[Test]
public override void TestSortedSetVariableLengthSingleValuedVsStoredFields()
{
base.TestSortedSetVariableLengthSingleValuedVsStoredFields();
}
[Test]
public override void TestSortedSetFixedLengthVsUninvertedField()
{
base.TestSortedSetFixedLengthVsUninvertedField();
}
[Test]
public override void TestSortedSetVariableLengthVsUninvertedField()
{
base.TestSortedSetVariableLengthVsUninvertedField();
}
[Test]
public override void TestGCDCompression()
{
base.TestGCDCompression();
}
[Test]
public override void TestZeros()
{
base.TestZeros();
}
[Test]
public override void TestZeroOrMin()
{
base.TestZeroOrMin();
}
[Test]
public override void TestTwoNumbersOneMissing()
{
base.TestTwoNumbersOneMissing();
}
[Test]
public override void TestTwoNumbersOneMissingWithMerging()
{
base.TestTwoNumbersOneMissingWithMerging();
}
[Test]
public override void TestThreeNumbersOneMissingWithMerging()
{
base.TestThreeNumbersOneMissingWithMerging();
}
[Test]
public override void TestTwoBytesOneMissing()
{
base.TestTwoBytesOneMissing();
}
[Test]
public override void TestTwoBytesOneMissingWithMerging()
{
base.TestTwoBytesOneMissingWithMerging();
}
[Test]
public override void TestThreeBytesOneMissingWithMerging()
{
base.TestThreeBytesOneMissingWithMerging();
}
// LUCENE-4853
[Test]
public override void TestHugeBinaryValues()
{
base.TestHugeBinaryValues();
}
// TODO: get this out of here and into the deprecated codecs (4.0, 4.2)
[Test]
public override void TestHugeBinaryValueLimit()
{
base.TestHugeBinaryValueLimit();
}
/// <summary>
/// Tests dv against stored fields with threads (binary/numeric/sorted, no missing)
/// </summary>
[Test]
public override void TestThreads()
{
base.TestThreads();
}
/// <summary>
/// Tests dv against stored fields with threads (all types + missing)
/// </summary>
[Test]
public override void TestThreads2()
{
base.TestThreads2();
}
// LUCENE-5218
[Test]
public override void TestEmptyBinaryValueOnPageSizes()
{
base.TestEmptyBinaryValueOnPageSizes();
}
#endregion
#region BaseIndexFileFormatTestCase
// LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct
// context in Visual Studio. This fixes that with the minimum amount of code necessary
// to run them in the correct context without duplicating all of the tests.
[Test]
public override void TestMergeStability()
{
base.TestMergeStability();
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Brokerages;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
///
/// QCU: Opening Breakout Algorithm
///
/// In this algorithm we attempt to provide a working algorithm that
/// addresses many of the primary algorithm concerns. These concerns
/// are:
///
/// 1. Signal Generation.
/// This algorithm aims to generate signals for an opening
/// breakout move before 10am. Signals are generated by
/// producing the opening five minute bar, and then trading
/// in the direction of the breakout from that bar.
///
/// 2. Position Sizing.
/// Positions are sized using recently the average true range.
/// The higher the recently movement, the smaller position.
/// This helps to reduce the risk of losing a lot on a single
/// transaction.
///
/// 3. Active Stop Loss.
/// Stop losses are maintained at a fixed global percentage to
/// limit maximum losses per day, while also a trailing stop
/// loss is implemented using the parabolic stop and reverse
/// in order to gauge exit points.
///
/// </summary>
/// <meta name="tag" content="strategy example" />
/// <meta name="tag" content="indicators" />
public class OpeningBreakoutAlgorithm : QCAlgorithm
{
#pragma warning disable 00162 // File contains unreachable code when EnableOrderUpdateLogging is false
// the equity symbol we're trading
private const string symbol = "SPY";
// plotting and logging control
private const bool EnablePlotting = true;
private const bool EnableOrderUpdateLogging = false;
private const int PricePlotFrequencyInSeconds = 15;
// risk control
private const decimal MaximumLeverage = 4;
private const decimal GlobalStopLossPercent = 0.001m;
private const decimal PercentProfitStartPsarTrailingStop = 0.0003m;
private const decimal MaximumPorfolioRiskPercentPerPosition = .0025m;
// entrance criteria
private const int OpeningSpanInMinutes = 3;
private const decimal BreakoutThresholdPercent = 0.00005m;
private const decimal AtrVolatilityThresholdPercent = 0.00275m;
private const decimal StdVolatilityThresholdPercent = 0.005m;
// this is the security we're trading
public Security Security;
// define our indicators used for trading decisions
public AverageTrueRange ATR14;
public StandardDeviation STD14;
public AverageDirectionalIndex ADX14;
public ParabolicStopAndReverse PSARMin;
// smoothed values
public ExponentialMovingAverage SmoothedSTD14;
public ExponentialMovingAverage SmoothedATR14;
// working variable to control our algorithm
// this flag is used to run some code only once after the algorithm is warmed up
private bool FinishedWarmup;
// this is used to record the last time we closed a position
private DateTime LastExitTime;
// this is our opening n minute bar
private TradeBar OpeningBarRange;
// this is the ticket from our market order (entrance)
private OrderTicket MarketTicket;
// this is the ticket from our stop loss order (exit)
private OrderTicket StopLossTicket;
// this flag is used to indicate we've switched from a global, non changing
// stop loss to a dynamic trailing stop using the PSAR
private bool EnablePsarTrailingStop;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
// initialize algorithm level parameters
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
//SetStartDate(2014, 01, 01);
//SetEndDate(2014, 06, 01);
SetCash(100000);
// leverage tradier $1 traders
SetBrokerageModel(BrokerageName.TradierBrokerage);
// request high resolution equity data
AddSecurity(SecurityType.Equity, symbol, Resolution.Second);
// save off our security so we can reference it quickly later
Security = Securities[symbol];
// Set our max leverage
Security.SetLeverage(MaximumLeverage);
// define our longer term indicators
ADX14 = ADX(symbol, 28, Resolution.Hour);
STD14 = STD(symbol, 14, Resolution.Daily);
ATR14 = ATR(symbol, 14, resolution: Resolution.Daily);
PSARMin = new ParabolicStopAndReverse(symbol, afStart: 0.0001m, afIncrement: 0.0001m);
// smooth our ATR over a week, we'll use this to determine if recent volatilty warrants entrance
var oneWeekInMarketHours = (int)(5*6.5);
SmoothedATR14 = new ExponentialMovingAverage("Smoothed_" + ATR14.Name, oneWeekInMarketHours).Of(ATR14);
// smooth our STD over a week as well
SmoothedSTD14 = new ExponentialMovingAverage("Smoothed_"+STD14.Name, oneWeekInMarketHours).Of(STD14);
// initialize our charts
var chart = new Chart(symbol);
chart.AddSeries(new Series(ADX14.Name, SeriesType.Line, 0));
chart.AddSeries(new Series("Enter", SeriesType.Scatter, 0));
chart.AddSeries(new Series("Exit", SeriesType.Scatter, 0));
chart.AddSeries(new Series(PSARMin.Name, SeriesType.Scatter, 0));
AddChart(chart);
var history = History(symbol, 20, Resolution.Daily);
foreach (var bar in history)
{
ADX14.Update(bar);
ATR14.Update(bar);
STD14.Update(bar.EndTime, bar.Close);
}
// schedule an event to run every day at five minutes after our symbol's market open
Schedule.Event("MarketOpenSpan")
.EveryDay(symbol)
.AfterMarketOpen(symbol, minutesAfterOpen: OpeningSpanInMinutes)
.Run(MarketOpeningSpanHandler);
Schedule.Event("MarketOpen")
.EveryDay(symbol)
.AfterMarketOpen(symbol, minutesAfterOpen: -1)
.Run(() => PSARMin.Reset());
}
/// <summary>
/// This function is scheduled to be run every day at the specified number of minutes after market open
/// </summary>
public void MarketOpeningSpanHandler()
{
// request the last n minutes of data in minute bars, we're going to
// define the opening rang
var history = History(symbol, OpeningSpanInMinutes, Resolution.Minute);
// this is our bar size
var openingSpan = TimeSpan.FromMinutes(OpeningSpanInMinutes);
// we only care about the high and low here
OpeningBarRange = new TradeBar
{
// time values
Time = Time - openingSpan,
EndTime = Time,
Period = openingSpan,
// high and low
High = Security.Close,
Low = Security.Close
};
// aggregate the high/low for the opening range
foreach (var tradeBar in history)
{
OpeningBarRange.Low = Math.Min(OpeningBarRange.Low, tradeBar.Low);
OpeningBarRange.High = Math.Max(OpeningBarRange.High, tradeBar.High);
}
// widen the bar when looking for breakouts
OpeningBarRange.Low *= 1 - BreakoutThresholdPercent;
OpeningBarRange.High *= 1 + BreakoutThresholdPercent;
Log("---------" + Time.Date + "---------");
Log("OpeningBarRange: Low: " + OpeningBarRange.Low.SmartRounding() + " High: " + OpeningBarRange.High.SmartRounding());
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
// we don't need to run any of this during our warmup phase
if (IsWarmingUp) return;
// when we're done warming up, register our indicators to start plotting
if (!IsWarmingUp && !FinishedWarmup)
{
// this is a run once flag for when we're finished warmup
FinishedWarmup = true;
// plot our hourly indicators automatically, wait for them to ready
PlotIndicator("ADX", ADX14);
PlotIndicator("ADX", ADX14.NegativeDirectionalIndex, ADX14.PositiveDirectionalIndex);
PlotIndicator("ATR", true, ATR14);
PlotIndicator("STD", true, STD14);
PlotIndicator("ATR", true, SmoothedATR14);
}
// update our PSAR
PSARMin.Update((TradeBar) Security.GetLastData());
// plot price until an hour after we close so we can see our execution skillz
if (ShouldPlot)
{
// we can plot price more often if we want
Plot(symbol, "Price", Security.Close);
// only plot psar on the minute
if (PSARMin.IsReady)
{
Plot(symbol, PSARMin);
}
}
// first wait for our opening range bar to be set to today
if (OpeningBarRange == null || OpeningBarRange.EndTime.Date != Time.Date || OpeningBarRange.EndTime == Time) return;
// we only trade max once per day, so if we've already exited the stop loss, bail
if (StopLossTicket != null && StopLossTicket.Status == OrderStatus.Filled)
{
// null these out to signal that we're done trading for the day
OpeningBarRange = null;
StopLossTicket = null;
return;
}
// now that we have our opening bar, test to see if we're already in a position
if (!Security.Invested)
{
ScanForEntrance();
}
else
{
// if we haven't exited yet then manage our stop loss, this controls our exit point
if (Security.Invested)
{
ManageStopLoss();
}
else if (StopLossTicket != null && StopLossTicket.Status.IsOpen())
{
StopLossTicket.Cancel();
}
}
}
/// <summary>
/// Scans for a breakout from the opening range bar
/// </summary>
private void ScanForEntrance()
{
// scan for entrances, we only want to do this before 10am
if (Time.TimeOfDay.Hours >= 10) return;
// expect capture 10% of the daily range
var expectedCaptureRange = 0.1m*ATR14;
var allowedDollarLoss = MaximumPorfolioRiskPercentPerPosition * Portfolio.TotalPortfolioValue;
var shares = (int) (allowedDollarLoss/expectedCaptureRange);
// determine a position size based on an acceptable loss in proporton to our total portfolio value
//var shares = (int) (MaximumLeverage*MaximumPorfolioRiskPercentPerPosition*Portfolio.TotalPortfolioValue/(0.4m*ATR14));
// max out at a little below our stated max, prevents margin calls and such
var maxShare = (int) CalculateOrderQuantity(symbol, MaximumLeverage);
shares = Math.Min(shares, maxShare);
// min out at 1x leverage
//var minShare = CalculateOrderQuantity(symbol, MaximumLeverage/2m);
//shares = Math.Max(shares, minShare);
// we're looking for a breakout of the opening range bar in the direction of the medium term trend
if (ShouldEnterLong)
{
// breakout to the upside, go long (fills synchronously)
MarketTicket = MarketOrder(symbol, shares);
Log("Enter long @ " + MarketTicket.AverageFillPrice.SmartRounding() + " Shares: " + shares);
Plot(symbol, "Enter", MarketTicket.AverageFillPrice);
// we'll start with a global, non-trailing stop loss
EnablePsarTrailingStop = false;
// submit stop loss order for max loss on the trade
var stopPrice = Security.Low*(1 - GlobalStopLossPercent);
StopLossTicket = StopMarketOrder(symbol, -shares, stopPrice);
if (EnableOrderUpdateLogging)
{
Log("Submitted stop loss @ " + stopPrice.SmartRounding());
}
}
else if (ShouldEnterShort)
{
// breakout to the downside, go short
MarketTicket = MarketOrder(symbol, - -shares);
Log("Enter short @ " + MarketTicket.AverageFillPrice.SmartRounding());
Plot(symbol, "Enter", MarketTicket.AverageFillPrice);
// we'll start with a global, non-trailing stop loss
EnablePsarTrailingStop = false;
// submit stop loss order for max loss on the trade
var stopPrice = Security.High*(1 + GlobalStopLossPercent);
StopLossTicket = StopMarketOrder(symbol, -shares, stopPrice);
if (EnableOrderUpdateLogging)
{
Log("Submitted stop loss @ " + stopPrice.SmartRounding() + " Shares: " + shares);
}
}
}
/// <summary>
/// Manages our stop loss ticket
/// </summary>
private void ManageStopLoss()
{
// if we've already exited then no need to do more
if (StopLossTicket == null || StopLossTicket.Status == OrderStatus.Filled) return;
// only do this once per minute
//if (Time.RoundDown(TimeSpan.FromMinutes(1)) != Time) return;
// get the current stop price
var stopPrice = StopLossTicket.Get(OrderField.StopPrice);
// check for enabling the psar trailing stop
if (ShouldEnablePsarTrailingStop(stopPrice))
{
EnablePsarTrailingStop = true;
Log("Enabled PSAR trailing stop @ ProfitPercent: " + Security.Holdings.UnrealizedProfitPercent.SmartRounding());
}
// we've trigger the psar trailing stop, so start updating our stop loss tick
if (EnablePsarTrailingStop && PSARMin.IsReady)
{
StopLossTicket.Update(new UpdateOrderFields {StopPrice = PSARMin});
Log("Submitted stop loss @ " + PSARMin.Current.Value.SmartRounding());
}
}
/// <summary>
/// This event handler is fired for each and every order event the algorithm
/// receives. We'll perform some logging and house keeping here
/// </summary>
public override void OnOrderEvent(OrderEvent orderEvent)
{
// print debug messages for all order events
if (LiveMode || orderEvent.Status.IsFill() || EnableOrderUpdateLogging)
{
LiveDebug("Filled: " + orderEvent.FillQuantity + " Price: " + orderEvent.FillPrice);
}
// if this is a fill and we now don't own any stock, that means we've closed for the day
if (!Security.Invested && orderEvent.Status == OrderStatus.Filled)
{
// reset values for tomorrow
LastExitTime = Time;
var ticket = Transactions.GetOrderTickets(x => x.OrderId == orderEvent.OrderId).Single();
Plot(symbol, "Exit", ticket.AverageFillPrice);
}
}
/// <summary>
/// If we're still invested by the end of the day, liquidate
/// </summary>
public override void OnEndOfDay(Symbol symbol)
{
if (symbol == Security.Symbol && Security.Invested)
{
Liquidate();
}
}
/// <summary>
/// Determines whether or not we should plot. This is used
/// to provide enough plot points but not too many, we don't
/// need to plot every second in backtests to get an idea of
/// how good or bad our algorithm is performing
/// </summary>
public bool ShouldPlot
{
get
{
// always in live
if (LiveMode) return true;
// set in top to override plotting during long backtests
if (!EnablePlotting) return false;
// every 30 seconds in backtest
if (Time.RoundDown(TimeSpan.FromSeconds(PricePlotFrequencyInSeconds)) != Time) return false;
// always if we're invested
if (Security.Invested) return true;
// always if it's before noon
if (Time.TimeOfDay.Hours < 10.25) return true;
// for an hour after our exit
if (Time - LastExitTime < TimeSpan.FromMinutes(30)) return true;
return false;
}
}
/// <summary>
/// In live mode it's nice to push messages to the debug window
/// as well as the log, this allows easy real time inspection of
/// how the algorithm is performing
/// </summary>
public void LiveDebug(object msg)
{
if (msg == null) return;
if (LiveMode)
{
Debug(msg.ToString());
Log(msg.ToString());
}
else
{
Log(msg.ToString());
}
}
/// <summary>
/// Determines whether or not we should end a long position
/// </summary>
private bool ShouldEnterLong
{
// check to go in the same direction of longer term trend and opening break out
get
{
return IsUptrend
&& HasEnoughRecentVolatility
&& Security.Close > OpeningBarRange.High;
}
}
/// <summary>
/// Determines whether or not we're currently in a medium term up trend
/// </summary>
private bool IsUptrend
{
get { return ADX14 > 20 && ADX14.PositiveDirectionalIndex > ADX14.NegativeDirectionalIndex; }
}
/// <summary>
/// Determines whether or not we should enter a short position
/// </summary>
private bool ShouldEnterShort
{
// check to go in the same direction of longer term trend and opening break out
get
{
return IsDowntrend
&& HasEnoughRecentVolatility
&& Security.Close < OpeningBarRange.Low;
}
}
/// <summary>
/// Determines whether or not we're currently in a medium term down trend
/// </summary>
private bool IsDowntrend
{
get { return ADX14 > 20 && ADX14.NegativeDirectionalIndex > ADX14.PositiveDirectionalIndex; }
}
/// <summary>
/// Determines whether or not there's been enough recent volatility for
/// this strategy to work
/// </summary>
private bool HasEnoughRecentVolatility
{
get
{
return SmoothedATR14 > Security.Close*AtrVolatilityThresholdPercent
|| SmoothedSTD14 > Security.Close*StdVolatilityThresholdPercent;
}
}
/// <summary>
/// Determines whether or not we should enable the psar trailing stop
/// </summary>
/// <param name="stopPrice">current stop price of our stop loss tick</param>
private bool ShouldEnablePsarTrailingStop(decimal stopPrice)
{
// no need to enable if it's already enabled
return !EnablePsarTrailingStop
// once we're up a certain percentage, we'll use PSAR to control our stop
&& Security.Holdings.UnrealizedProfitPercent > PercentProfitStartPsarTrailingStop
// make sure the PSAR is on the right side
&& PsarIsOnRightSideOfPrice
// make sure the PSAR is more profitable than our global loss
&& IsPsarMoreProfitableThanStop(stopPrice);
}
/// <summary>
/// Determines whether or not the PSAR is on the right side of price depending on our long/short
/// </summary>
private bool PsarIsOnRightSideOfPrice
{
get
{
return (Security.Holdings.IsLong && PSARMin < Security.Close)
|| (Security.Holdings.IsShort && PSARMin > Security.Close);
}
}
/// <summary>
/// Determines whether or not the PSAR stop price is better than the specified stop price
/// </summary>
private bool IsPsarMoreProfitableThanStop(decimal stopPrice)
{
return (Security.Holdings.IsLong && PSARMin > stopPrice)
|| (Security.Holdings.IsShort && PSARMin < stopPrice);
}
#pragma warning restore 00162
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using EPiServer;
using EPiServer.Configuration;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Filters;
using EPiServer.Logging;
using EPiServer.ServiceLocation;
using EPiServer.Web;
namespace TestSite.Business.ContentProviders
{
/// <summary>
/// Used to clone a part of the page tree
/// </summary>
/// <remarks>The current implementation only supports cloning of <see cref="PageData"/> content</remarks>
/// <code>
/// // Example of programmatically registering a cloned content provider
///
/// var rootPageOfContentToClone = new PageReference(10);
///
/// var pageWhereClonedContentShouldAppear = new PageReference(20);
///
/// var provider = new ClonedContentProvider(rootPageOfContentToClone, pageWhereClonedContentShouldAppear);
///
/// var providerManager = ServiceLocator.Current.GetInstance<IContentProviderManager>();
///
/// providerManager.ProviderMap.AddProvider(provider);
/// </code>
public class ClonedContentProvider : ContentProvider, IPageCriteriaQueryService
{
private static readonly ILogger Logger = LogManager.GetLogger();
private readonly NameValueCollection _parameters = new NameValueCollection(1);
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot) : this(cloneRoot, entryRoot, null) { }
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot, CategoryList categoryFilter)
{
if (cloneRoot.CompareToIgnoreWorkID(entryRoot))
{
throw new NotSupportedException("Entry root and clone root cannot be set to the same content reference");
}
if (ServiceLocator.Current.GetInstance<IContentLoader>().GetChildren<IContent>(entryRoot).Any())
{
throw new NotSupportedException("Unable to create ClonedContentProvider, the EntryRoot property must point to leaf content (without children)");
}
CloneRoot = cloneRoot;
EntryRoot = entryRoot;
Category = categoryFilter;
// Set the entry point parameter
Parameters.Add(ContentProviderElement.EntryPointString, EntryRoot.ID.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Clones a page to make it appear to come from where the content provider is attached
/// </summary>
private PageData ClonePage(PageData originalPage)
{
if (originalPage == null)
{
throw new ArgumentNullException("originalPage", "No page to clone specified");
}
Logger.Debug("Cloning page {0}...", originalPage.PageLink);
var clone = originalPage.CreateWritableClone();
// If original page was under the clone root, we make it appear to be under the entry root instead
if (originalPage.ParentLink.CompareToIgnoreWorkID(CloneRoot))
{
clone.ParentLink = EntryRoot;
}
// All pages but the entry root should appear to come from this content provider
if (!clone.PageLink.CompareToIgnoreWorkID(EntryRoot))
{
clone.ContentLink.ProviderName = ProviderKey;
}
// Unless the parent is the entry root, it should appear to come from this content provider
if (!clone.ParentLink.CompareToIgnoreWorkID(EntryRoot))
{
var parentLinkClone = clone.ParentLink.CreateWritableClone();
parentLinkClone.ProviderName = ProviderKey;
clone.ParentLink = parentLinkClone;
}
// This is integral to map the cloned page to this content provider
clone.LinkURL = ConstructContentUri(originalPage.PageTypeID, clone.ContentLink, clone.ContentGuid).ToString();
return clone;
}
/// <summary>
/// Filters out content references to content that does not match current category filters, if any
/// </summary>
/// <param name="contentReferences"></param>
/// <returns></returns>
private IList<T> FilterByCategory<T>(IEnumerable<T> contentReferences)
{
if (Category == null || !Category.Any())
{
return contentReferences.ToList();
}
// Filter by category if a category filter has been set
var filteredChildren = new List<T>();
foreach (var contentReference in contentReferences)
{
ICategorizable content = null;
if (contentReference is ContentReference)
{
content = (contentReference as ContentReference).Get<IContent>() as ICategorizable;
} else if (typeof(T) == typeof(GetChildrenReferenceResult))
{
content = (contentReference as GetChildrenReferenceResult).ContentLink.Get<IContent>() as ICategorizable;
}
if (content != null)
{
var atLeastOneMatchingCategory = content.Category.Any(c => Category.Contains(c));
if (atLeastOneMatchingCategory)
{
filteredChildren.Add(contentReference);
}
}
else // Non-categorizable content will also be included
{
filteredChildren.Add(contentReference);
}
}
return filteredChildren;
}
protected override IContent LoadContent(ContentReference contentLink, ILanguageSelector languageSelector)
{
if (ContentReference.IsNullOrEmpty(contentLink) || contentLink.ID == 0)
{
throw new ArgumentNullException("contentLink");
}
if (contentLink.WorkID > 0)
{
return ContentStore.LoadVersion(contentLink, -1);
}
var languageBranchRepository = ServiceLocator.Current.GetInstance<ILanguageBranchRepository>();
LanguageBranch langBr = null;
if (languageSelector.Language != null)
{
langBr = languageBranchRepository.Load(languageSelector.Language);
}
if (contentLink.GetPublishedOrLatest)
{
return ContentStore.LoadVersion(contentLink, langBr != null ? langBr.ID : -1);
}
// Get published version of Content
var originalContent = ContentStore.Load(contentLink, langBr != null ? langBr.ID : -1);
var page = originalContent as PageData;
if (page == null)
{
throw new NotSupportedException("Only cloning of pages is supported");
}
return ClonePage(page);
}
protected override ContentResolveResult ResolveContent(ContentReference contentLink)
{
var contentData = ContentCoreDataLoader.Service.Load(contentLink.ID);
// All pages but the entry root should appear to come from this content provider
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentData.ContentReference.ProviderName = ProviderKey;
}
var result = CreateContentResolveResult(contentData);
if (!result.ContentLink.CompareToIgnoreWorkID(EntryRoot))
{
result.ContentLink.ProviderName = ProviderKey;
}
return result;
}
protected override Uri ConstructContentUri(int contentTypeId, ContentReference contentLink, Guid contentGuid)
{
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentLink.ProviderName = ProviderKey;
}
return base.ConstructContentUri(contentTypeId, contentLink, contentGuid);
}
protected override IList<GetChildrenReferenceResult> LoadChildrenReferencesAndTypes(ContentReference contentLink, string languageID, out bool languageSpecific)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
FilterSortOrder sortOrder;
var children = ContentStore.LoadChildrenReferencesAndTypes(contentLink.ID, languageID, out sortOrder);
languageSpecific = sortOrder == FilterSortOrder.Alphabetical;
foreach (var contentReference in children.Where(contentReference => !contentReference.ContentLink.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ContentLink.ProviderName = ProviderKey;
}
return FilterByCategory <GetChildrenReferenceResult>(children);
}
protected override IEnumerable<IContent> LoadContents(IList<ContentReference> contentReferences, ILanguageSelector selector)
{
return contentReferences
.Select(contentReference => ClonePage(ContentLoader.Get<PageData>(contentReference.ToReferenceWithoutVersion())))
.Cast<IContent>()
.ToList();
}
protected override void SetCacheSettings(IContent content, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(content.ContentLink.ID)));
}
protected override void SetCacheSettings(ContentReference contentReference, IEnumerable<GetChildrenReferenceResult> children, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(contentReference.ID)));
foreach (var child in children)
{
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(child.ContentLink.ID)));
}
}
public override IList<ContentReference> GetDescendentReferences(ContentReference contentLink)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
var descendents = ContentStore.ListAll(contentLink);
foreach (var contentReference in descendents.Where(contentReference => !contentReference.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ProviderName = ProviderKey;
}
return FilterByCategory<ContentReference>(descendents);
}
public PageDataCollection FindAllPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindAllPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
public PageDataCollection FindPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
/// <summary>
/// Gets the content store used to get original content
/// </summary>
protected virtual ContentStore ContentStore
{
get { return ServiceLocator.Current.GetInstance<ContentStore>(); }
}
/// <summary>
/// Gets the content loader used to get content
/// </summary>
protected virtual IContentLoader ContentLoader
{
get { return ServiceLocator.Current.GetInstance<IContentLoader>(); }
}
/// <summary>
/// Gets the service used to query for pages using criterias
/// </summary>
protected virtual IPageCriteriaQueryService PageQueryService
{
get { return ServiceLocator.Current.GetInstance<IPageCriteriaQueryService>(); }
}
/// <summary>
/// Content that should be cloned at the entry point
/// </summary>
public PageReference CloneRoot { get; protected set; }
/// <summary>
/// Gets the page where the cloned content will appear
/// </summary>
public PageReference EntryRoot { get; protected set; }
/// <summary>
/// Gets the category filters used for this content provider
/// </summary>
/// <remarks>If set, pages not matching at least one of these categories will be excluded from this content provider</remarks>
public CategoryList Category { get; protected set; }
/// <summary>
/// Gets a unique key for this content provider instance
/// </summary>
public override string ProviderKey
{
get
{
return string.Format("ClonedContent-{0}-{1}", CloneRoot.ID, EntryRoot.ID);
}
}
/// <summary>
/// Gets capabilities indicating no content editing can be performed through this provider
/// </summary>
public override ContentProviderCapabilities ProviderCapabilities { get { return ContentProviderCapabilities.Search; } }
/// <summary>
/// Gets configuration parameters for this content provider instance
/// </summary>
public override NameValueCollection Parameters { get { return _parameters; } }
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2018 Helix Toolkit contributors
*/
using System;
using System.Collections.Generic;
using System.IO;
using SharpDX.DXGI;
using SharpDX.Direct3D11;
using SharpDX.IO;
using DeviceChild = SharpDX.Direct3D11.DeviceChild;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Base class for texture resources.
/// </summary>
public abstract class Texture : GraphicsResource, IComparable<Texture>
{
private long textureId;
/// <summary>
/// Common description for this texture.
/// </summary>
public readonly TextureDescription Description;
/// <summary>
/// Gets a boolean indicating whether this <see cref="Texture"/> is a using a block compress format (BC1, BC2, BC3, BC4, BC5, BC6H, BC7).
/// </summary>
public readonly bool IsBlockCompressed;
/// <summary>
/// The width stride in bytes (number of bytes per row).
/// </summary>
internal readonly int RowStride;
/// <summary>
/// The depth stride in bytes (number of bytes per depth slice).
/// </summary>
internal readonly int DepthStride;
/// <summary>
///
/// </summary>
/// <param name="device"></param>
/// <param name="description"></param>
protected Texture(Direct3D11.Device device, TextureDescription description) : base(device)
{
Description = description;
IsBlockCompressed = FormatHelper.IsCompressed(description.Format);
RowStride = this.Description.Width * ((PixelFormat)this.Description.Format).SizeInBytes;
DepthStride = RowStride * this.Description.Height;
}
/// <summary>
/// <dd> <p>Texture width (in texels). The range is from 1 to <see cref="SharpDX.Direct3D11.Resource.MaximumTexture1DSize"/> (16384). However, the range is actually constrained by the feature level at which you create the rendering device. For more information about restrictions, see Remarks.</p> </dd>
/// </summary>
/// <remarks>
/// This field is valid for all textures: <see cref="Texture1D"/>, <see cref="Texture2D"/>, <see cref="Texture3D"/> and <see cref="TextureCube"/>.
/// </remarks>
public int Width
{
get
{
return Description.Width;
}
}
/// <summary>
/// <dd> <p>Texture height (in texels). The range is from 1 to <see cref="SharpDX.Direct3D11.Resource.MaximumTexture3DSize"/> (2048). However, the range is actually constrained by the feature level at which you create the rendering device. For more information about restrictions, see Remarks.</p> </dd>
/// </summary>
/// <remarks>
/// This field is only valid for <see cref="Texture2D"/>, <see cref="Texture3D"/> and <see cref="TextureCube"/>.
/// </remarks>
public int Height
{
get
{
return Description.Height;
}
}
/// <summary>
/// <dd> <p>Texture depth (in texels). The range is from 1 to <see cref="SharpDX.Direct3D11.Resource.MaximumTexture3DSize"/> (2048). However, the range is actually constrained by the feature level at which you create the rendering device. For more information about restrictions, see Remarks.</p> </dd>
/// </summary>
/// <remarks>
/// This field is only valid for <see cref="Texture3D"/>.
/// </remarks>
public int Depth
{
get
{
return Description.Depth;
}
}
/// <summary>
/// Gets the texture format.
/// </summary>
/// <value>The texture format.</value>
public PixelFormat Format
{
get
{
return Description.Format;
}
}
/// <summary>
///
/// </summary>
/// <param name="resource"></param>
protected override void Initialize(DeviceChild resource)
{
// Be sure that we are storing only the main device (which contains the immediate context).
base.Initialize(resource);
// Gets a Texture ID
textureId = resource.NativePointer.ToInt64();
}
/// <summary>
/// Calculates the number of miplevels for a Texture 1D.
/// </summary>
/// <param name="width">The width of the texture.</param>
/// <param name="mipLevels">A <see cref="MipMapCount"/>, set to true to calculates all mipmaps, to false to calculate only 1 miplevel, or > 1 to calculate a specific amount of levels.</param>
/// <returns>The number of miplevels.</returns>
public static int CalculateMipLevels(int width, MipMapCount mipLevels)
{
if (mipLevels > 1)
{
var maxMips = CountMips(width);
if (mipLevels > maxMips)
throw new InvalidOperationException(String.Format("MipLevels must be <= {0}", maxMips));
}
else if (mipLevels == 0)
{
mipLevels = CountMips(width);
}
else
{
mipLevels = 1;
}
return mipLevels;
}
/// <summary>
/// Calculates the number of miplevels for a Texture 2D.
/// </summary>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="mipLevels">A <see cref="MipMapCount"/>, set to true to calculates all mipmaps, to false to calculate only 1 miplevel, or > 1 to calculate a specific amount of levels.</param>
/// <returns>The number of miplevels.</returns>
public static int CalculateMipLevels(int width, int height, MipMapCount mipLevels)
{
if (mipLevels > 1)
{
var maxMips = CountMips(width, height);
if (mipLevels > maxMips)
throw new InvalidOperationException(String.Format("MipLevels must be <= {0}", maxMips));
}
else if (mipLevels == 0)
{
mipLevels = CountMips(width, height);
}
else
{
mipLevels = 1;
}
return mipLevels;
}
/// <summary>
/// Calculates the number of miplevels for a Texture 2D.
/// </summary>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
/// <param name="mipLevels">A <see cref="MipMapCount"/>, set to true to calculates all mipmaps, to false to calculate only 1 miplevel, or > 1 to calculate a specific amount of levels.</param>
/// <returns>The number of miplevels.</returns>
public static int CalculateMipLevels(int width, int height, int depth, MipMapCount mipLevels)
{
if (mipLevels > 1)
{
if (!IsPow2(width) || !IsPow2(height) || !IsPow2(depth))
throw new InvalidOperationException("Width/Height/Depth must be power of 2");
var maxMips = CountMips(width, height, depth);
if (mipLevels > maxMips)
throw new InvalidOperationException(String.Format("MipLevels must be <= {0}", maxMips));
}
else if (mipLevels == 0)
{
if (!IsPow2(width) || !IsPow2(height) || !IsPow2(depth))
throw new InvalidOperationException("Width/Height/Depth must be power of 2");
mipLevels = CountMips(width, height, depth);
}
else
{
mipLevels = 1;
}
return mipLevels;
}
/// <summary>
///
/// </summary>
/// <param name="width"></param>
/// <param name="mipLevel"></param>
/// <returns></returns>
public static int CalculateMipSize(int width, int mipLevel)
{
mipLevel = Math.Min(mipLevel, CountMips(width));
width = width >> mipLevel;
return width > 0 ? width : 1;
}
/// <summary>
/// Gets the absolute sub-resource index from the array and mip slice.
/// </summary>
/// <param name="arraySlice">The array slice index.</param>
/// <param name="mipSlice">The mip slice index.</param>
/// <returns>A value equals to arraySlice * Description.MipLevels + mipSlice.</returns>
public int GetSubResourceIndex(int arraySlice, int mipSlice)
{
return arraySlice * Description.MipLevels + mipSlice;
}
/// <summary>
/// Calculates the expected width of a texture using a specified type.
/// </summary>
/// <typeparam name="TData">The type of the T pixel data.</typeparam>
/// <returns>The expected width</returns>
/// <exception cref="System.ArgumentException">If the size is invalid</exception>
public int CalculateWidth<TData>(int mipLevel = 0) where TData : struct
{
var widthOnMip = CalculateMipSize((int)Description.Width, mipLevel);
var rowStride = widthOnMip * ((PixelFormat)Description.Format).SizeInBytes;
var dataStrideInBytes = Utilities.SizeOf<TData>() * widthOnMip;
var width = ((double)rowStride / dataStrideInBytes) * widthOnMip;
if (Math.Abs(width - (int)width) > Double.Epsilon)
throw new ArgumentException("sizeof(TData) / sizeof(Format) * Width is not an integer");
return (int)width;
}
/// <summary>
/// Calculates the number of pixel data this texture is requiring for a particular mip level.
/// </summary>
/// <typeparam name="TData">The type of the T pixel data.</typeparam>
/// <param name="mipLevel">The mip level.</param>
/// <returns>The number of pixel data.</returns>
/// <remarks>This method is used to allocated a texture data buffer to hold pixel data: var textureData = new T[ texture.CalculatePixelCount<T>() ] ;.</remarks>
public int CalculatePixelDataCount<TData>(int mipLevel = 0) where TData : struct
{
return CalculateWidth<TData>(mipLevel) * CalculateMipSize(Description.Height, mipLevel) * CalculateMipSize(Description.Depth, mipLevel);
}
/// <summary>
/// Makes a copy of this texture.
/// </summary>
/// <remarks>
/// This method doesn't copy the content of the texture.
/// </remarks>
/// <returns>
/// A copy of this texture.
/// </returns>
public abstract Texture Clone();
/// <summary>
/// Makes a copy of this texture with type casting.
/// </summary>
/// <remarks>
/// This method doesn't copy the content of the texture.
/// </remarks>
/// <returns>
/// A copy of this texture.
/// </returns>
public T Clone<T>() where T : Texture
{
return (T)this.Clone();
}
/// <summary>
/// Creates a new texture with the specified generic texture description.
/// </summary>
/// <param name="graphicsDevice">The graphics device.</param>
/// <param name="description">The description.</param>
/// <returns>A Texture instance, either a RenderTarget or DepthStencilBuffer or Texture, depending on Binding flags.</returns>
public static Texture New(Direct3D11.Device graphicsDevice, TextureDescription description)
{
if (graphicsDevice == null)
{
throw new ArgumentNullException("graphicsDevice");
}
if ((description.BindFlags & BindFlags.RenderTarget) != 0)
{
throw new NotSupportedException("RenderTarget is not supported.");
}
else if ((description.BindFlags & BindFlags.DepthStencil) != 0)
{
throw new NotSupportedException("DepthStencil is not supported.");
}
else
{
switch (description.Dimension)
{
case TextureDimension.Texture1D:
return Texture1D.New(graphicsDevice, description);
case TextureDimension.Texture2D:
return Texture2D.New(graphicsDevice, description);
case TextureDimension.Texture3D:
return Texture3D.New(graphicsDevice, description);
case TextureDimension.TextureCube:
return TextureCube.New(graphicsDevice, description);
}
}
return null;
}
/// <summary>
/// Loads a texture from a stream.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="stream">The stream to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <returns>A texture</returns>
public static Texture Load(Direct3D11.Device device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
stream.Position = 0;
var image = Image.Load(stream);
if (image == null)
{
stream.Position = 0;
return null;
}
try
{
switch (image.Description.Dimension)
{
case TextureDimension.Texture1D:
return Texture1D.New(device, image, flags, usage);
case TextureDimension.Texture2D:
return Texture2D.New(device, image, flags, usage);
case TextureDimension.Texture3D:
return Texture3D.New(device, image, flags, usage);
case TextureDimension.TextureCube:
return TextureCube.New(device, image, flags, usage);
}
}
finally
{
image.Dispose();
stream.Position = 0;
}
throw new InvalidOperationException("Dimension not supported");
}
/// <summary>
/// Loads a texture from a file.
/// </summary>
/// <param name="device">Specify the device used to load and create a texture from a file.</param>
/// <param name="filePath">The file to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <returns>A texture</returns>
public static Texture Load(Direct3D11.Device device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read))
return Load(device, stream, flags, usage);
}
/// <summary>
/// Calculates the mip map count from a requested level.
/// </summary>
/// <param name="requestedLevel">The requested level.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <returns>The resulting mipmap count (clamp to [1, maxMipMapCount] for this texture)</returns>
internal static int CalculateMipMapCount(MipMapCount requestedLevel, int width, int height = 0, int depth = 0)
{
var size = Math.Max(Math.Max(width, height), depth);
var maxMipMap = 1 + (int)Math.Log(size, 2);
return requestedLevel == 0 ? maxMipMap : Math.Min(requestedLevel, maxMipMap);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="format"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="depth"></param>
/// <param name="textureData"></param>
/// <param name="fixedPointer"></param>
/// <returns></returns>
internal static DataBox GetDataBox<T>(Format format, int width, int height, int depth, T[] textureData, IntPtr fixedPointer) where T : unmanaged
{
// Check that the textureData size is correct
if (textureData == null)
throw new ArgumentNullException("textureData");
int rowPitch;
int slicePitch;
int widthCount;
int heightCount;
Image.ComputePitch(format, width, height, out rowPitch, out slicePitch, out widthCount, out heightCount);
if (Utilities.SizeOf(textureData) != (slicePitch * depth))
throw new ArgumentException("Invalid size for TextureData");
return new DataBox(fixedPointer, rowPitch, slicePitch);
}
internal static TextureDescription CreateTextureDescriptionFromImage(Image image, TextureFlags flags, ResourceUsage usage)
{
var desc = (TextureDescription)image.Description;
desc.BindFlags = BindFlags.ShaderResource;
desc.Usage = usage;
if ((flags & TextureFlags.UnorderedAccess) != 0)
desc.Usage = ResourceUsage.Default;
desc.BindFlags = GetBindFlagsFromTextureFlags(flags);
desc.CpuAccessFlags = GetCpuAccessFlagsFromUsage(usage);
return desc;
}
internal void GetViewSliceBounds(ViewType viewType, ref int arrayOrDepthIndex, ref int mipIndex, out int arrayOrDepthCount, out int mipCount)
{
var arrayOrDepthSize = this.Description.Depth > 1 ? this.Description.Depth : this.Description.ArraySize;
switch (viewType)
{
case ViewType.Full:
arrayOrDepthIndex = 0;
mipIndex = 0;
arrayOrDepthCount = arrayOrDepthSize;
mipCount = this.Description.MipLevels;
break;
case ViewType.Single:
arrayOrDepthCount = 1;
mipCount = 1;
break;
case ViewType.MipBand:
arrayOrDepthCount = arrayOrDepthSize - arrayOrDepthIndex;
mipCount = 1;
break;
case ViewType.ArrayBand:
arrayOrDepthCount = 1;
mipCount = Description.MipLevels - mipIndex;
break;
default:
arrayOrDepthCount = 0;
mipCount = 0;
break;
}
}
internal int GetViewCount()
{
var arrayOrDepthSize = this.Description.Depth > 1 ? this.Description.Depth : this.Description.ArraySize;
return GetViewIndex((ViewType)4, arrayOrDepthSize, this.Description.MipLevels);
}
internal int GetViewIndex(ViewType viewType, int arrayOrDepthIndex, int mipIndex)
{
var arrayOrDepthSize = this.Description.Depth > 1 ? this.Description.Depth : this.Description.ArraySize;
return (((int)viewType) * arrayOrDepthSize + arrayOrDepthIndex) * this.Description.MipLevels + mipIndex;
}
private static bool IsPow2(int x)
{
return ((x != 0) && (x & (x - 1)) == 0);
}
private static int CountMips(int width)
{
var mipLevels = 1;
while (width > 1)
{
++mipLevels;
if (width > 1)
width >>= 1;
}
return mipLevels;
}
private static int CountMips(int width, int height)
{
var mipLevels = 1;
while (height > 1 || width > 1)
{
++mipLevels;
if (height > 1)
height >>= 1;
if (width > 1)
width >>= 1;
}
return mipLevels;
}
private static int CountMips(int width, int height, int depth)
{
var mipLevels = 1;
while (height > 1 || width > 1 || depth > 1)
{
++mipLevels;
if (height > 1)
height >>= 1;
if (width > 1)
width >>= 1;
if (depth > 1)
depth >>= 1;
}
return mipLevels;
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int CompareTo(Texture obj)
{
return textureId.CompareTo(obj.textureId);
}
internal static BindFlags GetBindFlagsFromTextureFlags(TextureFlags flags)
{
var bindFlags = BindFlags.None;
if ((flags & TextureFlags.ShaderResource) != 0)
bindFlags |= BindFlags.ShaderResource;
if ((flags & TextureFlags.UnorderedAccess) != 0)
bindFlags |= BindFlags.UnorderedAccess;
if ((flags & TextureFlags.RenderTarget) != 0)
bindFlags |= BindFlags.RenderTarget;
return bindFlags;
}
internal struct TextureViewKey : IEquatable<TextureViewKey>
{
public TextureViewKey(Format viewFormat, ViewType viewType, int arrayOrDepthSlice, int mipIndex)
{
ViewFormat = viewFormat;
ViewType = viewType;
ArrayOrDepthSlice = arrayOrDepthSlice;
MipIndex = mipIndex;
}
public readonly DXGI.Format ViewFormat;
public readonly ViewType ViewType;
public readonly int ArrayOrDepthSlice;
public readonly int MipIndex;
public bool Equals(TextureViewKey other)
{
return ViewFormat == other.ViewFormat && ViewType == other.ViewType && ArrayOrDepthSlice == other.ArrayOrDepthSlice && MipIndex == other.MipIndex;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is TextureViewKey && Equals((TextureViewKey)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (int)ViewFormat;
hashCode = (hashCode * 397) ^ (int)ViewType;
hashCode = (hashCode * 397) ^ ArrayOrDepthSlice;
hashCode = (hashCode * 397) ^ MipIndex;
return hashCode;
}
}
public static bool operator ==(TextureViewKey left, TextureViewKey right)
{
return left.Equals(right);
}
public static bool operator !=(TextureViewKey left, TextureViewKey right)
{
return !left.Equals(right);
}
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Nancy.Cookies;
/// <summary>
/// Provides strongly-typed access to HTTP request headers.
/// </summary>
public class RequestHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>>
{
private readonly IDictionary<string, IEnumerable<string>> headers;
private readonly ConcurrentDictionary<string, IEnumerable<Tuple<string, decimal>>> cache;
/// <summary>
/// Initializes a new instance of the <see cref="RequestHeaders"/> class.
/// </summary>
/// <param name="headers">The headers.</param>
public RequestHeaders(IDictionary<string, IEnumerable<string>> headers)
{
this.headers = new Dictionary<string, IEnumerable<string>>(headers, StringComparer.OrdinalIgnoreCase);
this.cache = new ConcurrentDictionary<string, IEnumerable<Tuple<string, decimal>>>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Content-types that are acceptable.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<Tuple<string, decimal>> Accept
{
get { return this.GetWeightedValues("Accept"); }
set { this.SetHeaderValues("Accept", value, GetWeightedValuesAsStrings); }
}
/// <summary>
/// Character sets that are acceptable.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<Tuple<string, decimal>> AcceptCharset
{
get { return this.GetWeightedValues("Accept-Charset"); }
set { this.SetHeaderValues("Accept-Charset", value, GetWeightedValuesAsStrings); }
}
/// <summary>
/// Acceptable encodings.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> AcceptEncoding
{
get { return this.GetSplitValues("Accept-Encoding"); }
set { this.SetHeaderValues("Accept-Encoding", value, x => x); }
}
/// <summary>
/// Acceptable languages for response.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<Tuple<string, decimal>> AcceptLanguage
{
get { return this.GetWeightedValues("Accept-Language"); }
set { this.SetHeaderValues("Accept-Language", value, GetWeightedValuesAsStrings); }
}
/// <summary>
/// Authorization header value for request.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Authorization
{
get { return this.GetValue("Authorization", x => x.First(), string.Empty); }
set { this.SetHeaderValues("Authorization", value, x => new[] { x }); }
}
/// <summary>
/// Used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> CacheControl
{
get { return this.GetValue("Cache-Control"); }
set { this.SetHeaderValues("Cache-Control", value, x => x); }
}
/// <summary>
/// Contains name/value pairs of information stored for that URL.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains <see cref="INancyCookie"/> instances if they are available; otherwise it will be empty.</value>
public IEnumerable<INancyCookie> Cookie
{
get { return this.GetValue("Cookie", GetNancyCookies, Enumerable.Empty<INancyCookie>()); }
}
/// <summary>
/// What type of connection the user-agent would prefer.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Connection
{
get { return this.GetValue("Connection", x => x.First(), string.Empty); }
set { this.SetHeaderValues("Connection", value, x => new[] { x }); }
}
/// <summary>
/// The length of the request body in octets (8-bit bytes).
/// </summary>
/// <value>The length of the contents if it is available; otherwise 0.</value>
public long ContentLength
{
get { return this.GetValue("Content-Length", x => Convert.ToInt64(x.First()), 0); }
set { this.SetHeaderValues("Content-Length", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); }
}
/// <summary>
/// The mime type of the body of the request (used with POST and PUT requests).
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see langword="string.Empty"/>.</value>
public string ContentType
{
get { return this.GetValue("Content-Type", x => x.First(), string.Empty); }
set { this.SetHeaderValues("Content-Type", value, x => new[] { x }); }
}
/// <summary>
/// The date and time that the message was sent.
/// </summary>
/// <value>A <see cref="DateTime"/> instance that specifies when the message was sent. If not available then <see langword="null"/> will be returned.</value>
public DateTime? Date
{
get { return this.GetValue("Date", x => ParseDateTime(x.First()), null); }
set { this.SetHeaderValues("Date", value, x => new[] { GetDateAsString(value) }); }
}
/// <summary>
/// The domain name of the server (for virtual hosting), mandatory since HTTP/1.1
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Host
{
get { return this.GetValue("Host", x => x.First(), string.Empty); }
set { this.SetHeaderValues("Host", value, x => new[] { x }); }
}
/// <summary>
/// Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for methods like PUT to only update a resource if it has not been modified since the user last updated it.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> IfMatch
{
get { return this.GetValue("If-Match"); }
set { this.SetHeaderValues("If-Match", value, x => x); }
}
/// <summary>
/// Allows a 304 Not Modified to be returned if content is unchanged
/// </summary>
/// <value>A <see cref="DateTime"/> instance that specifies when the requested resource must have been changed since. If not available then <see langword="null"/> will be returned.</value>
public DateTime? IfModifiedSince
{
get { return this.GetValue("If-Modified-Since", x => ParseDateTime(x.First()), null); }
set { this.SetHeaderValues("If-Modified-Since", value, x => new[] { GetDateAsString(value) }); }
}
/// <summary>
/// Allows a 304 Not Modified to be returned if content is unchanged
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> IfNoneMatch
{
get { return this.GetValue("If-None-Match"); }
set { this.SetHeaderValues("If-None-Match", value, x => x); }
}
/// <summary>
/// If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string IfRange
{
get { return this.GetValue("If-Range", x => x.First(), string.Empty); }
set { this.SetHeaderValues("If-Range", value, x => new[] { x }); }
}
/// <summary>
/// Only send the response if the entity has not been modified since a specific time.
/// </summary>
/// <value>A <see cref="DateTime"/> instance that specifies when the requested resource may not have been changed since. If not available then <see langword="null"/> will be returned.</value>
public DateTime? IfUnmodifiedSince
{
get { return this.GetValue("If-Unmodified-Since", x => ParseDateTime(x.First()), null); }
set { this.SetHeaderValues("If-Unmodified-Since", value, x => new[] { GetDateAsString(value) }); }
}
/// <summary>
/// Gets the names of the available request headers.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> containing the names of the headers.</value>
public IEnumerable<string> Keys
{
get { return this.headers.Keys; }
}
/// <summary>
/// Limit the number of times the message can be forwarded through proxies or gateways.
/// </summary>
/// <value>The number of the maximum allowed number of forwards if it is available; otherwise 0.</value>
public int MaxForwards
{
get { return this.GetValue("Max-Forwards", x => Convert.ToInt32(x.First()), 0); }
set { this.SetHeaderValues("Max-Forwards", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); }
}
/// <summary>
/// This is the address of the previous web page from which a link to the currently requested page was followed.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Referrer
{
get { return this.GetValue("Referer", x => x.First(), string.Empty); }
set { this.SetHeaderValues("Referer", value, x => new[] { x }); }
}
/// <summary>
/// The user agent string of the user agent
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string UserAgent
{
get { return this.GetValue("User-Agent", x => x.First(), string.Empty); }
set { this.SetHeaderValues("User-Agent", value, x => new[] { x }); }
}
/// <summary>
/// Gets all the header values.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains all the header values.</value>
public IEnumerable<IEnumerable<string>> Values
{
get { return this.headers.Values; }
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.</returns>
public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator()
{
return this.headers.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Gets the values for the header identified by the <paramref name="name"/> parameter.
/// </summary>
/// <param name="name">The name of the header to return the values for.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains the values for the header. If the header is not defined then <see cref="Enumerable.Empty{TResult}"/> is returned.</returns>
public IEnumerable<string> this[string name]
{
get
{
return (this.headers.ContainsKey(name)) ?
this.headers[name] :
Enumerable.Empty<string>();
}
}
private static string GetDateAsString(DateTime? value)
{
return !value.HasValue ? null : value.Value.ToString("R", CultureInfo.InvariantCulture);
}
private IEnumerable<string> GetSplitValues(string header)
{
var values = this.GetValue(header);
return values
.SelectMany(x => x.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
.Select(x => x.Trim())
.ToList();
}
private IEnumerable<Tuple<string, decimal>> GetWeightedValues(string headerName)
{
return this.cache.GetOrAdd(headerName, r =>
{
var values = this.GetValue(r);
var result = new List<Tuple<string, decimal>>();
foreach (var header in values)
{
var buffer = string.Empty;
var name = string.Empty;
var quality = string.Empty;
var isReadingQuality = false;
var isInQuotedSection = false;
for (var index = 0; index < header.Length; index++)
{
var character = header[index];
if (character.Equals(' ') && (index != header.Length - 1) && !isInQuotedSection)
{
continue;
}
if (character.Equals('"'))
{
isInQuotedSection = !isInQuotedSection;
}
if (isInQuotedSection)
{
buffer += character;
if (index != header.Length - 1)
{
continue; ;
}
}
if (character.Equals(';') || character.Equals(',') || (index == header.Length - 1))
{
if (!(character.Equals(';') || character.Equals(',')))
{
buffer += character;
}
if (isReadingQuality)
{
quality = buffer;
}
else
{
if (name.Length > 0)
{
name += ';';
}
name += buffer;
}
buffer = string.Empty;
isReadingQuality = false;
isInQuotedSection = false;
}
if (character.Equals(';'))
{
continue;
}
if ((character.Equals('q') || character.Equals('Q')) && (index != header.Length - 1))
{
if (header[index + 1].Equals('='))
{
isReadingQuality = true;
continue;
}
}
if (isReadingQuality && character.Equals('='))
{
continue;
}
if (character.Equals(',') || (index == header.Length - 1))
{
var actualQuality = 1m;
decimal temp;
if (decimal.TryParse(quality, NumberStyles.Number, CultureInfo.InvariantCulture, out temp))
{
actualQuality = temp;
}
result.Add(new Tuple<string, decimal>(name, actualQuality));
name = string.Empty;
quality = string.Empty;
buffer = string.Empty;
isReadingQuality = false;
continue;
}
buffer += character;
}
}
return result.OrderByDescending(x => x.Item2);
});
}
private static IEnumerable<INancyCookie> GetNancyCookies(IEnumerable<string> cookies)
{
if (cookies == null)
{
yield break;
}
foreach (var cookie in cookies)
{
var cookieStrings = cookie.Split(';');
foreach (var cookieString in cookieStrings)
{
var equalPos = cookieString.IndexOf('=');
if (equalPos >= 0)
{
yield return new NancyCookie(cookieString.Substring(0, equalPos).TrimStart(), cookieString.Substring(equalPos+1).TrimEnd());
}
}
}
}
private IEnumerable<string> GetValue(string name)
{
return this.GetValue(name, x => x, new string[] {});
}
private T GetValue<T>(string name, Func<IEnumerable<string>, T> converter, T defaultValue)
{
IEnumerable<string> values;
if (!this.headers.TryGetValue(name, out values))
{
return defaultValue;
}
return converter.Invoke(values);
}
private static IEnumerable<string> GetWeightedValuesAsStrings(IEnumerable<Tuple<string, decimal>> values)
{
return values.Select(x => string.Concat(x.Item1, ";q=", x.Item2.ToString(CultureInfo.InvariantCulture)));
}
private static DateTime? ParseDateTime(string value)
{
DateTime result;
// note CultureInfo.InvariantCulture is ignored
if (DateTime.TryParseExact(value, "R", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
return result;
}
return null;
}
private void SetHeaderValues<T>(string header, T value, Func<T, IEnumerable<string>> valueTransformer)
{
this.InvalidateCacheEntry(header);
if (EqualityComparer<T>.Default.Equals(value, default(T)))
{
if (this.headers.ContainsKey(header))
{
this.headers.Remove(header);
}
}
else
{
this.headers[header] = valueTransformer.Invoke(value);
}
}
private void InvalidateCacheEntry(string header)
{
IEnumerable<Tuple<string, decimal>> values;
this.cache.TryRemove(header, out values);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Portable
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
/// <summary>
/// Resolves types by name.
/// </summary>
internal class TypeResolver
{
/** Regex to parse generic types from portable configuration. Allows nested generics in type arguments. */
private static readonly Regex GenericTypeRegex =
new Regex(@"([^`,\[\]]*)(?:`[0-9]+)?(?:\[((?:(?<br>\[)|(?<-br>\])|[^\[\]]*)+)\])?", RegexOptions.Compiled);
/** Assemblies loaded in ReflectionOnly mode. */
private readonly Dictionary<string, Assembly> _reflectionOnlyAssemblies = new Dictionary<string, Assembly>();
/// <summary>
/// Resolve type by name.
/// </summary>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblyName">Optional, name of the assembly.</param>
/// <returns>
/// Resolved type.
/// </returns>
public Type ResolveType(string typeName, string assemblyName = null)
{
Debug.Assert(!string.IsNullOrEmpty(typeName));
return ResolveType(assemblyName, typeName, AppDomain.CurrentDomain.GetAssemblies())
?? ResolveTypeInReferencedAssemblies(assemblyName, typeName);
}
/// <summary>
/// Resolve type by name in specified assembly set.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblies">Assemblies to look in.</param>
/// <returns>
/// Resolved type.
/// </returns>
private static Type ResolveType(string assemblyName, string typeName, ICollection<Assembly> assemblies)
{
return ResolveGenericType(assemblyName, typeName, assemblies) ??
ResolveNonGenericType(assemblyName, typeName, assemblies);
}
/// <summary>
/// Resolves non-generic type by searching provided assemblies.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblies">The assemblies.</param>
/// <returns>Resolved type, or null.</returns>
private static Type ResolveNonGenericType(string assemblyName, string typeName, ICollection<Assembly> assemblies)
{
if (!string.IsNullOrEmpty(assemblyName))
assemblies = assemblies
.Where(x => x.FullName == assemblyName || x.GetName().Name == assemblyName).ToArray();
if (!assemblies.Any())
return null;
// Trim assembly qualification
var commaIdx = typeName.IndexOf(',');
if (commaIdx > 0)
typeName = typeName.Substring(0, commaIdx);
return assemblies.Select(a => a.GetType(typeName, false, false)).FirstOrDefault(type => type != null);
}
/// <summary>
/// Resolves the name of the generic type by resolving each generic arg separately
/// and substituting it's fully qualified name.
/// (Assembly.GetType finds generic types only when arguments are fully qualified).
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblies">Assemblies</param>
/// <returns>Fully qualified generic type name, or null if argument(s) could not be resolved.</returns>
private static Type ResolveGenericType(string assemblyName, string typeName, ICollection<Assembly> assemblies)
{
var match = GenericTypeRegex.Match(typeName);
if (!match.Success || !match.Groups[2].Success)
return null;
// Try to construct generic type; each generic arg can also be a generic type.
var genericArgs = GenericTypeRegex.Matches(match.Groups[2].Value)
.OfType<Match>().Select(m => m.Value).Where(v => !string.IsNullOrWhiteSpace(v))
.Select(v => ResolveType(null, TrimBrackets(v), assemblies)).ToArray();
if (genericArgs.Any(x => x == null))
return null;
var genericType = ResolveNonGenericType(assemblyName,
string.Format("{0}`{1}", match.Groups[1].Value, genericArgs.Length), assemblies);
if (genericType == null)
return null;
return genericType.MakeGenericType(genericArgs);
}
/// <summary>
/// Trims the brackets from generic type arg.
/// </summary>
private static string TrimBrackets(string s)
{
return s.StartsWith("[") && s.EndsWith("]") ? s.Substring(1, s.Length - 2) : s;
}
/// <summary>
/// Resolve type by name in non-loaded referenced assemblies.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <returns>
/// Resolved type.
/// </returns>
private Type ResolveTypeInReferencedAssemblies(string assemblyName, string typeName)
{
ResolveEventHandler resolver = (sender, args) => GetReflectionOnlyAssembly(args.Name);
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolver;
try
{
var result = ResolveType(assemblyName, typeName, GetNotLoadedReferencedAssemblies().ToArray());
if (result == null)
return null;
// result is from ReflectionOnly assembly, load it properly into current domain
var asm = AppDomain.CurrentDomain.Load(result.Assembly.GetName());
return asm.GetType(result.FullName);
}
finally
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolver;
}
}
/// <summary>
/// Gets the reflection only assembly.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Assembly GetReflectionOnlyAssembly(string fullName)
{
Assembly result;
if (!_reflectionOnlyAssemblies.TryGetValue(fullName, out result))
{
try
{
result = Assembly.ReflectionOnlyLoad(fullName);
}
catch (Exception)
{
// Some assemblies may fail to load
result = null;
}
_reflectionOnlyAssemblies[fullName] = result;
}
return result;
}
/// <summary>
/// Recursively gets all referenced assemblies for current app domain, excluding those that are loaded.
/// </summary>
private IEnumerable<Assembly> GetNotLoadedReferencedAssemblies()
{
var roots = new Stack<Assembly>(AppDomain.CurrentDomain.GetAssemblies());
var visited = new HashSet<string>();
var loaded = new HashSet<string>(roots.Select(x => x.FullName));
while (roots.Any())
{
var asm = roots.Pop();
if (visited.Contains(asm.FullName))
continue;
if (!loaded.Contains(asm.FullName))
yield return asm;
visited.Add(asm.FullName);
foreach (var refAsm in asm.GetReferencedAssemblies()
.Where(x => !visited.Contains(x.FullName))
.Where(x => !loaded.Contains(x.FullName))
.Select(x => GetReflectionOnlyAssembly(x.FullName))
.Where(x => x != null))
roots.Push(refAsm);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using Cards.GUI;
using Microsoft.Win32;
namespace Cards
{
public enum gameMessages
{
gameStateUpdate,
chatMessage,
playerInfo
}
public struct playerPosition
{
public string seat; // E,W,N,S
public int x;
public int y;
}
/// <summary>
/// Struct that contains all the game information
/// </summary>
///
[Serializable]
public struct GameData
{
public gameMessages gameMessageType;
public int CurrentRound; // current round being played MAX is 5
public int HandCounter; // keeps track of played card MAX is 13
public int ActivePlayerId; // ID of the current player
/// <summary>
/// score[RoundIndex,PlayerID] = score;
/// RoundIndex starts from 0 and goes upto 4;
/// </summary>
public float[,] score;
public int HandWinnerID; // Player ID of the Hand Winner for animation
public int RoundStarter; // (not used but may be useful )
public GameState GameState; // state of the game
public Pile WastePile; // waste cards or Already played cards
public List<player> CurrentPlayerList; // list of current player currentPlayerList[0] is player with ID 0
public Pot CurrentPot; // when a valid card is played then it is added in the pot ( displayed in middle of screen)
}
[Serializable]
public enum GameState
{
INTRO,
BIDDING,
PLAYING,
ROUNDEND,
SCOREDISPLAY,
END
}
public enum AnimationSpeed
{
FAST,
NORMAL,
SLOW
}
[Serializable]
public partial class Main : Form
{
private Deck gameDeck;
private Cards.Card card = new Card();
public static int boardBelongsTo = 0; // variable to store playerID which clients board is this so that we can arranage the position
public const int gameRounds = 4; // starts with 0
public static string playerName;
delegate void refreshBoard();
private GameStateManager gameStateManager;
static public bool RefreshWholeBoard = true;
public static List<playerPosition> playerPositions = new List<playerPosition>(); // player position with respect to client
AnimationSpeed animationSpeed = AnimationSpeed.NORMAL; // controls the animation speed of the game ....
// Timer animate pot
private System.Windows.Forms.Timer animationTimer = new System.Windows.Forms.Timer();
private static int animationCounter = 40;
GameData gameData = new GameData();
private static bool _isAnimating = false;
/// <summary>
/// set to true is some animation is taking place
/// </summary>
public static bool IsAnimating
{
get { return Main._isAnimating; }
set { Main._isAnimating = value; }
}
public Main()
{
//this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
InitializeComponent();
}
/// <summary>
/// this method is called when ever painting of the board is needed
/// can be called by Invalidate,Refresh or Update method;
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
Graphics graphics = e.Graphics;
if (RefreshWholeBoard)
{
SpadesGui.refreshBoard(graphics, ref gameData);
}
}
/// <summary>
/// occurs when user clicks the mouse
/// just does some little animation to lift the card up
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Main_MouseClick(object sender, MouseEventArgs e)
{
int activePlayerId = gameData.ActivePlayerId;
foreach (SpadesCard card in gameData.CurrentPlayerList[activePlayerId].Hand.CardPile)
{
card.MoveUp = false;
}
// look for the card index from the mouse click
int mouseX = e.X;
int mouseY = e.Y;
// now calculate the card position form player initial position of refrence
// count how many cards are there in the pile
int cardCount = gameData.CurrentPlayerList[activePlayerId].Hand.CardPile.Count;
// check for valid click
// 71 is card width 97 is height
if (gameData.CurrentPlayerList[activePlayerId].Hand.CardPile.Count > 0)
{
if (mouseX >= playerPositions[activePlayerId].x && mouseX <= ((playerPositions[activePlayerId].x + 56) + (15 * cardCount)))
{
// check for y coordinate
if (mouseY >= playerPositions[activePlayerId].y && mouseY <= (playerPositions[activePlayerId].y + 97))
{
//valid coordinate
// calculate card index clicked
// 15 is the width of the card overlapping each other
int index = (int)(mouseX - playerPositions[activePlayerId].x) / 15;
// if index is more than last index then make it last index
if (index > (gameData.CurrentPlayerList[activePlayerId].Hand.CardPile.Count - 1))
{
index = gameData.CurrentPlayerList[activePlayerId].Hand.CardPile.Count - 1;
}
SpadesCard c = (SpadesCard)gameData.CurrentPlayerList[activePlayerId].Hand.CardPile[index];
c.MoveUp = true;
gameData.CurrentPlayerList[activePlayerId].Hand.CardPile[index] = c;
this.Invalidate();
}
}
}
}
/// <summary>
/// Event that occurs when the user double clicks the mouse on the form
/// checks if it is valid card or not first
/// If valid add to Pot
/// updates card position
/// updates turn
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Main_MouseDoubleClick(object sender, MouseEventArgs e)
{
int activePlayerId = gameData.ActivePlayerId;
if (gameData.CurrentPlayerList[boardBelongsTo].IsActivePlayer == false) return;
// look for the card index from the mouse click
int mouseX = e.X;
int mouseY = e.Y;
// now calculate the card position form player initial position of refrence
// count how many cards are there in the pile
int cardCount = gameData.CurrentPlayerList[activePlayerId].Hand.CardPile.Count;
// check for valid click
// 71 is card width 97 is height
if (cardCount > 0 && IsAnimating == false)
{
if (mouseX >= playerPositions[activePlayerId].x && mouseX <= ((playerPositions[activePlayerId].x + 56) + (15 * cardCount)))
{
// check for y coordinate
if (mouseY >= playerPositions[activePlayerId].y && mouseY <= (playerPositions[activePlayerId].y + 97))
{
//valid coordinate
// calculate card index clicked
int index = (int)(mouseX - playerPositions[activePlayerId].x) / 15;
// if index is more than last index then make it last index
if (index > (gameData.CurrentPlayerList[activePlayerId].Hand.CardPile.Count - 1))
{
index = gameData.CurrentPlayerList[activePlayerId].Hand.CardPile.Count - 1;
}
if (GameRule.isValidCard(gameData.CurrentPlayerList[activePlayerId], (SpadesCard)gameData.CurrentPlayerList[activePlayerId].Hand.CardPile[index], gameData.CurrentPot))
{
// check if its a valid card
// place the card in pot card
SpadesCard potCard = (SpadesCard)gameData.CurrentPlayerList[activePlayerId].Hand.CardPile[index];
// remove from hand
gameData.CurrentPlayerList[activePlayerId].Hand.CardPile.RemoveAt(index);
potCard.CardPositionX = playerPositions[activePlayerId].x + 80;
potCard.CardPositionY = playerPositions[activePlayerId].y - 120;
gameData.CurrentPot.AddPot(potCard, gameData.CurrentPlayerList[activePlayerId]);
this.updateTurn(activePlayerId);
}
}
}
}
}
/// <summary>
/// This function updates the player turn by incrementing the id by 1
///
/// E.g if given ID is 1 then this function set the ActivePlayerID to 2.
/// </summary>
/// <param name="playerID">ID of the last current player</param>
public void updateTurn(int playerID)
{
int nextTurn = playerID + 1;
if (nextTurn >= 4)
{
nextTurn = 0;
}
gameData.CurrentPlayerList[gameData.ActivePlayerId].IsActivePlayer = false;
gameData.ActivePlayerId = nextTurn;
updateGameState(gameData);
}
/// <summary>
/// initialize game and other thigs such as player,graphics animation timer etc
/// </summary>
/// <returns></returns>
public bool Initialize()
{
gameDeck = new Deck();
this.gameStateManager = new GameStateManager(null);
this.animationTimer.Tick += new EventHandler(animationTimer_Tick);
this.animationTimer.Interval = 5;
// initialize graphic class
//initialize score array to null
// score array
// for 5 rounds and 4 player
float[,] score = new float[5, 4];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
score[i, j] = 0; // initialize score to null
}
}
gameData.CurrentRound = 1;
gameData.ActivePlayerId = 0;
gameData.HandCounter = 0;
gameData.score = score;
gameData.HandWinnerID = 0;
gameData.RoundStarter = 0;
gameData.GameState = GameState.INTRO;
gameData.WastePile = new Pile();
gameData.CurrentPlayerList = new List<player>();
gameData.CurrentPot = new Pot();
initializePlayers();
SpadesGui.Initialize(ref gameData);
gameData.CurrentPot.PotAdd += new PotAddEventHandler(Pot_PotAdd);
initializePlayerBoardsPosition();
return true;
}
/// <summary>
/// Event handler of animationTimer
/// Lots of thing is going on here such as animating pot end , calculating socre , updating player tricks
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void animationTimer_Tick(object sender, EventArgs e)
{
if (animationCounter == 40)
{
if (animationSpeed == AnimationSpeed.FAST) Thread.Sleep(1000);
else if (animationSpeed == AnimationSpeed.NORMAL) Thread.Sleep(1500);
else if (animationSpeed == AnimationSpeed.SLOW) Thread.Sleep(2000);
}
gameData.HandWinnerID = gameData.CurrentPot.highestPlayer.ID;
foreach (SpadesCard card in gameData.CurrentPot.CardPile)
{
// make all cards go to winner
switch (playerPositions[gameData.HandWinnerID].seat)
{
case "S":
card.CardPositionY = card.CardPositionY + 80;
break;
case "W":
card.CardPositionX = card.CardPositionX - 80;
break;
case "N":
card.CardPositionY = card.CardPositionY - 80;
break;
case "E":
card.CardPositionX = card.CardPositionX + 80;
break;
}
}
this.Invalidate();
this.Update();
animationCounter--;
if (animationCounter == 0)
{
animationTimer.Stop();
// calculate Score
gameData.CurrentPlayerList[gameData.HandWinnerID].TotalTrick++; // update the trick of the player that has won the hand
// do hand counter increment here
gameData.HandCounter++;
// end of the round
if (gameData.HandCounter == 13)
{
// store score
// int roundIndex = CurrentRound - 1;
int roundIndex = gameData.CurrentRound - 1;
CalculateScore(roundIndex);
updateRoundStarter(gameData.RoundStarter);
gameData.CurrentRound++; // increase the round number
if (gameData.CurrentRound > (gameRounds +1))
{
// this is the finsh of the game
GameFinished();
return;
}
gameData.GameState = GameState.ROUNDEND;
updateGameState(gameData);
return;
}
IsAnimating = false;
gameData.CurrentPot.ClearPot(); // clear the pot for next round
updateTurn(gameData.HandWinnerID - 1);
}
}
/// <summary>
/// Updates the Id of round starter. (who is going to bid first)
/// </summary>
/// <param name="p"></param>
private void updateRoundStarter(int p)
{
gameData.RoundStarter = p + 1;
if (gameData.RoundStarter > 3) gameData.RoundStarter = 0;
updateGameState(gameData);
return;
//throw new NotImplementedException();
}
/// <summary>
/// End of Round 5
/// compares score and shows respective dialog
///
/// </summary>
private void GameFinished()
{
gameData.GameState = GameState.END;
bool isWinner = true;
float playerOneScore = gameData.CurrentPlayerList[0].TotalScore; // SpadesPlayer[0].TotalScore;
foreach (player p in gameData.CurrentPlayerList) //SpadesPlayer)
{
if (p.ID != 0 && p.TotalScore > playerOneScore) isWinner = false;
}
if (isWinner == false)
{
LooserForm LF = new LooserForm();
//LF.MdiParent = this;
LF.StartPosition = FormStartPosition.CenterParent;
LF.ShowDialog();
}
else
{
WinnerForm WF = new WinnerForm();
WF.StartPosition = FormStartPosition.CenterParent;
WF.ShowDialog();
}
ResetGame();
startGame();
// throw new NotImplementedException();
}
/// <summary>
/// Resets game variables
/// </summary>
private void ResetGame()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
gameData.score[i, j] = 0; // initialize score to null
}
}
gameData.CurrentRound = 1;
gameData.ActivePlayerId = 0;
gameData.HandCounter = 0;
gameData.HandWinnerID = 0;
gameData.RoundStarter = 0;
gameData.GameState = GameState.PLAYING;
gameData.CurrentPot.ClearPot();
IsAnimating = false;
}
/// <summary>
/// stores score in gameData.score
/// gameData.score is a multiDimension array
/// score[RoundIndex,PlayerID] = score;
/// RoundIndex starts from 0 and goes upto 4;
///
/// </summary>
/// <param name="roundIndex">round-1 to calculate the score (because index starts from 0) eg . if round 1 then pass 0 </param>
private void CalculateScore(int roundIndex)
{
foreach (player p in gameData.CurrentPlayerList)
{
if (p.TotalBid > p.TotalTrick)
{
// player has negative hand
gameData.score[roundIndex, p.ID] = 0 - p.TotalBid; // negative
}
else if (p.TotalBid == p.TotalTrick)
{
gameData.score[roundIndex, p.ID] = p.TotalBid;
}
else
{
// has greater number of tricks than the bid add as float
float difference = p.TotalTrick - p.TotalBid;
float point = difference / 10;
gameData.score[roundIndex, p.ID] = (float)Math.Round((p.TotalBid + point), 1);
}
}
}
/// <summary>
/// Events that occurs when a card is added to pot
/// when there are 4 cards in the pot it starts the animation
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Pot_PotAdd(object sender, PileEventArgs e)
{
gameData.WastePile.AddCard(e.card); // add the played card to waste pile too
if (gameData.CurrentPot.CardPile.Count == 4)
{
lock (this)
{
IsAnimating = true;
animationCounter = 40;
this.animationTimer.Start();
}
}
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
gameDeck = new Deck();
playerName = "";
gameStateManager.switchState(new IntroState(ref playerName));//SpadesPlayer));
gameStateManager.Process();
initializePlayerBoardsPosition(); // re position
int i = 0;
RegistryKey regKey = Registry.CurrentUser.OpenSubKey("Software\\Games\\CallBreak");
foreach (player p in gameData.CurrentPlayerList)
{
string key = "AIPlayer" + i.ToString();
if (i == 0) p.Name = playerName;
else p.Name = regKey.GetValue(key, "AI - I").ToString();
i++;
}
startGame();
}
/// <summary>
/// Iniialize Round, state of game and Starts the Turn
/// </summary>
/// <returns></returns>
public bool startGame()
{
startRound(gameData.CurrentRound);
this.Refresh();
gameData.GameState = GameState.PLAYING;
IsAnimating = false;
this.startTurn();
return true;
}
void bidState_BeforeBid(object sender, BidEventArgs e)
{
gameStatusLabel.Text = " waiting for " + gameData.CurrentPlayerList[e.PlayerID].Name + " to bid .....";
this.Update();
this.Invalidate();
}
void bidState_Bidded(object sender, BidEventArgs e)
{
updateTurn(gameData.ActivePlayerId);
}
/// <summary>
/// Starts the turn of the player [ ActivePlayerID ]
/// if its user turn , does nothing and waits for users input mouse clicks
/// </summary>
public void startTurn()
{
if (IsAnimating) newToolStripMenuItem.Enabled = false;
else newToolStripMenuItem.Enabled = true;
foreach (player p in gameData.CurrentPlayerList) //SpadesPlayer
{
p.IsActivePlayer = false;
}
// this is to prevent computer moves overlap
if (IsAnimating == true) return;
gameData.CurrentPlayerList[gameData.ActivePlayerId].IsActivePlayer = true;
gameStatusLabel.Text = " Waiting for " + gameData.CurrentPlayerList[gameData.ActivePlayerId].Name + " ....";
this.Invalidate();
this.Update();
if (gameData.CurrentPlayerList[gameData.ActivePlayerId] is AIPlayer)
{
// make a computer move
// can control speed of the movement here // fast or slow computer moves
// Thread.Sleep(10);
Thread.Sleep(Convert.ToInt32(animationSpeed) * 50);
SpadesCard card = gameData.CurrentPlayerList[gameData.ActivePlayerId].makeMove(gameData);
if (playerPositions[gameData.ActivePlayerId].seat == "N")
{
card.CardPositionX = playerPositions[gameData.ActivePlayerId].x + 80;
card.CardPositionY = playerPositions[gameData.ActivePlayerId].y + 120;
}
if (playerPositions[gameData.ActivePlayerId].seat == "W")
{
card.CardPositionX = playerPositions[gameData.ActivePlayerId].x + 180;
card.CardPositionY = playerPositions[gameData.ActivePlayerId].y + 80;
}
if (playerPositions[gameData.ActivePlayerId].seat == "S")
{
card.CardPositionX = playerPositions[gameData.ActivePlayerId].x + 80;
card.CardPositionY = playerPositions[gameData.ActivePlayerId].y - 120;
}
if (playerPositions[gameData.ActivePlayerId].seat == "E")
{
card.CardPositionX = playerPositions[gameData.ActivePlayerId].x - 180;
card.CardPositionY = playerPositions[gameData.ActivePlayerId].y + 90;
}
gameData.CurrentPot.AddPot(card, gameData.CurrentPlayerList[gameData.ActivePlayerId]);
gameData.CurrentPlayerList[gameData.ActivePlayerId].Hand.CardPile.Remove(card);
string msg = (gameData.ActivePlayerId + " Played " + card.Rank + " of " + card.Suit + "\r\n");
this.Invalidate();
this.Update();
updateTurn(gameData.ActivePlayerId);
}
else
{
return; // wait for human move
}
}
/// <summary>
/// Initialize players and there respective positions
/// </summary>
/// <returns></returns>
public bool initializePlayers()
{
bool isHuman = false;
for (int id = 0; id < 4; id++)
{
isHuman = (id == 0) ? true : false; // if id = 0 make it a human player else AI player
if (isHuman)
{
HumanPlayer p = new HumanPlayer(id);
gameData.CurrentPlayerList.Add(p);
}
else
gameData.CurrentPlayerList.Add(new AIPlayer(id));
}
return true;
}
public void initializePlayerBoardsPosition()
{
//add dummy positions
playerPositions.Clear();
for (int j = 0; j < 4; j++)
{
playerPositions.Add(new playerPosition());
}
int StartPosition = boardBelongsTo;
for (int i = 0; i < 4; i++)
{
playerPosition Position = new playerPosition();
if (StartPosition > 3) StartPosition = 0;
if (i == 0)
{
Position.seat = "S";
Position.x = 175;
Position.y = 350;
}
if (i == 1)
{
Position.seat = "W";
Position.x = 20;
Position.y = 100;
}
if (i == 2)
{
Position.seat = "N";
Position.x = 175;
Position.y = 30;
}
if (i == 3)
{
Position.seat = "E";
Position.x = 480;
Position.y = 100;
}
playerPositions[StartPosition] = Position;
StartPosition++;
}
}
/// <summary>
/// This method initializes PlayerHands and initializes round
/// TO DO :: SET ACTIVE PLAYER ID TO START THE ROUND
/// </summary>
/// <param name="round">Round Index</param>
/// <returns></returns>
public bool startRound(int round)
{
gameData.ActivePlayerId = gameData.RoundStarter;
this.gameRoundStatusLabel.Text = "Round : " + gameData.CurrentRound;
gameData.HandCounter = 0;
gameData.CurrentPot.ClearPot();
gameDeck = new Deck();
gameDeck.Shuffle();
Hand[] hand = new Hand[4];
int counter = 0;
for (int j = 0; j < 4; j++)
{
hand[j] = new Hand();
for (int i = counter; i < counter + 13; i++)
{
hand[j].AddCard((SpadesCard)gameDeck.CardPile[i]);
}
counter = counter + 13;
hand[j].sort();
}
// initialize 4 players hand
int k = 0;
foreach (player p in gameData.CurrentPlayerList)
{
p.Hand = hand[k];
k++;
p.TotalBid = 0;
p.TotalTrick = 0;
}
gameData.GameState = GameState.BIDDING;
updateGameState(gameData);
return true;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.ExitThread();
}
private void displayScoreToolStripMenuItem_Click(object sender, EventArgs e)
{
ScoreDisplay SD = new ScoreDisplay(ref gameData);
SD.ShowDialog();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Call Break 0.0.0 \nNishes Joshi 2009");
}
private void Main_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control == true && e.KeyCode == Keys.C)
{
SpadesGui.CardFaceCheat = !SpadesGui.CardFaceCheat;
this.Refresh();
}
}
private void playerNamesToolStripMenuItem_Click(object sender, EventArgs e)
{
AIPlayerNames PlayerNameBox = new AIPlayerNames();
PlayerNameBox.StartPosition = FormStartPosition.CenterParent;
PlayerNameBox.ShowDialog(this);
}
private void deckToolStripMenuItem_Click(object sender, EventArgs e)
{
ChooseDeck cd = new ChooseDeck();
cd.StartPosition = FormStartPosition.CenterParent;
if (cd.ShowDialog() == DialogResult.OK)
{
SpadesGui.CardBack = cd.choosenCardBack;
Refresh();
}
}
private void fastToolStripMenuItem_Click(object sender, EventArgs e)
{
this.animationSpeed = AnimationSpeed.FAST;
this.fastToolStripMenuItem.Checked = true;
this.mediumToolStripMenuItem.Checked = false;
this.slowToolStripMenuItem.Checked = false;
}
private void mediumToolStripMenuItem_Click(object sender, EventArgs e)
{
this.animationSpeed = AnimationSpeed.NORMAL;
this.mediumToolStripMenuItem.Checked = true;
this.fastToolStripMenuItem.Checked = false;
this.slowToolStripMenuItem.Checked = false;
}
private void slowToolStripMenuItem_Click(object sender, EventArgs e)
{
this.animationSpeed = AnimationSpeed.SLOW;
this.slowToolStripMenuItem.Checked = true;
this.fastToolStripMenuItem.Checked = false;
this.mediumToolStripMenuItem.Checked = false;
}
private void Main_Load(object sender, EventArgs e)
{
gameStateManager.switchState(new SplashScreenState());
gameStateManager.Process();
gameStatusLabel.TextChanged += new EventHandler(gameStatusLabel_TextChanged);
}
void gameStatusLabel_TextChanged(object sender, EventArgs e)
{
this.Invalidate();
}
public void updateGameState(GameData gdata)
{
this.gameData = gdata;
gameData.CurrentPot.PotAdd += new PotAddEventHandler(Pot_PotAdd);
RefreshWholeBoard = true;
if (gameData.GameState == GameState.BIDDING)
{
enterBiddingState();
}
else if (gameData.GameState == GameState.PLAYING)
{
enterPlayingState();
}
else if (gameData.GameState == GameState.ROUNDEND)
{
showScoreBoard();
}
else
{
redrawForm();
}
}
public void enterBiddingState()
{
initializePlayerBoardsPosition();
redrawForm();
makeBid();
}
public void showScoreBoard()
{
ScoreDisplay sd = new ScoreDisplay(ref gameData);
sd.ShowDialog();
startGame();
}
private void makeBid()
{
if (this.InvokeRequired)
{
// We're not in the UI thread, so we need to call BeginInvoke
this.Invoke(new refreshBoard(makeBid));
return;
}
BiddingState bidState = new BiddingState(ref gameData);
bidState.Bidded += new BidEventHandler(bidState_Bidded);
bidState.BeforeBid += new BeforeBidEventHandler(bidState_BeforeBid);
gameStateManager.switchState(bidState);
gameStateManager.Process();
}
public void enterPlayingState()
{
redrawForm();
this.startTurn();
}
public void redrawForm()
{
if (this.InvokeRequired)
{
// We're not in the UI thread, so we need to call BeginInvoke
this.Invoke(new refreshBoard(redrawForm));
return;
}
SpadesGui.Initialize(ref gameData);
this.Update();
this.Refresh();
}
}
}
| |
namespace Boxed.DotnetNewTest
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// <see cref="Process"/> extension methods.
/// </summary>
public static partial class ProcessExtensions
{
/// <summary>
/// Starts the a <see cref="Process"/> asynchronously.
/// </summary>
/// <param name="workingDirectory">The working directory.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="arguments">The arguments.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result and console output from executing the process.</returns>
public static async Task<(ProcessResult processResult, string message)> StartAsync(
string workingDirectory,
string fileName,
string arguments,
CancellationToken cancellationToken)
{
TestLogger.WriteLine($"Executing {fileName} {arguments} from {workingDirectory}");
var output = new StringBuilder();
var error = new StringBuilder();
ProcessResult processResult;
try
{
var exitCode = await StartProcess(
fileName,
arguments,
workingDirectory,
cancellationToken,
new StringWriter(output),
new StringWriter(error));
processResult = exitCode == 0 ? ProcessResult.Succeeded : ProcessResult.Failed;
}
catch (TaskCanceledException)
{
TestLogger.WriteLine($"Timed Out {fileName} {arguments} from {workingDirectory}");
processResult = ProcessResult.TimedOut;
}
var standardOutput = output.ToString();
var standardError = error.ToString();
var message = GetAndWriteMessage(
processResult,
standardOutput,
standardError);
return (processResult, message);
}
private static string GetAndWriteMessage(
ProcessResult result,
string standardOutput,
string standardError)
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"Result: {result}");
TestLogger.Write("Result: ");
TestLogger.WriteLine(result.ToString(), result == ProcessResult.Succeeded ? ConsoleColor.Green : ConsoleColor.Red);
if (!string.IsNullOrEmpty(standardError))
{
stringBuilder
.AppendLine()
.AppendLine($"StandardError: {standardError}");
TestLogger.WriteLine("StandardError: ");
TestLogger.WriteLine(standardError, ConsoleColor.Red);
TestLogger.WriteLine();
}
if (!string.IsNullOrEmpty(standardOutput))
{
stringBuilder
.AppendLine()
.AppendLine($"StandardOutput: {standardOutput}");
TestLogger.WriteLine();
TestLogger.WriteLine($"StandardOutput: {standardOutput}");
}
return stringBuilder.ToString();
}
private static async Task<int> StartProcess(
string filename,
string arguments,
string workingDirectory = null,
CancellationToken cancellationToken = default,
TextWriter outputTextWriter = null,
TextWriter errorTextWriter = null)
{
var processStartInfo = new ProcessStartInfo()
{
CreateNoWindow = true,
Arguments = arguments,
FileName = filename,
RedirectStandardOutput = outputTextWriter != null,
RedirectStandardError = errorTextWriter != null,
UseShellExecute = false,
WorkingDirectory = workingDirectory,
};
try
{
using (var process = new Process() { StartInfo = processStartInfo })
{
process.Start();
var tasks = new List<Task>(3) { process.WaitForExitAsync(cancellationToken) };
if (outputTextWriter != null)
{
tasks.Add(ReadAsync(
x =>
{
process.OutputDataReceived += x;
process.BeginOutputReadLine();
},
x => process.OutputDataReceived -= x,
outputTextWriter,
cancellationToken));
}
if (errorTextWriter != null)
{
tasks.Add(ReadAsync(
x =>
{
process.ErrorDataReceived += x;
process.BeginErrorReadLine();
},
x => process.ErrorDataReceived -= x,
errorTextWriter,
cancellationToken));
}
try
{
await Task.WhenAll(tasks);
}
catch
{
if (!process.HasExited)
{
// Add process.Kill(true) when 3.0 comes out to kill the entire process tree.
process.KillTree();
}
throw;
}
return process.ExitCode;
}
}
catch (Exception exception)
{
throw new ProcessStartException(processStartInfo, exception);
}
}
/// <summary>
/// Reads the data from the specified data received event and writes it to the
/// <paramref name="textWriter"/>.
/// </summary>
/// <param name="addHandler">Adds the event handler.</param>
/// <param name="removeHandler">Removes the event handler.</param>
/// <param name="textWriter">The text writer.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private static Task ReadAsync(
this Action<DataReceivedEventHandler> addHandler,
Action<DataReceivedEventHandler> removeHandler,
TextWriter textWriter,
CancellationToken cancellationToken = default)
{
var taskCompletionSource = new TaskCompletionSource<object>();
DataReceivedEventHandler handler = null;
handler = new DataReceivedEventHandler(
(sender, e) =>
{
if (e.Data == null)
{
removeHandler(handler);
taskCompletionSource.TrySetResult(null);
}
else
{
textWriter.WriteLine(e.Data);
}
});
addHandler(handler);
if (cancellationToken != default)
{
cancellationToken.Register(
() =>
{
removeHandler(handler);
taskCompletionSource.TrySetCanceled();
});
}
return taskCompletionSource.Task;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Collections;
using System.IO;
using System.Xml;
using Zeus;
using Zeus.Configuration;
using Zeus.Projects;
using Zeus.Serializers;
using Zeus.UserInterface;
using MyGeneration;
using MyMeta;
using Microsoft.Win32;
namespace Zeus
{
/// <summary>
/// Summary description for ZeusCmd.
/// </summary>
class ZeusCmd
{
private const string EXT_XML_NAMESPACE = "http://schemas.microsoft.com/AutomationExtensibility";
private Log _log;
private CmdInput _argmgr;
private int _returnValue = 0;
public ZeusCmd(string[] args)
{
_log = new Log();
if (_ProcessArgs(args))
{
_log.IsInternalUseMode = _argmgr.InternalUseOnly;
switch (_argmgr.Mode)
{
case ProcessMode.Project:
_ProcessProject();
break;
case ProcessMode.Template:
_ProcessTemplate();
break;
case ProcessMode.MyMeta:
_ProcessMyMeta();
break;
case ProcessMode.Other:
if (_argmgr.InstallVS2005)
{
// Install Visual Studio 2005 Add In
_InstallVS2005();
}
break;
}
}
else
{
_returnValue = -1;
}
_log.Close();
}
public int ReturnValue { get { return _returnValue; } }
private bool _ProcessArgs(string[] args)
{
//Process arguments, validate, fill variables
_argmgr = new CmdInput(args);
if (_argmgr.ShowHelp)
{
Console.Write(HELP_TEXT);
return false;
}
if (_argmgr.IntrinsicObjects.Count > 0)
{
ZeusConfig cfg = ZeusConfig.Current;
foreach (ZeusIntrinsicObject io in _argmgr.IntrinsicObjects)
{
bool exists = false;
foreach (ZeusIntrinsicObject existingObj in cfg.IntrinsicObjects)
{
if (existingObj.VariableName == io.VariableName)
{
exists = true;
break;
}
}
if (!exists)
{
cfg.IntrinsicObjects.Add(io);
}
}
cfg.Save();
}
if (_argmgr.IntrinsicObjectsToRemove.Count > 0)
{
ZeusConfig cfg = ZeusConfig.Current;
foreach (ZeusIntrinsicObject io in _argmgr.IntrinsicObjectsToRemove)
{
cfg.IntrinsicObjects.Remove(io);
}
cfg.Save();
}
if (_argmgr.IsValid)
{
if (_argmgr.EnableLog)
{
_log.IsLogEnabled = true;
_log.FileName = _argmgr.PathLog;
}
_log.IsConsoleEnabled = !_argmgr.IsSilent;
return true;
}
else
{
Console.WriteLine(_argmgr.ErrorMessage);
Console.Write("Use the \"-?\" switch to view the help.");
return false;
}
}
private void _InstallVS2005()
{
// Parameters required to pass in from installer
string productName = "MyGeneration Visual Studio 2005 Add-in";
string assemblyName = "MyGenVS2005";
// Setup .addin path and assembly path
string addinTargetPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Visual Studio 2005\Addins");
string assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string addinControlFileName = assemblyName + ".Addin";
string addinAssemblyFileName = assemblyName + ".dll";
try
{
DirectoryInfo dirInfo = new DirectoryInfo(addinTargetPath);
if (!dirInfo.Exists)
{
dirInfo.Create();
}
string sourceFile = Path.Combine(assemblyPath, addinControlFileName);
XmlDocument doc = new XmlDocument();
doc.Load(sourceFile);
XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
xnm.AddNamespace("def", EXT_XML_NAMESPACE);
// Update Addin/Assembly node
XmlNode node = doc.SelectSingleNode("/def:Extensibility/def:Addin/def:Assembly", xnm);
if (node != null)
{
node.InnerText = Path.Combine(assemblyPath, addinAssemblyFileName);
}
// Update ToolsOptionsPage/Assembly node
node = doc.SelectSingleNode("/def:Extensibility/def:ToolsOptionsPage/def:Category/def:SubCategory/def:Assembly", xnm);
if (node != null)
{
node.InnerText = Path.Combine(assemblyPath, addinAssemblyFileName);
}
doc.Save(sourceFile);
string targetFile = Path.Combine(addinTargetPath, addinControlFileName);
File.Copy(sourceFile, targetFile, true);
}
catch (Exception ex)
{
_log.Write(ex);
_log.Write("Installation of visual studio add-in failed.");
}
}
private void _ProcessMyMeta()
{
if (_argmgr.MergeMetaFiles)
{
try
{
dbRoot.MergeUserMetaDataFiles(_argmgr.MetaFile1, _argmgr.MetaDatabase1, _argmgr.MetaFile2, _argmgr.MetaDatabase2, _argmgr.MetaFileMerged);
}
catch (Exception ex)
{
this._log.Write(ex);
this._log.Write("Merge UserMetaData files failed.");
}
}
else
{
IDbConnection connection = null;
try
{
dbRoot mymeta = new dbRoot();
connection = mymeta.BuildConnection(_argmgr.ConnectionType, _argmgr.ConnectionString);
_log.Write("Beginning test for {0}: {1}", connection.GetType().ToString(), _argmgr.ConnectionString);
connection.Open();
connection.Close();
_log.Write("Test Successful");
}
catch (Exception ex)
{
_log.Write("Test Failed");
if (_log != null) _log.Write(ex);
_returnValue = -1;
}
if (connection != null)
{
connection.Close();
connection = null;
}
}
}
private void _ProcessProject()
{
ZeusProject proj = this._argmgr.Project;
this._log.Write("Begin Project Processing: " + proj.Name);
if (this._argmgr.ModuleNames.Count > 0)
{
foreach (string mod in _argmgr.ModuleNames)
{
this._log.Write("Executing: " + mod);
try
{
if (!ExecuteModule(proj, mod))
{
this._log.Write("Project Folder not found: {0}.", mod);
}
}
catch (Exception ex)
{
this._log.Write(ex);
this._log.Write("Project Folder execution failed for folder: {0}.", mod);
}
}
}
else if (!string.IsNullOrEmpty(this._argmgr.ProjectItemToRecord) &&
!string.IsNullOrEmpty(this._argmgr.PathTemplate))
{
string item = _argmgr.ProjectItemToRecord;
string template = _argmgr.PathTemplate;
this._log.Write("Collecting: " + item + " for template " + template);
try
{
if (!CollectProjectItem(proj, item, template))
{
this._log.Write("Project Item not found: {0}.", item);
}
}
catch (Exception ex)
{
this._log.Write(ex);
this._log.Write("Project Item collection failed for item: {0}.", item);
}
}
else if (this._argmgr.ProjectItems.Count > 0)
{
foreach (string item in _argmgr.ProjectItems)
{
this._log.Write("Executing: " + item);
try
{
if (!ExecuteProjectItem(proj, item))
{
this._log.Write("Project Item not found: {0}.", item);
}
}
catch (Exception ex)
{
this._log.Write(ex);
this._log.Write("Project Item execution failed for item: {0}.", item);
}
}
}
else
{
this._log.Write("Executing: " + proj.Name);
try
{
proj.Execute(this._argmgr.Timeout, this._log);
if (this._argmgr.InternalUseOnly)
{
foreach (string file in proj.SavedFiles)
{
this._log.Write("[GENERATED_FILE]" + file);
}
}
}
catch (Exception ex)
{
this._log.Write(ex);
this._log.Write("Project execution failed.");
}
}
this._log.Write("End Project Processing: " + proj.Name);
if (_argmgr.InternalUseOnly) this._log.Write("[PROJECT_GENERATION_COMPLETE]");
}
private bool ExecuteModule(ZeusModule parent, string projectPath)
{
bool complete = false;
ZeusModule m = FindModule(parent, projectPath);
if (m != null)
{
complete = true;
m.Execute(this._argmgr.Timeout, this._log);
if (this._argmgr.InternalUseOnly)
{
foreach (string file in m.SavedFiles)
{
this._log.Write("[GENERATED_FILE]" + file);
}
}
}
return complete;
}
private bool ExecuteProjectItem(ZeusModule parent, string projectPath)
{
bool complete = false;
int moduleIndex = projectPath.LastIndexOf('/');
if (moduleIndex >= 0)
{
string modulePath = projectPath.Substring(0, moduleIndex),
objectName = projectPath.Substring(moduleIndex + 1);
ZeusModule m = FindModule(parent, modulePath);
if (m != null)
{
if (m.SavedObjects.Contains(objectName))
{
m.SavedObjects[objectName].Execute(this._argmgr.Timeout, this._log);
if (this._argmgr.InternalUseOnly)
{
foreach (string file in m.SavedObjects[objectName].SavedFiles)
{
this._log.Write("[GENERATED_FILE]" + file);
}
}
}
complete = true;
}
}
return complete;
}
private bool CollectProjectItem(ZeusModule parent, string projectPath, string templatePath)
{
bool complete = false;
int moduleIndex = projectPath.LastIndexOf('/');
if (moduleIndex >= 0)
{
string modulePath = projectPath.Substring(0, moduleIndex),
objectName = projectPath.Substring(moduleIndex + 1);
ZeusModule m = FindModule(parent, modulePath);
if (m != null)
{
ZeusTemplate template = new ZeusTemplate(templatePath);
DefaultSettings settings = DefaultSettings.Instance;
SavedTemplateInput savedInput = null;
if (m.SavedObjects.Contains(objectName))
{
savedInput = m.SavedObjects[objectName];
}
else
{
savedInput = new SavedTemplateInput();
savedInput.SavedObjectName = objectName;
}
ZeusContext context = new ZeusContext();
context.Log = this._log;
savedInput.TemplateUniqueID = template.UniqueID;
savedInput.TemplatePath = template.FilePath + template.FileName;
settings.PopulateZeusContext(context);
if (m != null)
{
m.PopulateZeusContext(context);
m.OverrideSavedData(savedInput.InputItems);
}
if (template.Collect(context, settings.ScriptTimeout, savedInput.InputItems))
{
//this._lastRecordedSelectedNode = this.SelectedTemplate;
}
if (this._argmgr.InternalUseOnly)
{
this._log.Write("[BEGIN_RECORDING]");
this._log.Write(savedInput.XML);
this._log.Write("[END_RECORDING]");
}
complete = true;
}
}
return complete;
}
private ZeusModule FindModule(ZeusModule parent, string projectPath)
{
ZeusModule m = null;
if (parent.ProjectPath.Equals(projectPath, StringComparison.CurrentCultureIgnoreCase))
{
m = parent;
}
else
{
foreach (ZeusModule module in parent.ChildModules)
{
if (module.ProjectPath.Equals(projectPath, StringComparison.CurrentCultureIgnoreCase))
{
m = module;
break;
}
else
{
m = FindModule(module, projectPath);
if (m != null) break;
}
}
}
return m;
}
private void _ProcessTemplate()
{
ZeusTemplate template = this._argmgr.Template;
ZeusSavedInput savedInput = this._argmgr.SavedInput;
ZeusSavedInput collectedInput = this._argmgr.InputToSave;
ZeusContext context = new ZeusContext();
context.Log = _log;
DefaultSettings settings;
this._log.Write("Executing: " + template.Title);
try
{
if (savedInput != null)
{
context.Input.AddItems(savedInput.InputData.InputItems);
template.Execute(context, this._argmgr.Timeout, true);
}
else if (collectedInput != null)
{
settings = DefaultSettings.Instance;
settings.PopulateZeusContext(context);
template.ExecuteAndCollect(context, this._argmgr.Timeout, collectedInput.InputData.InputItems);
collectedInput.Save();
}
else
{
settings = DefaultSettings.Instance;
settings.PopulateZeusContext(context);
template.Execute(context, this._argmgr.Timeout, false);
}
if (this._argmgr.PathOutput != null)
{
StreamWriter writer = File.CreateText(this._argmgr.PathOutput);
writer.Write(context.Output.text);
writer.Flush();
writer.Close();
}
else
{
if (!_argmgr.IsSilent)
Console.WriteLine(context.Output.text);
}
}
catch (Exception ex)
{
this._log.Write(ex);
this._log.Write("Template execution failed.");
}
if (context != null && this._argmgr.InternalUseOnly)
{
foreach (string file in context.Output.SavedFiles)
{
this._log.Write("[GENERATED_FILE]" + file);
}
}
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
ZeusCmd cmd = new ZeusCmd(args);
return cmd.ReturnValue;
}
#region Help Text
public const string HELP_TEXT = @"
|========================================================================
| ZeusCmd.exe: Switches, arguments, etc.
|========================================================================
| General switches
|------------------------------------------------------------------------
| -?, -h | show usage text
| -s | silent mode (no console output)
| -r | make paths relative to exe
| -l <logpath> | log process events and errors
| -e <integer> | template execution timeout
|------------------------------------------------------------------------
| Project switches
|------------------------------------------------------------------------
| -p <projectfilepath> | generate an entire project
| -pf <projectlocation> | regenerate a project folder
| -m <projectlocation> | same as -pf above for modules
| -ti <projectlocation> | same as -pf above for templates
|------------------------------------------------------------------------
| Template switches
|------------------------------------------------------------------------
| -i <xmldatapath> | xml input file
| -t <templatepath> | template file path
| -o <outputpath> | output path
| -c <saveinputpath> | collect input and save to file
|------------------------------------------------------------------------
| Intrinsic Object switches
|------------------------------------------------------------------------
| -aio <dllpath> <classpath> <varname> | add an intrinsic object
| -rio <varname> | remove an intrinsic object
|------------------------------------------------------------------------
| MyMeta switches
|------------------------------------------------------------------------
| -tc <providername> <connectstring> | test a db connection
| -mumd <file1> <entry1> <file2> <entry2> <result> | merge user meta data
|========================================================================
| EXAMPLE 1
| Execute a template:
|------------------------------------------------------------------------
| ZeusCmd -t c:\template.jgen
|========================================================================
| EXAMPLE 2
| Execute a template, no console output, log to file:
|------------------------------------------------------------------------
| ZeusCmd -s -t c:\template.jgen -l c:\zeuscmd.log
|========================================================================
| EXAMPLE 3
| Execute template, save input to an xml file:
|------------------------------------------------------------------------
| ZeusCmd -t c:\template.jgen -c c:\savedInput.zinp
|========================================================================
| EXAMPLE 4
| Regenerate from the saved input in example 3 above:
|------------------------------------------------------------------------
| ZeusCmd -i c:\savedInput.zinp
|=========================================================================
| EXAMPLE 5
| Add an intrinsic object to the Zeus Configuration file.
|------------------------------------------------------------------------
| ZeusCmd -aio TheDLLOfmyDreams.dll Lib.MyGen.Plugin.Utilities myVar
|=========================================================================
| EXAMPLE 6
| Remove an intrinsic object to the Zeus Configuration file.
|------------------------------------------------------------------------
| ZeusCmd -rio myVar
|=========================================================================
| EXAMPLE 7
| Test a MyMeta Connection
|------------------------------------------------------------------------
| ZeusCmd -tc SQL ""Provider=SQLOLEDB.1;User ID=sa;Data Source=localhost""
|=========================================================================
| EXAMPLE 8
| Merge two UserMetaData files into a new one.
|------------------------------------------------------------------------
| ZeusCmd -mumd umd1.xml Northwind umd2.xml Northwind22 out.xml
|=========================================================================
";
#endregion
}
}
| |
#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.Diagnostics;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json;
using System.IO;
using System.Reflection;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Tests.TestObjects.JsonTextReaderTests;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests
{
[TestFixture]
public class JsonTextWriterTest : TestFixtureBase
{
[Test]
public void BufferTest()
{
FakeArrayPool arrayPool = new FakeArrayPool();
string longString = new string('A', 2000);
string longEscapedString = "Hello!" + new string('!', 50) + new string('\n', 1000) + "Good bye!";
string longerEscapedString = "Hello!" + new string('!', 2000) + new string('\n', 1000) + "Good bye!";
for (int i = 0; i < 1000; i++)
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.ArrayPool = arrayPool;
writer.WriteStartObject();
writer.WritePropertyName("Prop1");
writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc));
writer.WritePropertyName("Prop2");
writer.WriteValue(longString);
writer.WritePropertyName("Prop3");
writer.WriteValue(longEscapedString);
writer.WritePropertyName("Prop4");
writer.WriteValue(longerEscapedString);
writer.WriteEndObject();
}
if ((i + 1) % 100 == 0)
{
Console.WriteLine("Allocated buffers: " + arrayPool.FreeArrays.Count);
}
}
Assert.AreEqual(0, arrayPool.UsedArrays.Count);
Assert.AreEqual(3, arrayPool.FreeArrays.Count);
}
[Test]
public void BufferTest_WithError()
{
FakeArrayPool arrayPool = new FakeArrayPool();
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
try
{
// dispose will free used buffers
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.ArrayPool = arrayPool;
writer.WriteStartObject();
writer.WritePropertyName("Prop1");
writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc));
writer.WritePropertyName("Prop2");
writer.WriteValue("This is an escaped \n string!");
writer.WriteValue("Error!");
}
Assert.Fail();
}
catch
{
}
Assert.AreEqual(0, arrayPool.UsedArrays.Count);
Assert.AreEqual(1, arrayPool.FreeArrays.Count);
}
#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0
[Test]
public void BufferErroringWithInvalidSize()
{
JObject o = new JObject
{
{"BodyHtml", "<h3>Title!</h3>" + Environment.NewLine + new string(' ', 100) + "<p>Content!</p>"}
};
JsonArrayPool arrayPool = new JsonArrayPool();
StringWriter sw = new StringWriter();
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.ArrayPool = arrayPool;
o.WriteTo(writer);
}
string result = o.ToString();
StringAssert.AreEqual(@"{
""BodyHtml"": ""<h3>Title!</h3>\r\n <p>Content!</p>""
}", result);
}
#endif
[Test]
public void NewLine()
{
MemoryStream ms = new MemoryStream();
using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" })
using (var jsonWriter = new JsonTextWriter(streamWriter)
{
CloseOutput = true,
Indentation = 2,
Formatting = Formatting.Indented
})
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("prop");
jsonWriter.WriteValue(true);
jsonWriter.WriteEndObject();
}
byte[] data = ms.ToArray();
string json = Encoding.UTF8.GetString(data, 0, data.Length);
Assert.AreEqual(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json);
}
[Test]
public void QuoteNameAndStrings()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false };
writer.WriteStartObject();
writer.WritePropertyName("name");
writer.WriteValue("value");
writer.WriteEndObject();
writer.Flush();
Assert.AreEqual(@"{name:""value""}", sb.ToString());
}
[Test]
public void CloseOutput()
{
MemoryStream ms = new MemoryStream();
JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms));
Assert.IsTrue(ms.CanRead);
writer.Close();
Assert.IsFalse(ms.CanRead);
ms = new MemoryStream();
writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false };
Assert.IsTrue(ms.CanRead);
writer.Close();
Assert.IsTrue(ms.CanRead);
}
#if !(PORTABLE) || NETSTANDARD2_0
[Test]
public void WriteIConvertable()
{
var sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(new ConvertibleInt(1));
Assert.AreEqual("1", sw.ToString());
}
#endif
[Test]
public void ValueFormatting()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue('@');
jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
jsonWriter.WriteValue(true);
jsonWriter.WriteValue(10);
jsonWriter.WriteValue(10.99);
jsonWriter.WriteValue(0.99);
jsonWriter.WriteValue(0.000000000000000001d);
jsonWriter.WriteValue(0.000000000000000001m);
jsonWriter.WriteValue((string)null);
jsonWriter.WriteValue((object)null);
jsonWriter.WriteValue("This is a string.");
jsonWriter.WriteNull();
jsonWriter.WriteUndefined();
jsonWriter.WriteEndArray();
}
string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]";
string result = sb.ToString();
Assert.AreEqual(expected, result);
}
[Test]
public void NullableValueFormatting()
{
StringWriter sw = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue((char?)null);
jsonWriter.WriteValue((char?)'c');
jsonWriter.WriteValue((bool?)null);
jsonWriter.WriteValue((bool?)true);
jsonWriter.WriteValue((byte?)null);
jsonWriter.WriteValue((byte?)1);
jsonWriter.WriteValue((sbyte?)null);
jsonWriter.WriteValue((sbyte?)1);
jsonWriter.WriteValue((short?)null);
jsonWriter.WriteValue((short?)1);
jsonWriter.WriteValue((ushort?)null);
jsonWriter.WriteValue((ushort?)1);
jsonWriter.WriteValue((int?)null);
jsonWriter.WriteValue((int?)1);
jsonWriter.WriteValue((uint?)null);
jsonWriter.WriteValue((uint?)1);
jsonWriter.WriteValue((long?)null);
jsonWriter.WriteValue((long?)1);
jsonWriter.WriteValue((ulong?)null);
jsonWriter.WriteValue((ulong?)1);
jsonWriter.WriteValue((double?)null);
jsonWriter.WriteValue((double?)1.1);
jsonWriter.WriteValue((float?)null);
jsonWriter.WriteValue((float?)1.1);
jsonWriter.WriteValue((decimal?)null);
jsonWriter.WriteValue((decimal?)1.1m);
jsonWriter.WriteValue((DateTime?)null);
jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc));
#if !NET20
jsonWriter.WriteValue((DateTimeOffset?)null);
jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero));
#endif
jsonWriter.WriteEndArray();
}
string json = sw.ToString();
string expected;
#if !NET20
expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]";
#else
expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]";
#endif
Assert.AreEqual(expected, json);
}
[Test]
public void WriteValueObjectWithNullable()
{
StringWriter sw = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
char? value = 'c';
jsonWriter.WriteStartArray();
jsonWriter.WriteValue((object)value);
jsonWriter.WriteEndArray();
}
string json = sw.ToString();
string expected = @"[""c""]";
Assert.AreEqual(expected, json);
}
[Test]
public void WriteValueObjectWithUnsupportedValue()
{
ExceptionAssert.Throws<JsonWriterException>(() =>
{
StringWriter sw = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(new Version(1, 1, 1, 1));
jsonWriter.WriteEndArray();
}
}, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''.");
}
[Test]
public void StringEscaping()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(@"""These pretzels are making me thirsty!""");
jsonWriter.WriteValue("Jeff's house was burninated.");
jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club.");
jsonWriter.WriteValue("35% of\t statistics\n are made\r up.");
jsonWriter.WriteEndArray();
}
string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]";
string result = sb.ToString();
Assert.AreEqual(expected, result);
}
[Test]
public void WriteEnd()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("CPU");
jsonWriter.WriteValue("Intel");
jsonWriter.WritePropertyName("PSU");
jsonWriter.WriteValue("500W");
jsonWriter.WritePropertyName("Drives");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue("DVD read/writer");
jsonWriter.WriteComment("(broken)");
jsonWriter.WriteValue("500 gigabyte hard drive");
jsonWriter.WriteValue("200 gigabyte hard drive");
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
}
string expected = @"{
""CPU"": ""Intel"",
""PSU"": ""500W"",
""Drives"": [
""DVD read/writer""
/*(broken)*/,
""500 gigabyte hard drive"",
""200 gigabyte hard drive""
]
}";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void CloseWithRemainingContent()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("CPU");
jsonWriter.WriteValue("Intel");
jsonWriter.WritePropertyName("PSU");
jsonWriter.WriteValue("500W");
jsonWriter.WritePropertyName("Drives");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue("DVD read/writer");
jsonWriter.WriteComment("(broken)");
jsonWriter.WriteValue("500 gigabyte hard drive");
jsonWriter.WriteValue("200 gigabyte hard drive");
jsonWriter.Close();
}
string expected = @"{
""CPU"": ""Intel"",
""PSU"": ""500W"",
""Drives"": [
""DVD read/writer""
/*(broken)*/,
""500 gigabyte hard drive"",
""200 gigabyte hard drive""
]
}";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void Indenting()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("CPU");
jsonWriter.WriteValue("Intel");
jsonWriter.WritePropertyName("PSU");
jsonWriter.WriteValue("500W");
jsonWriter.WritePropertyName("Drives");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue("DVD read/writer");
jsonWriter.WriteComment("(broken)");
jsonWriter.WriteValue("500 gigabyte hard drive");
jsonWriter.WriteValue("200 gigabyte hard drive");
jsonWriter.WriteEnd();
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
}
// {
// "CPU": "Intel",
// "PSU": "500W",
// "Drives": [
// "DVD read/writer"
// /*(broken)*/,
// "500 gigabyte hard drive",
// "200 gigabyte hard drive"
// ]
// }
string expected = @"{
""CPU"": ""Intel"",
""PSU"": ""500W"",
""Drives"": [
""DVD read/writer""
/*(broken)*/,
""500 gigabyte hard drive"",
""200 gigabyte hard drive""
]
}";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void State()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
jsonWriter.WriteStartObject();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual("", jsonWriter.Path);
jsonWriter.WritePropertyName("CPU");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual("CPU", jsonWriter.Path);
jsonWriter.WriteValue("Intel");
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual("CPU", jsonWriter.Path);
jsonWriter.WritePropertyName("Drives");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual("Drives", jsonWriter.Path);
jsonWriter.WriteStartArray();
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual("Drives[0]", jsonWriter.Path);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual("Drives", jsonWriter.Path);
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
Assert.AreEqual("", jsonWriter.Path);
}
}
[Test]
public void FloatingPointNonFiniteNumbers_Symbol()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteEndArray();
jsonWriter.Flush();
}
string expected = @"[
NaN,
Infinity,
-Infinity,
NaN,
Infinity,
-Infinity
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void FloatingPointNonFiniteNumbers_Zero()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteValue((double?)double.NaN);
jsonWriter.WriteValue((double?)double.PositiveInfinity);
jsonWriter.WriteValue((double?)double.NegativeInfinity);
jsonWriter.WriteValue((float?)float.NaN);
jsonWriter.WriteValue((float?)float.PositiveInfinity);
jsonWriter.WriteValue((float?)float.NegativeInfinity);
jsonWriter.WriteEndArray();
jsonWriter.Flush();
}
string expected = @"[
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
null,
null,
null,
null,
null,
null
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void FloatingPointNonFiniteNumbers_String()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.String;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteEndArray();
jsonWriter.Flush();
}
string expected = @"[
""NaN"",
""Infinity"",
""-Infinity"",
""NaN"",
""Infinity"",
""-Infinity""
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void FloatingPointNonFiniteNumbers_QuoteChar()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.String;
jsonWriter.QuoteChar = '\'';
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteEndArray();
jsonWriter.Flush();
}
string expected = @"[
'NaN',
'Infinity',
'-Infinity',
'NaN',
'Infinity',
'-Infinity'
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void WriteRawInStart()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
jsonWriter.WriteRaw("[1,2,3,4,5]");
jsonWriter.WriteWhitespace(" ");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteEndArray();
}
string expected = @"[1,2,3,4,5] [
NaN
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void WriteRawInArray()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteRaw(",[1,2,3,4,5]");
jsonWriter.WriteRaw(",[1,2,3,4,5]");
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteEndArray();
}
string expected = @"[
NaN,[1,2,3,4,5],[1,2,3,4,5],
NaN
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void WriteRawInObject()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]");
jsonWriter.WriteEnd();
}
string expected = @"{""PropertyName"":[1,2,3,4,5]}";
string result = sb.ToString();
Assert.AreEqual(expected, result);
}
[Test]
public void WriteToken()
{
JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]"));
reader.Read();
reader.Read();
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteToken(reader);
Assert.AreEqual("1", sw.ToString());
}
[Test]
public void WriteRawValue()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
int i = 0;
string rawJson = "[1,2]";
jsonWriter.WriteStartObject();
while (i < 3)
{
jsonWriter.WritePropertyName("d" + i);
jsonWriter.WriteRawValue(rawJson);
i++;
}
jsonWriter.WriteEndObject();
}
Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString());
}
[Test]
public void WriteObjectNestedInConstructor()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("con");
jsonWriter.WriteStartConstructor("Ext.data.JsonStore");
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("aa");
jsonWriter.WriteValue("aa");
jsonWriter.WriteEndObject();
jsonWriter.WriteEndConstructor();
jsonWriter.WriteEndObject();
}
Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString());
}
[Test]
public void WriteFloatingPointNumber()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(0.0);
jsonWriter.WriteValue(0f);
jsonWriter.WriteValue(0.1);
jsonWriter.WriteValue(1.0);
jsonWriter.WriteValue(1.000001);
jsonWriter.WriteValue(0.000001);
jsonWriter.WriteValue(double.Epsilon);
jsonWriter.WriteValue(double.PositiveInfinity);
jsonWriter.WriteValue(double.NegativeInfinity);
jsonWriter.WriteValue(double.NaN);
jsonWriter.WriteValue(double.MaxValue);
jsonWriter.WriteValue(double.MinValue);
jsonWriter.WriteValue(float.PositiveInfinity);
jsonWriter.WriteValue(float.NegativeInfinity);
jsonWriter.WriteValue(float.NaN);
jsonWriter.WriteEndArray();
}
#if !(NETSTANDARD2_0 || NETSTANDARD1_3)
Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString());
#else
Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,5E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString());
#endif
}
[Test]
public void WriteIntegerNumber()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented })
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(int.MaxValue);
jsonWriter.WriteValue(int.MinValue);
jsonWriter.WriteValue(0);
jsonWriter.WriteValue(-0);
jsonWriter.WriteValue(9L);
jsonWriter.WriteValue(9UL);
jsonWriter.WriteValue(long.MaxValue);
jsonWriter.WriteValue(long.MinValue);
jsonWriter.WriteValue(ulong.MaxValue);
jsonWriter.WriteValue(ulong.MinValue);
jsonWriter.WriteValue((ulong)uint.MaxValue - 1);
jsonWriter.WriteValue((ulong)uint.MaxValue);
jsonWriter.WriteValue((ulong)uint.MaxValue + 1);
jsonWriter.WriteEndArray();
}
Console.WriteLine(sb.ToString());
StringAssert.AreEqual(@"[
2147483647,
-2147483648,
0,
0,
9,
9,
9223372036854775807,
-9223372036854775808,
18446744073709551615,
0,
4294967294,
4294967295,
4294967296
]", sb.ToString());
}
[Test]
public void WriteTokenDirect()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteToken(JsonToken.StartArray);
jsonWriter.WriteToken(JsonToken.Integer, 1);
jsonWriter.WriteToken(JsonToken.StartObject);
jsonWriter.WriteToken(JsonToken.PropertyName, "integer");
jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue);
jsonWriter.WriteToken(JsonToken.PropertyName, "null-string");
jsonWriter.WriteToken(JsonToken.String, null);
jsonWriter.WriteToken(JsonToken.EndObject);
jsonWriter.WriteToken(JsonToken.EndArray);
}
Assert.AreEqual(@"[1,{""integer"":2147483647,""null-string"":null}]", sb.ToString());
}
[Test]
public void WriteTokenDirect_BadValue()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteToken(JsonToken.StartArray);
ExceptionAssert.Throws<FormatException>(() => { jsonWriter.WriteToken(JsonToken.Integer, "three"); }, "Input string was not in a correct format.");
ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(JsonToken.Integer); }, @"Value cannot be null.
Parameter name: value", "Value cannot be null. (Parameter 'value')");
}
}
[Test]
public void WriteTokenNullCheck()
{
using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter()))
{
ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null); });
ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null, true); });
}
}
[Test]
public void TokenTypeOutOfRange()
{
using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter()))
{
ArgumentOutOfRangeException ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue));
Assert.AreEqual("token", ex.ParamName);
ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue, "test"));
Assert.AreEqual("token", ex.ParamName);
}
}
[Test]
public void BadWriteEndArray()
{
ExceptionAssert.Throws<JsonWriterException>(() =>
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(0.0);
jsonWriter.WriteEndArray();
jsonWriter.WriteEndArray();
}
}, "No token to close. Path ''.");
}
[Test]
public void InvalidQuoteChar()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.QuoteChar = '*';
}
}, @"Invalid JavaScript string quote character. Valid quote characters are ' and "".");
}
[Test]
public void Indentation()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol;
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
jsonWriter.Indentation = 5;
Assert.AreEqual(5, jsonWriter.Indentation);
jsonWriter.IndentChar = '_';
Assert.AreEqual('_', jsonWriter.IndentChar);
jsonWriter.QuoteName = true;
Assert.AreEqual(true, jsonWriter.QuoteName);
jsonWriter.QuoteChar = '\'';
Assert.AreEqual('\'', jsonWriter.QuoteChar);
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("propertyName");
jsonWriter.WriteValue(double.NaN);
jsonWriter.IndentChar = '?';
Assert.AreEqual('?', jsonWriter.IndentChar);
jsonWriter.Indentation = 6;
Assert.AreEqual(6, jsonWriter.Indentation);
jsonWriter.WritePropertyName("prop2");
jsonWriter.WriteValue(123);
jsonWriter.WriteEndObject();
}
string expected = @"{
_____'propertyName': NaN,
??????'prop2': 123
}";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void WriteSingleBytes()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string text = "Hello world.";
byte[] data = Encoding.UTF8.GetBytes(text);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
jsonWriter.WriteValue(data);
}
string expected = @"""SGVsbG8gd29ybGQu""";
string result = sb.ToString();
Assert.AreEqual(expected, result);
byte[] d2 = Convert.FromBase64String(result.Trim('"'));
Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length));
}
[Test]
public void WriteBytesInArray()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string text = "Hello world.";
byte[] data = Encoding.UTF8.GetBytes(text);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(data);
jsonWriter.WriteValue(data);
jsonWriter.WriteValue((object)data);
jsonWriter.WriteValue((byte[])null);
jsonWriter.WriteValue((Uri)null);
jsonWriter.WriteEndArray();
}
string expected = @"[
""SGVsbG8gd29ybGQu"",
""SGVsbG8gd29ybGQu"",
""SGVsbG8gd29ybGQu"",
null,
null
]";
string result = sb.ToString();
StringAssert.AreEqual(expected, result);
}
[Test]
public void Path()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string text = "Hello world.";
byte[] data = Encoding.UTF8.GetBytes(text);
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartArray();
Assert.AreEqual("", writer.Path);
writer.WriteStartObject();
Assert.AreEqual("[0]", writer.Path);
writer.WritePropertyName("Property1");
Assert.AreEqual("[0].Property1", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[0].Property1", writer.Path);
writer.WriteValue(1);
Assert.AreEqual("[0].Property1[0]", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[0].Property1[1]", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[0].Property1[1][0]", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[0].Property1[1][0][0]", writer.Path);
writer.WriteEndObject();
Assert.AreEqual("[0]", writer.Path);
writer.WriteStartObject();
Assert.AreEqual("[1]", writer.Path);
writer.WritePropertyName("Property2");
Assert.AreEqual("[1].Property2", writer.Path);
writer.WriteStartConstructor("Constructor1");
Assert.AreEqual("[1].Property2", writer.Path);
writer.WriteNull();
Assert.AreEqual("[1].Property2[0]", writer.Path);
writer.WriteStartArray();
Assert.AreEqual("[1].Property2[1]", writer.Path);
writer.WriteValue(1);
Assert.AreEqual("[1].Property2[1][0]", writer.Path);
writer.WriteEnd();
Assert.AreEqual("[1].Property2[1]", writer.Path);
writer.WriteEndObject();
Assert.AreEqual("[1]", writer.Path);
writer.WriteEndArray();
Assert.AreEqual("", writer.Path);
}
StringAssert.AreEqual(@"[
{
""Property1"": [
1,
[
[
[]
]
]
]
},
{
""Property2"": new Constructor1(
null,
[
1
]
)
}
]", sb.ToString());
}
[Test]
public void BuildStateArray()
{
JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray();
var valueStates = JsonWriter.StateArrayTemplate[7];
foreach (JsonToken valueToken in GetValues(typeof(JsonToken)))
{
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:
Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states.");
break;
}
}
}
private static IList<object> GetValues(Type enumType)
{
if (!enumType.IsEnum())
{
throw new ArgumentException("Type {0} is not an enum.".FormatWith(CultureInfo.InvariantCulture, enumType.Name), nameof(enumType));
}
List<object> values = new List<object>();
foreach (FieldInfo field in enumType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
object value = field.GetValue(enumType);
values.Add(value);
}
return values;
}
[Test]
public void DateTimeZoneHandling()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
};
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));
Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString());
}
[Test]
public void HtmlStringEscapeHandling()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
string script = @"<script type=""text/javascript"">alert('hi');</script>";
writer.WriteValue(script);
string json = sw.ToString();
Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json);
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.AreEqual(script, reader.ReadAsString());
}
[Test]
public void NonAsciiStringEscapeHandling()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
string unicode = "\u5f20";
writer.WriteValue(unicode);
string json = sw.ToString();
Assert.AreEqual(8, json.Length);
Assert.AreEqual(@"""\u5f20""", json);
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.AreEqual(unicode, reader.ReadAsString());
sw = new StringWriter();
writer = new JsonTextWriter(sw)
{
StringEscapeHandling = StringEscapeHandling.Default
};
writer.WriteValue(unicode);
json = sw.ToString();
Assert.AreEqual(3, json.Length);
Assert.AreEqual("\"\u5f20\"", json);
}
[Test]
public void WriteEndOnProperty()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.QuoteChar = '\'';
writer.WriteStartObject();
writer.WritePropertyName("Blah");
writer.WriteEnd();
Assert.AreEqual("{'Blah':null}", sw.ToString());
}
[Test]
public void WriteEndOnProperty_Close()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.QuoteChar = '\'';
writer.WriteStartObject();
writer.WritePropertyName("Blah");
writer.Close();
Assert.AreEqual("{'Blah':null}", sw.ToString());
}
[Test]
public void WriteEndOnProperty_Dispose()
{
StringWriter sw = new StringWriter();
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.QuoteChar = '\'';
writer.WriteStartObject();
writer.WritePropertyName("Blah");
}
Assert.AreEqual("{'Blah':null}", sw.ToString());
}
[Test]
public void AutoCompleteOnClose_False()
{
StringWriter sw = new StringWriter();
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.AutoCompleteOnClose = false;
writer.QuoteChar = '\'';
writer.WriteStartObject();
writer.WritePropertyName("Blah");
}
Assert.AreEqual("{'Blah':", sw.ToString());
}
#if !NET20
[Test]
public void QuoteChar()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.Formatting = Formatting.Indented;
writer.QuoteChar = '\'';
writer.WriteStartArray();
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
writer.DateFormatString = "yyyy gg";
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
writer.WriteValue(new byte[] { 1, 2, 3 });
writer.WriteValue(TimeSpan.Zero);
writer.WriteValue(new Uri("http://www.google.com/"));
writer.WriteValue(Guid.Empty);
writer.WriteEnd();
StringAssert.AreEqual(@"[
'2000-01-01T01:01:01Z',
'2000-01-01T01:01:01+00:00',
'\/Date(946688461000)\/',
'\/Date(946688461000+0000)\/',
'2000 A.D.',
'2000 A.D.',
'AQID',
'00:00:00',
'http://www.google.com/',
'00000000-0000-0000-0000-000000000000'
]", sw.ToString());
}
[Test]
public void Culture()
{
CultureInfo culture = new CultureInfo("en-NZ");
culture.DateTimeFormat.AMDesignator = "a.m.";
culture.DateTimeFormat.PMDesignator = "p.m.";
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.Formatting = Formatting.Indented;
writer.DateFormatString = "yyyy tt";
writer.Culture = culture;
writer.QuoteChar = '\'';
writer.WriteStartArray();
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc));
writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
writer.WriteEnd();
StringAssert.AreEqual(@"[
'2000 a.m.',
'2000 a.m.'
]", sw.ToString());
}
#endif
[Test]
public void CompareNewStringEscapingWithOld()
{
char c = (char)0;
do
{
StringWriter swNew = new StringWriter();
char[] buffer = null;
JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
StringWriter swOld = new StringWriter();
WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true);
string newText = swNew.ToString();
string oldText = swOld.ToString();
if (newText != oldText)
{
throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText));
}
c++;
} while (c != char.MaxValue);
}
private const string EscapedUnicodeText = "!";
private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters)
{
// leading delimiter
if (appendDelimiters)
{
writer.Write(delimiter);
}
if (s != null)
{
char[] chars = null;
char[] unicodeBuffer = null;
int lastWritePosition = 0;
for (int i = 0; i < s.Length; i++)
{
var c = s[i];
// don't escape standard text/numbers except '\' and the text delimiter
if (c >= ' ' && c < 128 && c != '\\' && c != delimiter)
{
continue;
}
string escapedValue;
switch (c)
{
case '\t':
escapedValue = @"\t";
break;
case '\n':
escapedValue = @"\n";
break;
case '\r':
escapedValue = @"\r";
break;
case '\f':
escapedValue = @"\f";
break;
case '\b':
escapedValue = @"\b";
break;
case '\\':
escapedValue = @"\\";
break;
case '\u0085': // Next Line
escapedValue = @"\u0085";
break;
case '\u2028': // Line Separator
escapedValue = @"\u2028";
break;
case '\u2029': // Paragraph Separator
escapedValue = @"\u2029";
break;
case '\'':
// this charater is being used as the delimiter
escapedValue = @"\'";
break;
case '"':
// this charater is being used as the delimiter
escapedValue = "\\\"";
break;
default:
if (c <= '\u001f')
{
if (unicodeBuffer == null)
{
unicodeBuffer = new char[6];
}
StringUtils.ToCharAsUnicode(c, unicodeBuffer);
// slightly hacky but it saves multiple conditions in if test
escapedValue = EscapedUnicodeText;
}
else
{
escapedValue = null;
}
break;
}
if (escapedValue == null)
{
continue;
}
if (i > lastWritePosition)
{
if (chars == null)
{
chars = s.ToCharArray();
}
// write unchanged chars before writing escaped text
writer.Write(chars, lastWritePosition, i - lastWritePosition);
}
lastWritePosition = i + 1;
if (!string.Equals(escapedValue, EscapedUnicodeText))
{
writer.Write(escapedValue);
}
else
{
writer.Write(unicodeBuffer);
}
}
if (lastWritePosition == 0)
{
// no escaped text, write entire string
writer.Write(s);
}
else
{
if (chars == null)
{
chars = s.ToCharArray();
}
// write remaining text
writer.Write(chars, lastWritePosition, s.Length - lastWritePosition);
}
}
// trailing delimiter
if (appendDelimiters)
{
writer.Write(delimiter);
}
}
[Test]
public void CustomJsonTextWriterTests()
{
StringWriter sw = new StringWriter();
CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented };
writer.WriteStartObject();
Assert.AreEqual(WriteState.Object, writer.WriteState);
writer.WritePropertyName("Property1");
Assert.AreEqual(WriteState.Property, writer.WriteState);
Assert.AreEqual("Property1", writer.Path);
writer.WriteNull();
Assert.AreEqual(WriteState.Object, writer.WriteState);
writer.WriteEndObject();
Assert.AreEqual(WriteState.Start, writer.WriteState);
StringAssert.AreEqual(@"{{{
""1ytreporP"": NULL!!!
}}}", sw.ToString());
}
[Test]
public void QuoteDictionaryNames()
{
var d = new Dictionary<string, int>
{
{ "a", 1 },
};
var jsonSerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
};
var serializer = JsonSerializer.Create(jsonSerializerSettings);
using (var stringWriter = new StringWriter())
{
using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false })
{
serializer.Serialize(writer, d);
writer.Close();
}
StringAssert.AreEqual(@"{
a: 1
}", stringWriter.ToString());
}
}
[Test]
public void WriteComments()
{
string json = @"//comment*//*hi*/
{//comment
Name://comment
true//comment after true" + StringUtils.CarriageReturn + @"
,//comment after comma" + StringUtils.CarriageReturnLineFeed + @"
""ExpiryDate""://comment" + StringUtils.LineFeed + @"
new
" + StringUtils.LineFeed +
@"Constructor
(//comment
null//comment
),
""Price"": 3.99,
""Sizes"": //comment
[//comment
""Small""//comment
]//comment
}//comment
//comment 1 ";
JsonTextReader r = new JsonTextReader(new StringReader(json));
StringWriter sw = new StringWriter();
JsonTextWriter w = new JsonTextWriter(sw);
w.Formatting = Formatting.Indented;
w.WriteToken(r, true);
StringAssert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/
""Name"": /*comment*/ true/*comment after true*//*comment after comma*/,
""ExpiryDate"": /*comment*/ new Constructor(
/*comment*/,
null
/*comment*/
),
""Price"": 3.99,
""Sizes"": /*comment*/ [
/*comment*/
""Small""
/*comment*/
]/*comment*/
}/*comment *//*comment 1 */", sw.ToString());
}
[Test]
public void DisposeSupressesFinalization()
{
UnmanagedResourceFakingJsonWriter.CreateAndDispose();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.AreEqual(1, UnmanagedResourceFakingJsonWriter.DisposalCalls);
}
}
public class CustomJsonTextWriter : JsonTextWriter
{
protected readonly TextWriter _writer;
public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter)
{
_writer = textWriter;
}
public override void WritePropertyName(string name)
{
WritePropertyName(name, true);
}
public override void WritePropertyName(string name, bool escape)
{
SetWriteState(JsonToken.PropertyName, name);
if (QuoteName)
{
_writer.Write(QuoteChar);
}
_writer.Write(new string(name.ToCharArray().Reverse().ToArray()));
if (QuoteName)
{
_writer.Write(QuoteChar);
}
_writer.Write(':');
}
public override void WriteNull()
{
SetWriteState(JsonToken.Null, null);
_writer.Write("NULL!!!");
}
public override void WriteStartObject()
{
SetWriteState(JsonToken.StartObject, null);
_writer.Write("{{{");
}
public override void WriteEndObject()
{
SetWriteState(JsonToken.EndObject, null);
}
protected override void WriteEnd(JsonToken token)
{
if (token == JsonToken.EndObject)
{
_writer.Write("}}}");
}
else
{
base.WriteEnd(token);
}
}
}
public class UnmanagedResourceFakingJsonWriter : JsonWriter
{
public static int DisposalCalls;
public static void CreateAndDispose()
{
((IDisposable)new UnmanagedResourceFakingJsonWriter()).Dispose();
}
public UnmanagedResourceFakingJsonWriter()
{
DisposalCalls = 0;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
++DisposalCalls;
}
~UnmanagedResourceFakingJsonWriter()
{
Dispose(false);
}
public override void Flush()
{
throw new NotImplementedException();
}
}
}
| |
/********************************************************************
*
* PropertyBag.cs
* --------------
* Derived from PropertyBag.cs by Tony Allowatt
* CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp
* Last Update: 04/05/2005
*
********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Design;
using System.Reflection;
using CslaGenerator.Attributes;
using CslaGenerator.Metadata;
namespace CslaGenerator.Util.PropertyBags
{
/// <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 RuleBag : ICustomTypeDescriptor
{
#region PropertySpecCollection class definition
/// <summary>
/// Encapsulates a collection of PropertySpec objects.
/// </summary>
[Serializable]
public class PropertySpecCollection : IList
{
private readonly ArrayList _innerArray;
/// <summary>
/// Initializes a new instance of the PropertySpecCollection class.
/// </summary>
public PropertySpecCollection()
{
_innerArray = new ArrayList();
}
/// <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; }
}
#region IList Members
/// <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>
/// Removes all elements from the PropertySpecCollection.
/// </summary>
public void Clear()
{
_innerArray.Clear();
}
/// <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>
/// 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);
}
#endregion
/// <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>
/// 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>
/// 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)
if (spec.TargetProperty == 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>
/// 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 this[index]; }
set { 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
private class PropertySpecDescriptor : PropertyDescriptor
{
private readonly RuleBag _bag;
private readonly PropertySpec _item;
public PropertySpecDescriptor(PropertySpec item, RuleBag bag, string name, Attribute[] attrs)
:
base(name, attrs)
{
_bag = bag;
_item = item;
}
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); }
}
public override bool CanResetValue(object component)
{
if (_item.DefaultValue == null)
return false;
return !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.
var 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.
var e = new PropertySpecEventArgs(_item, value);
_bag.OnSetValue(e);
}
public override bool ShouldSerializeValue(object component)
{
object val = GetValue(component);
if (_item.DefaultValue == null && val == null)
return false;
return !val.Equals(_item.DefaultValue);
}
}
#endregion
#region Properties and Events
private readonly PropertySpecCollection _properties;
private string _defaultProperty;
private Rule[] _selectedObject;
/// <summary>
/// Initializes a new instance of the RuleBag class.
/// </summary>
public RuleBag()
{
_defaultProperty = null;
_properties = new PropertySpecCollection();
}
public RuleBag(Rule obj) : this(new[] {obj})
{
}
public RuleBag(Rule[] obj)
{
_defaultProperty = "Name";
_properties = new PropertySpecCollection();
_selectedObject = obj;
InitPropertyBag();
}
/// <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 or sets the name of the default property in the collection.
/// </summary>
public Rule[] SelectedObject
{
get { return _selectedObject; }
set
{
_selectedObject = value;
InitPropertyBag();
}
}
/// <summary>
/// Gets the collection of properties contained within this RuleBag.
/// </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;
/// <summary>
/// Raises the GetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnGetValue(PropertySpecEventArgs e)
{
if (e.Value != null)
GetValue(this, e);
e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue);
}
/// <summary>
/// Raises the SetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnSetValue(PropertySpecEventArgs e)
{
if (SetValue != null)
SetValue(this, e);
SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value);
}
#endregion
#region Initialize Propertybag
private void InitPropertyBag()
{
PropertyInfo pi;
Type t = typeof (Rule); // _selectedObject.GetType();
PropertyInfo[] props = t.GetProperties();
// Display information for all properties.
for (int i = 0; i < props.Length; i++)
{
pi = props[i];
object[] myAttributes = pi.GetCustomAttributes(true);
string category = "";
string description = "";
bool isreadonly = false;
bool isbrowsable = true;
object defaultvalue = null;
string userfriendlyname = "";
string typeconverter = "";
string designertypename = "";
string helptopic = "";
bool bindable = true;
string editor = "";
for (int n = 0; n < myAttributes.Length; n++)
{
var a = (Attribute) myAttributes[n];
switch (a.GetType().ToString())
{
case "System.ComponentModel.CategoryAttribute":
category = ((CategoryAttribute) a).Category;
break;
case "System.ComponentModel.DescriptionAttribute":
description = ((DescriptionAttribute) a).Description;
break;
case "System.ComponentModel.ReadOnlyAttribute":
isreadonly = ((ReadOnlyAttribute) a).IsReadOnly;
break;
case "System.ComponentModel.BrowsableAttribute":
isbrowsable = ((BrowsableAttribute) a).Browsable;
break;
case "System.ComponentModel.DefaultValueAttribute":
defaultvalue = ((DefaultValueAttribute) a).Value;
break;
case "CslaGenerator.Attributes.UserFriendlyNameAttribute":
userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName;
break;
case "CslaGenerator.Attributes.HelpTopicAttribute":
helptopic = ((HelpTopicAttribute) a).HelpTopic;
break;
case "System.ComponentModel.TypeConverterAttribute":
typeconverter = ((TypeConverterAttribute) a).ConverterTypeName;
break;
case "System.ComponentModel.DesignerAttribute":
designertypename = ((DesignerAttribute) a).DesignerTypeName;
break;
case "System.ComponentModel.BindableAttribute":
bindable = ((BindableAttribute) a).Bindable;
break;
case "System.ComponentModel.EditorAttribute":
editor = ((EditorAttribute) a).EditorTypeName;
break;
}
}
userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : pi.Name;
var types = new List<string>();
foreach (var obj in _selectedObject)
{
if (!types.Contains(obj.Name))
types.Add(obj.Name);
}
// here get rid of ComponentName and Parent
bool isValidProperty = (pi.Name != "Properties" && pi.Name != "ComponentName" && pi.Name != "Parent");
if (isValidProperty && IsBrowsable(types.ToArray(), pi.Name))
{
// CR added missing parameters
//this.Properties.Add(new PropertySpec(userfriendlyname,pi.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, pi.Name,helptopic));
Properties.Add(new PropertySpec(userfriendlyname, pi.PropertyType.AssemblyQualifiedName, category,
description, defaultvalue, editor, typeconverter, _selectedObject,
pi.Name, helptopic, isreadonly, isbrowsable, designertypename,
bindable));
}
}
}
#endregion
private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>();
private PropertyInfo GetPropertyInfoCache(string propertyName)
{
if (!propertyInfoCache.ContainsKey(propertyName))
{
propertyInfoCache.Add(propertyName, typeof (Rule).GetProperty(propertyName));
}
return propertyInfoCache[propertyName];
}
private bool IsEnumerable(PropertyInfo prop)
{
if (prop.PropertyType == typeof (string))
return false;
Type[] interfaces = prop.PropertyType.GetInterfaces();
foreach (Type typ in interfaces)
if (typ.Name.Contains("IEnumerable"))
return true;
return false;
}
#region IsBrowsable map objecttype:propertyname -> true | false
private bool IsBrowsable(string[] objectType, string propertyName)
{
try
{
if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == Authorization.None ||
GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == Authorization.ObjectLevel) &&
(propertyName == "AllowReadRoles" ||
propertyName == "AllowWriteRoles" ||
propertyName == "DenyReadRoles" ||
propertyName == "DenyWriteRoles"))
return false;
if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName)))
return false;
return true;
}
catch //(Exception e)
{
Debug.WriteLine(objectType + ":" + propertyName);
return true;
}
}
#endregion
#region Reflection functions
private object GetField(Type t, string name, object target)
{
object obj = null;
Type tx;
FieldInfo[] fields;
//fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
fields = target.GetType().GetFields(BindingFlags.Public);
tx = target.GetType();
obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {});
return obj;
}
private object SetField(Type t, string name, object value, object target)
{
object obj;
obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value});
return obj;
}
private bool SetProperty(object obj, string propertyName, object val)
{
try
{
// get a reference to the PropertyInfo, exit if no property with that
// name
PropertyInfo pi = typeof (Rule).GetProperty(propertyName);
if (pi == null)
return false;
// convert the value to the expected type
val = Convert.ChangeType(val, pi.PropertyType);
// attempt the assignment
foreach (Rule bo in (Rule[]) obj)
pi.SetValue(bo, val, null);
return true;
}
catch
{
return false;
}
}
private object GetProperty(object obj, string propertyName, object defaultValue)
{
try
{
PropertyInfo pi = GetPropertyInfoCache(propertyName);
if (!(pi == null))
{
var objs = (Rule[]) obj;
var valueList = new ArrayList();
foreach (Rule bo in objs)
{
object value = pi.GetValue(bo, null);
if (!valueList.Contains(value))
{
valueList.Add(value);
}
}
switch (valueList.Count)
{
case 1:
return valueList[0];
default:
return string.Empty;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// if property doesn't exist or throws
return defaultValue;
}
#endregion
#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()
{
// 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);
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)
{
// Rather than passing this function on to the default TypeDescriptor,
// which would return the actual properties of RuleBag, I construct
// a list here that contains property descriptors for the elements of the
// Properties list in the bag.
var props = new ArrayList();
foreach (PropertySpec property in _properties)
{
var 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);
if (property.DefaultValue != null)
attrs.Add(new DefaultValueAttribute(property.DefaultValue));
attrs.Add(new BrowsableAttribute(property.Browsable));
attrs.Add(new ReadOnlyAttribute(property.ReadOnly));
attrs.Add(new BindableAttribute(property.Bindable));
var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute));
// Create a new property descriptor for the property item, and add
// it to the list.
var pd = new PropertySpecDescriptor(property,
this, property.Name, attrArray);
props.Add(pd);
}
// Convert the list of PropertyDescriptors to a collection that the
// ICustomTypeDescriptor can use, and return it.
var propArray = (PropertyDescriptor[]) props.ToArray(
typeof (PropertyDescriptor));
return new PropertyDescriptorCollection(propArray);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
}
| |
using System;
using System.Reflection;
using System.Text;
using QiLeYuan.Tatala.socket.to;
using QiLeYuan.Tatala.socket.util;
using QiLeYuan.Tools.debug;
/**
* This class helps TransferObject convert byte array into
* primitive type data and user-defined object.
*
* @author JimT
*/
namespace QiLeYuan.Tatala.socket.io {
public class TransferInputStream {
private byte[] buf;
private int loc;
public TransferInputStream(byte[] buf) {
this.buf = buf;
this.loc = 0;
}
public byte[] getBuf() {
return buf;
}
public void setBuf(byte[] buf) {
this.buf = buf;
}
public void readFully(byte[] b, int off, int len) {
int n = 0;
while (n < len) {
int count = read(b, off + n, len - n);
n += count;
}
}
public int read(byte[] b, int off, int len) {
Array.Copy(buf, loc, b, off, len);
loc += len;
return len;
}
public int read() {
int val = buf[loc++] & 0xff;
return val;
}
public byte readByte() {
int ch = read();
return (byte)(ch);
}
public byte[] readByteArray() {
int len = readInt();
if (len == TransferOutputStream.NULL_PLACE_HOLDER) {
return null;
}
byte[] byteArray = new byte[len];
for (int i = 0; i < len; i++) {
byteArray[i] = readByte();
}
return byteArray;
}
public bool readBoolean() {
int ch = read();
return (ch == TransferOutputStream.TRUEBYTE);
}
public short readShort() {
int ch1 = read();
int ch2 = read();
return (short)((ch1 << 8) + (ch2 << 0));
}
public char readChar() {
return (char)readShort();
}
public int readInt() {
int ch1 = read();
int ch2 = read();
int ch3 = read();
int ch4 = read();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}
public int[] readIntArray() {
int len = readInt();
if (len == TransferOutputStream.NULL_PLACE_HOLDER) {
return null;
}
int[] intArray = new int[len];
for (int i = 0; i < len; i++) {
intArray[i] = readInt();
}
return intArray;
}
public long readLong() {
byte[] b = new byte[8];
readFully(b, 0, 8);
return (((long)b[0] << 56) + ((long)(b[1] & 255) << 48)
+ ((long)(b[2] & 255) << 40) + ((long)(b[3] & 255) << 32)
+ ((long)(b[4] & 255) << 24) + ((b[5] & 255) << 16)
+ ((b[6] & 255) << 8) + ((b[7] & 255) << 0));
}
public long[] readLongArray() {
int len = readInt();
if (len == TransferOutputStream.NULL_PLACE_HOLDER) {
return null;
}
long[] longArray = new long[len];
for (int i = 0; i < len; i++) {
longArray[i] = readLong();
}
return longArray;
}
public float readFloat() {
return BitConverter.ToSingle(BitConverter.GetBytes(readInt()), 0);
}
public float[] readFloatArray() {
int len = readInt();
if (len == TransferOutputStream.NULL_PLACE_HOLDER) {
return null;
}
float[] floatArray = new float[len];
for (int i = 0; i < len; i++) {
floatArray[i] = readFloat();
}
return floatArray;
}
public double readDouble() {
return BitConverter.Int64BitsToDouble(readLong());
}
public double[] readDoubleArray() {
int len = readInt();
if (len == TransferOutputStream.NULL_PLACE_HOLDER) {
return null;
}
double[] doubleArray = new double[len];
for (int i = 0; i < len; i++) {
doubleArray[i] = readDouble();
}
return doubleArray;
}
public DateTime readDate() {
//need convert UTC long time value to local time base on 1970/01/01 00:00:00 GMT/UTC for Java
DateTime javaUtc = new DateTime(1970, 1, 1);
return new DateTime(readLong() * 10000 + javaUtc.Ticks).ToLocalTime();
}
public String readString() {
int len = readInt();
if (len == TransferOutputStream.NULL_PLACE_HOLDER) {
return null;
}
byte[] bytearr = new byte[len];
readFully(bytearr, 0, len);
String str = null;
try {
str = Encoding.UTF8.GetString(bytearr);
} catch (Exception e) {
Logging.LogError(e.ToString());
}
return str;
}
public String[] readStringArray() {
int len = readInt();
if (len == TransferOutputStream.NULL_PLACE_HOLDER) {
return null;
}
String[] strArray = new String[len];
for (int i = 0; i < len; i++) {
strArray[i] = readString();
}
return strArray;
}
public TransferObjectWrapper readWrapper() {
int len = readInt();
if (len == TransferOutputStream.NULL_PLACE_HOLDER) {
return null;
}
String wrapperClassName = readString();
len -= TransferUtil.getLengthOfString(wrapperClassName);
byte[] bytearr = new byte[len];
readFully(bytearr, 0, len);
Object retobj = null;
try {
Type type = Type.GetType(wrapperClassName);
Object instance = Activator.CreateInstance(type);
TransferInputStream tins = new TransferInputStream(bytearr);
MethodInfo method = type.GetMethod("getObjectWrapper");
retobj = method.Invoke(instance, new object[] { tins });
} catch (Exception e) {
Logging.LogError(e.ToString());
}
return (TransferObjectWrapper)retobj;
}
public bool isFinished() {
return loc >= buf.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.
////////////////////////////////////////////////////////////////////////////
//
//
//
// Purpose: This class implements a set of methods for comparing
// strings.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Reflection;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
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);
//
// 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;
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:
** ArugmentNullException 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);
}
Contract.EndContractBlock();
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:
** ArugmentNullException 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));
}
Contract.EndContractBlock();
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));
}
Contract.EndContractBlock();
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 (m_name != null)
{
InitSort(CultureInfo.GetCultureInfo(m_name));
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx) { }
///////////////////////////----- 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 unsafe 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, 0, string1.Length, string2, 0, string2.Length);
return String.CompareOrdinal(string1, string2);
}
return CompareString(string1, 0, string1.Length, string2, 0, string2.Length, options);
}
////////////////////////////////////////////////////////////////////////
//
// 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 unsafe 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);
}
if (options == CompareOptions.Ordinal)
{
return CompareOrdinal(string1, offset1, length1,
string2, offset2, length2);
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2);
return CompareOrdinal(string1, offset1, length1, string2, offset2, length2);
}
return CompareString(string1, offset1, length1,
string2, offset2, length2,
options);
}
private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
int result = String.CompareOrdinal(string1, offset1, string2, offset2,
(length1 < length2 ? length1 : length2));
if ((length1 != length2) && result == 0)
{
return (length1 > length2 ? 1 : -1);
}
return (result);
}
//
// 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 unsafe 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);
int length = Math.Min(lengthA, lengthB);
int range = length;
fixed (char* ap = strA) fixed (char* bp = strB)
{
char* a = ap + indexA;
char* b = bp + indexB;
// in InvariantMode we support all range and not only the ascii characters.
char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x80);
while (length != 0 && (*a <= maxChar) && (*b <= maxChar))
{
int charA = *a;
int charB = *b;
if (charA == charB)
{
a++; b++;
length--;
continue;
}
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
// Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
if (length == 0)
return lengthA - lengthB;
Debug.Assert(!GlobalizationMode.Invariant);
range -= length;
return CompareStringOrdinalIgnoreCase(a, lengthA - range, b, lengthB - range);
}
}
////////////////////////////////////////////////////////////////////////
//
// 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);
}
Contract.EndContractBlock();
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);
}
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);
}
Contract.EndContractBlock();
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);
}
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));
Contract.EndContractBlock();
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));
Contract.EndContractBlock();
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));
Contract.EndContractBlock();
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));
Contract.EndContractBlock();
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));
Contract.EndContractBlock();
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));
Contract.EndContractBlock();
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));
Contract.EndContractBlock();
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));
Contract.EndContractBlock();
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);
Contract.EndContractBlock();
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);
}
Contract.EndContractBlock();
// 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);
}
// 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));
Contract.EndContractBlock();
// 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));
Contract.EndContractBlock();
// 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));
Contract.EndContractBlock();
// 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));
Contract.EndContractBlock();
// 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));
Contract.EndContractBlock();
// 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));
Contract.EndContractBlock();
// 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));
}
Contract.EndContractBlock();
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 TextInfo.GetHashCodeOrdinalIgnoreCase(source);
}
//
// 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;
}
}
}
}
| |
using Bridge.Html5;
using System;
namespace Bridge.jQuery2
{
public partial class jQuery
{
/// <summary>
/// Remove from the queue all items that have not yet been run.
/// </summary>
/// <returns></returns>
public virtual jQuery ClearQueue()
{
return null;
}
/// <summary>
/// Remove from the queue all items that have not yet been run.
/// </summary>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <returns></returns>
public virtual string ClearQueue(string queueName)
{
return null;
}
/// <summary>
/// Store arbitrary data associated with the matched elements.
/// </summary>
/// <param name="key">A string naming the piece of data to set.</param>
/// <param name="value">The new data value; it can be any Javascript type including Array or Object.</param>
/// <returns></returns>
public virtual jQuery Data(string key, object value)
{
return null;
}
/// <summary>
/// Store arbitrary data associated with the matched elements.
/// </summary>
/// <param name="obj">An object of key-value pairs of data to update.</param>
/// <returns></returns>
public virtual jQuery Data(object obj)
{
return null;
}
/// <summary>
/// Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
/// </summary>
/// <param name="key">Name of the data stored.</param>
/// <returns></returns>
public virtual object Data(string key)
{
return null;
}
/// <summary>
/// Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
/// </summary>
/// <typeparam name="T">Return Type of Data object</typeparam>
/// <param name="key">Name of the data stored.</param>
/// <returns></returns>
public virtual T Data<T>(string key)
{
return default(T);
}
/// <summary>
/// Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
/// </summary>
/// <returns></returns>
public virtual object Data()
{
return null;
}
/// <summary>
/// Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
/// </summary>
/// <typeparam name="T">Return Type of Data object</typeparam>
/// <returns></returns>
public virtual T Data<T>()
{
return default(T);
}
/// <summary>
/// Execute the next function on the queue for the matched elements.
/// </summary>
/// <returns></returns>
public virtual jQuery Dequeue()
{
return null;
}
/// <summary>
/// Execute the next function on the queue for the matched elements.
/// </summary>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <returns></returns>
public virtual jQuery Dequeue(string queueName)
{
return null;
}
/// <summary>
/// Show the queue of functions to be executed on the matched elements.
/// </summary>
/// <returns></returns>
public virtual Array Queue()
{
return null;
}
/// <summary>
/// Show the queue of functions to be executed on the matched elements.
/// </summary>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <returns></returns>
public virtual Array Queue(string queueName)
{
return null;
}
/// <summary>
/// Manipulate the queue of functions to be executed, once for each matched element.
/// </summary>
/// <param name="newQueue"></param>
/// <returns></returns>
public virtual jQuery Queue(Array newQueue)
{
return null;
}
/// <summary>
/// Manipulate the queue of functions to be executed, once for each matched element.
/// </summary>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <param name="newQueue">An array of functions to replace the current queue contents.</param>
/// <returns></returns>
public virtual jQuery Queue(string queueName, Array newQueue)
{
return null;
}
/// <summary>
/// Manipulate the queue of functions to be executed, once for each matched element.
/// </summary>
/// <param name="callback">The new function to add to the queue, with a function to call that will dequeue the next item.</param>
/// <returns></returns>
public virtual jQuery Queue(Delegate callback)
{
return null;
}
/// <summary>
/// Manipulate the queue of functions to be executed, once for each matched element.
/// </summary>
/// <param name="callback">The new function to add to the queue, with a function to call that will dequeue the next item.</param>
/// <returns></returns>
public virtual jQuery Queue(Action callback)
{
return null;
}
/// <summary>
/// Manipulate the queue of functions to be executed, once for each matched element.
/// </summary>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <param name="callback">The new function to add to the queue, with a function to call that will dequeue the next item.</param>
/// <returns></returns>
public virtual jQuery Queue(string queueName, Delegate callback)
{
return null;
}
/// <summary>
/// Manipulate the queue of functions to be executed, once for each matched element.
/// </summary>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <param name="callback">The new function to add to the queue, with a function to call that will dequeue the next item.</param>
/// <returns></returns>
public virtual jQuery Queue(string queueName, Action callback)
{
return null;
}
/// <summary>
/// Remove a previously-stored piece of data.
/// </summary>
/// <returns></returns>
public virtual jQuery RemoveData()
{
return null;
}
/// <summary>
/// Remove a previously-stored piece of data.
/// </summary>
/// <param name="name">A string naming the piece of data to delete.</param>
/// <returns></returns>
public virtual jQuery RemoveData(string name)
{
return null;
}
/// <summary>
/// Remove a previously-stored piece of data.
/// </summary>
/// <param name="list">An array or space-separated string naming the pieces of data to delete.</param>
/// <returns></returns>
public virtual jQuery RemoveData(Array list)
{
return null;
}
/// <summary>
/// Store arbitrary data associated with the specified element. Returns the value that was set.
/// </summary>
/// <param name="element">The DOM element to associate with the data.</param>
/// <param name="key">A string naming the piece of data to set.</param>
/// <param name="value">The new data value.</param>
/// <returns></returns>
public static object Data(Element element, string key, object value)
{
return null;
}
/// <summary>
/// Store arbitrary data associated with the specified element. Returns the value that was set.
/// </summary>
/// <typeparam name="T">Type T of object to return</typeparam>
/// <param name="element">The DOM element to associate with the data.</param>
/// <param name="key">A string naming the piece of data to set.</param>
/// <param name="value">The new data value.</param>
/// <returns></returns>
public static T Data<T>(Element element, string key, T value)
{
return default(T);
}
/// <summary>
/// Store arbitrary data associated with the specified element. Returns the value that was set.
/// </summary>
/// <param name="element">The DOM element to associate with the data.</param>
/// <param name="key">A string naming the piece of data to set.</param>
/// <returns></returns>
public static object Data(Element element, string key)
{
return null;
}
/// <summary>
/// Store arbitrary data associated with the specified element. Returns the value that was set.
/// </summary>
/// <param name="element">The DOM element to associate with the data.</param>
/// <returns></returns>
public static object Data(Element element)
{
return null;
}
/// <summary>
/// Execute the next function on the queue for the matched element.
/// </summary>
/// <param name="element"></param>
public static void Dequeue(Element element)
{
}
/// <summary>
/// Execute the next function on the queue for the matched element.
/// </summary>
/// <param name="element"></param>
/// <param name="queueName"></param>
public static void Dequeue(Element element, string queueName)
{
}
/// <summary>
/// Determine whether an element has any jQuery data associated with it.
/// </summary>
/// <param name="element">A DOM element to be checked for data.</param>
/// <returns></returns>
public static bool HasData(Element element)
{
return false;
}
/// <summary>
/// Show the queue of functions to be executed on the matched element.
/// </summary>
/// <param name="element">A DOM element to inspect for an attached queue.</param>
/// <returns></returns>
public static Array Queue(Element element)
{
return null;
}
/// <summary>
/// Show the queue of functions to be executed on the matched element.
/// </summary>
/// <param name="element">A DOM element to inspect for an attached queue.</param>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <returns></returns>
public static Array Queue(Element element, string queueName)
{
return null;
}
/// <summary>
/// Manipulate the queue of functions to be executed on the matched element.
/// </summary>
/// <param name="element">A DOM element where the array of queued functions is attached.</param>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <param name="newQueue">An array of functions to replace the current queue contents.</param>
/// <returns></returns>
public static jQuery Queue(Element element, string queueName, Array newQueue)
{
return null;
}
/// <summary>
/// Manipulate the queue of functions to be executed on the matched element.
/// </summary>
/// <param name="element">A DOM element where the array of queued functions is attached.</param>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <param name="callback">he new function to add to the queue.</param>
/// <returns></returns>
public static jQuery Queue(Element element, string queueName, Delegate callback)
{
return null;
}
/// <summary>
/// Manipulate the queue of functions to be executed on the matched element.
/// </summary>
/// <param name="element">A DOM element where the array of queued functions is attached.</param>
/// <param name="queueName">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param>
/// <param name="callback">he new function to add to the queue.</param>
/// <returns></returns>
public static jQuery Queue(Element element, string queueName, Action callback)
{
return null;
}
/// <summary>
/// Remove a previously-stored piece of data.
/// </summary>
/// <param name="element">A DOM element from which to remove data.</param>
/// <returns></returns>
public static jQuery RemoveData(Element element)
{
return null;
}
/// <summary>
/// Remove a previously-stored piece of data.
/// </summary>
/// <param name="element">A DOM element from which to remove data.</param>
/// <param name="name">A string naming the piece of data to remove.</param>
/// <returns></returns>
public static jQuery RemoveData(Element element, string name)
{
return null;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedNetworksClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<Networks.NetworksClient> mockGrpcClient = new moq::Mock<Networks.NetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNetworkRequest request = new GetNetworkRequest
{
Project = "projectaa6ff846",
Network = "networkd22ce091",
};
Network expectedResponse = new Network
{
Id = 11672635353343658936UL,
Mtu = 1280318054,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
IPv4Range = "I_pv4_range613b129f",
Peerings =
{
new NetworkPeering(),
},
GatewayIPv4 = "gateway_i_pv47f9ce361",
AutoCreateSubnetworks = false,
Subnetworks =
{
"subnetworks81f34af0",
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
RoutingConfig = new NetworkRoutingConfig(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworksClient client = new NetworksClientImpl(mockGrpcClient.Object, null);
Network response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<Networks.NetworksClient> mockGrpcClient = new moq::Mock<Networks.NetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNetworkRequest request = new GetNetworkRequest
{
Project = "projectaa6ff846",
Network = "networkd22ce091",
};
Network expectedResponse = new Network
{
Id = 11672635353343658936UL,
Mtu = 1280318054,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
IPv4Range = "I_pv4_range613b129f",
Peerings =
{
new NetworkPeering(),
},
GatewayIPv4 = "gateway_i_pv47f9ce361",
AutoCreateSubnetworks = false,
Subnetworks =
{
"subnetworks81f34af0",
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
RoutingConfig = new NetworkRoutingConfig(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Network>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworksClient client = new NetworksClientImpl(mockGrpcClient.Object, null);
Network responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Network responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<Networks.NetworksClient> mockGrpcClient = new moq::Mock<Networks.NetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNetworkRequest request = new GetNetworkRequest
{
Project = "projectaa6ff846",
Network = "networkd22ce091",
};
Network expectedResponse = new Network
{
Id = 11672635353343658936UL,
Mtu = 1280318054,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
IPv4Range = "I_pv4_range613b129f",
Peerings =
{
new NetworkPeering(),
},
GatewayIPv4 = "gateway_i_pv47f9ce361",
AutoCreateSubnetworks = false,
Subnetworks =
{
"subnetworks81f34af0",
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
RoutingConfig = new NetworkRoutingConfig(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworksClient client = new NetworksClientImpl(mockGrpcClient.Object, null);
Network response = client.Get(request.Project, request.Network);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<Networks.NetworksClient> mockGrpcClient = new moq::Mock<Networks.NetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNetworkRequest request = new GetNetworkRequest
{
Project = "projectaa6ff846",
Network = "networkd22ce091",
};
Network expectedResponse = new Network
{
Id = 11672635353343658936UL,
Mtu = 1280318054,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
IPv4Range = "I_pv4_range613b129f",
Peerings =
{
new NetworkPeering(),
},
GatewayIPv4 = "gateway_i_pv47f9ce361",
AutoCreateSubnetworks = false,
Subnetworks =
{
"subnetworks81f34af0",
},
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
RoutingConfig = new NetworkRoutingConfig(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Network>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworksClient client = new NetworksClientImpl(mockGrpcClient.Object, null);
Network responseCallSettings = await client.GetAsync(request.Project, request.Network, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Network responseCancellationToken = await client.GetAsync(request.Project, request.Network, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEffectiveFirewallsRequestObject()
{
moq::Mock<Networks.NetworksClient> mockGrpcClient = new moq::Mock<Networks.NetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEffectiveFirewallsNetworkRequest request = new GetEffectiveFirewallsNetworkRequest
{
Project = "projectaa6ff846",
Network = "networkd22ce091",
};
NetworksGetEffectiveFirewallsResponse expectedResponse = new NetworksGetEffectiveFirewallsResponse
{
Firewalls = { new Firewall(), },
FirewallPolicys =
{
new NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy(),
},
};
mockGrpcClient.Setup(x => x.GetEffectiveFirewalls(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworksClient client = new NetworksClientImpl(mockGrpcClient.Object, null);
NetworksGetEffectiveFirewallsResponse response = client.GetEffectiveFirewalls(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEffectiveFirewallsRequestObjectAsync()
{
moq::Mock<Networks.NetworksClient> mockGrpcClient = new moq::Mock<Networks.NetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEffectiveFirewallsNetworkRequest request = new GetEffectiveFirewallsNetworkRequest
{
Project = "projectaa6ff846",
Network = "networkd22ce091",
};
NetworksGetEffectiveFirewallsResponse expectedResponse = new NetworksGetEffectiveFirewallsResponse
{
Firewalls = { new Firewall(), },
FirewallPolicys =
{
new NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy(),
},
};
mockGrpcClient.Setup(x => x.GetEffectiveFirewallsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworksGetEffectiveFirewallsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworksClient client = new NetworksClientImpl(mockGrpcClient.Object, null);
NetworksGetEffectiveFirewallsResponse responseCallSettings = await client.GetEffectiveFirewallsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
NetworksGetEffectiveFirewallsResponse responseCancellationToken = await client.GetEffectiveFirewallsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEffectiveFirewalls()
{
moq::Mock<Networks.NetworksClient> mockGrpcClient = new moq::Mock<Networks.NetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEffectiveFirewallsNetworkRequest request = new GetEffectiveFirewallsNetworkRequest
{
Project = "projectaa6ff846",
Network = "networkd22ce091",
};
NetworksGetEffectiveFirewallsResponse expectedResponse = new NetworksGetEffectiveFirewallsResponse
{
Firewalls = { new Firewall(), },
FirewallPolicys =
{
new NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy(),
},
};
mockGrpcClient.Setup(x => x.GetEffectiveFirewalls(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworksClient client = new NetworksClientImpl(mockGrpcClient.Object, null);
NetworksGetEffectiveFirewallsResponse response = client.GetEffectiveFirewalls(request.Project, request.Network);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEffectiveFirewallsAsync()
{
moq::Mock<Networks.NetworksClient> mockGrpcClient = new moq::Mock<Networks.NetworksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEffectiveFirewallsNetworkRequest request = new GetEffectiveFirewallsNetworkRequest
{
Project = "projectaa6ff846",
Network = "networkd22ce091",
};
NetworksGetEffectiveFirewallsResponse expectedResponse = new NetworksGetEffectiveFirewallsResponse
{
Firewalls = { new Firewall(), },
FirewallPolicys =
{
new NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy(),
},
};
mockGrpcClient.Setup(x => x.GetEffectiveFirewallsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworksGetEffectiveFirewallsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworksClient client = new NetworksClientImpl(mockGrpcClient.Object, null);
NetworksGetEffectiveFirewallsResponse responseCallSettings = await client.GetEffectiveFirewallsAsync(request.Project, request.Network, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
NetworksGetEffectiveFirewallsResponse responseCancellationToken = await client.GetEffectiveFirewallsAsync(request.Project, request.Network, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT!
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace DotNetty.Codecs.ProtocolBuffers {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Addressbook {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_DotNetty_Codecs_ProtocolBuffers_Person__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::DotNetty.Codecs.ProtocolBuffers.Person, global::DotNetty.Codecs.ProtocolBuffers.Person.Builder> internal__static_DotNetty_Codecs_ProtocolBuffers_Person__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_DotNetty_Codecs_ProtocolBuffers_Person_PhoneNumber__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber, global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber.Builder> internal__static_DotNetty_Codecs_ProtocolBuffers_Person_PhoneNumber__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_DotNetty_Codecs_ProtocolBuffers_AddressBook__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::DotNetty.Codecs.ProtocolBuffers.AddressBook, global::DotNetty.Codecs.ProtocolBuffers.AddressBook.Builder> internal__static_DotNetty_Codecs_ProtocolBuffers_AddressBook__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static Addressbook() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChFhZGRyZXNzYm9vay5wcm90bxIfRG90TmV0dHkuQ29kZWNzLlByb3RvY29s",
"QnVmZmVycyKIAgoGUGVyc29uEgwKBG5hbWUYASACKAkSCgoCaWQYAiACKAUS",
"DQoFZW1haWwYAyABKAkSQgoFcGhvbmUYBCADKAsyMy5Eb3ROZXR0eS5Db2Rl",
"Y3MuUHJvdG9jb2xCdWZmZXJzLlBlcnNvbi5QaG9uZU51bWJlchpkCgtQaG9u",
"ZU51bWJlchIOCgZudW1iZXIYASACKAkSRQoEdHlwZRgCIAEoDjIxLkRvdE5l",
"dHR5LkNvZGVjcy5Qcm90b2NvbEJ1ZmZlcnMuUGVyc29uLlBob25lVHlwZToE",
"SE9NRSIrCglQaG9uZVR5cGUSCgoGTU9CSUxFEAASCAoESE9NRRABEggKBFdP",
"UksQAiJGCgtBZGRyZXNzQm9vaxI3CgZwZXJzb24YASADKAsyJy5Eb3ROZXR0",
"eS5Db2RlY3MuUHJvdG9jb2xCdWZmZXJzLlBlcnNvbkICSAE="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_DotNetty_Codecs_ProtocolBuffers_Person__Descriptor = Descriptor.MessageTypes[0];
internal__static_DotNetty_Codecs_ProtocolBuffers_Person__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::DotNetty.Codecs.ProtocolBuffers.Person, global::DotNetty.Codecs.ProtocolBuffers.Person.Builder>(internal__static_DotNetty_Codecs_ProtocolBuffers_Person__Descriptor,
new string[] { "Name", "Id", "Email", "Phone", });
internal__static_DotNetty_Codecs_ProtocolBuffers_Person_PhoneNumber__Descriptor = internal__static_DotNetty_Codecs_ProtocolBuffers_Person__Descriptor.NestedTypes[0];
internal__static_DotNetty_Codecs_ProtocolBuffers_Person_PhoneNumber__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber, global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber.Builder>(internal__static_DotNetty_Codecs_ProtocolBuffers_Person_PhoneNumber__Descriptor,
new string[] { "Number", "Type", });
internal__static_DotNetty_Codecs_ProtocolBuffers_AddressBook__Descriptor = Descriptor.MessageTypes[1];
internal__static_DotNetty_Codecs_ProtocolBuffers_AddressBook__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::DotNetty.Codecs.ProtocolBuffers.AddressBook, global::DotNetty.Codecs.ProtocolBuffers.AddressBook.Builder>(internal__static_DotNetty_Codecs_ProtocolBuffers_AddressBook__Descriptor,
new string[] { "Person", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Person : pb::GeneratedMessage<Person, Person.Builder> {
private Person() { }
private static readonly Person defaultInstance = new Person().MakeReadOnly();
private static readonly string[] _personFieldNames = new string[] { "email", "id", "name", "phone" };
private static readonly uint[] _personFieldTags = new uint[] { 26, 16, 10, 34 };
public static Person DefaultInstance {
get { return defaultInstance; }
}
public override Person DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override Person ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::DotNetty.Codecs.ProtocolBuffers.Addressbook.internal__static_DotNetty_Codecs_ProtocolBuffers_Person__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<Person, Person.Builder> InternalFieldAccessors {
get { return global::DotNetty.Codecs.ProtocolBuffers.Addressbook.internal__static_DotNetty_Codecs_ProtocolBuffers_Person__FieldAccessorTable; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum PhoneType {
MOBILE = 0,
HOME = 1,
WORK = 2,
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PhoneNumber : pb::GeneratedMessage<PhoneNumber, PhoneNumber.Builder> {
private PhoneNumber() { }
private static readonly PhoneNumber defaultInstance = new PhoneNumber().MakeReadOnly();
private static readonly string[] _phoneNumberFieldNames = new string[] { "number", "type" };
private static readonly uint[] _phoneNumberFieldTags = new uint[] { 10, 16 };
public static PhoneNumber DefaultInstance {
get { return defaultInstance; }
}
public override PhoneNumber DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override PhoneNumber ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::DotNetty.Codecs.ProtocolBuffers.Addressbook.internal__static_DotNetty_Codecs_ProtocolBuffers_Person_PhoneNumber__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<PhoneNumber, PhoneNumber.Builder> InternalFieldAccessors {
get { return global::DotNetty.Codecs.ProtocolBuffers.Addressbook.internal__static_DotNetty_Codecs_ProtocolBuffers_Person_PhoneNumber__FieldAccessorTable; }
}
public const int NumberFieldNumber = 1;
private bool hasNumber;
private string number_ = "";
public bool HasNumber {
get { return hasNumber; }
}
public string Number {
get { return number_; }
}
public const int TypeFieldNumber = 2;
private bool hasType;
private global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneType type_ = global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneType.HOME;
public bool HasType {
get { return hasType; }
}
public global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneType Type {
get { return type_; }
}
public override bool IsInitialized {
get {
if (!hasNumber) return false;
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _phoneNumberFieldNames;
if (hasNumber) {
output.WriteString(1, field_names[0], Number);
}
if (hasType) {
output.WriteEnum(2, field_names[1], (int) Type, Type);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasNumber) {
size += pb::CodedOutputStream.ComputeStringSize(1, Number);
}
if (hasType) {
size += pb::CodedOutputStream.ComputeEnumSize(2, (int) Type);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static PhoneNumber ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PhoneNumber ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PhoneNumber ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PhoneNumber ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PhoneNumber ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PhoneNumber ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static PhoneNumber ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PhoneNumber ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private PhoneNumber MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(PhoneNumber prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<PhoneNumber, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(PhoneNumber cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private PhoneNumber result;
private PhoneNumber PrepareBuilder() {
if (resultIsReadOnly) {
PhoneNumber original = result;
result = new PhoneNumber();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override PhoneNumber MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber.Descriptor; }
}
public override PhoneNumber DefaultInstanceForType {
get { return global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber.DefaultInstance; }
}
public override PhoneNumber BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is PhoneNumber) {
return MergeFrom((PhoneNumber) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(PhoneNumber other) {
if (other == global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber.DefaultInstance) return this;
PrepareBuilder();
if (other.HasNumber) {
Number = other.Number;
}
if (other.HasType) {
Type = other.Type;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_phoneNumberFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _phoneNumberFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasNumber = input.ReadString(ref result.number_);
break;
}
case 16: {
object unknown;
if(input.ReadEnum(ref result.type_, out unknown)) {
result.hasType = true;
} else if(unknown is int) {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
unknownFields.MergeVarintField(2, (ulong)(int)unknown);
}
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasNumber {
get { return result.hasNumber; }
}
public string Number {
get { return result.Number; }
set { SetNumber(value); }
}
public Builder SetNumber(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasNumber = true;
result.number_ = value;
return this;
}
public Builder ClearNumber() {
PrepareBuilder();
result.hasNumber = false;
result.number_ = "";
return this;
}
public bool HasType {
get { return result.hasType; }
}
public global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneType Type {
get { return result.Type; }
set { SetType(value); }
}
public Builder SetType(global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneType value) {
PrepareBuilder();
result.hasType = true;
result.type_ = value;
return this;
}
public Builder ClearType() {
PrepareBuilder();
result.hasType = false;
result.type_ = global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneType.HOME;
return this;
}
}
static PhoneNumber() {
object.ReferenceEquals(global::DotNetty.Codecs.ProtocolBuffers.Addressbook.Descriptor, null);
}
}
}
#endregion
public const int NameFieldNumber = 1;
private bool hasName;
private string name_ = "";
public bool HasName {
get { return hasName; }
}
public string Name {
get { return name_; }
}
public const int IdFieldNumber = 2;
private bool hasId;
private int id_;
public bool HasId {
get { return hasId; }
}
public int Id {
get { return id_; }
}
public const int EmailFieldNumber = 3;
private bool hasEmail;
private string email_ = "";
public bool HasEmail {
get { return hasEmail; }
}
public string Email {
get { return email_; }
}
public const int PhoneFieldNumber = 4;
private pbc::PopsicleList<global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber> phone_ = new pbc::PopsicleList<global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber>();
public scg::IList<global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber> PhoneList {
get { return phone_; }
}
public int PhoneCount {
get { return phone_.Count; }
}
public global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber GetPhone(int index) {
return phone_[index];
}
public override bool IsInitialized {
get {
if (!hasName) return false;
if (!hasId) return false;
foreach (global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber element in PhoneList) {
if (!element.IsInitialized) return false;
}
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _personFieldNames;
if (hasName) {
output.WriteString(1, field_names[2], Name);
}
if (hasId) {
output.WriteInt32(2, field_names[1], Id);
}
if (hasEmail) {
output.WriteString(3, field_names[0], Email);
}
if (phone_.Count > 0) {
output.WriteMessageArray(4, field_names[3], phone_);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasName) {
size += pb::CodedOutputStream.ComputeStringSize(1, Name);
}
if (hasId) {
size += pb::CodedOutputStream.ComputeInt32Size(2, Id);
}
if (hasEmail) {
size += pb::CodedOutputStream.ComputeStringSize(3, Email);
}
foreach (global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber element in PhoneList) {
size += pb::CodedOutputStream.ComputeMessageSize(4, element);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static Person ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Person ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Person ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Person ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Person ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Person ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Person ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static Person ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static Person ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Person ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private Person MakeReadOnly() {
phone_.MakeReadOnly();
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(Person prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<Person, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(Person cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private Person result;
private Person PrepareBuilder() {
if (resultIsReadOnly) {
Person original = result;
result = new Person();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override Person MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::DotNetty.Codecs.ProtocolBuffers.Person.Descriptor; }
}
public override Person DefaultInstanceForType {
get { return global::DotNetty.Codecs.ProtocolBuffers.Person.DefaultInstance; }
}
public override Person BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is Person) {
return MergeFrom((Person) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(Person other) {
if (other == global::DotNetty.Codecs.ProtocolBuffers.Person.DefaultInstance) return this;
PrepareBuilder();
if (other.HasName) {
Name = other.Name;
}
if (other.HasId) {
Id = other.Id;
}
if (other.HasEmail) {
Email = other.Email;
}
if (other.phone_.Count != 0) {
result.phone_.Add(other.phone_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_personFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _personFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasName = input.ReadString(ref result.name_);
break;
}
case 16: {
result.hasId = input.ReadInt32(ref result.id_);
break;
}
case 26: {
result.hasEmail = input.ReadString(ref result.email_);
break;
}
case 34: {
input.ReadMessageArray(tag, field_name, result.phone_, global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber.DefaultInstance, extensionRegistry);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasName {
get { return result.hasName; }
}
public string Name {
get { return result.Name; }
set { SetName(value); }
}
public Builder SetName(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasName = true;
result.name_ = value;
return this;
}
public Builder ClearName() {
PrepareBuilder();
result.hasName = false;
result.name_ = "";
return this;
}
public bool HasId {
get { return result.hasId; }
}
public int Id {
get { return result.Id; }
set { SetId(value); }
}
public Builder SetId(int value) {
PrepareBuilder();
result.hasId = true;
result.id_ = value;
return this;
}
public Builder ClearId() {
PrepareBuilder();
result.hasId = false;
result.id_ = 0;
return this;
}
public bool HasEmail {
get { return result.hasEmail; }
}
public string Email {
get { return result.Email; }
set { SetEmail(value); }
}
public Builder SetEmail(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasEmail = true;
result.email_ = value;
return this;
}
public Builder ClearEmail() {
PrepareBuilder();
result.hasEmail = false;
result.email_ = "";
return this;
}
public pbc::IPopsicleList<global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber> PhoneList {
get { return PrepareBuilder().phone_; }
}
public int PhoneCount {
get { return result.PhoneCount; }
}
public global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber GetPhone(int index) {
return result.GetPhone(index);
}
public Builder SetPhone(int index, global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.phone_[index] = value;
return this;
}
public Builder SetPhone(int index, global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.phone_[index] = builderForValue.Build();
return this;
}
public Builder AddPhone(global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.phone_.Add(value);
return this;
}
public Builder AddPhone(global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.phone_.Add(builderForValue.Build());
return this;
}
public Builder AddRangePhone(scg::IEnumerable<global::DotNetty.Codecs.ProtocolBuffers.Person.Types.PhoneNumber> values) {
PrepareBuilder();
result.phone_.Add(values);
return this;
}
public Builder ClearPhone() {
PrepareBuilder();
result.phone_.Clear();
return this;
}
}
static Person() {
object.ReferenceEquals(global::DotNetty.Codecs.ProtocolBuffers.Addressbook.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class AddressBook : pb::GeneratedMessage<AddressBook, AddressBook.Builder> {
private AddressBook() { }
private static readonly AddressBook defaultInstance = new AddressBook().MakeReadOnly();
private static readonly string[] _addressBookFieldNames = new string[] { "person" };
private static readonly uint[] _addressBookFieldTags = new uint[] { 10 };
public static AddressBook DefaultInstance {
get { return defaultInstance; }
}
public override AddressBook DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override AddressBook ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::DotNetty.Codecs.ProtocolBuffers.Addressbook.internal__static_DotNetty_Codecs_ProtocolBuffers_AddressBook__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<AddressBook, AddressBook.Builder> InternalFieldAccessors {
get { return global::DotNetty.Codecs.ProtocolBuffers.Addressbook.internal__static_DotNetty_Codecs_ProtocolBuffers_AddressBook__FieldAccessorTable; }
}
public const int PersonFieldNumber = 1;
private pbc::PopsicleList<global::DotNetty.Codecs.ProtocolBuffers.Person> person_ = new pbc::PopsicleList<global::DotNetty.Codecs.ProtocolBuffers.Person>();
public scg::IList<global::DotNetty.Codecs.ProtocolBuffers.Person> PersonList {
get { return person_; }
}
public int PersonCount {
get { return person_.Count; }
}
public global::DotNetty.Codecs.ProtocolBuffers.Person GetPerson(int index) {
return person_[index];
}
public override bool IsInitialized {
get {
foreach (global::DotNetty.Codecs.ProtocolBuffers.Person element in PersonList) {
if (!element.IsInitialized) return false;
}
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _addressBookFieldNames;
if (person_.Count > 0) {
output.WriteMessageArray(1, field_names[0], person_);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
foreach (global::DotNetty.Codecs.ProtocolBuffers.Person element in PersonList) {
size += pb::CodedOutputStream.ComputeMessageSize(1, element);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static AddressBook ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static AddressBook ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static AddressBook ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static AddressBook ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static AddressBook ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static AddressBook ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static AddressBook ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static AddressBook ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private AddressBook MakeReadOnly() {
person_.MakeReadOnly();
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(AddressBook prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<AddressBook, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(AddressBook cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private AddressBook result;
private AddressBook PrepareBuilder() {
if (resultIsReadOnly) {
AddressBook original = result;
result = new AddressBook();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override AddressBook MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::DotNetty.Codecs.ProtocolBuffers.AddressBook.Descriptor; }
}
public override AddressBook DefaultInstanceForType {
get { return global::DotNetty.Codecs.ProtocolBuffers.AddressBook.DefaultInstance; }
}
public override AddressBook BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is AddressBook) {
return MergeFrom((AddressBook) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(AddressBook other) {
if (other == global::DotNetty.Codecs.ProtocolBuffers.AddressBook.DefaultInstance) return this;
PrepareBuilder();
if (other.person_.Count != 0) {
result.person_.Add(other.person_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_addressBookFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _addressBookFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
input.ReadMessageArray(tag, field_name, result.person_, global::DotNetty.Codecs.ProtocolBuffers.Person.DefaultInstance, extensionRegistry);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public pbc::IPopsicleList<global::DotNetty.Codecs.ProtocolBuffers.Person> PersonList {
get { return PrepareBuilder().person_; }
}
public int PersonCount {
get { return result.PersonCount; }
}
public global::DotNetty.Codecs.ProtocolBuffers.Person GetPerson(int index) {
return result.GetPerson(index);
}
public Builder SetPerson(int index, global::DotNetty.Codecs.ProtocolBuffers.Person value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.person_[index] = value;
return this;
}
public Builder SetPerson(int index, global::DotNetty.Codecs.ProtocolBuffers.Person.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.person_[index] = builderForValue.Build();
return this;
}
public Builder AddPerson(global::DotNetty.Codecs.ProtocolBuffers.Person value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.person_.Add(value);
return this;
}
public Builder AddPerson(global::DotNetty.Codecs.ProtocolBuffers.Person.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.person_.Add(builderForValue.Build());
return this;
}
public Builder AddRangePerson(scg::IEnumerable<global::DotNetty.Codecs.ProtocolBuffers.Person> values) {
PrepareBuilder();
result.person_.Add(values);
return this;
}
public Builder ClearPerson() {
PrepareBuilder();
result.person_.Clear();
return this;
}
}
static AddressBook() {
object.ReferenceEquals(global::DotNetty.Codecs.ProtocolBuffers.Addressbook.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.IO;
using System.Net.Test.Common;
using System.Security.Authentication.ExtendedProtection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
// Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
// to separately Dispose (or have a 'using' statement) for the handler.
public class HttpClientHandlerTest
{
readonly ITestOutputHelper _output;
private const string ExpectedContent = "Test contest";
private const string Username = "testuser";
private const string Password = "password";
private readonly NetworkCredential _credential = new NetworkCredential(Username, Password);
public readonly static object[][] EchoServers = HttpTestServers.EchoServers;
public readonly static object[][] VerifyUploadServers = HttpTestServers.VerifyUploadServers;
public readonly static object[][] CompressedServers = HttpTestServers.CompressedServers;
public readonly static object[][] HeaderValueAndUris = {
new object[] { "X-CustomHeader", "x-value", HttpTestServers.RemoteEchoServer },
new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RemoteEchoServer },
new object[] { "X-CustomHeader", "x-value", HttpTestServers.RedirectUriForDestinationUri(
secure:false,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1) },
new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RedirectUriForDestinationUri(
secure:false,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1) },
};
public readonly static object[][] Http2Servers = HttpTestServers.Http2Servers;
// Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3
// "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE"
public readonly static IEnumerable<object[]> HttpMethods =
GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1");
public readonly static IEnumerable<object[]> HttpMethodsThatAllowContent =
GetMethods("GET", "POST", "PUT", "DELETE", "CUSTOM1");
private static IEnumerable<object[]> GetMethods(params string[] methods)
{
foreach (string method in methods)
{
foreach (bool secure in new[] { true, false })
{
yield return new object[] { method, secure };
}
}
}
public HttpClientHandlerTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void Ctor_ExpectedDefaultPropertyValues()
{
using (var handler = new HttpClientHandler())
{
// Same as .NET Framework (Desktop).
Assert.True(handler.AllowAutoRedirect);
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
CookieContainer cookies = handler.CookieContainer;
Assert.NotNull(cookies);
Assert.Equal(0, cookies.Count);
Assert.Null(handler.Credentials);
Assert.Equal(50, handler.MaxAutomaticRedirections);
Assert.False(handler.PreAuthenticate);
Assert.Equal(null, handler.Proxy);
Assert.True(handler.SupportsAutomaticDecompression);
Assert.True(handler.SupportsProxy);
Assert.True(handler.SupportsRedirectConfiguration);
Assert.True(handler.UseCookies);
Assert.False(handler.UseDefaultCredentials);
Assert.True(handler.UseProxy);
// Changes from .NET Framework (Desktop).
Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression);
Assert.Equal(0, handler.MaxRequestContentBufferSize);
}
}
[Fact]
public void MaxRequestContentBufferSize_Get_ReturnsZero()
{
using (var handler = new HttpClientHandler())
{
Assert.Equal(0, handler.MaxRequestContentBufferSize);
}
}
[Fact]
public void MaxRequestContentBufferSize_Set_ThrowsPlatformNotSupportedException()
{
using (var handler = new HttpClientHandler())
{
Assert.Throws<PlatformNotSupportedException>(() => handler.MaxRequestContentBufferSize = 1024);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy)
{
var handler = new HttpClientHandler();
handler.UseProxy = useProxy;
handler.UseDefaultCredentials = false;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.NegotiateAuthUriForDefaultCreds(secure:false);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SendAsync_SimpleGet_Success(Uri remoteServer)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(remoteServer))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[Fact]
public async Task SendAsync_MultipleRequestsReusingSameClient_Success()
{
using (var client = new HttpClient())
{
HttpResponseMessage response;
for (int i = 0; i < 3; i++)
{
response = await client.GetAsync(HttpTestServers.RemoteEchoServer);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
response.Dispose();
}
}
}
[Fact]
public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success()
{
HttpResponseMessage response = null;
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer);
}
Assert.NotNull(response);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
[Fact]
public async Task SendAsync_Cancel_CancellationTokenPropagates()
{
var cts = new CancellationTokenSource();
cts.Cancel();
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, HttpTestServers.RemoteEchoServer);
TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, cts.Token));
Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested");
Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested");
}
}
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_DefaultAutomaticDecompression_ContentDecompressed(Uri server)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(server))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_DefaultAutomaticDecompression_HeadersRemoved(Uri server)
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found");
Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found");
}
}
[Fact]
public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK()
{
var handler = new HttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized()
{
using (var client = new HttpClient())
{
Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:false,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:false,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:false,
destinationUri:HttpTestServers.SecureRemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:true,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
Uri targetUri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(secure:false, destinationUri:targetUri, hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(targetUri, response.RequestMessage.RequestUri);
}
}
}
[Theory]
[InlineData(6)]
public async Task GetAsync_MaxAutomaticRedirectionsNServerHopsNPlus1_Throw(int hops)
{
var handler = new HttpClientHandler();
handler.MaxAutomaticRedirections = hops;
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() =>
client.GetAsync(HttpTestServers.RedirectUriForDestinationUri(
secure:false,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:(hops + 1))));
}
}
[Fact]
public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized()
{
var handler = new HttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
Uri redirectUri = HttpTestServers.RedirectUriForCreds(secure:false, userName:Username, password:Password);
using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri))
{
Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK()
{
Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
Uri redirectUri = HttpTestServers.RedirectUriForCreds(secure:false, userName:Username, password:Password);
_output.WriteLine(uri.AbsoluteUri);
_output.WriteLine(redirectUri.AbsoluteUri);
var credentialCache = new CredentialCache();
credentialCache.Add(uri, "Basic", _credential);
var handler = new HttpClientHandler();
handler.Credentials = credentialCache;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(redirectUri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_DefaultCoookieContainer_NoCookieSent()
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer))
{
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Cookie"));
}
}
}
[Theory]
[InlineData("cookieName1", "cookieValue1")]
public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue)
{
var handler = new HttpClientHandler();
var cookieContainer = new CookieContainer();
cookieContainer.Add(HttpTestServers.RemoteEchoServer, new Cookie(cookieName, cookieValue));
handler.CookieContainer = cookieContainer;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue));
}
}
}
[Theory]
[InlineData("cookieName1", "cookieValue1")]
public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(string cookieName, string cookieValue)
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:false,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add(
"X-SetCookie",
string.Format("{0}={1};Path=/", cookieName, cookieValue));
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue));
}
}
}
[Theory, MemberData(nameof(HeaderValueAndUris))]
public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add(name, value);
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value));
}
}
}
private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int overallHeaderValueLength)
{
string emptyHeaderValue = $"{name}=; Path=/";
Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length);
int valueCount = overallHeaderValueLength - emptyHeaderValue.Length;
string value = new string(repeat, valueCount);
return new KeyValuePair<string, string>(name, value);
}
public static object[][] CookieNameValues =
{
// WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values,
// using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders
// returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer.
// Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the
// iteration index, which would cause header values to be missed if not handled correctly.
//
// In particular, WinHttpQueryHeader behaves as follows for the following header value lengths:
// * 0-127 chars: succeeds, index advances from 0 to 1.
// * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1.
// * 256+ chars: fails due to insufficient buffer, index stays at 0.
//
// The below overall header value lengths were chosen to exercise reading header values at these
// edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers.
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257) },
new object[]
{
new KeyValuePair<string, string>(
".AspNetCore.Antiforgery.Xam7_OeLcN4",
"CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM")
}
};
[Theory]
[MemberData(nameof(CookieNameValues))]
public async Task GetAsync_ResponseWithSetCookieHeaders_AllCookiesRead(KeyValuePair<string, string> cookie1)
{
var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM");
var cookie3 = new KeyValuePair<string, string>("name", "value");
string url = string.Format(
"http://httpbin.org/cookies/set?{0}={1}&{2}={3}&{4}={5}",
cookie1.Key,
cookie1.Value,
cookie2.Key,
cookie2.Value,
cookie3.Key,
cookie3.Value);
var handler = new HttpClientHandler()
{
AllowAutoRedirect = false
};
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
CookieCollection cookies = handler.CookieContainer.GetCookies(new Uri(url));
Assert.Equal(3, handler.CookieContainer.Count);
Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value);
Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value);
Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value);
}
}
[Fact]
public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock()
{
using (var client = new HttpClient())
{
const int NumGets = 5;
Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets)
select client.GetAsync(HttpTestServers.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead)).ToArray();
for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available
{
using (HttpResponseMessage response = await responseTasks[i])
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
}
[Fact]
public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK()
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, HttpTestServers.SecureRemoteEchoServer);
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[ActiveIssue(4259, PlatformID.AnyUnix)]
[OuterLoop]
[Fact]
public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned()
{
// TODO: This is a placeholder until GitHub Issue #2383 gets resolved.
const string SlowStreamingServer = "http://httpbin.org/drip?numbytes=8192&duration=15&delay=1&code=200";
int bytesRead;
byte[] buffer = new byte[8192];
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, SlowStreamingServer);
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
Stream stream = await response.Content.ReadAsStreamAsync();
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
}
_output.WriteLine("Bytes read from stream: {0}", bytesRead);
Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length");
}
}
#region Post Methods Tests
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
string data = "Test String";
var content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
HttpResponseMessage response;
using (response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
// Repeat call.
content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
using (response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb";
var content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))]
public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, Stream requestContentStream, byte[] expectedData)
{
using (var client = new HttpClient())
{
HttpContent content = new StreamContent(requestContentStream);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData
{
get
{
foreach (object[] serverArr in VerifyUploadServers)
{
Uri server = (Uri)serverArr[0];
byte[] data = new byte[1234];
new Random(42).NextBytes(data);
// A MemoryStream
{
var memStream = new MemoryStream(data, writable: false);
yield return new object[] { server, memStream, data };
}
// A stream that provides the data synchronously and has a known length
{
var wrappedMemStream = new MemoryStream(data, writable: false);
var syncKnownLengthStream = new DelegateStream(
canReadFunc: () => wrappedMemStream.CanRead,
canSeekFunc: () => wrappedMemStream.CanSeek,
lengthFunc: () => wrappedMemStream.Length,
positionGetFunc: () => wrappedMemStream.Position,
readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token));
yield return new object[] { server, syncKnownLengthStream, data };
}
// A stream that provides the data synchronously and has an unknown length
{
int syncUnknownLengthStreamOffset = 0;
var syncUnknownLengthStream = new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => false,
readAsyncFunc: (buffer, offset, count, token) =>
{
int bytesRemaining = data.Length - syncUnknownLengthStreamOffset;
int bytesToCopy = Math.Min(bytesRemaining, count);
Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy);
syncUnknownLengthStreamOffset += bytesToCopy;
return Task.FromResult(bytesToCopy);
});
yield return new object[] { server, syncUnknownLengthStream, data };
}
// A stream that provides the data asynchronously
{
int asyncStreamOffset = 0, maxDataPerRead = 100;
var asyncStream = new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => false,
readAsyncFunc: async (buffer, offset, count, token) =>
{
await Task.Delay(1).ConfigureAwait(false);
int bytesRemaining = data.Length - asyncStreamOffset;
int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count));
Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy);
asyncStreamOffset += bytesToCopy;
return bytesToCopy;
});
yield return new object[] { server, asyncStream, data };
}
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_NullContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.PostAsync(remoteServer, null))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
string.Empty);
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
var content = new StringContent(string.Empty);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
string.Empty);
}
}
}
[Theory]
[InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")]
[InlineData(HttpStatusCode.MethodNotAllowed, "")]
public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.StatusCodeUri(
false,
(int)statusCode,
reasonPhrase)))
{
Assert.Equal(statusCode, response.StatusCode);
Assert.Equal(reasonPhrase, response.ReasonPhrase);
}
}
}
[Fact]
public async Task PostAsync_Post_ChannelBindingHasExpectedValue()
{
using (var client = new HttpClient())
{
string expectedContent = "Test contest";
var content = new ChannelBindingAwareContent(expectedContent);
using (HttpResponseMessage response = await client.PostAsync(HttpTestServers.SecureRemoteEchoServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ChannelBinding channelBinding = content.ChannelBinding;
Assert.NotNull(channelBinding);
_output.WriteLine("Channel Binding: {0}", channelBinding);
}
}
}
#endregion
#region Various HTTP Method Tests
[Theory, MemberData(nameof(HttpMethods))]
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer);
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
}
}
}
[Theory, MemberData(nameof(HttpMethodsThatAllowContent))]
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer);
request.Content = new StringContent(ExpectedContent);
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
ExpectedContent);
}
}
}
#endregion
#region Version tests
// The HTTP RFC 7230 states that servers are NOT required to respond back with the same
// minor version if they support a higher minor version. In fact, the RFC states that
// servers SHOULD send back the highest minor version they support. So, testing the
// response version to see if the client sent a particular request version only works
// for some servers. In particular the 'Http2Servers' used in these tests always seem
// to echo the minor version of the request.
[Theory, MemberData(nameof(Http2Servers))]
public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request(Uri server)
{
Version responseVersion = await SendRequestAndGetResponseVersionAsync(new Version(1, 0), server);
Assert.Equal(new Version(1, 0), responseVersion);
}
[Theory, MemberData(nameof(Http2Servers))]
public async Task SendAsync_RequestVersion11_ServerReceivesVersion11Request(Uri server)
{
Version responseVersion = await SendRequestAndGetResponseVersionAsync(new Version(1, 1), server);
Assert.Equal(new Version(1, 1), responseVersion);
}
[Theory, MemberData(nameof(Http2Servers))]
public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request(Uri server)
{
Version responseVersion = await SendRequestAndGetResponseVersionAsync(null, server);
Assert.Equal(new Version(1, 1), responseVersion);
}
[Theory, MemberData(nameof(Http2Servers))]
public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server)
{
// We don't currently have a good way to test whether HTTP/2 is supported without
// using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses.
Version responseVersion = await SendRequestAndGetResponseVersionAsync(new Version(2, 0), server);
Assert.True(
responseVersion == new Version(2, 0) ||
responseVersion == new Version(1, 1),
"Response version " + responseVersion);
}
private async Task<Version> SendRequestAndGetResponseVersionAsync(Version requestVersion, Uri server)
{
var request = new HttpRequestMessage(HttpMethod.Get, server);
if (requestVersion != null)
{
request.Version = requestVersion;
}
else
{
// The default value for HttpRequestMessage.Version is Version(1,1).
// So, we need to set something different to test the "unknown" version.
request.Version = new Version(0,0);
}
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return response.Version;
}
}
#endregion
#region SSL Version tests
[Theory]
[InlineData("SSLv2", HttpTestServers.SSLv2RemoteServer)]
[InlineData("SSLv3", HttpTestServers.SSLv3RemoteServer)]
public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url)
{
using (HttpClient client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[Theory]
[InlineData("TLSv1.0", HttpTestServers.TLSv10RemoteServer)]
[InlineData("TLSv1.1", HttpTestServers.TLSv11RemoteServer)]
[InlineData("TLSv1.2", HttpTestServers.TLSv12RemoteServer)]
public async Task GetAsync_SupportedSSLVersion_Succeeds(string name, string url)
{
using (HttpClient client = new HttpClient())
using (await client.GetAsync(url))
{
}
}
#endregion
#region Proxy tests
[Theory]
[MemberData(nameof(CredentialsForProxy))]
public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
{
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: creds != null && creds != CredentialCache.DefaultCredentials,
expectCreds: true);
Uri proxyUrl = new Uri($"http://localhost:{port}");
const string BasicAuth = "Basic";
if (wrapCredsInCache)
{
Assert.IsAssignableFrom<NetworkCredential>(creds);
var cache = new CredentialCache();
cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds);
creds = cache;
}
using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) })
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer);
Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
Task.WaitAll(proxyTask, responseTask, responseStringTask);
TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);
NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth);
string expectedAuth =
nc == null || nc == CredentialCache.DefaultCredentials ? null :
string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
$"{nc.Domain}\\{nc.UserName}:{nc.Password}";
Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
}
}
[Theory]
[MemberData(nameof(BypassedProxies))]
public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy)
{
using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy }))
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteEchoServer))
{
TestHelper.VerifyResponseBody(
await response.Content.ReadAsStringAsync(),
response.Content.Headers.ContentMD5,
false,
null);
}
}
[Fact]
public void Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode()
{
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: true,
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null) })
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer);
Task.WaitAll(proxyTask, responseTask);
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode);
}
}
private sealed class UseSpecifiedUriWebProxy : IWebProxy
{
private readonly Uri _uri;
private readonly bool _bypass;
public UseSpecifiedUriWebProxy(Uri uri, ICredentials credentials = null, bool bypass = false)
{
_uri = uri;
_bypass = bypass;
Credentials = credentials;
}
public ICredentials Credentials { get; set; }
public Uri GetProxy(Uri destination) => _uri;
public bool IsBypassed(Uri host) => _bypass;
}
private sealed class PlatformNotSupportedWebProxy : IWebProxy
{
public ICredentials Credentials { get; set; }
public Uri GetProxy(Uri destination) { throw new PlatformNotSupportedException(); }
public bool IsBypassed(Uri host) { throw new PlatformNotSupportedException(); }
}
private static IEnumerable<object[]> BypassedProxies()
{
yield return new object[] { null };
yield return new object[] { new PlatformNotSupportedWebProxy() };
yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) };
}
private static IEnumerable<object[]> CredentialsForProxy()
{
yield return new object[] { null, false };
foreach (bool wrapCredsInCache in new[] { true, false })
{
yield return new object[] { CredentialCache.DefaultCredentials, wrapCredsInCache };
yield return new object[] { new NetworkCredential("username", "password"), wrapCredsInCache };
yield return new object[] { new NetworkCredential("username", "password", "domain"), wrapCredsInCache };
}
}
#endregion
}
}
| |
//
// 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;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.AzureStack.Management
{
/// <summary>
/// Operations on the subscription as a tenant (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for
/// more information)
/// </summary>
internal partial class SubscriptionOperations : IServiceOperations<AzureStackClient>, ISubscriptionOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SubscriptionOperations(AzureStackClient client)
{
this._client = client;
}
private AzureStackClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.AzureStack.Management.AzureStackClient.
/// </summary>
public AzureStackClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates the subscription as a tenant
/// </summary>
/// <param name='parameters'>
/// Required. Parameters for creating or updating the subscription
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Subscription definition object after create or update operation
/// </returns>
public async Task<SubscriptionCreateOrUpdateResult> CreateOrUpdateAsync(SubscriptionCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Subscription == null)
{
throw new ArgumentNullException("parameters.Subscription");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (parameters.Subscription.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(parameters.Subscription.SubscriptionId);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject subscriptionCreateOrUpdateParametersValue = new JObject();
requestDoc = subscriptionCreateOrUpdateParametersValue;
if (parameters.Subscription.Id != null)
{
subscriptionCreateOrUpdateParametersValue["id"] = parameters.Subscription.Id;
}
if (parameters.Subscription.SubscriptionId != null)
{
subscriptionCreateOrUpdateParametersValue["subscriptionId"] = parameters.Subscription.SubscriptionId;
}
if (parameters.Subscription.DisplayName != null)
{
subscriptionCreateOrUpdateParametersValue["displayName"] = parameters.Subscription.DisplayName;
}
if (parameters.Subscription.ExternalReferenceId != null)
{
subscriptionCreateOrUpdateParametersValue["externalReferenceId"] = parameters.Subscription.ExternalReferenceId;
}
if (parameters.Subscription.OfferId != null)
{
subscriptionCreateOrUpdateParametersValue["offerId"] = parameters.Subscription.OfferId;
}
if (parameters.Subscription.State != null)
{
subscriptionCreateOrUpdateParametersValue["state"] = parameters.Subscription.State.Value.ToString();
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
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)
{
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
SubscriptionCreateOrUpdateResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionCreateOrUpdateResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
SubscriptionDefinition subscriptionInstance = new SubscriptionDefinition();
result.Subscription = subscriptionInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
subscriptionInstance.Id = idInstance;
}
JToken subscriptionIdValue = responseDoc["subscriptionId"];
if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
{
string subscriptionIdInstance = ((string)subscriptionIdValue);
subscriptionInstance.SubscriptionId = subscriptionIdInstance;
}
JToken displayNameValue = responseDoc["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
subscriptionInstance.DisplayName = displayNameInstance;
}
JToken externalReferenceIdValue = responseDoc["externalReferenceId"];
if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null)
{
string externalReferenceIdInstance = ((string)externalReferenceIdValue);
subscriptionInstance.ExternalReferenceId = externalReferenceIdInstance;
}
JToken offerIdValue = responseDoc["offerId"];
if (offerIdValue != null && offerIdValue.Type != JTokenType.Null)
{
string offerIdInstance = ((string)offerIdValue);
subscriptionInstance.OfferId = offerIdInstance;
}
JToken stateValue = responseDoc["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true));
subscriptionInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete operation of the subscription
/// </summary>
/// <param name='subscriptionId'>
/// Required. Subscription Id
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string subscriptionId, CancellationToken cancellationToken)
{
// Validate
if (subscriptionId == null)
{
throw new ArgumentNullException("subscriptionId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
url = url + Uri.EscapeDataString(subscriptionId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the subscription given the id
/// </summary>
/// <param name='subscriptionId'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Result of subscription get operation
/// </returns>
public async Task<SubscriptionGetResult> GetAsync(string subscriptionId, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (subscriptionId != null)
{
url = url + Uri.EscapeDataString(subscriptionId);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SubscriptionGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
SubscriptionDefinition subscriptionInstance = new SubscriptionDefinition();
result.Subscription = subscriptionInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
subscriptionInstance.Id = idInstance;
}
JToken subscriptionIdValue = responseDoc["subscriptionId"];
if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
{
string subscriptionIdInstance = ((string)subscriptionIdValue);
subscriptionInstance.SubscriptionId = subscriptionIdInstance;
}
JToken displayNameValue = responseDoc["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
subscriptionInstance.DisplayName = displayNameInstance;
}
JToken externalReferenceIdValue = responseDoc["externalReferenceId"];
if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null)
{
string externalReferenceIdInstance = ((string)externalReferenceIdValue);
subscriptionInstance.ExternalReferenceId = externalReferenceIdInstance;
}
JToken offerIdValue = responseDoc["offerId"];
if (offerIdValue != null && offerIdValue.Type != JTokenType.Null)
{
string offerIdInstance = ((string)offerIdValue);
subscriptionInstance.OfferId = offerIdInstance;
}
JToken stateValue = responseDoc["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true));
subscriptionInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Lists the subscriptions under the user account
/// </summary>
/// <param name='includeDetails'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Result of subscription list operation
/// </returns>
public async Task<SubscriptionListResult> ListAsync(bool includeDetails, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("includeDetails", includeDetails);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
queryParameters.Add("includeDetails=" + Uri.EscapeDataString(includeDetails.ToString().ToLower()));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SubscriptionListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
SubscriptionDefinition subscriptionDefinitionInstance = new SubscriptionDefinition();
result.Subscriptions.Add(subscriptionDefinitionInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
subscriptionDefinitionInstance.Id = idInstance;
}
JToken subscriptionIdValue = valueValue["subscriptionId"];
if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
{
string subscriptionIdInstance = ((string)subscriptionIdValue);
subscriptionDefinitionInstance.SubscriptionId = subscriptionIdInstance;
}
JToken displayNameValue = valueValue["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
subscriptionDefinitionInstance.DisplayName = displayNameInstance;
}
JToken externalReferenceIdValue = valueValue["externalReferenceId"];
if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null)
{
string externalReferenceIdInstance = ((string)externalReferenceIdValue);
subscriptionDefinitionInstance.ExternalReferenceId = externalReferenceIdInstance;
}
JToken offerIdValue = valueValue["offerId"];
if (offerIdValue != null && offerIdValue.Type != JTokenType.Null)
{
string offerIdInstance = ((string)offerIdValue);
subscriptionDefinitionInstance.OfferId = offerIdInstance;
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true));
subscriptionDefinitionInstance.State = stateInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Lists the next set of subscriptions
/// </summary>
/// <param name='nextLink'>
/// Required. URL to get the next set of results
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Result of subscription list operation
/// </returns>
public async Task<SubscriptionListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + Uri.EscapeDataString(nextLink);
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SubscriptionListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
SubscriptionDefinition subscriptionDefinitionInstance = new SubscriptionDefinition();
result.Subscriptions.Add(subscriptionDefinitionInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
subscriptionDefinitionInstance.Id = idInstance;
}
JToken subscriptionIdValue = valueValue["subscriptionId"];
if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
{
string subscriptionIdInstance = ((string)subscriptionIdValue);
subscriptionDefinitionInstance.SubscriptionId = subscriptionIdInstance;
}
JToken displayNameValue = valueValue["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
subscriptionDefinitionInstance.DisplayName = displayNameInstance;
}
JToken externalReferenceIdValue = valueValue["externalReferenceId"];
if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null)
{
string externalReferenceIdInstance = ((string)externalReferenceIdValue);
subscriptionDefinitionInstance.ExternalReferenceId = externalReferenceIdInstance;
}
JToken offerIdValue = valueValue["offerId"];
if (offerIdValue != null && offerIdValue.Type != JTokenType.Null)
{
string offerIdInstance = ((string)offerIdValue);
subscriptionDefinitionInstance.OfferId = offerIdInstance;
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true));
subscriptionDefinitionInstance.State = stateInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Collections.Generic;
using Xunit;
public class AsyncTargetWrapperTests : NLogTestBase
{
[Fact]
public void AsyncTargetWrapperInitTest()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper(myTarget, 300, AsyncTargetWrapperOverflowAction.Grow);
Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, targetWrapper.OverflowAction);
Assert.Equal(300, targetWrapper.QueueLimit);
Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
Assert.Equal(100, targetWrapper.BatchSize);
}
[Fact]
public void AsyncTargetWrapperInitTest2()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper()
{
WrappedTarget = myTarget,
};
Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, targetWrapper.OverflowAction);
Assert.Equal(10000, targetWrapper.QueueLimit);
Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
Assert.Equal(100, targetWrapper.BatchSize);
}
/// <summary>
/// Test for https://github.com/NLog/NLog/issues/1069
/// </summary>
[Fact]
public void AsyncTargetWrapperInitTest_WhenTimeToSleepBetweenBatchesIsEqualToZero_ShouldThrowNLogConfigurationException() {
LogManager.ThrowConfigExceptions = true;
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper() {
WrappedTarget = myTarget,
TimeToSleepBetweenBatches = 0,
};
Assert.Throws<NLogConfigurationException>(() => targetWrapper.Initialize(null));
}
[Fact]
public void AsyncTargetWrapperSyncTest1()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper
{
WrappedTarget = myTarget,
Name = "AsyncTargetWrapperSyncTest1_Wrapper",
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
ManualResetEvent continuationHit = new ManualResetEvent(false);
Thread continuationThread = null;
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationThread = Thread.CurrentThread;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
// continuation was not hit
Assert.True(continuationHit.WaitOne(2000));
Assert.NotSame(continuationThread, Thread.CurrentThread);
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotSame(continuationThread, Thread.CurrentThread);
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperAsyncTest1()
{
var myTarget = new MyAsyncTarget();
var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperAsyncTest1_Wrapper" };
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit.WaitOne());
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperAsyncWithExceptionTest1()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true,
};
var targetWrapper = new AsyncTargetWrapper(myTarget) {Name = "AsyncTargetWrapperAsyncWithExceptionTest1_Wrapper"};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit.WaitOne());
Assert.NotNull(lastException);
Assert.IsType(typeof(InvalidOperationException), lastException);
// no flush on exception
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
lastException = null;
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType(typeof(InvalidOperationException), lastException);
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperFlushTest()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true
};
var targetWrapper = new AsyncTargetWrapper(myTarget)
{
Name = "AsyncTargetWrapperFlushTest_Wrapper",
OverflowAction = AsyncTargetWrapperOverflowAction.Grow
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
List<Exception> exceptions = new List<Exception>();
int eventCount = 5000;
for (int i = 0; i < eventCount; ++i)
{
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(
ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
}));
}
Exception lastException = null;
ManualResetEvent mre = new ManualResetEvent(false);
string internalLog = RunAndCaptureInternalLog(
() =>
{
targetWrapper.Flush(
cont =>
{
try
{
// by this time all continuations should be completed
Assert.Equal(eventCount, exceptions.Count);
// with just 1 flush of the target
Assert.Equal(1, myTarget.FlushCount);
// and all writes should be accounted for
Assert.Equal(eventCount, myTarget.WriteCount);
}
catch (Exception ex)
{
lastException = ex;
}
finally
{
mre.Set();
}
});
Assert.True(mre.WaitOne());
},
LogLevel.Trace);
if (lastException != null)
{
Assert.True(false, lastException.ToString() + "\r\n" + internalLog);
}
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperCloseTest()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true
};
var targetWrapper = new AsyncTargetWrapper(myTarget)
{
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 1000,
Name = "AsyncTargetWrapperCloseTest_Wrapper",
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
// quickly close the target before the timer elapses
targetWrapper.Close();
}
[Fact]
public void AsyncTargetWrapperExceptionTest()
{
var targetWrapper = new AsyncTargetWrapper
{
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 500,
WrappedTarget = new DebugTarget(),
Name = "AsyncTargetWrapperExceptionTest_Wrapper"
};
LogManager.ThrowExceptions = false;
targetWrapper.Initialize(null);
// null out wrapped target - will cause exception on the timer thread
targetWrapper.WrappedTarget = null;
string internalLog = RunAndCaptureInternalLog(
() =>
{
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
targetWrapper.Close();
},
LogLevel.Trace);
Assert.True(internalLog.Contains("AsyncWrapper 'AsyncTargetWrapperExceptionTest_Wrapper': WrappedTarget is NULL"), internalLog);
}
[Fact]
public void FlushingMultipleTimesSimultaneous()
{
var asyncTarget = new AsyncTargetWrapper
{
TimeToSleepBetweenBatches = 2000,
WrappedTarget = new DebugTarget(),
Name = "FlushingMultipleTimesSimultaneous_Wrapper"
};
asyncTarget.Initialize(null);
try
{
asyncTarget.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
var firstContinuationCalled = false;
var secondContinuationCalled = false;
var firstContinuationResetEvent = new ManualResetEvent(false);
var secondContinuationResetEvent = new ManualResetEvent(false);
asyncTarget.Flush(ex =>
{
firstContinuationCalled = true;
firstContinuationResetEvent.Set();
});
asyncTarget.Flush(ex =>
{
secondContinuationCalled = true;
secondContinuationResetEvent.Set();
});
firstContinuationResetEvent.WaitOne();
secondContinuationResetEvent.WaitOne();
Assert.True(firstContinuationCalled);
Assert.True(secondContinuationCalled);
}
finally
{
asyncTarget.Close();
}
}
class MyAsyncTarget : Target
{
public int FlushCount;
public int WriteCount;
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
Interlocked.Increment(ref this.WriteCount);
ThreadPool.QueueUserWorkItem(
s =>
{
if (this.ThrowExceptions)
{
logEvent.Continuation(new InvalidOperationException("Some problem!"));
logEvent.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
logEvent.Continuation(null);
logEvent.Continuation(null);
}
});
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
Interlocked.Increment(ref this.FlushCount);
ThreadPool.QueueUserWorkItem(
s => asyncContinuation(null));
}
public bool ThrowExceptions { get; set; }
}
class MyTarget : Target
{
public int FlushCount { get; set; }
public int WriteCount { get; set; }
protected override void Write(LogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
this.WriteCount++;
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
asyncContinuation(null);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;
namespace iiNotificationService
{
/// <summary>
/// NotificationServiceBase Handling all registration service.
/// </summary>
public abstract class NotificationServiceBase : IntentService
{
#region Private Declarations
const string Tag = "GCMBaseIntentService";
const string WakelockKey = "GCM_LIB";
static PowerManager.WakeLock sWakeLock;
static object Lock = new object();
static int serviceId = 1;
static string[] SenderIds = new string[] { };
//int sCounter = 1;
Random sRandom = new Random();
const int MaxBackoffMs = 3600000; //1 hour
string Token = "";
const string ExtraToken = "token";
#endregion
#region Constructor
protected NotificationServiceBase() : base() { }
public NotificationServiceBase(params string[] senderIds)
: base("GCMIntentService-" + (serviceId++).ToString())
{
SenderIds = senderIds;
}
#endregion
#region Ovverridable Methods
protected abstract void OnMessage(Context context, Intent intent);
protected virtual void OnDeletedMessages(Context context, int total)
{
}
protected virtual bool OnRecoverableError(Context context, string errorId)
{
return true;
}
protected abstract void OnError(Context context, string errorId);
protected abstract void OnRegistered(Context context, string registrationId);
protected abstract void OnUnRegistered(Context context, string registrationId);
#endregion
#region Handle Intent Method
protected override void OnHandleIntent(Intent intent)
{
try
{
var context = this.ApplicationContext;
var action = intent.Action;
if (action.Equals(iiNotificationConstants.iiGcmRegistrationCallback))
{
handleRegistration(context, intent);
}
else if (action.Equals(iiNotificationConstants.iiGcmMessage))
{
// checks for special messages
var messageType = intent.GetStringExtra(iiNotificationConstants.iiExtraSpecialMessage);
if (messageType != null)
{
if (messageType.Equals(iiNotificationConstants.iiValueDeletedMessages))
{
var sTotal = intent.GetStringExtra(iiNotificationConstants.iiExtraTotalDeleted);
if (!string.IsNullOrEmpty(sTotal))
{
int nTotal = 0;
if (int.TryParse(sTotal, out nTotal))
{
Log.Verbose(Tag, "Received deleted messages notification: " + nTotal);
OnDeletedMessages(context, nTotal);
}
else
Log.Error(Tag, "GCM returned invalid number of deleted messages: " + sTotal);
}
}
else
{
// application is not using the latest GCM library
Log.Error(Tag, "Received unknown special message: " + messageType);
}
}
else
{
OnMessage(context, intent);
}
}
else if (action.Equals(iiNotificationConstants.iiGcmLibraryRetry))
{
var token = intent.GetStringExtra(ExtraToken);
if (!string.IsNullOrEmpty(token) && !Token.Equals(token))
{
// make sure intent was generated by this class, not by a
// malicious app.
Log.Error(Tag, "Received invalid token: " + token);
return;
}
// retry last call
if (iiNotificationHandler.IsRegistered(context))
iiNotificationHandler.internalUnRegister(context);
else
iiNotificationHandler.internalRegister(context, SenderIds);
}
}
finally
{
// Release the power lock, so phone can get back to sleep.
// The lock is reference-counted by default, so multiple
// messages are ok.
// If OnMessage() needs to spawn a thread or do something else,
// it should use its own lock.
lock (Lock)
{
//Sanity check for null as this is a public method
if (sWakeLock != null)
{
Log.Verbose(Tag, "Releasing Wakelock");
sWakeLock.Release();
}
else
{
//Should never happen during normal workflow
Log.Error(Tag, "Wakelock reference is null");
}
}
}
}
#endregion
#region Run Intent Service
internal static void RunIntentInService(Context context, Intent intent, Type classType)
{
lock (Lock)
{
if (sWakeLock == null)
{
// This is called from BroadcastReceiver, there is no init.
var pm = PowerManager.FromContext(context);
sWakeLock = pm.NewWakeLock(WakeLockFlags.Partial, WakelockKey);
}
}
Log.Verbose(Tag, "Acquiring wakelock");
sWakeLock.Acquire();
//intent.SetClassName(context, className);
intent.SetClass(context, classType);
context.StartService(intent);
}
#endregion
#region Handle Registration
private void handleRegistration(Context context, Intent intent)
{
var registrationId = intent.GetStringExtra(iiNotificationConstants.iiExtraRegistrationID);
var error = intent.GetStringExtra(iiNotificationConstants.iiExtraError);
var unregistered = intent.GetStringExtra(iiNotificationConstants.iiExtraUnregistered);
Log.Debug(Tag, string.Format("handleRegistration: registrationId = {0}, error = {1}, unregistered = {2}", registrationId, error, unregistered));
// registration succeeded
if (registrationId != null)
{
iiNotificationHandler.ResetBackoff(context);
iiNotificationHandler.SetRegistrationID(context, registrationId);
OnRegistered(context, registrationId);
return;
}
// unregistration succeeded
if (unregistered != null)
{
// Remember we are unregistered
iiNotificationHandler.ResetBackoff(context);
var oldRegistrationId = iiNotificationHandler.ClearRegistrationID(context);
OnUnRegistered(context, oldRegistrationId);
return;
}
// last operation (registration or unregistration) returned an error;
Log.Debug(Tag, "Registration error: " + error);
// Registration failed
if (iiNotificationConstants.iiErrorSrviceNotAvailable.Equals(error))
{
var retry = OnRecoverableError(context, error);
if (retry)
{
int backoffTimeMs = iiNotificationHandler.GetBackoff(context);
int nextAttempt = backoffTimeMs / 2 + sRandom.Next(backoffTimeMs);
Log.Debug(Tag, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")");
var retryIntent = new Intent(iiNotificationConstants.iiGcmLibraryRetry);
retryIntent.PutExtra(ExtraToken, Token);
var retryPendingIntent = PendingIntent.GetBroadcast(context, 0, retryIntent, PendingIntentFlags.OneShot);
var am = AlarmManager.FromContext(context);
am.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + nextAttempt, retryPendingIntent);
// Next retry should wait longer.
if (backoffTimeMs < MaxBackoffMs)
{
iiNotificationHandler.SetBackoff(context, backoffTimeMs * 2);
}
}
else
{
Log.Debug(Tag, "Not retrying failed operation");
}
}
else
{
// Unrecoverable error, notify app
OnError(context, error);
}
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
// To simplify the process of finding the toolbox bitmap resource:
// #1 Create an internal class called "resfinder" outside of the root namespace.
// #2 Use "resfinder" in the toolbox bitmap attribute instead of the control name.
// #3 use the "<default namespace>.<resourcename>" string to locate the resource.
// See: http://www.bobpowell.net/toolboxbitmap.htm
internal class resfinder
{
}
namespace WeifenLuo.WinFormsUI.Docking
{
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "0#")]
public delegate IDockContent DeserializeDockContent(string persistString);
[LocalizedDescription("DockPanel_Description")]
[Designer("System.Windows.Forms.Design.ControlDesigner, System.Design")]
[ToolboxBitmap(typeof(resfinder), "WeifenLuo.WinFormsUI.Docking.DockPanel.bmp")]
[DefaultProperty("DocumentStyle")]
[DefaultEvent("ActiveContentChanged")]
public partial class DockPanel : Panel
{
private readonly FocusManagerImpl m_focusManager;
private readonly DockPanelExtender m_extender;
private readonly DockPaneCollection m_panes;
private readonly FloatWindowCollection m_floatWindows;
private AutoHideWindowControl m_autoHideWindow;
private DockWindowCollection m_dockWindows;
private readonly DockContent m_dummyContent;
private readonly Control m_dummyControl;
public DockPanel()
{
ShowAutoHideContentOnHover = true;
m_focusManager = new FocusManagerImpl(this);
m_extender = new DockPanelExtender(this);
m_panes = new DockPaneCollection();
m_floatWindows = new FloatWindowCollection();
SuspendLayout();
m_autoHideWindow = Extender.AutoHideWindowFactory.CreateAutoHideWindow(this);
m_autoHideWindow.Visible = false;
m_autoHideWindow.ActiveContentChanged += m_autoHideWindow_ActiveContentChanged;
SetAutoHideWindowParent();
m_dummyControl = new DummyControl();
m_dummyControl.Bounds = new Rectangle(0, 0, 1, 1);
Controls.Add(m_dummyControl);
LoadDockWindows();
m_dummyContent = new DockContent();
ResumeLayout();
}
private Color m_BackColor;
/// <summary>
/// Determines the color with which the client rectangle will be drawn.
/// If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).
/// The BackColor property changes the borders of surrounding controls (DockPane).
/// Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).
/// For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control)
/// </summary>
[Description("Determines the color with which the client rectangle will be drawn.\r\n" +
"If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).\r\n" +
"The BackColor property changes the borders of surrounding controls (DockPane).\r\n" +
"Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).\r\n" +
"For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control).")]
public Color DockBackColor
{
get
{
return !m_BackColor.IsEmpty ? m_BackColor : base.BackColor;
}
set
{
if (m_BackColor != value)
{
m_BackColor = value;
this.Refresh();
}
}
}
private bool ShouldSerializeDockBackColor()
{
return !m_BackColor.IsEmpty;
}
private void ResetDockBackColor()
{
DockBackColor = Color.Empty;
}
private AutoHideStripBase m_autoHideStripControl = null;
internal AutoHideStripBase AutoHideStripControl
{
get
{
if (m_autoHideStripControl == null)
{
m_autoHideStripControl = AutoHideStripFactory.CreateAutoHideStrip(this);
Controls.Add(m_autoHideStripControl);
}
return m_autoHideStripControl;
}
}
internal void ResetAutoHideStripControl()
{
if (m_autoHideStripControl != null)
m_autoHideStripControl.Dispose();
m_autoHideStripControl = null;
}
private void MdiClientHandleAssigned(object sender, EventArgs e)
{
SetMdiClient();
PerformLayout();
}
private void MdiClient_Layout(object sender, LayoutEventArgs e)
{
if (DocumentStyle != DocumentStyle.DockingMdi)
return;
foreach (DockPane pane in Panes)
if (pane.DockState == DockState.Document)
pane.SetContentBounds();
InvalidateWindowRegion();
}
private bool m_disposed = false;
protected override void Dispose(bool disposing)
{
if (!m_disposed && disposing)
{
m_focusManager.Dispose();
if (m_mdiClientController != null)
{
m_mdiClientController.HandleAssigned -= new EventHandler(MdiClientHandleAssigned);
m_mdiClientController.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate);
m_mdiClientController.Layout -= new LayoutEventHandler(MdiClient_Layout);
m_mdiClientController.Dispose();
}
FloatWindows.Dispose();
Panes.Dispose();
DummyContent.Dispose();
m_disposed = true;
}
base.Dispose(disposing);
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IDockContent ActiveAutoHideContent
{
get { return AutoHideWindow.ActiveContent; }
set { AutoHideWindow.ActiveContent = value; }
}
private bool m_allowSplitterDrag = !Win32Helper.IsRunningOnMono;
[LocalizedCategory( "Category_Docking" )]
[LocalizedDescription( "DockPanel_AllowSplitterDrag_Description" )]
[DefaultValue( true )]
public bool AllowSplitterDrag {
get {
if ( Win32Helper.IsRunningOnMono && m_allowSplitterDrag )
m_allowSplitterDrag = false;
return m_allowSplitterDrag;
}
set {
if ( Win32Helper.IsRunningOnMono && value )
throw new InvalidOperationException( "AllowSplitterDrag can only be false if running on Mono" );
m_allowSplitterDrag = value;
}
}
bool canClosePane = false;
public bool CanClosePane
{
get
{
return canClosePane;
}
set
{
canClosePane = value;
}
}
bool canHidePane = false;
public bool CanHidePane
{
get
{
return canHidePane;
}
set
{
canHidePane = value;
}
}
private bool m_allowEndUserDocking = !Win32Helper.IsRunningOnMono;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_AllowEndUserDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserDocking
{
get
{
if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking)
m_allowEndUserDocking = false;
return m_allowEndUserDocking;
}
set
{
if (Win32Helper.IsRunningOnMono && value)
throw new InvalidOperationException("AllowEndUserDocking can only be false if running on Mono");
m_allowEndUserDocking = value;
}
}
private bool m_allowEndUserNestedDocking = !Win32Helper.IsRunningOnMono;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_AllowEndUserNestedDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserNestedDocking
{
get
{
if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking)
m_allowEndUserDocking = false;
return m_allowEndUserNestedDocking;
}
set
{
if (Win32Helper.IsRunningOnMono && value)
throw new InvalidOperationException("AllowEndUserNestedDocking can only be false if running on Mono");
m_allowEndUserNestedDocking = value;
}
}
private DockContentCollection m_contents = new DockContentCollection();
[Browsable(false)]
public DockContentCollection Contents
{
get { return m_contents; }
}
internal DockContent DummyContent
{
get { return m_dummyContent; }
}
private bool m_rightToLeftLayout = false;
[DefaultValue(false)]
[LocalizedCategory("Appearance")]
[LocalizedDescription("DockPanel_RightToLeftLayout_Description")]
public bool RightToLeftLayout
{
get { return m_rightToLeftLayout; }
set
{
if (m_rightToLeftLayout == value)
return;
m_rightToLeftLayout = value;
foreach (FloatWindow floatWindow in FloatWindows)
floatWindow.RightToLeftLayout = value;
}
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
foreach (FloatWindow floatWindow in FloatWindows)
{
if (floatWindow.RightToLeft != RightToLeft)
floatWindow.RightToLeft = RightToLeft;
}
}
private bool m_showDocumentIcon = false;
[DefaultValue(false)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_ShowDocumentIcon_Description")]
public bool ShowDocumentIcon
{
get { return m_showDocumentIcon; }
set
{
if (m_showDocumentIcon == value)
return;
m_showDocumentIcon = value;
Refresh();
}
}
private DocumentTabStripLocation m_documentTabStripLocation = DocumentTabStripLocation.Top;
[DefaultValue(DocumentTabStripLocation.Top)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DocumentTabStripLocation")]
public DocumentTabStripLocation DocumentTabStripLocation
{
get { return m_documentTabStripLocation; }
set { m_documentTabStripLocation = value; }
}
[Browsable(false)]
public DockPanelExtender Extender
{
get { return m_extender; }
}
[Browsable(false)]
public DockPanelExtender.IDockPaneFactory DockPaneFactory
{
get { return Extender.DockPaneFactory; }
}
[Browsable(false)]
public DockPanelExtender.IFloatWindowFactory FloatWindowFactory
{
get { return Extender.FloatWindowFactory; }
}
[Browsable(false)]
public DockPanelExtender.IDockWindowFactory DockWindowFactory
{
get { return Extender.DockWindowFactory; }
}
internal DockPanelExtender.IDockPaneCaptionFactory DockPaneCaptionFactory
{
get { return Extender.DockPaneCaptionFactory; }
}
internal DockPanelExtender.IDockPaneStripFactory DockPaneStripFactory
{
get { return Extender.DockPaneStripFactory; }
}
internal DockPanelExtender.IAutoHideStripFactory AutoHideStripFactory
{
get { return Extender.AutoHideStripFactory; }
}
[Browsable(false)]
public DockPaneCollection Panes
{
get { return m_panes; }
}
internal Rectangle DockArea
{
get
{
return new Rectangle(DockPadding.Left, DockPadding.Top,
ClientRectangle.Width - DockPadding.Left - DockPadding.Right,
ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom);
}
}
private double m_dockBottomPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockBottomPortion_Description")]
[DefaultValue(0.25)]
public double DockBottomPortion
{
get { return m_dockBottomPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockBottomPortion)
return;
m_dockBottomPortion = value;
if (m_dockBottomPortion < 1 && m_dockTopPortion < 1)
{
if (m_dockTopPortion + m_dockBottomPortion > 1)
m_dockTopPortion = 1 - m_dockBottomPortion;
}
PerformLayout();
}
}
private double m_dockLeftPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockLeftPortion_Description")]
[DefaultValue(0.25)]
public double DockLeftPortion
{
get { return m_dockLeftPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockLeftPortion)
return;
m_dockLeftPortion = value;
if (m_dockLeftPortion < 1 && m_dockRightPortion < 1)
{
if (m_dockLeftPortion + m_dockRightPortion > 1)
m_dockRightPortion = 1 - m_dockLeftPortion;
}
PerformLayout();
}
}
private double m_dockRightPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockRightPortion_Description")]
[DefaultValue(0.25)]
public double DockRightPortion
{
get { return m_dockRightPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockRightPortion)
return;
m_dockRightPortion = value;
if (m_dockLeftPortion < 1 && m_dockRightPortion < 1)
{
if (m_dockLeftPortion + m_dockRightPortion > 1)
m_dockLeftPortion = 1 - m_dockRightPortion;
}
PerformLayout();
}
}
private double m_dockTopPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockTopPortion_Description")]
[DefaultValue(0.25)]
public double DockTopPortion
{
get { return m_dockTopPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockTopPortion)
return;
m_dockTopPortion = value;
if (m_dockTopPortion < 1 && m_dockBottomPortion < 1)
{
if (m_dockTopPortion + m_dockBottomPortion > 1)
m_dockBottomPortion = 1 - m_dockTopPortion;
}
PerformLayout();
}
}
[Browsable(false)]
public DockWindowCollection DockWindows
{
get { return m_dockWindows; }
}
public void UpdateDockWindowZOrder(DockStyle dockStyle, bool fullPanelEdge)
{
if (dockStyle == DockStyle.Left)
{
if (fullPanelEdge)
DockWindows[DockState.DockLeft].SendToBack();
else
DockWindows[DockState.DockLeft].BringToFront();
}
else if (dockStyle == DockStyle.Right)
{
if (fullPanelEdge)
DockWindows[DockState.DockRight].SendToBack();
else
DockWindows[DockState.DockRight].BringToFront();
}
else if (dockStyle == DockStyle.Top)
{
if (fullPanelEdge)
DockWindows[DockState.DockTop].SendToBack();
else
DockWindows[DockState.DockTop].BringToFront();
}
else if (dockStyle == DockStyle.Bottom)
{
if (fullPanelEdge)
DockWindows[DockState.DockBottom].SendToBack();
else
DockWindows[DockState.DockBottom].BringToFront();
}
}
[Browsable(false)]
public int DocumentsCount
{
get
{
int count = 0;
foreach (IDockContent content in Documents)
count++;
return count;
}
}
public IDockContent[] DocumentsToArray()
{
int count = DocumentsCount;
IDockContent[] documents = new IDockContent[count];
int i = 0;
foreach (IDockContent content in Documents)
{
documents[i] = content;
i++;
}
return documents;
}
[Browsable(false)]
public IEnumerable<IDockContent> Documents
{
get
{
foreach (IDockContent content in Contents)
{
if (content.DockHandler.DockState == DockState.Document)
yield return content;
}
}
}
private Control DummyControl
{
get { return m_dummyControl; }
}
[Browsable(false)]
public FloatWindowCollection FloatWindows
{
get { return m_floatWindows; }
}
private Size m_defaultFloatWindowSize = new Size(300, 300);
[Category("Layout")]
[LocalizedDescription("DockPanel_DefaultFloatWindowSize_Description")]
public Size DefaultFloatWindowSize
{
get { return m_defaultFloatWindowSize; }
set { m_defaultFloatWindowSize = value; }
}
private bool ShouldSerializeDefaultFloatWindowSize()
{
return DefaultFloatWindowSize != new Size(300, 300);
}
private void ResetDefaultFloatWindowSize()
{
DefaultFloatWindowSize = new Size(300, 300);
}
private DocumentStyle m_documentStyle = DocumentStyle.DockingMdi;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DocumentStyle_Description")]
[DefaultValue(DocumentStyle.DockingMdi)]
public DocumentStyle DocumentStyle
{
get { return m_documentStyle; }
set
{
if (value == m_documentStyle)
return;
if (!Enum.IsDefined(typeof(DocumentStyle), value))
throw new InvalidEnumArgumentException();
if (value == DocumentStyle.SystemMdi && DockWindows[DockState.Document].VisibleNestedPanes.Count > 0)
throw new InvalidEnumArgumentException();
m_documentStyle = value;
SuspendLayout(true);
SetAutoHideWindowParent();
SetMdiClient();
InvalidateWindowRegion();
foreach (IDockContent content in Contents)
{
if (content.DockHandler.DockState == DockState.Document)
content.DockHandler.SetPaneAndVisible(content.DockHandler.Pane);
}
PerformMdiClientLayout();
ResumeLayout(true, true);
}
}
private bool _supprtDeeplyNestedContent = false;
[LocalizedCategory("Category_Performance")]
[LocalizedDescription("DockPanel_SupportDeeplyNestedContent_Description")]
[DefaultValue(false)]
public bool SupportDeeplyNestedContent
{
get { return _supprtDeeplyNestedContent; }
set { _supprtDeeplyNestedContent = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_ShowAutoHideContentOnHover_Description")]
[DefaultValue(true)]
public bool ShowAutoHideContentOnHover { get; set; }
public int GetDockWindowSize(DockState dockState)
{
if (dockState == DockState.DockLeft || dockState == DockState.DockRight)
{
int width = ClientRectangle.Width - DockPadding.Left - DockPadding.Right;
int dockLeftSize = m_dockLeftPortion >= 1 ? (int)m_dockLeftPortion : (int)(width * m_dockLeftPortion);
int dockRightSize = m_dockRightPortion >= 1 ? (int)m_dockRightPortion : (int)(width * m_dockRightPortion);
if (dockLeftSize < MeasurePane.MinSize)
dockLeftSize = MeasurePane.MinSize;
if (dockRightSize < MeasurePane.MinSize)
dockRightSize = MeasurePane.MinSize;
if (dockLeftSize + dockRightSize > width - MeasurePane.MinSize)
{
int adjust = (dockLeftSize + dockRightSize) - (width - MeasurePane.MinSize);
dockLeftSize -= adjust / 2;
dockRightSize -= adjust / 2;
}
return dockState == DockState.DockLeft ? dockLeftSize : dockRightSize;
}
else if (dockState == DockState.DockTop || dockState == DockState.DockBottom)
{
int height = ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom;
int dockTopSize = m_dockTopPortion >= 1 ? (int)m_dockTopPortion : (int)(height * m_dockTopPortion);
int dockBottomSize = m_dockBottomPortion >= 1 ? (int)m_dockBottomPortion : (int)(height * m_dockBottomPortion);
if (dockTopSize < MeasurePane.MinSize)
dockTopSize = MeasurePane.MinSize;
if (dockBottomSize < MeasurePane.MinSize)
dockBottomSize = MeasurePane.MinSize;
if (dockTopSize + dockBottomSize > height - MeasurePane.MinSize)
{
int adjust = (dockTopSize + dockBottomSize) - (height - MeasurePane.MinSize);
dockTopSize -= adjust / 2;
dockBottomSize -= adjust / 2;
}
return dockState == DockState.DockTop ? dockTopSize : dockBottomSize;
}
else
return 0;
}
protected override void OnLayout(LayoutEventArgs levent)
{
SuspendLayout(true);
AutoHideStripControl.Bounds = ClientRectangle;
CalculateDockPadding();
DockWindows[DockState.DockLeft].Width = GetDockWindowSize(DockState.DockLeft);
DockWindows[DockState.DockRight].Width = GetDockWindowSize(DockState.DockRight);
DockWindows[DockState.DockTop].Height = GetDockWindowSize(DockState.DockTop);
DockWindows[DockState.DockBottom].Height = GetDockWindowSize(DockState.DockBottom);
AutoHideWindow.Bounds = GetAutoHideWindowBounds(AutoHideWindowRectangle);
DockWindows[DockState.Document].BringToFront();
AutoHideWindow.BringToFront();
base.OnLayout(levent);
if (DocumentStyle == DocumentStyle.SystemMdi && MdiClientExists)
{
SetMdiClientBounds(SystemMdiClientBounds);
InvalidateWindowRegion();
}
else if (DocumentStyle == DocumentStyle.DockingMdi)
InvalidateWindowRegion();
ResumeLayout(true, true);
}
internal Rectangle GetTabStripRectangle(DockState dockState)
{
return AutoHideStripControl.GetTabStripRectangle(dockState);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (DockBackColor == BackColor) return;
Graphics g = e.Graphics;
SolidBrush bgBrush = new SolidBrush(DockBackColor);
g.FillRectangle(bgBrush, ClientRectangle);
}
internal void AddContent(IDockContent content)
{
if (content == null)
throw(new ArgumentNullException());
if (!Contents.Contains(content))
{
Contents.Add(content);
OnContentAdded(new DockContentEventArgs(content));
}
}
internal void AddPane(DockPane pane)
{
if (Panes.Contains(pane))
return;
Panes.Add(pane);
}
internal void AddFloatWindow(FloatWindow floatWindow)
{
if (FloatWindows.Contains(floatWindow))
return;
FloatWindows.Add(floatWindow);
}
private void CalculateDockPadding()
{
DockPadding.All = 0;
int height = AutoHideStripControl.MeasureHeight();
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockLeftAutoHide) > 0)
DockPadding.Left = height;
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockRightAutoHide) > 0)
DockPadding.Right = height;
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockTopAutoHide) > 0)
DockPadding.Top = height;
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockBottomAutoHide) > 0)
DockPadding.Bottom = height;
}
internal void RemoveContent(IDockContent content)
{
if (content == null)
throw(new ArgumentNullException());
if (Contents.Contains(content))
{
Contents.Remove(content);
OnContentRemoved(new DockContentEventArgs(content));
}
}
internal void RemovePane(DockPane pane)
{
if (!Panes.Contains(pane))
return;
Panes.Remove(pane);
}
internal void RemoveFloatWindow(FloatWindow floatWindow)
{
if (!FloatWindows.Contains(floatWindow))
return;
FloatWindows.Remove(floatWindow);
if (FloatWindows.Count != 0)
return;
if (ParentForm == null)
return;
ParentForm.Focus();
}
public void SetPaneIndex(DockPane pane, int index)
{
int oldIndex = Panes.IndexOf(pane);
if (oldIndex == -1)
throw(new ArgumentException(Strings.DockPanel_SetPaneIndex_InvalidPane));
if (index < 0 || index > Panes.Count - 1)
if (index != -1)
throw(new ArgumentOutOfRangeException(Strings.DockPanel_SetPaneIndex_InvalidIndex));
if (oldIndex == index)
return;
if (oldIndex == Panes.Count - 1 && index == -1)
return;
Panes.Remove(pane);
if (index == -1)
Panes.Add(pane);
else if (oldIndex < index)
Panes.AddAt(pane, index - 1);
else
Panes.AddAt(pane, index);
}
public void SuspendLayout(bool allWindows)
{
FocusManager.SuspendFocusTracking();
SuspendLayout();
if (allWindows)
SuspendMdiClientLayout();
}
public void ResumeLayout(bool performLayout, bool allWindows)
{
FocusManager.ResumeFocusTracking();
ResumeLayout(performLayout);
if (allWindows)
ResumeMdiClientLayout(performLayout);
}
internal Form ParentForm
{
get
{
if (!IsParentFormValid())
throw new InvalidOperationException(Strings.DockPanel_ParentForm_Invalid);
return GetMdiClientController().ParentForm;
}
}
private bool IsParentFormValid()
{
if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow)
return true;
if (!MdiClientExists)
GetMdiClientController().RenewMdiClient();
return (MdiClientExists);
}
protected override void OnParentChanged(EventArgs e)
{
SetAutoHideWindowParent();
GetMdiClientController().ParentForm = (this.Parent as Form);
base.OnParentChanged (e);
}
private void SetAutoHideWindowParent()
{
Control parent;
if (DocumentStyle == DocumentStyle.DockingMdi ||
DocumentStyle == DocumentStyle.SystemMdi)
parent = this.Parent;
else
parent = this;
if (AutoHideWindow.Parent != parent)
{
AutoHideWindow.Parent = parent;
AutoHideWindow.BringToFront();
}
}
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged (e);
if (Visible)
SetMdiClient();
}
private Rectangle SystemMdiClientBounds
{
get
{
if (!IsParentFormValid() || !Visible)
return Rectangle.Empty;
Rectangle rect = ParentForm.RectangleToClient(RectangleToScreen(DocumentWindowBounds));
return rect;
}
}
internal Rectangle DocumentWindowBounds
{
get
{
Rectangle rectDocumentBounds = DisplayRectangle;
if (DockWindows[DockState.DockLeft].Visible)
{
rectDocumentBounds.X += DockWindows[DockState.DockLeft].Width;
rectDocumentBounds.Width -= DockWindows[DockState.DockLeft].Width;
}
if (DockWindows[DockState.DockRight].Visible)
rectDocumentBounds.Width -= DockWindows[DockState.DockRight].Width;
if (DockWindows[DockState.DockTop].Visible)
{
rectDocumentBounds.Y += DockWindows[DockState.DockTop].Height;
rectDocumentBounds.Height -= DockWindows[DockState.DockTop].Height;
}
if (DockWindows[DockState.DockBottom].Visible)
rectDocumentBounds.Height -= DockWindows[DockState.DockBottom].Height;
return rectDocumentBounds;
}
}
private PaintEventHandler m_dummyControlPaintEventHandler = null;
private void InvalidateWindowRegion()
{
if (DesignMode)
return;
if (m_dummyControlPaintEventHandler == null)
m_dummyControlPaintEventHandler = new PaintEventHandler(DummyControl_Paint);
DummyControl.Paint += m_dummyControlPaintEventHandler;
DummyControl.Invalidate();
}
void DummyControl_Paint(object sender, PaintEventArgs e)
{
DummyControl.Paint -= m_dummyControlPaintEventHandler;
UpdateWindowRegion();
}
private void UpdateWindowRegion()
{
if (this.DocumentStyle == DocumentStyle.DockingMdi)
UpdateWindowRegion_ClipContent();
else if (this.DocumentStyle == DocumentStyle.DockingSdi ||
this.DocumentStyle == DocumentStyle.DockingWindow)
UpdateWindowRegion_FullDocumentArea();
else if (this.DocumentStyle == DocumentStyle.SystemMdi)
UpdateWindowRegion_EmptyDocumentArea();
}
private void UpdateWindowRegion_FullDocumentArea()
{
SetRegion(null);
}
private void UpdateWindowRegion_EmptyDocumentArea()
{
Rectangle rect = DocumentWindowBounds;
SetRegion(new Rectangle[] { rect });
}
private void UpdateWindowRegion_ClipContent()
{
int count = 0;
foreach (DockPane pane in this.Panes)
{
if (!pane.Visible || pane.DockState != DockState.Document)
continue;
count ++;
}
if (count == 0)
{
SetRegion(null);
return;
}
Rectangle[] rects = new Rectangle[count];
int i = 0;
foreach (DockPane pane in this.Panes)
{
if (!pane.Visible || pane.DockState != DockState.Document)
continue;
rects[i] = RectangleToClient(pane.RectangleToScreen(pane.ContentRectangle));
i++;
}
SetRegion(rects);
}
private Rectangle[] m_clipRects = null;
private void SetRegion(Rectangle[] clipRects)
{
if (!IsClipRectsChanged(clipRects))
return;
m_clipRects = clipRects;
if (m_clipRects == null || m_clipRects.GetLength(0) == 0)
Region = null;
else
{
Region region = new Region(new Rectangle(0, 0, this.Width, this.Height));
foreach (Rectangle rect in m_clipRects)
region.Exclude(rect);
if (Region != null)
{
Region.Dispose();
}
Region = region;
}
}
private bool IsClipRectsChanged(Rectangle[] clipRects)
{
if (clipRects == null && m_clipRects == null)
return false;
else if ((clipRects == null) != (m_clipRects == null))
return true;
foreach (Rectangle rect in clipRects)
{
bool matched = false;
foreach (Rectangle rect2 in m_clipRects)
{
if (rect == rect2)
{
matched = true;
break;
}
}
if (!matched)
return true;
}
foreach (Rectangle rect2 in m_clipRects)
{
bool matched = false;
foreach (Rectangle rect in clipRects)
{
if (rect == rect2)
{
matched = true;
break;
}
}
if (!matched)
return true;
}
return false;
}
private static readonly object ActiveAutoHideContentChangedEvent = new object();
[LocalizedCategory("Category_DockingNotification")]
[LocalizedDescription("DockPanel_ActiveAutoHideContentChanged_Description")]
public event EventHandler ActiveAutoHideContentChanged
{
add { Events.AddHandler(ActiveAutoHideContentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveAutoHideContentChangedEvent, value); }
}
protected virtual void OnActiveAutoHideContentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveAutoHideContentChangedEvent];
if (handler != null)
handler(this, e);
}
private void m_autoHideWindow_ActiveContentChanged(object sender, EventArgs e)
{
OnActiveAutoHideContentChanged(e);
}
private static readonly object ContentAddedEvent = new object();
[LocalizedCategory("Category_DockingNotification")]
[LocalizedDescription("DockPanel_ContentAdded_Description")]
public event EventHandler<DockContentEventArgs> ContentAdded
{
add { Events.AddHandler(ContentAddedEvent, value); }
remove { Events.RemoveHandler(ContentAddedEvent, value); }
}
protected virtual void OnContentAdded(DockContentEventArgs e)
{
EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentAddedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ContentRemovedEvent = new object();
[LocalizedCategory("Category_DockingNotification")]
[LocalizedDescription("DockPanel_ContentRemoved_Description")]
public event EventHandler<DockContentEventArgs> ContentRemoved
{
add { Events.AddHandler(ContentRemovedEvent, value); }
remove { Events.RemoveHandler(ContentRemovedEvent, value); }
}
protected virtual void OnContentRemoved(DockContentEventArgs e)
{
EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentRemovedEvent];
if (handler != null)
handler(this, e);
}
internal void ReloadDockWindows()
{
var old = m_dockWindows;
LoadDockWindows();
foreach (var dockWindow in old)
{
Controls.Remove(dockWindow);
dockWindow.Dispose();
}
}
internal void LoadDockWindows()
{
m_dockWindows = new DockWindowCollection(this);
foreach (var dockWindow in DockWindows)
{
Controls.Add(dockWindow);
}
}
public void ResetAutoHideStripWindow()
{
var old = m_autoHideWindow;
m_autoHideWindow = Extender.AutoHideWindowFactory.CreateAutoHideWindow(this);
m_autoHideWindow.Visible = false;
SetAutoHideWindowParent();
old.Visible = false;
old.Parent = null;
old.Dispose();
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using CreateThis.VR.UI.Interact;
using MeshEngine.Controller;
namespace MeshEngine {
public class Triangles {
class TriangleToRemove {
public int[] triangle;
}
public List<int> triangles;
public List<Triangle> triangleInstances;
public Mesh mesh;
public bool autoCreateTriangleObjects;
public bool selectVerticesWhileAddingTriangles;
public bool hideTriangles;
private bool triangleInstancesSelectable;
private bool triangleInstancesCreated;
private Dictionary<int, int> triangleInstanceIndexByTriangleIndex;
private bool triangleInstanceIndexByTriangleIndexValid;
private List<GameObject> triangleInstancesPool;
public bool log;
public bool trianglesChanged;
public void DeactivateAndMoveToPool(GameObject triangleGameObject) {
triangleGameObject.SetActive(false);
triangleGameObject.transform.parent = null;
triangleInstancesPool.Add(triangleGameObject);
}
public GameObject InstantiateOrGetFromPool(Vector3 position, Quaternion rotation) {
if (triangleInstancesPool.Count > 0) {
int index = triangleInstancesPool.Count - 1;
GameObject triangleGameObject = triangleInstancesPool[index];
triangleInstancesPool.RemoveAt(index);
triangleGameObject.SetActive(true);
triangleGameObject.transform.position = position;
triangleGameObject.transform.rotation = rotation;
return triangleGameObject;
} else {
return GameObject.Instantiate(mesh.trianglePrefab, position, rotation);
}
}
public Triangles(Mesh mesh) {
this.mesh = mesh;
triangles = new List<int>();
triangleInstancesPool = new List<GameObject>();
triangleInstances = new List<Triangle>();
triangleInstancesCreated = false;
selectVerticesWhileAddingTriangles = true;
triangleInstanceIndexByTriangleIndex = new Dictionary<int, int>();
triangleInstanceIndexByTriangleIndexValid = false;
log = true;
trianglesChanged = false;
}
public string TriangleInstancesToString() {
List<string> result = new List<string>();
for (int i = 0; i < triangleInstances.Count; i++) {
Triangle triangle = triangleInstances[i];
result.Add("([" + i + "].index=" + triangle.index + ")");
}
return string.Join(",", result.ToArray());
}
public string TrianglesToString(int[] triangles = null) {
List<string> result = new List<string>();
if (triangles == null) {
triangles = mesh.uMesh.triangles;
}
for (int i = 0; i + 2 < triangles.Length; i += 3) {
result.Add("[" + i + "](" + triangles[i] + "," + triangles[i + 1] + "," + triangles[i + 2] + ")");
}
return string.Join(",", result.ToArray());
}
public Triangle TriangleByIndex(int index) {
if (triangleInstanceIndexByTriangleIndexValid) {
if (triangleInstanceIndexByTriangleIndex.ContainsKey(index)) {
return triangleInstances[triangleInstanceIndexByTriangleIndex[index]];
}
} else {
foreach (Triangle triangle in triangleInstances) {
if (triangle.index == index) return triangle;
}
}
return null;
}
public void CreateTriangleInstance(int triangleIndex) {
Vertex a = mesh.vertices.vertices[triangles[triangleIndex]];
Vertex b = mesh.vertices.vertices[triangles[triangleIndex + 1]];
Vertex c = mesh.vertices.vertices[triangles[triangleIndex + 2]];
Vector3 center = mesh.Center(a.position, b.position, c.position);
GameObject triangleInstance = InstantiateOrGetFromPool(center, mesh.transform.rotation);
triangleInstance.transform.parent = mesh.transform;
triangleInstance.transform.localPosition = center;
TriangleController triangleController = triangleInstance.GetComponent<TriangleController>();
triangleController.mesh = mesh;
triangleController.Initialize();
//Debug.Log("Creating triangle a=" + a + ",b=" + b + ",c=" + c);
triangleController.Populate(a, b, c, center);
Triangle triangle = new Triangle();
triangle.index = triangleIndex;
triangle.instance = triangleInstance;
Material mmMaterial = mesh.materials.MaterialByTriangleIndex(triangleIndex);
triangle.material = MaterialUtils.MaterialToInstance(mmMaterial, true, true, true);
//Debug.Log("CreateTriangleInstance fillColor=" + ColorUtility.ToHtmlStringRGBA(meshController.settingsPanelController.GetComponent<SettingsController>().fillColor) + ",mmMaterial.color=" + ColorUtility.ToHtmlStringRGBA(mmMaterial.color) + ",triangle.material.color="+ ColorUtility.ToHtmlStringRGBA(triangle.material.color));
triangleController.material = triangle.material;
triangleController.SyncMaterials();
Selectable selectable = triangleInstance.GetComponent<Selectable>();
selectable.Initialize();
selectable.renderMesh = true;
selectable.renderWireframe = true;
selectable.renderNormals = true;
triangleController.SetSelectable(triangleInstancesSelectable);
triangleController.SetStickySelected(false);
triangleInstance.SetActive(!hideTriangles);
triangleInstances.Add(triangle);
//if (log) Debug.Log("CreateTriangleInstance triangle.index=" + triangle.index+ ", triangleInstances.Count - 1="+ (triangleInstances.Count - 1)+", triangle.instance.ID=" + triangle.instance.GetInstanceID());
triangleInstanceIndexByTriangleIndex.Add(triangle.index, triangleInstances.Count - 1);
}
public void UpdateAllTriangleInstancesSelectable() {
foreach (Triangle triangle in triangleInstances) {
GameObject triangleInstance = triangle.instance;
TriangleController triangleController = triangleInstance.GetComponent<TriangleController>();
triangleController.SetSelectable(triangleInstancesSelectable);
}
}
public void SetTriangleInstancesSelectable(bool value) {
if (triangleInstancesSelectable == value) return;
triangleInstancesSelectable = value;
UpdateAllTriangleInstancesSelectable();
}
public void CreateTriangleInstances() {
if (mesh.materials.materialsChanged) trianglesChanged = true;
if (triangleInstancesCreated) return;
triangleInstanceIndexByTriangleIndex.Clear();
for (int i = 0; i + 2 < triangles.Count; i += 3) {
CreateTriangleInstance(i);
}
triangleInstancesCreated = true;
}
public void SubtractThreeFromTriangleInstanceIndexAboveIndex(int index) {
foreach (Triangle triangle in triangleInstances) {
if (triangle.index >= index) {
triangle.index -= 3;
}
}
//if (log) Debug.Log("SubtractThreeFromTriangleInstanceIndexAboveIndex index=" + index + ",triangleInstances.Count=" + triangleInstances.Count + ",triangleInstances=" + TriangleInstancesToString());
}
public void RebuildTriangleInstanceIndex() {
//if (log) Debug.Log("RebuildTriangleInstanceIndex triangleInstances.Count=" + triangleInstances.Count + ",triangleInstances=" + TriangleInstancesToString());
triangleInstanceIndexByTriangleIndex.Clear();
for (int i = 0; i < triangleInstances.Count; i++) {
Triangle triangle = triangleInstances[i];
triangleInstanceIndexByTriangleIndex.Add(triangle.index, i);
}
triangleInstanceIndexByTriangleIndexValid = true;
}
public void Clear() {
DeleteTriangleInstances();
triangles.Clear();
triangleInstanceIndexByTriangleIndex.Clear();
trianglesChanged = true;
}
public void TruncateToCount(int count) {
for (int i = triangles.Count - 1; i >= count; i--) {
if (triangleInstanceIndexByTriangleIndex.ContainsKey(i)) triangleInstanceIndexByTriangleIndex.Remove(i);
triangles.RemoveAt(i);
}
trianglesChanged = true;
}
public void DeleteTriangleInstances() {
foreach (Triangle triangle in triangleInstances) {
DeactivateAndMoveToPool(triangle.instance);
}
triangleInstances.Clear();
triangleInstanceIndexByTriangleIndex.Clear();
mesh.selection.ClearSelectedTriangles();
triangleInstancesCreated = false;
}
public void AddQuadByVertices(GameObject vertexInstanceA, GameObject vertexInstanceB, GameObject vertexInstanceC, GameObject vertexInstanceD, int materialIndex = -1) {
AddTriangleByVertices(vertexInstanceA, vertexInstanceB, vertexInstanceC, materialIndex);
AddTriangleByVertices(vertexInstanceA, vertexInstanceC, vertexInstanceD, materialIndex);
}
public void AddTriangleByVertices(GameObject vertexInstanceA, GameObject vertexInstanceB, GameObject vertexInstanceC, int materialIndex = -1) {
bool oldValue = selectVerticesWhileAddingTriangles;
selectVerticesWhileAddingTriangles = false;
AddTriangleVertex(vertexInstanceA, materialIndex);
AddTriangleVertex(vertexInstanceB, materialIndex);
AddTriangleVertex(vertexInstanceC, materialIndex);
selectVerticesWhileAddingTriangles = oldValue;
}
public void AddTriangleVertex(GameObject vertexInstance, int materialIndex = -1) {
int index = mesh.vertices.IndexOfInstance(vertexInstance);
AddTriangleVertexIndex(index, vertexInstance, materialIndex);
}
public void AddTriangleVertexIndex(int vertexIndex, GameObject vertexInstance, int materialIndex = -1) {
if (triangles.Count % 3 != 0) {
int lastVertexIndex = triangles[triangles.Count - 1];
if (lastVertexIndex == vertexIndex) {
// don't allow user to select same vertex twice, unless immediately after completing a triangle.
return;
}
}
if ((triangles.Count == 2 || triangles.Count % 3 == 2) &&
vertexIndex == triangles[triangles.Count - 2]) {
// don't allow user to select the first vertex same as the last vertex in a triangle (this would make a straight line, not a triangle).
return;
}
triangles.Add(vertexIndex);
if (selectVerticesWhileAddingTriangles) mesh.selection.SelectVertex(vertexInstance);
//Debug.Log("MeshController: instance.newTriangles.Count=" + instance.newTriangles.Count + ",instance.newTriangles.Count % 3 = " + instance.newTriangles.Count % 3);
if (triangles.Count % 3 == 0) {
if (materialIndex == -1) {
mesh.materials.AppendTriangleUsingFillColorMaterial();
} else {
mesh.materials.AppendTriangleUsingMaterialIndex(materialIndex);
}
trianglesChanged = true;
mesh.persistence.changedSinceLastSave = true;
if (selectVerticesWhileAddingTriangles) mesh.selection.ClearSelectedVertices();
if (autoCreateTriangleObjects) CreateTriangleInstance(triangles.Count - 3);
}
//Debug.Log("MeshController: Added triangle index[" + index + "]=" + vertexIndex);
//Debug.Log("vertices=" + VerticesToString());
//Debug.Log("triangles=" + TrianglesToString());
}
public bool BuildTriangles() {
if (!trianglesChanged && !mesh.materials.materialsChanged) return false;
List<UnityEngine.Material> materials = MaterialUtils.GetMaterials(mesh);
UnityEngine.Material[] materialArray = MaterialUtils.AssignMaterials(mesh, materials);
mesh.uMesh.subMeshCount = materials.Count;
List<Materials.MaterialTriangles> materialTriangles = mesh.materials.GetTriangles();
for (int i = 0; i < materials.Count; i++) {
mesh.uMesh.SetTriangles(materialTriangles[i].triangles.ToArray(), i);
}
Selectable selectable = mesh.GetComponent<Selectable>();
mesh.materials.materialsChanged = false;
if (selectable != null) {
UnityEngine.Mesh outlineMesh = new UnityEngine.Mesh();
outlineMesh.vertices = mesh.uMesh.vertices;
outlineMesh.triangles = mesh.triangles.triangles.ToArray();
outlineMesh.RecalculateNormals();
selectable.outlineMesh = outlineMesh;
selectable.unselectedMaterials = materialArray;
selectable.UpdateSelectedMaterials();
} else {
// BoxSelectionController mesh only
mesh.uMesh.triangles = triangles.ToArray();
}
trianglesChanged = false;
return true;
}
public List<int> SubtractFromEachTriangleVertexIndexAboveVertexIndex(int index, int subtract, List<int> myTriangles) {
//if (log) Debug.Log("SubtractFromEachTriangleVertexIndexAboveVertexIndex before index=" + index + ",myTriangles=" + TrianglesToString(myTriangles.ToArray()));
List<int> myTriangles2 = new List<int>();
foreach (int value in myTriangles) {
myTriangles2.Add(value > index ? value - subtract : value);
}
//if (log) Debug.Log("SubtractFromEachTriangleVertexIndexAboveVertexIndex after index=" + index + ",myTriangles2=" + TrianglesToString(myTriangles2.ToArray()));
return myTriangles2;
}
public void RemoveTrianglesWithVertexIndex(int index) {
//if (log) Debug.Log("RemoveTrianglesWithVertexIndex index="+index+", triangles=" + TrianglesToString());
List<int> myTriangles = new List<int>();
List<int> triangleIndexesToRemove = new List<int>();
for (int i = 0; i + 2 < triangles.Count; i += 3) {
int first = triangles[i];
int second = triangles[i + 1];
int third = triangles[i + 2];
if (first == index || second == index || third == index) {
// remove by doing nothing
//Debug.Log("RemoveTrianglesWithVertexIndex removing triangle with vertex i=" + i + ",indices first=" + first + ",second=" + second + ",third=" + third);
//if (log) Debug.Log("RemoveTriangle i=" + i + ",first=" + first + ",second=" + second + ",third=" + third);
RemoveTriangleGameObjectByIndex(i);
triangleIndexesToRemove.Add(i);
} else {
myTriangles.Add(first);
myTriangles.Add(second);
myTriangles.Add(third);
}
}
List<int> myTriangles2 = SubtractFromEachTriangleVertexIndexAboveVertexIndex(index, 1, myTriangles);
for (int i = triangleIndexesToRemove.Count - 1; i >= 0; i--) {
int triangleIndex = triangleIndexesToRemove[i];
SubtractThreeFromTriangleInstanceIndexAboveIndex(triangleIndex);
mesh.materials.RemoveTriangleByIndex(triangleIndex);
}
//Debug.Log("RemoveTrianglesWithVertexIndex vertex index=" + index + ", numberTrianglesRemoved=" + numberTrianglesRemoved);
//Debug.Log("RemoveTrianglesWithVertexIndex myTriangles after=" + TrianglesToString(myTriangles2.ToArray()));
triangles = myTriangles2;
trianglesChanged = true;
mesh.persistence.changedSinceLastSave = true;
if (triangleIndexesToRemove.Count > 0) {
// triangles were removed, so rebuild index
RebuildTriangleInstanceIndex();
}
//Debug.Log("RemoveTrianglesWithVertexIndex triangles after=" + TrianglesToString());
}
public void RemoveTriangleByVertices(Vertex[] vertices) {
int a_index = mesh.vertices.IndexOfVertex(vertices[0]);
int b_index = mesh.vertices.IndexOfVertex(vertices[1]);
int c_index = mesh.vertices.IndexOfVertex(vertices[2]);
int[] triangleIndices = new int[] { a_index, b_index, c_index };
RemoveTriangle(triangleIndices);
}
public void RemoveTriangleGameObjectByIndex(int index) {
//if (log) Debug.Log("RemoveTriangleGameObjectByIndex before index=" + index + ",triangleInstances.Count=" + triangleInstances.Count + ",triangleInstances=" + TriangleInstancesToString());
Triangle triangle = TriangleByIndex(index);
DeactivateAndMoveToPool(triangle.instance);
triangleInstances.Remove(triangle);
triangleInstanceIndexByTriangleIndex.Remove(index);
//if (log) Debug.Log("RemoveTriangleGameObjectByIndex after index=" + index + ",triangleInstances.Count=" + triangleInstances.Count + ",triangleInstances=" + TriangleInstancesToString());
triangleInstanceIndexByTriangleIndexValid = false;
}
public void RemoveTriangle(int[] triangle) {
//if (log) Debug.Log("RemoveTriangle before (" + triangle[0] + "," + triangle[1] + "," + triangle[2] + "), triangles=" + TrianglesToString());
List<int> myTriangles = new List<int>();
List<int> triangleIndexesToRemove = new List<int>();
for (int i = 0; i + 2 < triangles.Count; i += 3) {
int a = triangles[i];
int b = triangles[i + 1];
int c = triangles[i + 2];
if (triangle[0] == a && triangle[1] == b && triangle[2] == c) {
// remove by doing nothing
//if (log) Debug.Log("RemoveTriangle i="+i+",a=" + a + ",b=" + b + ",c=" + c);
RemoveTriangleGameObjectByIndex(i);
triangleIndexesToRemove.Add(i);
} else {
myTriangles.Add(a);
myTriangles.Add(b);
myTriangles.Add(c);
}
}
for (int i = triangleIndexesToRemove.Count - 1; i >= 0; i--) {
int triangleIndex = triangleIndexesToRemove[i];
SubtractThreeFromTriangleInstanceIndexAboveIndex(triangleIndex);
mesh.materials.RemoveTriangleByIndex(triangleIndex);
}
triangles = myTriangles;
if (triangleIndexesToRemove.Count > 0) {
// triangles were removed, so rebuild
trianglesChanged = true;
mesh.persistence.changedSinceLastSave = true;
RebuildTriangleInstanceIndex();
}
//if (log) Debug.Log("RemoveTriangle after (" + triangle[0] + "," + triangle[1] + "," + triangle[2] + "), triangles=" + TrianglesToString());
}
public Vector3 CalculateNormal(Vector3 a, Vector3 b, Vector3 c) {
Vector3 planeNormal = Vector3.Cross(b - a, c - a).normalized;
return planeNormal;
}
public Vector3 CalculateNormalOfTriangle(Triangle triangle) {
int triangleIndex = triangle.index;
int a_index = triangles[triangleIndex];
int b_index = triangles[triangleIndex + 1];
int c_index = triangles[triangleIndex + 2];
Vertex a = mesh.vertices.vertices[a_index];
Vertex b = mesh.vertices.vertices[b_index];
Vertex c = mesh.vertices.vertices[c_index];
return triangle.instance.transform.rotation * CalculateNormal(a.position, b.position, c.position);
}
public void FlipNormalsOfSelection() {
if (mesh.selection.selectedTriangles.Count < 1) return;
foreach (Triangle triangle in mesh.selection.selectedTriangles) {
FlipNormalByTriangle(triangle);
}
}
public void FlipNormalByTriangle(Triangle triangle) {
int triangleIndex = triangle.index;
int a_index = triangles[triangleIndex];
int b_index = triangles[triangleIndex + 1];
int c_index = triangles[triangleIndex + 2];
triangles[triangleIndex] = c_index;
triangles[triangleIndex + 1] = b_index;
triangles[triangleIndex + 2] = a_index;
trianglesChanged = true;
mesh.persistence.changedSinceLastSave = true;
if (triangle.instance != null) {
Vertex a = mesh.vertices.vertices[a_index];
Vertex b = mesh.vertices.vertices[b_index];
Vertex c = mesh.vertices.vertices[c_index];
Vector3 center = mesh.Center(a.position, b.position, c.position);
TriangleController triangleController = triangle.instance.GetComponent<TriangleController>();
triangleController.Populate(c, b, a, center);
}
}
public Triangle FindTriangleByVertices(Vertex[] vertices) {
int a_index = mesh.vertices.IndexOfVertex(vertices[0]);
int b_index = mesh.vertices.IndexOfVertex(vertices[1]);
int c_index = mesh.vertices.IndexOfVertex(vertices[2]);
if (a_index == -1 || b_index == -1 || c_index == -1) {
Debug.Log("FindTriangleByVertices couldn't find a vertex");
return null;
}
int triangleIndex = -1;
for (int i = 0; i < triangles.Count; i += 3) {
int a_index2 = triangles[i];
int b_index2 = triangles[i + 1];
int c_index2 = triangles[i + 2];
if (a_index2 == a_index && b_index2 == b_index && c_index2 == c_index) {
triangleIndex = i;
break;
}
}
if (triangleIndex == -1) {
Debug.Log("FindTriangleByVertices couldn't find triangle");
return null;
}
return TriangleByIndex(triangleIndex);
}
public void FlipNormalByVertices(Vertex[] vertices) {
Triangle triangle = FindTriangleByVertices(vertices);
if (triangle != null) FlipNormalByTriangle(triangle);
}
public void MoveTriangleIndexFromToVertexIndex(int triangleIndex, int triangleOffset, int vertexIndex, Vertex fromVertex, Vertex toVertex) {
triangles[triangleIndex + triangleOffset] = vertexIndex;
Triangle triangle = TriangleByIndex(triangleIndex);
if (triangle == null) {
Debug.Log("MoveTriangleIndexFromToVertexIndex no triangle at triangleIndex=" + triangleIndex + ",triangleOffset=" + triangleOffset + ",triangleInstancesCreated =" + triangleInstancesCreated);
return;
}
triangle.index = vertexIndex;
TriangleController triangleController = triangle.instance.GetComponent<TriangleController>();
Vertex[] vertices = triangleController.GetTriangle();
Vertex a = vertices[0];
Vertex b = vertices[1];
Vertex c = vertices[2];
if (a.ID == fromVertex.ID) triangleController.SetA(toVertex.position);
if (b.ID == fromVertex.ID) triangleController.SetB(toVertex.position);
if (c.ID == fromVertex.ID) triangleController.SetC(toVertex.position);
}
public void MoveAllTrianglesFromFirstToSecondVertex(Vertex first, Vertex second) {
int firstIndex = mesh.vertices.IndexOfVertex(first);
if (firstIndex == -1) Debug.Log("MoveAllTrianglesFromFirstToSecondVertex firstIndex = -1");
int secondIndex = mesh.vertices.IndexOfVertex(second);
if (secondIndex == -1) Debug.Log("MoveAllTrianglesFromFirstToSecondVertex secondIndex = -1");
List<TriangleToRemove> trianglesToRemove = new List<TriangleToRemove>();
for (int i = 0; i + 2 < triangles.Count; i += 3) {
int a = triangles[i];
int b = triangles[i + 1];
int c = triangles[i + 2];
if ((a == firstIndex || b == firstIndex || c == firstIndex) && (a == secondIndex || b == secondIndex || c == secondIndex)) {
// triangle has both vertices, so it should be removed.
TriangleToRemove triangleToRemove = new TriangleToRemove();
triangleToRemove.triangle = new int[] { a, b, c };
trianglesToRemove.Add(triangleToRemove);
//Debug.Log("MoveAllTrianglesFromFirstToSecondVertex triangleToRemove a=" + a + ",b=" + b + ",c=" + c);
} else {
if (a == firstIndex) MoveTriangleIndexFromToVertexIndex(i, 0, secondIndex, first, second);
if (b == firstIndex) MoveTriangleIndexFromToVertexIndex(i, 1, secondIndex, first, second);
if (c == firstIndex) MoveTriangleIndexFromToVertexIndex(i, 2, secondIndex, first, second);
}
}
foreach (TriangleToRemove triangleToRemove in trianglesToRemove) {
RemoveTriangle(triangleToRemove.triangle);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Reflection;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.Packets;
using GridProxy;
using Logger = OpenMetaverse.Logger;
namespace GridProxy
{
public class ProxyFrame
{
public Proxy proxy;
private Dictionary<string, CommandDelegate> commandDelegates = new Dictionary<string, CommandDelegate>();
private UUID agentID;
private UUID sessionID;
private UUID secureSessionID;
private UUID inventoryRoot;
private bool logLogin = false;
private string[] args;
public delegate void CommandDelegate(string[] words);
public string[] Args
{
get { return args; }
}
public UUID AgentID
{
get { return agentID; }
}
public UUID SessionID
{
get { return sessionID; }
}
public UUID SecureSessionID
{
get { return secureSessionID; }
}
public UUID InventoryRoot
{
get { return inventoryRoot; }
}
public void AddCommand(string cmd, CommandDelegate deleg)
{
commandDelegates[cmd] = deleg;
}
public ProxyFrame(string[] args)
{
Init(args, null);
}
public ProxyFrame(string[] args, ProxyConfig proxyConfig)
{
Init(args, proxyConfig);
}
private void Init(string[] args, ProxyConfig proxyConfig)
{
//bool externalPlugin = false;
this.args = args;
if (proxyConfig == null)
{
proxyConfig = new ProxyConfig("GridProxy", "Austin Jennings / Andrew Ortman", args, true);
}
proxy = new Proxy(proxyConfig);
// add delegates for login
proxy.AddLoginRequestDelegate(new XmlRpcRequestDelegate(LoginRequest));
proxy.AddLoginResponseDelegate(new XmlRpcResponseDelegate(LoginResponse));
// add a delegate for outgoing chat
proxy.AddDelegate(PacketType.ChatFromViewer, Direction.Outgoing, new PacketDelegate(ChatFromViewerOut));
// handle command line arguments
foreach (string arg in args)
if (arg == "--log-login")
logLogin = true;
else if (arg.Substring(0, 2) == "--")
{
int ipos = arg.IndexOf("=");
if (ipos != -1)
{
string sw = arg.Substring(0, ipos);
string val = arg.Substring(ipos + 1);
Logger.Log("arg '" + sw + "' val '" + val + "'", Helpers.LogLevel.Debug);
if (sw == "--load")
{
//externalPlugin = true;
LoadPlugin(val);
}
}
}
commandDelegates["/load"] = new CommandDelegate(CmdLoad);
}
private void CmdLoad(string[] words)
{
if (words.Length != 2)
SayToUser("Usage: /load <plugin name>");
else
{
try
{
LoadPlugin(words[1]);
}
catch (Exception e)
{
Logger.Log("LoadPlugin exception", Helpers.LogLevel.Error, e);
}
}
}
public void LoadPlugin(string name)
{
Assembly assembly = Assembly.LoadFile(Path.GetFullPath(name));
foreach (Type t in assembly.GetTypes())
{
try
{
if (t.IsSubclassOf(typeof(ProxyPlugin)))
{
ConstructorInfo info = t.GetConstructor(new Type[] { typeof(ProxyFrame) });
ProxyPlugin plugin = (ProxyPlugin)info.Invoke(new object[] { this });
plugin.Init();
}
}
catch (Exception e)
{
Logger.Log("LoadPlugin exception", Helpers.LogLevel.Error, e);
}
}
}
// LoginRequest: dump a login request to the console
private void LoginRequest(object sender, XmlRpcRequestEventArgs e)
{
if (logLogin)
{
Console.WriteLine("==> Login Request");
Console.WriteLine(e.m_Request);
}
}
// Loginresponse: dump a login response to the console
private void LoginResponse(XmlRpcResponse response)
{
System.Collections.Hashtable values = (System.Collections.Hashtable)response.Value;
if (values.Contains("agent_id"))
agentID = new UUID((string)values["agent_id"]);
if (values.Contains("session_id"))
sessionID = new UUID((string)values["session_id"]);
if (values.Contains("secure_session_id"))
secureSessionID = new UUID((string)values["secure_session_id"]);
if (values.Contains("inventory-root"))
{
inventoryRoot = new UUID(
(string)((System.Collections.Hashtable)(((System.Collections.ArrayList)values["inventory-root"])[0]))["folder_id"]
);
if (logLogin)
{
Console.WriteLine("inventory root: " + inventoryRoot);
}
}
if (logLogin)
{
Console.WriteLine("<== Login Response");
Console.WriteLine(response);
}
}
// ChatFromViewerOut: outgoing ChatFromViewer delegate; check for Analyst commands
private Packet ChatFromViewerOut(Packet packet, IPEndPoint sim)
{
// deconstruct the packet
ChatFromViewerPacket cpacket = (ChatFromViewerPacket)packet;
string message = System.Text.Encoding.UTF8.GetString(cpacket.ChatData.Message).Replace("\0", "");
if (message.Length > 1 && message[0] == '/')
{
string[] words = message.Split(' ');
if (commandDelegates.ContainsKey(words[0]))
{
// this is an Analyst command; act on it and drop the chat packet
((CommandDelegate)commandDelegates[words[0]])(words);
return null;
}
}
return packet;
}
/// <summary>
/// Send a message to the viewer
/// </summary>
/// <param name="message">A string containing the message to send</param>
public void SayToUser(string message)
{
SayToUser("GridProxy", message);
}
/// <summary>
/// Send a message to the viewer
/// </summary>
/// <param name="fromName">A string containing text indicating the origin of the message</param>
/// <param name="message">A string containing the message to send</param>
public void SayToUser(string fromName, string message)
{
ChatFromSimulatorPacket packet = new ChatFromSimulatorPacket();
packet.ChatData.SourceID = UUID.Random();
packet.ChatData.FromName = Utils.StringToBytes(fromName);
packet.ChatData.OwnerID = agentID;
packet.ChatData.SourceType = (byte)2;
packet.ChatData.ChatType = (byte)1;
packet.ChatData.Audible = (byte)1;
packet.ChatData.Position = new Vector3(0, 0, 0);
packet.ChatData.Message = Utils.StringToBytes(message);
proxy.InjectPacket(packet, Direction.Incoming);
}
}
public abstract class ProxyPlugin : MarshalByRefObject
{
// public abstract ProxyPlugin(ProxyFrame main);
public abstract void Init();
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using Elasticsearch.Net.Connection;
using Elasticsearch.Net.ConnectionPool;
using Nest.Resolvers;
using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// Provides NEST's ElasticClient with configurationsettings
/// </summary>
public class ConnectionSettings : ConnectionSettings<ConnectionSettings>
{
/// <summary>
/// Instantiate a new connectionsettings object that proves ElasticClient with configuration values
/// </summary>
/// <param name="uri">A single uri representing the root of the node you want to connect to
/// <para>defaults to http://localhost:9200</para>
/// </param>
/// <param name="defaultIndex">The default index/alias name used for operations that expect an index/alias name,
/// By specifying it once alot of magic string can be avoided.
/// <para>You can also specify specific default index/alias names for types using .SetDefaultTypeIndices(</para>
/// <para>If you do not specify this, NEST might throw a runtime exception if an explicit indexname was not provided for a call</para>
/// </param>
public ConnectionSettings(Uri uri = null, string defaultIndex = null)
: base(uri, defaultIndex)
{
}
/// <summary>
/// Instantiate a new connectionsettings object that proves ElasticClient with configuration values
/// </summary>
/// <param name="connectionPool">A connection pool implementation that'll tell the client what nodes are available</param>
/// <param name="defaultIndex">The default index/alias name used for operations that expect an index/alias name,
/// By specifying it once alot of magic string can be avoided.
/// <para>You can also specify specific default index/alias names for types using .SetDefaultTypeIndices(</para>
/// <para>If you do not specify this, NEST might throw a runtime exception if an explicit indexname was not provided for a call</para>
/// </param>
public ConnectionSettings(IConnectionPool connectionPool, string defaultIndex = null) : base(connectionPool, defaultIndex)
{
}
}
/// <summary>
/// Control how NEST's behaviour.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ConnectionSettings<T> : ConnectionConfiguration<T> , IConnectionSettingsValues
where T : ConnectionSettings<T>
{
private string _defaultIndex;
string IConnectionSettingsValues.DefaultIndex
{
get
{
//if (this._defaultIndex.IsNullOrEmpty())
// throw new NullReferenceException("No default index set on connection!");
return this._defaultIndex;
}
}
private ElasticInferrer _inferrer;
ElasticInferrer IConnectionSettingsValues.Inferrer { get { return _inferrer; } }
private Func<Type, string> _defaultTypeNameInferrer;
Func<Type, string> IConnectionSettingsValues.DefaultTypeNameInferrer { get { return _defaultTypeNameInferrer; } }
private FluentDictionary<Type, string> _defaultIndices;
FluentDictionary<Type, string> IConnectionSettingsValues.DefaultIndices { get { return _defaultIndices; } }
private FluentDictionary<Type, string> _defaultTypeNames;
FluentDictionary<Type, string> IConnectionSettingsValues.DefaultTypeNames { get { return _defaultTypeNames; } }
private Func<string, string> _defaultPropertyNameInferrer;
Func<string, string> IConnectionSettingsValues.DefaultPropertyNameInferrer { get { return _defaultPropertyNameInferrer; } }
//these are set once to make sure we don't query the Uri too often
//Serializer settings
private Action<JsonSerializerSettings> _modifyJsonSerializerSettings;
Action<JsonSerializerSettings> IConnectionSettingsValues.ModifyJsonSerializerSettings { get { return _modifyJsonSerializerSettings; } }
private ReadOnlyCollection<Func<Type, JsonConverter>> _contractConverters;
ReadOnlyCollection<Func<Type, JsonConverter>> IConnectionSettingsValues.ContractConverters { get { return _contractConverters; } }
public ConnectionSettings(IConnectionPool connectionPool, string defaultIndex) : base(connectionPool)
{
if (!defaultIndex.IsNullOrEmpty())
this.SetDefaultIndex(defaultIndex);
this._defaultTypeNameInferrer = (t => t.Name.ToLowerInvariant());
this._defaultPropertyNameInferrer = (p => p.ToCamelCase());
this._defaultIndices = new FluentDictionary<Type, string>();
this._defaultTypeNames = new FluentDictionary<Type, string>();
this._modifyJsonSerializerSettings = (j) => { };
this._contractConverters = Enumerable.Empty<Func<Type, JsonConverter>>().ToList().AsReadOnly();
this._inferrer = new ElasticInferrer(this);
}
public ConnectionSettings(Uri uri, string defaultIndex)
: this(new SingleNodeConnectionPool(uri ?? new Uri("http://localhost:9200")), defaultIndex)
{
}
/// <summary>
/// This calls SetDefaultTypenameInferrer with an implementation that will pluralize type names. This used to be the default prior to Nest 0.90
/// </summary>
public T PluralizeTypeNames()
{
this._defaultTypeNameInferrer = this.LowerCaseAndPluralizeTypeNameInferrer;
return (T)this;
}
/// <summary>
/// Allows you to update internal the json.net serializer settings to your liking
/// </summary>
public T SetJsonSerializerSettingsModifier(Action<JsonSerializerSettings> modifier)
{
if (modifier == null)
return (T)this;
this._modifyJsonSerializerSettings = modifier;
return (T)this;
}
/// <summary>
/// Add a custom JsonConverter to the build in json serialization by passing in a predicate for a type.
/// This is faster then adding them using AddJsonConverters() because this way they will be part of the cached
/// Json.net contract for a type.
/// </summary>
public T AddContractJsonConverters(params Func<Type, JsonConverter>[] contractSelectors)
{
this._contractConverters = contractSelectors.ToList().AsReadOnly();
return (T)this;
}
/// <summary>
/// Index to default to when no index is specified.
/// </summary>
/// <param name="defaultIndex">When null/empty/not set might throw NRE later on
/// when not specifying index explicitly while indexing.
/// </param>
public T SetDefaultIndex(string defaultIndex)
{
this._defaultIndex = defaultIndex;
return (T)this;
}
private string LowerCaseAndPluralizeTypeNameInferrer(Type type)
{
type.ThrowIfNull("type");
return Inflector.MakePlural(type.Name).ToLowerInvariant();
}
/// <summary>
/// By default NEST camelCases property names (EmailAddress => emailAddress) that do not have an explicit propertyname
/// either via an ElasticProperty attribute or because they are part of Dictionary where the keys should be treated verbatim.
/// <pre>
/// Here you can register a function that transforms propertynames (default casing, pre- or suffixing)
/// </pre>
/// </summary>
public T SetDefaultPropertyNameInferrer(Func<string, string> propertyNameSelector)
{
this._defaultPropertyNameInferrer = propertyNameSelector;
return (T)this;
}
/// <summary>
/// Allows you to override how type names should be reprented, the default will call .ToLowerInvariant() on the type's name.
/// </summary>
public T SetDefaultTypeNameInferrer(Func<Type, string> defaultTypeNameInferrer)
{
defaultTypeNameInferrer.ThrowIfNull("defaultTypeNameInferrer");
this._defaultTypeNameInferrer = defaultTypeNameInferrer;
return (T)this;
}
/// <summary>
/// Map types to a index names. Takes precedence over SetDefaultIndex().
/// </summary>
public T MapDefaultTypeIndices(Action<FluentDictionary<Type, string>> mappingSelector)
{
mappingSelector.ThrowIfNull("mappingSelector");
mappingSelector(this._defaultIndices);
return (T)this;
}
/// <summary>
/// Allows you to override typenames, takes priority over the global SetDefaultTypeNameInferrer()
/// </summary>
public T MapDefaultTypeNames(Action<FluentDictionary<Type, string>> mappingSelector)
{
mappingSelector.ThrowIfNull("mappingSelector");
mappingSelector(this._defaultTypeNames);
return (T)this;
}
}
}
| |
/***************************************************************************
* Timer.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id: Timer.cs 816 2012-01-04 08:45:24Z asayre $
*
***************************************************************************/
/***************************************************************************
*
* 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.
*
***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Server.Diagnostics;
namespace Server
{
public enum TimerPriority
{
EveryTick,
TenMS,
TwentyFiveMS,
FiftyMS,
TwoFiftyMS,
OneSecond,
FiveSeconds,
OneMinute
}
public delegate void TimerCallback();
public delegate void TimerStateCallback( object state );
public delegate void TimerStateCallback<T>( T state );
public class Timer
{
private DateTime m_Next;
private TimeSpan m_Delay;
private TimeSpan m_Interval;
private bool m_Running;
private int m_Index, m_Count;
private TimerPriority m_Priority;
private List<Timer> m_List;
private bool m_PrioritySet;
private static string FormatDelegate( Delegate callback )
{
if ( callback == null )
return "null";
return String.Format( "{0}.{1}", callback.Method.DeclaringType.FullName, callback.Method.Name );
}
public static void DumpInfo( TextWriter tw )
{
TimerThread.DumpInfo( tw );
}
public TimerPriority Priority
{
get
{
return m_Priority;
}
set
{
if ( !m_PrioritySet )
m_PrioritySet = true;
if ( m_Priority != value )
{
m_Priority = value;
if ( m_Running )
TimerThread.PriorityChange( this, (int)m_Priority );
}
}
}
public DateTime Next
{
get { return m_Next; }
}
public TimeSpan Delay
{
get { return m_Delay; }
set { m_Delay = value; }
}
public TimeSpan Interval
{
get { return m_Interval; }
set { m_Interval = value; }
}
public bool Running
{
get { return m_Running; }
set {
if ( value ) {
Start();
} else {
Stop();
}
}
}
public TimerProfile GetProfile()
{
if ( !Core.Profiling ) {
return null;
}
string name = ToString();
if ( name == null ) {
name = "null";
}
return TimerProfile.Acquire( name );
}
public class TimerThread
{
private static Queue m_ChangeQueue = Queue.Synchronized( new Queue() );
private static DateTime[] m_NextPriorities = new DateTime[8];
private static TimeSpan[] m_PriorityDelays = new TimeSpan[8]
{
TimeSpan.Zero,
TimeSpan.FromMilliseconds( 10.0 ),
TimeSpan.FromMilliseconds( 25.0 ),
TimeSpan.FromMilliseconds( 50.0 ),
TimeSpan.FromMilliseconds( 250.0 ),
TimeSpan.FromSeconds( 1.0 ),
TimeSpan.FromSeconds( 5.0 ),
TimeSpan.FromMinutes( 1.0 )
};
private static List<Timer>[] m_Timers = new List<Timer>[8]
{
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
new List<Timer>(),
};
public static void DumpInfo( TextWriter tw )
{
for ( int i = 0; i < 8; ++i )
{
tw.WriteLine( "Priority: {0}", (TimerPriority)i );
tw.WriteLine();
Dictionary<string, List<Timer>> hash = new Dictionary<string, List<Timer>>();
for ( int j = 0; j < m_Timers[i].Count; ++j )
{
Timer t = m_Timers[i][j];
string key = t.ToString();
List<Timer> list;
hash.TryGetValue( key, out list );
if ( list == null )
hash[key] = list = new List<Timer>();
list.Add( t );
}
foreach ( KeyValuePair<string, List<Timer>> kv in hash )
{
string key = kv.Key;
List<Timer> list = kv.Value;
tw.WriteLine( "Type: {0}; Count: {1}; Percent: {2}%", key, list.Count, (int)(100 * (list.Count / (double)m_Timers[i].Count)) );
}
tw.WriteLine();
tw.WriteLine();
}
}
private class TimerChangeEntry
{
public Timer m_Timer;
public int m_NewIndex;
public bool m_IsAdd;
private TimerChangeEntry( Timer t, int newIndex, bool isAdd )
{
m_Timer = t;
m_NewIndex = newIndex;
m_IsAdd = isAdd;
}
public void Free()
{
//m_InstancePool.Enqueue( this );
}
private static Queue<TimerChangeEntry> m_InstancePool = new Queue<TimerChangeEntry>();
public static TimerChangeEntry GetInstance( Timer t, int newIndex, bool isAdd )
{
TimerChangeEntry e;
if ( m_InstancePool.Count > 0 )
{
e = m_InstancePool.Dequeue();
if ( e == null )
e = new TimerChangeEntry( t, newIndex, isAdd );
else
{
e.m_Timer = t;
e.m_NewIndex = newIndex;
e.m_IsAdd = isAdd;
}
}
else
{
e = new TimerChangeEntry( t, newIndex, isAdd );
}
return e;
}
}
public TimerThread()
{
}
public static void Change( Timer t, int newIndex, bool isAdd )
{
m_ChangeQueue.Enqueue( TimerChangeEntry.GetInstance( t, newIndex, isAdd ) );
m_Signal.Set();
}
public static void AddTimer( Timer t )
{
Change( t, (int)t.Priority, true );
}
public static void PriorityChange( Timer t, int newPrio )
{
Change( t, newPrio, false );
}
public static void RemoveTimer( Timer t )
{
Change( t, -1, false );
}
private static void ProcessChangeQueue()
{
while ( m_ChangeQueue.Count > 0 )
{
TimerChangeEntry tce = (TimerChangeEntry)m_ChangeQueue.Dequeue();
Timer timer = tce.m_Timer;
int newIndex = tce.m_NewIndex;
if ( timer.m_List != null )
timer.m_List.Remove( timer );
if ( tce.m_IsAdd )
{
timer.m_Next = DateTime.Now + timer.m_Delay;
timer.m_Index = 0;
}
if ( newIndex >= 0 )
{
timer.m_List = m_Timers[newIndex];
timer.m_List.Add( timer );
}
else
{
timer.m_List = null;
}
tce.Free();
}
}
private static AutoResetEvent m_Signal = new AutoResetEvent( false );
public static void Set() { m_Signal.Set(); }
public void TimerMain()
{
DateTime now;
int i, j;
bool loaded;
while ( !Core.Closing )
{
ProcessChangeQueue();
loaded = false;
for ( i = 0; i < m_Timers.Length; i++)
{
now = DateTime.Now;
if ( now < m_NextPriorities[i] )
break;
m_NextPriorities[i] = now + m_PriorityDelays[i];
for ( j = 0; j < m_Timers[i].Count; j++)
{
Timer t = m_Timers[i][j];
if ( !t.m_Queued && now > t.m_Next )
{
t.m_Queued = true;
lock ( m_Queue )
m_Queue.Enqueue( t );
loaded = true;
if ( t.m_Count != 0 && (++t.m_Index >= t.m_Count) )
{
t.Stop();
}
else
{
t.m_Next = now + t.m_Interval;
}
}
}
}
if ( loaded )
Core.Set();
m_Signal.WaitOne( 10, false );
}
}
}
private static Queue<Timer> m_Queue = new Queue<Timer>();
private static int m_BreakCount = 20000;
public static int BreakCount{ get{ return m_BreakCount; } set{ m_BreakCount = value; } }
private static int m_QueueCountAtSlice;
private bool m_Queued;
public static void Slice()
{
lock ( m_Queue )
{
m_QueueCountAtSlice = m_Queue.Count;
int index = 0;
while ( index < m_BreakCount && m_Queue.Count != 0 )
{
Timer t = m_Queue.Dequeue();
TimerProfile prof = t.GetProfile();
if ( prof != null ) {
prof.Start();
}
t.OnTick();
t.m_Queued = false;
++index;
if ( prof != null ) {
prof.Finish();
}
}
}
}
public Timer( TimeSpan delay ) : this( delay, TimeSpan.Zero, 1 )
{
}
public Timer( TimeSpan delay, TimeSpan interval ) : this( delay, interval, 0 )
{
}
public virtual bool DefRegCreation
{
get{ return true; }
}
public virtual void RegCreation()
{
TimerProfile prof = GetProfile();
if ( prof != null ) {
prof.Created++;
}
}
public Timer( TimeSpan delay, TimeSpan interval, int count )
{
m_Delay = delay;
m_Interval = interval;
m_Count = count;
if ( !m_PrioritySet ) {
if ( count == 1 ) {
m_Priority = ComputePriority( delay );
} else {
m_Priority = ComputePriority( interval );
}
m_PrioritySet = true;
}
if ( DefRegCreation )
RegCreation();
}
public override string ToString()
{
return GetType().FullName;
}
public static TimerPriority ComputePriority( TimeSpan ts )
{
if ( ts >= TimeSpan.FromMinutes( 1.0 ) )
return TimerPriority.FiveSeconds;
if ( ts >= TimeSpan.FromSeconds( 10.0 ) )
return TimerPriority.OneSecond;
if ( ts >= TimeSpan.FromSeconds( 5.0 ) )
return TimerPriority.TwoFiftyMS;
if ( ts >= TimeSpan.FromSeconds( 2.5 ) )
return TimerPriority.FiftyMS;
if ( ts >= TimeSpan.FromSeconds( 1.0 ) )
return TimerPriority.TwentyFiveMS;
if ( ts >= TimeSpan.FromSeconds( 0.5 ) )
return TimerPriority.TenMS;
return TimerPriority.EveryTick;
}
#region DelayCall(..)
public static Timer DelayCall(TimerCallback callback)
{
return DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback);
}
public static Timer DelayCall(TimeSpan delay, TimerCallback callback)
{
return DelayCall(delay, TimeSpan.Zero, 1, callback);
}
public static Timer DelayCall(TimeSpan delay, TimeSpan interval, TimerCallback callback)
{
return DelayCall(delay, interval, 0, callback);
}
public static Timer DelayCall(TimeSpan delay, TimeSpan interval, int count, TimerCallback callback)
{
Timer t = new DelayCallTimer(delay, interval, count, callback);
if (count == 1)
t.Priority = ComputePriority(delay);
else
t.Priority = ComputePriority(interval);
t.Start();
return t;
}
public static Timer DelayCall(TimerStateCallback callback, object state)
{
return DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, state);
}
public static Timer DelayCall(TimeSpan delay, TimerStateCallback callback, object state)
{
return DelayCall(delay, TimeSpan.Zero, 1, callback, state);
}
public static Timer DelayCall(TimeSpan delay, TimeSpan interval, TimerStateCallback callback, object state)
{
return DelayCall(delay, interval, 0, callback, state);
}
public static Timer DelayCall(TimeSpan delay, TimeSpan interval, int count, TimerStateCallback callback, object state)
{
Timer t = new DelayStateCallTimer(delay, interval, count, callback, state);
if (count == 1)
t.Priority = ComputePriority(delay);
else
t.Priority = ComputePriority(interval);
t.Start();
return t;
}
#endregion
#region DelayCall<T>(..)
public static Timer DelayCall<T>(TimerStateCallback<T> callback, T state)
{
return DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, state);
}
public static Timer DelayCall<T>(TimeSpan delay, TimerStateCallback<T> callback, T state)
{
return DelayCall(delay, TimeSpan.Zero, 1, callback, state);
}
public static Timer DelayCall<T>(TimeSpan delay, TimeSpan interval, TimerStateCallback<T> callback, T state)
{
return DelayCall(delay, interval, 0, callback, state);
}
public static Timer DelayCall<T>(TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T> callback, T state)
{
Timer t = new DelayStateCallTimer<T>(delay, interval, count, callback, state);
if (count == 1)
t.Priority = ComputePriority(delay);
else
t.Priority = ComputePriority(interval);
t.Start();
return t;
}
#endregion
#region DelayCall Timers
private class DelayCallTimer : Timer
{
private TimerCallback m_Callback;
public TimerCallback Callback{ get{ return m_Callback; } }
public override bool DefRegCreation{ get{ return false; } }
public DelayCallTimer( TimeSpan delay, TimeSpan interval, int count, TimerCallback callback ) : base( delay, interval, count )
{
m_Callback = callback;
RegCreation();
}
protected override void OnTick()
{
if ( m_Callback != null )
m_Callback();
}
public override string ToString()
{
return String.Format( "DelayCallTimer[{0}]", FormatDelegate( m_Callback ) );
}
}
private class DelayStateCallTimer : Timer
{
private TimerStateCallback m_Callback;
private object m_State;
public TimerStateCallback Callback{ get{ return m_Callback; } }
public override bool DefRegCreation{ get{ return false; } }
public DelayStateCallTimer( TimeSpan delay, TimeSpan interval, int count, TimerStateCallback callback, object state ) : base( delay, interval, count )
{
m_Callback = callback;
m_State = state;
RegCreation();
}
protected override void OnTick()
{
if ( m_Callback != null )
m_Callback( m_State );
}
public override string ToString()
{
return String.Format( "DelayStateCall[{0}]", FormatDelegate( m_Callback ) );
}
}
private class DelayStateCallTimer<T> : Timer
{
private TimerStateCallback<T> m_Callback;
private T m_State;
public TimerStateCallback<T> Callback { get { return m_Callback; } }
public override bool DefRegCreation { get { return false; } }
public DelayStateCallTimer( TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T> callback, T state )
: base( delay, interval, count )
{
m_Callback = callback;
m_State = state;
RegCreation();
}
protected override void OnTick()
{
if( m_Callback != null )
m_Callback( m_State );
}
public override string ToString()
{
return String.Format( "DelayStateCall[{0}]", FormatDelegate( m_Callback ) );
}
}
#endregion
public void Start()
{
if ( !m_Running )
{
m_Running = true;
TimerThread.AddTimer( this );
TimerProfile prof = GetProfile();
if ( prof != null ) {
prof.Started++;
}
}
}
public void Stop()
{
if ( m_Running )
{
m_Running = false;
TimerThread.RemoveTimer( this );
TimerProfile prof = GetProfile();
if ( prof != null ) {
prof.Stopped++;
}
}
}
protected virtual void OnTick()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
///<summary>
///System.Test.UnicodeEncoding.GetByteCount(System.Char[],System.Int32,System.Int32) [v-zuolan]
///</summary>
public class UnicodeEncodingGetByteCount
{
public static int Main()
{
UnicodeEncodingGetByteCount testObj = new UnicodeEncodingGetByteCount();
TestLibrary.TestFramework.BeginTestCase("for field of System.Test.UnicodeEncoding");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("Positive");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("Positive");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Helper Method
//Create a None-Surrogate-Char Array.
public Char[] GetCharArray(int length)
{
if (length <= 0) return new Char[] { };
Char[] charArray = new Char[length];
int i = 0;
while (i < length)
{
Char temp = TestLibrary.Generator.GetChar(-55);
if (!Char.IsSurrogate(temp))
{
charArray[i] = temp;
i++;
}
}
return charArray;
}
//Convert Char Array to String
public String ToString(Char[] chars)
{
String str = "{";
for (int i = 0;i < chars.Length; i++)
{
str = str + @"\u" + String.Format("{0:X04}", (int)chars[i]);
if (i != chars.Length - 1) str = str + ",";
}
str = str + "}";
return str;
}
#endregion
#region Positive Test Logic
public bool PosTest1()
{
bool retVal = true;
Char[] chars = new Char[] { } ;
UnicodeEncoding uEncoding = new UnicodeEncoding();
int expectedValue = 0;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method with a empty char array.");
try
{
actualValue = uEncoding.GetByteCount(chars,0,0);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
UnicodeEncoding uEncoding = new UnicodeEncoding();
int expectedValue = 20;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method with max length of the char array.");
try
{
actualValue = uEncoding.GetByteCount(chars, 0, chars.Length);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ") when chars is:" + ToString(chars));
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e + "when chars is:" + ToString(chars));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
Char[] chars = GetCharArray(1);
UnicodeEncoding uEncoding = new UnicodeEncoding();
int expectedValue = 2;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method with one char array.");
try
{
actualValue = uEncoding.GetByteCount(chars, 0, 1);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ") when chars is:" + ToString(chars));
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception:" + e + "when chars is:" + ToString(chars));
retVal = false;
}
return retVal;
}
#endregion
#region Negative Test Logic
public bool NegTest1()
{
bool retVal = true;
//Char[] chars = new Char[]{};
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
TestLibrary.TestFramework.BeginScenario("NegTest1:Invoke the method with null");
try
{
actualValue = uEncoding.GetByteCount((char[])null, 0, 0);
TestLibrary.TestFramework.LogError("007", "No ArgumentNullException throw out expected.");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
TestLibrary.TestFramework.BeginScenario("NegTest2:Invoke the method with index out of range.");
try
{
actualValue = uEncoding.GetByteCount(chars, 10, 1);
TestLibrary.TestFramework.LogError("009", "No ArgumentOutOfRangeException throw out expected when chars is:" + ToString(chars));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception:" + e + " when chars is:" + ToString(chars));
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
TestLibrary.TestFramework.BeginScenario("NegTest3:Invoke the method with count out of range.");
try
{
actualValue = uEncoding.GetByteCount(chars, 5, -1);
TestLibrary.TestFramework.LogError("011", "No ArgumentOutOfRangeException throw out expected when chars is:" + ToString(chars));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception:" + e + " when chars is:" + ToString(chars));
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ToolStripCustomizer.ColorTables
{
sealed class SystemColorTable : PresetColorTable
{
public SystemColorTable()
: base("System Colors")
{
}
public override Color ButtonSelectedBorder
{
get
{
return Color.FromName("ButtonShadow");
}
}
public override Color ButtonCheckedGradientBegin
{
get
{
return Color.FromName("ButtonFace");
}
}
public override Color ButtonCheckedGradientMiddle
{
get
{
return Color.FromName("ButtonFace");
}
}
public override Color ButtonCheckedGradientEnd
{
get
{
return Color.FromName("ButtonHighlight");
}
}
public override Color ButtonSelectedGradientBegin
{
get
{
return Color.FromName("ButtonHighlight");
}
}
public override Color ButtonSelectedGradientMiddle
{
get
{
return Color.FromName("ButtonHighlight");
}
}
public override Color ButtonSelectedGradientEnd
{
get
{
return Color.FromName("ButtonFace");
}
}
public override Color ButtonPressedGradientBegin
{
get
{
return Color.FromName("ButtonFace");
}
}
public override Color ButtonPressedGradientMiddle
{
get
{
return Color.FromName("ButtonFace");
}
}
public override Color ButtonPressedGradientEnd
{
get
{
return Color.FromName("ButtonHighlight");
}
}
public override Color CheckBackground
{
get
{
return Color.FromName("Menu");
}
}
public override Color CheckSelectedBackground
{
get
{
return Color.FromName("Menu");
}
}
public override Color CheckPressedBackground
{
get
{
return Color.FromName("MenuHighlight");
}
}
public override Color GripDark
{
get
{
return Color.FromName("ControlDark");
}
}
public override Color GripLight
{
get
{
return Color.FromName("ControlLight");
}
}
public override Color ImageMarginGradientBegin
{
get
{
return Color.FromName("ControlLight");
}
}
public override Color ImageMarginGradientMiddle
{
get
{
return Color.FromName("ControlLight");
}
}
public override Color ImageMarginGradientEnd
{
get
{
return Color.FromName("ControlLight");
}
}
public override Color ImageMarginRevealedGradientBegin
{
get
{
return Color.FromName("ControlLightLight");
}
}
public override Color ImageMarginRevealedGradientMiddle
{
get
{
return Color.FromName("ControlLightLight");
}
}
public override Color ImageMarginRevealedGradientEnd
{
get
{
return Color.FromName("Menu");
}
}
public override Color MenuStripGradientBegin
{
get
{
return Color.FromName("ControlLight");
}
}
public override Color MenuStripGradientEnd
{
get
{
return Color.FromName("ControlLight");
}
}
public override Color MenuItemSelected
{
get
{
return Color.FromName("MenuHighlight");
}
}
public override Color MenuItemBorder
{
get
{
return Color.FromArgb(0, 0, 0, 0);
}
}
public override Color MenuBorder
{
get
{
return Color.FromName("ControlDark");
}
}
public override Color MenuItemSelectedGradientBegin
{
get
{
return Color.FromName("MenuHighlight");
}
}
public override Color MenuItemSelectedGradientEnd
{
get
{
return Color.FromName("MenuHighlight");
}
}
public override Color MenuItemPressedGradientBegin
{
get
{
return Color.FromName("Menu");
}
}
public override Color MenuItemPressedGradientMiddle
{
get
{
return Color.FromName("Menu");
}
}
public override Color MenuItemPressedGradientEnd
{
get
{
return Color.FromName("Menu");
}
}
public override Color RaftingContainerGradientBegin
{
get
{
return Color.FromName("Control");
}
}
public override Color RaftingContainerGradientEnd
{
get
{
return Color.FromName("Control");
}
}
public override Color SeparatorDark
{
get
{
return Color.FromName("ActiveBorder");
}
}
public override Color SeparatorLight
{
get
{
return Color.FromName("Control");
}
}
public override Color StatusStripGradientBegin
{
get
{
return Color.FromName("ControlLight");
}
}
public override Color StatusStripGradientEnd
{
get
{
return Color.FromName("Control");
}
}
public override Color ToolStripBorder
{
get
{
return Color.FromName("ControlDark");
}
}
public override Color ToolStripDropDownBackground
{
get
{
return Color.FromName("Menu");
}
}
public override Color ToolStripGradientBegin
{
get
{
return Color.FromName("MenuBar");
}
}
public override Color ToolStripGradientMiddle
{
get
{
return Color.FromName("MenuBar");
}
}
public override Color ToolStripGradientEnd
{
get
{
return Color.FromName("MenuBar");
}
}
public override Color ToolStripContentPanelGradientBegin
{
get
{
return Color.FromName("AppWorkspace");
}
}
public override Color ToolStripContentPanelGradientEnd
{
get
{
return Color.FromName("AppWorkspace");
}
}
public override Color ToolStripPanelGradientBegin
{
get
{
return Color.FromName("ControlLight");
}
}
public override Color ToolStripPanelGradientEnd
{
get
{
return Color.FromName("Control");
}
}
public override Color OverflowButtonGradientBegin
{
get
{
return Color.FromName("ControlLightLight");
}
}
public override Color OverflowButtonGradientMiddle
{
get
{
return Color.FromName("ControlLight");
}
}
public override Color OverflowButtonGradientEnd
{
get
{
return Color.FromName("Control");
}
}
}
}
| |
namespace java.util
{
using java.lang;
public class LinkedList<V> : AbstractList<V>
{
private int currentIndex;
private int len;
private readonly Node<V> head;
private Node<V> currentNode;
public LinkedList()
{
Node<V> h = new Node<V>(default);
h.next = h;
h.prev = h;
this.head = h;
this.len = 0;
this.currentNode = h;
this.currentIndex = -1;
}
public LinkedList(Collection<V> collection) : this()
{
AddAll(collection);
}
public override V Get(int index)
{
return Seek(index).element;
}
public override V Set(int index, V element)
{
Node<V> n = Seek(index);
V prev = n.element;
n.element = element;
return prev;
}
public override void Add(int index, V element)
{
Node<V> n = new Node<V>(element);
Node<V> y;
if (index == len)
{
y = head;
}
else
{
y = Seek(index);
if (currentIndex >= index) { currentIndex++; }
}
Node<V> x = y.prev;
n.prev = x;
n.next = y;
x.next = n;
y.prev = n;
len++;
return;
}
public override V Remove(int index)
{
Node<V> n = Seek(index);
Node<V> x = n.prev;
Node<V> y = n.next;
x.next = y;
y.prev = x;
len--;
if (currentIndex >= index)
{
if (currentIndex == index)
{
currentNode = x;
}
currentIndex--;
}
return n.element;
}
public override int Size()
{
return len;
}
private Node<V> Seek(int index)
{
if (index < 0 || index >= len) { throw new IndexOutOfBoundsException(); }
if (index == 0) { return head.next; }
if (index == len - 1) { return head.prev; }
int ci = currentIndex;
if (index == ci) { return currentNode; }
Node<V> n = null;
if (index < ci)
{
if (index <= ci - index)
{
n = head.next;
for (int i = 0; i < index; i++)
{
n = n.next;
}
}
else
{
n = currentNode;
for (int i = currentIndex; i > index; i--)
{
n = n.prev;
}
}
}
else
{
if (index - ci <= len - index)
{
n = currentNode;
for (int i = ci; i < index; i++)
{
n = n.next;
}
}
else
{
n = head.prev;
for (int i = len - 1; i > index; i--)
{
n = n.prev;
}
}
}
currentNode = n;
currentIndex = index;
return n;
}
class Node<T>
{
public T element;
public Node<T> prev;
public Node<T> next;
public Node(T element)
{
this.element = element;
prev = null;
next = null;
}
}
public virtual void AddFirst(V obj)
{
Add(0, obj);
}
public virtual void AddLast(V obj)
{
Add(Size(), obj);
}
public virtual V GetFirst()
{
return Get(0);
}
public virtual V GetLast()
{
return Get(Size() - 1);
}
public virtual V RemoveFirst()
{
return Remove(0);
}
public virtual V RemoveLast()
{
return Remove(Size() - 1);
}
public override void Clear()
{
Node<V> h = head;
h.next = h;
h.prev = h;
len = 0;
currentNode = h;
currentIndex = -1;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Data.Common;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient
{
sealed internal class SqlSequentialTextReader : System.IO.TextReader
{
private SqlDataReader _reader; // The SqlDataReader that we are reading data from
private int _columnIndex; // The index of out column in the table
private Encoding _encoding; // Encoding for this character stream
private Decoder _decoder; // Decoder based on the encoding (NOTE: Decoders are stateful as they are designed to process streams of data)
private byte[] _leftOverBytes; // Bytes leftover from the last Read() operation - this can be null if there were no bytes leftover (Possible optimization: re-use the same array?)
private int _peekedChar; // The last character that we peeked at (or -1 if we haven't peeked at anything)
private Task _currentTask; // The current async task
private CancellationTokenSource _disposalTokenSource; // Used to indicate that a cancellation is requested due to disposal
internal SqlSequentialTextReader(SqlDataReader reader, int columnIndex, Encoding encoding)
{
Debug.Assert(reader != null, "Null reader when creating sequential textreader");
Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential textreader");
Debug.Assert(encoding != null, "Null encoding when creating sequential textreader");
_reader = reader;
_columnIndex = columnIndex;
_encoding = encoding;
_decoder = encoding.GetDecoder();
_leftOverBytes = null;
_peekedChar = -1;
_currentTask = null;
_disposalTokenSource = new CancellationTokenSource();
}
internal int ColumnIndex
{
get { return _columnIndex; }
}
public override int Peek()
{
if (_currentTask != null)
{
throw ADP.AsyncOperationPending();
}
if (IsClosed)
{
throw ADP.ObjectDisposed(this);
}
if (!HasPeekedChar)
{
_peekedChar = Read();
}
Debug.Assert(_peekedChar == -1 || ((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue)), string.Format("Bad peeked character: {0}", _peekedChar));
return _peekedChar;
}
public override int Read()
{
if (_currentTask != null)
{
throw ADP.AsyncOperationPending();
}
if (IsClosed)
{
throw ADP.ObjectDisposed(this);
}
int readChar = -1;
// If there is already a peeked char, then return it
if (HasPeekedChar)
{
readChar = _peekedChar;
_peekedChar = -1;
}
// If there is data available try to read a char
else
{
char[] tempBuffer = new char[1];
int charsRead = InternalRead(tempBuffer, 0, 1);
if (charsRead == 1)
{
readChar = tempBuffer[0];
}
}
Debug.Assert(readChar == -1 || ((readChar >= char.MinValue) && (readChar <= char.MaxValue)), string.Format("Bad read character: {0}", readChar));
return readChar;
}
public override int Read(char[] buffer, int index, int count)
{
ValidateReadParameters(buffer, index, count);
if (IsClosed)
{
throw ADP.ObjectDisposed(this);
}
if (_currentTask != null)
{
throw ADP.AsyncOperationPending();
}
int charsRead = 0;
int charsNeeded = count;
// Load in peeked char
if ((charsNeeded > 0) && (HasPeekedChar))
{
Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar));
buffer[index + charsRead] = (char)_peekedChar;
charsRead++;
charsNeeded--;
_peekedChar = -1;
}
// If we need more data and there is data avaiable, read
charsRead += InternalRead(buffer, index + charsRead, charsNeeded);
return charsRead;
}
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
ValidateReadParameters(buffer, index, count);
TaskCompletionSource<int> completion = new TaskCompletionSource<int>();
if (IsClosed)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else
{
try
{
Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null);
if (original != null)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
}
else
{
bool completedSynchronously = true;
int charsRead = 0;
int adjustedIndex = index;
int charsNeeded = count;
// Load in peeked char
if ((HasPeekedChar) && (charsNeeded > 0))
{
// Take a copy of _peekedChar in case it is cleared during close
int peekedChar = _peekedChar;
if (peekedChar >= char.MinValue)
{
Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar));
buffer[adjustedIndex] = (char)peekedChar;
adjustedIndex++;
charsRead++;
charsNeeded--;
_peekedChar = -1;
}
}
int byteBufferUsed;
byte[] byteBuffer = PrepareByteBuffer(charsNeeded, out byteBufferUsed);
// Permit a 0 byte read in order to advance the reader to the correct column
if ((byteBufferUsed < byteBuffer.Length) || (byteBuffer.Length == 0))
{
int bytesRead;
var reader = _reader;
if (reader != null)
{
Task<int> getBytesTask = reader.GetBytesAsync(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed, Timeout.Infinite, _disposalTokenSource.Token, out bytesRead);
if (getBytesTask == null)
{
byteBufferUsed += bytesRead;
}
else
{
// We need more data - setup the callback, and mark this as not completed sync
completedSynchronously = false;
getBytesTask.ContinueWith((t) =>
{
_currentTask = null;
// If we completed but the textreader is closed, then report cancellation
if ((t.Status == TaskStatus.RanToCompletion) && (!IsClosed))
{
try
{
int bytesReadFromStream = t.Result;
byteBufferUsed += bytesReadFromStream;
if (byteBufferUsed > 0)
{
charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded);
}
completion.SetResult(charsRead);
}
catch (Exception ex)
{
completion.SetException(ex);
}
}
else if (IsClosed)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else if (t.Status == TaskStatus.Faulted)
{
if (t.Exception.InnerException is SqlException)
{
// ReadAsync can't throw a SqlException, so wrap it in an IOException
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException)));
}
else
{
completion.SetException(t.Exception.InnerException);
}
}
else
{
completion.SetCanceled();
}
}, TaskScheduler.Default);
}
if ((completedSynchronously) && (byteBufferUsed > 0))
{
// No more data needed, decode what we have
charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded);
}
}
else
{
// Reader is null, close must of happened in the middle of this read
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
}
if (completedSynchronously)
{
_currentTask = null;
if (IsClosed)
{
completion.SetCanceled();
}
else
{
completion.SetResult(charsRead);
}
}
}
}
catch (Exception ex)
{
// In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it
completion.TrySetException(ex);
Interlocked.CompareExchange(ref _currentTask, null, completion.Task);
throw;
}
}
return completion.Task;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Set the textreader as closed
SetClosed();
}
base.Dispose(disposing);
}
/// <summary>
/// Forces the TextReader to act as if it was closed
/// This does not actually close the stream, read off the rest of the data or dispose this
/// </summary>
internal void SetClosed()
{
_disposalTokenSource.Cancel();
_reader = null;
_peekedChar = -1;
// Wait for pending task
var currentTask = _currentTask;
if (currentTask != null)
{
((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();
}
}
/// <summary>
/// Performs the actual reading and converting
/// NOTE: This assumes that buffer, index and count are all valid, we're not closed (!IsClosed) and that there is data left (IsDataLeft())
/// </summary>
/// <param name="buffer"></param>
/// <param name="index"></param>
/// <param name="count"></param>
/// <returns></returns>
private int InternalRead(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null, "Null output buffer");
Debug.Assert((index >= 0) && (count >= 0) && (index + count <= buffer.Length), string.Format("Bad count: {0} or index: {1}", count, index));
Debug.Assert(!IsClosed, "Can't read while textreader is closed");
try
{
int byteBufferUsed;
byte[] byteBuffer = PrepareByteBuffer(count, out byteBufferUsed);
byteBufferUsed += _reader.GetBytesInternalSequential(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed);
if (byteBufferUsed > 0)
{
return DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, index, count);
}
else
{
// Nothing to read, or nothing read
return 0;
}
}
catch (SqlException ex)
{
// Read can't throw a SqlException - so wrap it in an IOException
throw ADP.ErrorReadingFromStream(ex);
}
}
/// <summary>
/// Creates a byte array large enough to store all bytes for the characters in the current encoding, then fills it with any leftover bytes
/// </summary>
/// <param name="numberOfChars">Number of characters that are to be read</param>
/// <param name="byteBufferUsed">Number of bytes pre-filled by the leftover bytes</param>
/// <returns>A byte array of the correct size, pre-filled with leftover bytes</returns>
private byte[] PrepareByteBuffer(int numberOfChars, out int byteBufferUsed)
{
Debug.Assert(numberOfChars >= 0, "Can't prepare a byte buffer for negative characters");
byte[] byteBuffer;
if (numberOfChars == 0)
{
byteBuffer = new byte[0];
byteBufferUsed = 0;
}
else
{
int byteBufferSize = _encoding.GetMaxByteCount(numberOfChars);
if (_leftOverBytes != null)
{
// If we have more leftover bytes than we need for this conversion, then just re-use the leftover buffer
if (_leftOverBytes.Length > byteBufferSize)
{
byteBuffer = _leftOverBytes;
byteBufferUsed = byteBuffer.Length;
}
else
{
// Otherwise, copy over the leftover buffer
byteBuffer = new byte[byteBufferSize];
Array.Copy(_leftOverBytes, byteBuffer, _leftOverBytes.Length);
byteBufferUsed = _leftOverBytes.Length;
}
}
else
{
byteBuffer = new byte[byteBufferSize];
byteBufferUsed = 0;
}
}
return byteBuffer;
}
/// <summary>
/// Decodes the given bytes into characters, and stores the leftover bytes for later use
/// </summary>
/// <param name="inBuffer">Buffer of bytes to decode</param>
/// <param name="inBufferCount">Number of bytes to decode from the inBuffer</param>
/// <param name="outBuffer">Buffer to write the characters to</param>
/// <param name="outBufferOffset">Offset to start writing to outBuffer at</param>
/// <param name="outBufferCount">Maximum number of characters to decode</param>
/// <returns>The actual number of characters decoded</returns>
private int DecodeBytesToChars(byte[] inBuffer, int inBufferCount, char[] outBuffer, int outBufferOffset, int outBufferCount)
{
Debug.Assert(inBuffer != null, "Null input buffer");
Debug.Assert((inBufferCount > 0) && (inBufferCount <= inBuffer.Length), string.Format("Bad inBufferCount: {0}", inBufferCount));
Debug.Assert(outBuffer != null, "Null output buffer");
Debug.Assert((outBufferOffset >= 0) && (outBufferCount > 0) && (outBufferOffset + outBufferCount <= outBuffer.Length), string.Format("Bad outBufferCount: {0} or outBufferOffset: {1}", outBufferCount, outBufferOffset));
int charsRead;
int bytesUsed;
bool completed;
_decoder.Convert(inBuffer, 0, inBufferCount, outBuffer, outBufferOffset, outBufferCount, false, out bytesUsed, out charsRead, out completed);
// completed may be false and there is no spare bytes if the Decoder has stored bytes to use later
if ((!completed) && (bytesUsed < inBufferCount))
{
_leftOverBytes = new byte[inBufferCount - bytesUsed];
Array.Copy(inBuffer, bytesUsed, _leftOverBytes, 0, _leftOverBytes.Length);
}
else
{
// If Convert() sets completed to true, then it must have used all of the bytes we gave it
Debug.Assert(bytesUsed >= inBufferCount, "Converted completed, but not all bytes were used");
_leftOverBytes = null;
}
Debug.Assert(((_reader == null) || (_reader.ColumnDataBytesRemaining() > 0) || (!completed) || (_leftOverBytes == null)), "Stream has run out of data and the decoder finished, but there are leftover bytes");
Debug.Assert(charsRead > 0, "Converted no chars. Bad encoding?");
return charsRead;
}
/// <summary>
/// True if this TextReader is supposed to be closed
/// </summary>
private bool IsClosed
{
get { return (_reader == null); }
}
/// <summary>
/// True if there is data left to read
/// </summary>
/// <returns></returns>
private bool IsDataLeft
{
get { return ((_leftOverBytes != null) || (_reader.ColumnDataBytesRemaining() > 0)); }
}
/// <summary>
/// True if there is a peeked character available
/// </summary>
private bool HasPeekedChar
{
get { return (_peekedChar >= char.MinValue); }
}
/// <summary>
/// Checks the the parameters passed into a Read() method are valid
/// </summary>
/// <param name="buffer"></param>
/// <param name="index"></param>
/// <param name="count"></param>
internal static void ValidateReadParameters(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw ADP.ArgumentNull(ADP.ParameterBuffer);
}
if (index < 0)
{
throw ADP.ArgumentOutOfRange(ADP.ParameterIndex);
}
if (count < 0)
{
throw ADP.ArgumentOutOfRange(ADP.ParameterCount);
}
try
{
if (checked(index + count) > buffer.Length)
{
throw ExceptionBuilder.InvalidOffsetLength();
}
}
catch (OverflowException)
{
// If we've overflowed when adding index and count, then they never would have fit into buffer anyway
throw ExceptionBuilder.InvalidOffsetLength();
}
}
}
sealed internal class SqlUnicodeEncoding : Encoding
{
private static SqlUnicodeEncoding s_singletonEncoding = new SqlUnicodeEncoding();
private SqlUnicodeEncoding()
{ }
public override int GetByteCount(char[] chars, int index, int count)
{
return GetMaxByteCount(count);
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
throw NotImplemented.ByDesignWithMessage("Not required");
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return GetMaxCharCount(count);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
throw NotImplemented.ByDesignWithMessage("Not required");
}
public override int GetMaxCharCount(int byteCount)
{
return byteCount / 2;
}
public override Decoder GetDecoder()
{
return new SqlUnicodeDecoder();
}
public override int GetMaxByteCount(int charCount)
{
// SQL Server never sends a BOM, so we can assume that its 2 bytes per char
return charCount * 2;
}
public static Encoding SqlUnicodeEncodingInstance
{
get { return s_singletonEncoding; }
}
sealed private class SqlUnicodeDecoder : Decoder
{
public override int GetCharCount(byte[] bytes, int index, int count)
{
// SQL Server never sends a BOM, so we can assume that its 2 bytes per char
return count / 2;
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
// This method is required - simply call Convert()
int bytesUsed;
int charsUsed;
bool completed;
Convert(bytes, byteIndex, byteCount, chars, charIndex, chars.Length - charIndex, true, out bytesUsed, out charsUsed, out completed);
return charsUsed;
}
public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
{
// Assume 2 bytes per char and no BOM
charsUsed = Math.Min(charCount, byteCount / 2);
bytesUsed = charsUsed * 2;
completed = (bytesUsed == byteCount);
// BlockCopy uses offsets\length measured in bytes, not the actual array index
Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * 2, bytesUsed);
}
}
}
}
| |
// 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 gcov = Google.Cloud.OrgPolicy.V2;
using sys = System;
namespace Google.Cloud.OrgPolicy.V2
{
/// <summary>Resource name for the <c>Constraint</c> resource.</summary>
public sealed partial class ConstraintName : gax::IResourceName, sys::IEquatable<ConstraintName>
{
/// <summary>The possible contents of <see cref="ConstraintName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/constraints/{constraint}</c>.</summary>
ProjectConstraint = 1,
/// <summary>A resource name with pattern <c>folders/{folder}/constraints/{constraint}</c>.</summary>
FolderConstraint = 2,
/// <summary>
/// A resource name with pattern <c>organizations/{organization}/constraints/{constraint}</c>.
/// </summary>
OrganizationConstraint = 3,
}
private static gax::PathTemplate s_projectConstraint = new gax::PathTemplate("projects/{project}/constraints/{constraint}");
private static gax::PathTemplate s_folderConstraint = new gax::PathTemplate("folders/{folder}/constraints/{constraint}");
private static gax::PathTemplate s_organizationConstraint = new gax::PathTemplate("organizations/{organization}/constraints/{constraint}");
/// <summary>Creates a <see cref="ConstraintName"/> 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="ConstraintName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ConstraintName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ConstraintName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ConstraintName"/> with the pattern <c>projects/{project}/constraints/{constraint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ConstraintName"/> constructed from the provided ids.</returns>
public static ConstraintName FromProjectConstraint(string projectId, string constraintId) =>
new ConstraintName(ResourceNameType.ProjectConstraint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), constraintId: gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId)));
/// <summary>
/// Creates a <see cref="ConstraintName"/> with the pattern <c>folders/{folder}/constraints/{constraint}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ConstraintName"/> constructed from the provided ids.</returns>
public static ConstraintName FromFolderConstraint(string folderId, string constraintId) =>
new ConstraintName(ResourceNameType.FolderConstraint, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), constraintId: gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId)));
/// <summary>
/// Creates a <see cref="ConstraintName"/> with the pattern
/// <c>organizations/{organization}/constraints/{constraint}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ConstraintName"/> constructed from the provided ids.</returns>
public static ConstraintName FromOrganizationConstraint(string organizationId, string constraintId) =>
new ConstraintName(ResourceNameType.OrganizationConstraint, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), constraintId: gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConstraintName"/> with pattern
/// <c>projects/{project}/constraints/{constraint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ConstraintName"/> with pattern
/// <c>projects/{project}/constraints/{constraint}</c>.
/// </returns>
public static string Format(string projectId, string constraintId) => FormatProjectConstraint(projectId, constraintId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConstraintName"/> with pattern
/// <c>projects/{project}/constraints/{constraint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ConstraintName"/> with pattern
/// <c>projects/{project}/constraints/{constraint}</c>.
/// </returns>
public static string FormatProjectConstraint(string projectId, string constraintId) =>
s_projectConstraint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConstraintName"/> with pattern
/// <c>folders/{folder}/constraints/{constraint}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ConstraintName"/> with pattern
/// <c>folders/{folder}/constraints/{constraint}</c>.
/// </returns>
public static string FormatFolderConstraint(string folderId, string constraintId) =>
s_folderConstraint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConstraintName"/> with pattern
/// <c>organizations/{organization}/constraints/{constraint}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ConstraintName"/> with pattern
/// <c>organizations/{organization}/constraints/{constraint}</c>.
/// </returns>
public static string FormatOrganizationConstraint(string organizationId, string constraintId) =>
s_organizationConstraint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId)));
/// <summary>Parses the given resource name string into a new <see cref="ConstraintName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/constraints/{constraint}</c></description></item>
/// <item><description><c>folders/{folder}/constraints/{constraint}</c></description></item>
/// <item><description><c>organizations/{organization}/constraints/{constraint}</c></description></item>
/// </list>
/// </remarks>
/// <param name="constraintName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ConstraintName"/> if successful.</returns>
public static ConstraintName Parse(string constraintName) => Parse(constraintName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ConstraintName"/> 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>projects/{project}/constraints/{constraint}</c></description></item>
/// <item><description><c>folders/{folder}/constraints/{constraint}</c></description></item>
/// <item><description><c>organizations/{organization}/constraints/{constraint}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="constraintName">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="ConstraintName"/> if successful.</returns>
public static ConstraintName Parse(string constraintName, bool allowUnparsed) =>
TryParse(constraintName, allowUnparsed, out ConstraintName 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="ConstraintName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/constraints/{constraint}</c></description></item>
/// <item><description><c>folders/{folder}/constraints/{constraint}</c></description></item>
/// <item><description><c>organizations/{organization}/constraints/{constraint}</c></description></item>
/// </list>
/// </remarks>
/// <param name="constraintName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ConstraintName"/>, 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 constraintName, out ConstraintName result) =>
TryParse(constraintName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ConstraintName"/> 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>projects/{project}/constraints/{constraint}</c></description></item>
/// <item><description><c>folders/{folder}/constraints/{constraint}</c></description></item>
/// <item><description><c>organizations/{organization}/constraints/{constraint}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="constraintName">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="ConstraintName"/>, 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 constraintName, bool allowUnparsed, out ConstraintName result)
{
gax::GaxPreconditions.CheckNotNull(constraintName, nameof(constraintName));
gax::TemplatedResourceName resourceName;
if (s_projectConstraint.TryParseName(constraintName, out resourceName))
{
result = FromProjectConstraint(resourceName[0], resourceName[1]);
return true;
}
if (s_folderConstraint.TryParseName(constraintName, out resourceName))
{
result = FromFolderConstraint(resourceName[0], resourceName[1]);
return true;
}
if (s_organizationConstraint.TryParseName(constraintName, out resourceName))
{
result = FromOrganizationConstraint(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(constraintName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ConstraintName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string constraintId = null, string folderId = null, string organizationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ConstraintId = constraintId;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ConstraintName"/> class from the component parts of pattern
/// <c>projects/{project}/constraints/{constraint}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param>
public ConstraintName(string projectId, string constraintId) : this(ResourceNameType.ProjectConstraint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), constraintId: gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId)))
{
}
/// <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>Constraint</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string ConstraintId { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { 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.ProjectConstraint: return s_projectConstraint.Expand(ProjectId, ConstraintId);
case ResourceNameType.FolderConstraint: return s_folderConstraint.Expand(FolderId, ConstraintId);
case ResourceNameType.OrganizationConstraint: return s_organizationConstraint.Expand(OrganizationId, ConstraintId);
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 ConstraintName);
/// <inheritdoc/>
public bool Equals(ConstraintName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ConstraintName a, ConstraintName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ConstraintName a, ConstraintName b) => !(a == b);
}
public partial class Constraint
{
/// <summary>
/// <see cref="gcov::ConstraintName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::ConstraintName ConstraintName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::ConstraintName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.IO
{
public partial class BinaryReader : System.IDisposable
{
public BinaryReader(System.IO.Stream input) { }
public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding) { }
public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding, bool leaveOpen) { }
public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } }
public virtual void Close() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected virtual void FillBuffer(int numBytes) { }
public virtual int PeekChar() { return default(int); }
public virtual int Read() { return default(int); }
public virtual int Read(byte[] buffer, int index, int count) { return default(int); }
public virtual int Read(char[] buffer, int index, int count) { return default(int); }
protected internal int Read7BitEncodedInt() { return default(int); }
public virtual bool ReadBoolean() { return default(bool); }
public virtual byte ReadByte() { return default(byte); }
public virtual byte[] ReadBytes(int count) { return default(byte[]); }
public virtual char ReadChar() { return default(char); }
public virtual char[] ReadChars(int count) { return default(char[]); }
public virtual decimal ReadDecimal() { return default(decimal); }
public virtual double ReadDouble() { return default(double); }
public virtual short ReadInt16() { return default(short); }
public virtual int ReadInt32() { return default(int); }
public virtual long ReadInt64() { return default(long); }
[System.CLSCompliantAttribute(false)]
public virtual sbyte ReadSByte() { return default(sbyte); }
public virtual float ReadSingle() { return default(float); }
public virtual string ReadString() { return default(string); }
[System.CLSCompliantAttribute(false)]
public virtual ushort ReadUInt16() { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public virtual uint ReadUInt32() { return default(uint); }
[System.CLSCompliantAttribute(false)]
public virtual ulong ReadUInt64() { return default(ulong); }
}
public partial class BinaryWriter : System.IDisposable
{
public static readonly System.IO.BinaryWriter Null;
protected System.IO.Stream OutStream;
protected BinaryWriter() { }
public BinaryWriter(System.IO.Stream output) { }
public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding) { }
public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding, bool leaveOpen) { }
public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } }
public virtual void Close() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual void Flush() { }
public virtual long Seek(int offset, System.IO.SeekOrigin origin) { return default(long); }
public virtual void Write(bool value) { }
public virtual void Write(byte value) { }
public virtual void Write(byte[] buffer) { }
public virtual void Write(byte[] buffer, int index, int count) { }
public virtual void Write(char ch) { }
public virtual void Write(char[] chars) { }
public virtual void Write(char[] chars, int index, int count) { }
public virtual void Write(decimal value) { }
public virtual void Write(double value) { }
public virtual void Write(short value) { }
public virtual void Write(int value) { }
public virtual void Write(long value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(sbyte value) { }
public virtual void Write(float value) { }
public virtual void Write(string value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(ushort value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(ulong value) { }
protected void Write7BitEncodedInt(int value) { }
}
public sealed partial class BufferedStream : System.IO.Stream
{
public BufferedStream(Stream stream) { }
public BufferedStream(Stream stream, int bufferSize) { }
public override bool CanRead { get { return default(bool); } }
public override bool CanSeek { get { return default(bool); } }
public override bool CanWrite { get { return default(bool); } }
public override long Length { get { return default(long); } }
public override long Position { get { return default(long); } set { } }
public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); }
public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); }
protected override void Dispose(bool disposing) { }
public override int EndRead(System.IAsyncResult asyncResult) { return 0; }
public override void EndWrite(System.IAsyncResult asyncResult) { return; }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public override int Read(byte[] array, int offset, int count) { return default(int); }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); }
public override int ReadByte() { return default(int); }
public override long Seek(long offset, SeekOrigin origin) { return default(long); }
public override void SetLength(long value) { }
public override void Write(byte[] array, int offset, int count) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public override void WriteByte(byte value) { }
}
public partial class EndOfStreamException : System.IO.IOException
{
public EndOfStreamException() { }
public EndOfStreamException(string message) { }
public EndOfStreamException(string message, System.Exception innerException) { }
}
public sealed partial class InvalidDataException : System.Exception
{
public InvalidDataException() { }
public InvalidDataException(string message) { }
public InvalidDataException(string message, System.Exception innerException) { }
}
public partial class MemoryStream : System.IO.Stream
{
public MemoryStream() { }
public MemoryStream(byte[] buffer) { }
public MemoryStream(byte[] buffer, bool writable) { }
public MemoryStream(byte[] buffer, int index, int count) { }
public MemoryStream(byte[] buffer, int index, int count, bool writable) { }
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { }
public MemoryStream(int capacity) { }
public override bool CanRead { get { return default(bool); } }
public override bool CanSeek { get { return default(bool); } }
public override bool CanWrite { get { return default(bool); } }
public virtual int Capacity { get { return default(int); } set { } }
public override long Length { get { return default(long); } }
public override long Position { get { return default(long); } set { } }
public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); }
public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); }
public override System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
protected override void Dispose(bool disposing) { }
public override int EndRead(System.IAsyncResult asyncResult) { return 0; }
public override void EndWrite(System.IAsyncResult asyncResult) { return; }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public virtual byte[] GetBuffer() { return default(byte[]); }
public override int Read(byte[] buffer, int offset, int count) { buffer = default(byte[]); return default(int); }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); }
public override int ReadByte() { return default(int); }
public override long Seek(long offset, System.IO.SeekOrigin loc) { return default(long); }
public override void SetLength(long value) { }
public virtual byte[] ToArray() { return default(byte[]); }
public virtual bool TryGetBuffer(out System.ArraySegment<byte> buffer) { buffer = default(System.ArraySegment<byte>); return default(bool); }
public override void Write(byte[] buffer, int offset, int count) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
public override void WriteByte(byte value) { }
public virtual void WriteTo(System.IO.Stream stream) { }
}
public partial class StreamReader : System.IO.TextReader
{
public static readonly new System.IO.StreamReader Null;
public StreamReader(System.IO.Stream stream) { }
public StreamReader(System.IO.Stream stream, bool detectEncodingFromByteOrderMarks) { }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding) { }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks) { }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen) { }
public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } }
public virtual System.Text.Encoding CurrentEncoding { get { return default(System.Text.Encoding); } }
public bool EndOfStream { get { return default(bool); } }
public void DiscardBufferedData() { }
public override void Close() { }
protected override void Dispose(bool disposing) { }
public override int Peek() { return default(int); }
public override int Read() { return default(int); }
public override int Read(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public override System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public override int ReadBlock(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public override System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public override string ReadLine() { return default(string); }
public override System.Threading.Tasks.Task<string> ReadLineAsync() { return default(System.Threading.Tasks.Task<string>); }
public override string ReadToEnd() { return default(string); }
public override System.Threading.Tasks.Task<string> ReadToEndAsync() { return default(System.Threading.Tasks.Task<string>); }
}
public partial class StreamWriter : System.IO.TextWriter
{
public static readonly new System.IO.StreamWriter Null;
public StreamWriter(System.IO.Stream stream) { }
public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding) { }
public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize) { }
public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize, bool leaveOpen) { }
public virtual bool AutoFlush { get { return default(bool); } set { } }
public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } }
public override System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } }
public override void Close() { }
protected override void Dispose(bool disposing) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); }
public override void Write(char value) { }
public override void Write(char[] buffer) { }
public override void Write(char[] buffer, int index, int count) { }
public override void Write(string value) { }
public override System.Threading.Tasks.Task WriteAsync(char value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteAsync(string value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync() { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(char value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(string value) { return default(System.Threading.Tasks.Task); }
}
public partial class StringReader : System.IO.TextReader
{
public StringReader(string s) { }
public override void Close() { }
protected override void Dispose(bool disposing) { }
public override int Peek() { return default(int); }
public override int Read() { return default(int); }
public override int Read(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public override System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public override System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public override string ReadLine() { return default(string); }
public override System.Threading.Tasks.Task<string> ReadLineAsync() { return default(System.Threading.Tasks.Task<string>); }
public override string ReadToEnd() { return default(string); }
public override System.Threading.Tasks.Task<string> ReadToEndAsync() { return default(System.Threading.Tasks.Task<string>); }
}
public partial class StringWriter : System.IO.TextWriter
{
public StringWriter() { }
public StringWriter(System.IFormatProvider formatProvider) { }
public StringWriter(System.Text.StringBuilder sb) { }
public StringWriter(System.Text.StringBuilder sb, System.IFormatProvider formatProvider) { }
public override System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } }
public override void Close() { }
protected override void Dispose(bool disposing) { }
public override System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); }
public virtual System.Text.StringBuilder GetStringBuilder() { return default(System.Text.StringBuilder); }
public override string ToString() { return default(string); }
public override void Write(char value) { }
public override void Write(char[] buffer, int index, int count) { }
public override void Write(string value) { }
public override System.Threading.Tasks.Task WriteAsync(char value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteAsync(string value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(char value) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public override System.Threading.Tasks.Task WriteLineAsync(string value) { return default(System.Threading.Tasks.Task); }
}
public abstract partial class TextReader : System.IDisposable
{
public static readonly System.IO.TextReader Null;
protected TextReader() { }
public virtual void Close() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual int Peek() { return default(int); }
public virtual int Read() { return default(int); }
public virtual int Read(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual int ReadBlock(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual string ReadLine() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadLineAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual string ReadToEnd() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadToEndAsync() { return default(System.Threading.Tasks.Task<string>); }
}
public abstract partial class TextWriter : System.IDisposable
{
protected char[] CoreNewLine;
public static readonly System.IO.TextWriter Null;
protected TextWriter() { }
protected TextWriter(System.IFormatProvider formatProvider) { }
public abstract System.Text.Encoding Encoding { get; }
public virtual System.IFormatProvider FormatProvider { get { return default(System.IFormatProvider); } }
public virtual string NewLine { get { return default(string); } set { } }
public virtual void Close() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual void Flush() { }
public virtual System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); }
public virtual void Write(bool value) { }
public abstract void Write(char value);
public virtual void Write(char[] buffer) { }
public virtual void Write(char[] buffer, int index, int count) { }
public virtual void Write(decimal value) { }
public virtual void Write(double value) { }
public virtual void Write(int value) { }
public virtual void Write(long value) { }
public virtual void Write(object value) { }
public virtual void Write(float value) { }
public virtual void Write(string value) { }
public virtual void Write(string format, object arg0) { }
public virtual void Write(string format, object arg0, object arg1) { }
public virtual void Write(string format, object arg0, object arg1, object arg2) { }
public virtual void Write(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(ulong value) { }
public virtual System.Threading.Tasks.Task WriteAsync(char value) { return default(System.Threading.Tasks.Task); }
public System.Threading.Tasks.Task WriteAsync(char[] buffer) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteAsync(string value) { return default(System.Threading.Tasks.Task); }
public virtual void WriteLine() { }
public virtual void WriteLine(bool value) { }
public virtual void WriteLine(char value) { }
public virtual void WriteLine(char[] buffer) { }
public virtual void WriteLine(char[] buffer, int index, int count) { }
public virtual void WriteLine(decimal value) { }
public virtual void WriteLine(double value) { }
public virtual void WriteLine(int value) { }
public virtual void WriteLine(long value) { }
public virtual void WriteLine(object value) { }
public virtual void WriteLine(float value) { }
public virtual void WriteLine(string value) { }
public virtual void WriteLine(string format, object arg0) { }
public virtual void WriteLine(string format, object arg0, object arg1) { }
public virtual void WriteLine(string format, object arg0, object arg1, object arg2) { }
public virtual void WriteLine(string format, params object[] arg) { }
[System.CLSCompliantAttribute(false)]
public virtual void WriteLine(uint value) { }
[System.CLSCompliantAttribute(false)]
public virtual void WriteLine(ulong value) { }
public virtual System.Threading.Tasks.Task WriteLineAsync() { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteLineAsync(char value) { return default(System.Threading.Tasks.Task); }
public System.Threading.Tasks.Task WriteLineAsync(char[] buffer) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteLineAsync(string value) { return default(System.Threading.Tasks.Task); }
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Originally from the Microsoft Research Singularity code base.
//
namespace Microsoft.Zelig.MetaData.Importer.PdbInfo
{
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Zelig.MetaData.Importer.PdbInfo.CodeView;
using Microsoft.Zelig.MetaData.Importer.PdbInfo.Features;
public class PdbFile
{
//
// State
//
const int c_Index_PdbStream = 1;
const int c_Index_DbiStream = 3;
private PdbFileHeader m_head;
private MsfDirectory m_dir;
private PdbStream m_pdbStream;
private PdbFunction[] m_funcs;
private Dictionary< uint, PdbFunction > m_lookupToken;
//
// Constructor Methods
//
public PdbFile( ArrayReader image )
{
PdbReader pdbReader;
m_head = new PdbFileHeader( image );
pdbReader = new PdbReader ( image , m_head.pageSize );
m_dir = new MsfDirectory ( pdbReader, m_head );
m_pdbStream = new PdbStream ( m_dir.GetArrayReaderForStream( c_Index_PdbStream ) );
int nameStream = m_pdbStream.GetStreamNumber( "/names" );
if(nameStream <= 0)
{
throw new PdbException( "No name stream" );
}
ushort tokenRidMapStream;
uint[] tokenRidMap = null;
Dictionary< int, string > names = LoadNameStream( m_dir.GetArrayReaderForStream( nameStream ) );
List< DbiModuleInfo > modules = LoadDbiStream ( m_dir.GetArrayReaderForStream( c_Index_DbiStream ), out tokenRidMapStream );
if(tokenRidMapStream != 0xFFFF)
{
tokenRidMap = LoadTokenRidMap( m_dir.GetArrayReaderForStream( tokenRidMapStream ) );
}
List< PdbFunction > funcList = new List< PdbFunction >();
foreach(DbiModuleInfo module in modules)
{
if(module.stream > 0)
{
LoadFuncsFromDbiModule( m_dir.GetArrayReaderForStream( module.stream ), module, names, funcList );
}
}
m_funcs = funcList.ToArray();
m_lookupToken = new Dictionary< uint, PdbFunction >();
//
// Remap function tokens.
//
foreach(PdbFunction func in m_funcs)
{
uint token = func.Token;
if(tokenRidMap != null)
{
TokenType tt = MetaData.UnpackTokenAsType( (int)token );
if(tt == TokenType.Method)
{
int index = MetaData.UnpackTokenAsIndex( (int)token );
if(index >= 0 && index < tokenRidMap.Length)
{
token = (uint)MetaData.PackToken( TokenType.Method, (int)tokenRidMap[index] );
func.Token = token;
}
}
}
m_lookupToken[token] = func;
}
Array.Sort( m_funcs, PdbFunction.byAddress );
}
public byte[] Emit()
{
ArrayWriter writer = new ArrayWriter();
int pageSize = m_head.pageSize;
while(true)
{
int totalNumberOfPages = 3;
for(int i = 0; i < m_dir.Streams.Length; i++)
{
int size = m_dir.Streams[i].Length;
totalNumberOfPages += (size + pageSize - 1) / pageSize;
}
if(totalNumberOfPages < pageSize * 8)
{
break;
}
pageSize *= 2;
}
PdbWriter pdbWriter = new PdbWriter( writer, pageSize );
MsfDirectory newDir = new MsfDirectory();
for(int i = 0; i < m_dir.Streams.Length; i++)
{
DataStream src = m_dir .Streams[i];
DataStream dst = newDir.CreateNewStream( i );
dst.Copy( pdbWriter, src );
}
pdbWriter.Emit( newDir );
return writer.ToArray();
}
public DataStream GetStream( string name )
{
int idx = m_pdbStream.GetStreamNumber( name );
if(idx == -1)
{
return null;
}
return m_dir.Streams[ idx ];
}
public DataStream CreateNewStream( string name )
{
DataStream res = GetStream( name );
if(res == null)
{
int idx;
res = m_dir.CreateNewStream( out idx );
m_pdbStream.SetStreamNumber( name, idx );
DataStream stream = m_dir.CreateNewStream( c_Index_PdbStream );
ArrayWriter writer = new ArrayWriter();
m_pdbStream.Emit( writer );
stream.Payload = writer.ToArray();
}
return res;
}
public PdbFunction[] Functions
{
get
{
return m_funcs;
}
}
public PdbFunction FindFunction( uint token )
{
PdbFunction res;
if(m_lookupToken.TryGetValue( token, out res ))
{
return res;
}
return null;
}
//--//
static Dictionary< int, string > LoadNameStream( ArrayReader bits )
{
Dictionary< int, string > ht = new Dictionary< int, string >();
uint sig = bits.ReadUInt32(); // 0..3 Signature
int ver = bits.ReadInt32(); // 4..7 Version
if(sig != 0xEFFEEFFE || ver != 1)
{
throw new PdbException( "Unsupported Name Stream version" );
}
// Read (or skip) string buffer.
int stringBufLen = bits.ReadInt32(); // 8..11 Bytes of Strings
ArrayReader stringBits = bits.CreateSubsetAndAdvance( stringBufLen );
// Read hash table.
int siz = bits.ReadInt32(); // n+0..3 Number of hash buckets.
ArrayReader subBits = new ArrayReader( bits, 0 );
for(int i = 0; i < siz; i++)
{
int ni = subBits.ReadInt32();
if(ni != 0)
{
stringBits.Position = ni;
string name = stringBits.ReadZeroTerminatedUTF8String();
ht.Add( ni, name );
}
}
return ht;
}
private static PdbFunction FindFunction( PdbFunction[] funcs ,
ushort sec ,
uint off )
{
PdbFunction match = new PdbFunction();
match.Segment = sec;
match.Address = off;
int item = Array.BinarySearch( funcs, match, PdbFunction.byAddress );
if(item >= 0)
{
return funcs[item];
}
return null;
}
static void LoadManagedLines( PdbFunction[] funcs ,
Dictionary<int,string> names ,
ArrayReader bits ,
uint limit )
{
Dictionary<int,PdbSource> checks = new Dictionary<int,PdbSource>();
Array.Sort( funcs, PdbFunction.byAddress );
// Read the files first
ArrayReader subBits = bits.CreateSubset( (int)(limit - bits.Position) );
while(subBits.IsEOF == false)
{
DEBUG_S_SUBSECTION sig = (DEBUG_S_SUBSECTION)subBits.ReadInt32();
int siz = subBits.ReadInt32();
ArrayReader subsectionBits = subBits.CreateSubsetAndAdvance( siz );
switch(sig)
{
case DEBUG_S_SUBSECTION.FILECHKSMS:
while(subsectionBits.IsEOF == false)
{
CV_FileCheckSum chk;
int ni = subsectionBits.Position;
chk.name = subsectionBits.ReadUInt32();
chk.len = subsectionBits.ReadUInt8 ();
chk.type = subsectionBits.ReadUInt8 ();
string name = names[(int)chk.name];
PdbSource src = new PdbSource( (uint)ni, name );
checks.Add( ni, src );
subsectionBits.Seek( chk.len );
subsectionBits.AlignAbsolute( 4 );
}
break;
}
}
// Read the lines next.
subBits.Rewind();
while(subBits.IsEOF == false)
{
DEBUG_S_SUBSECTION sig = (DEBUG_S_SUBSECTION)subBits.ReadInt32();
int siz = subBits.ReadInt32();
ArrayReader subsectionBits = subBits.CreateSubsetAndAdvance( siz );
switch(sig)
{
case DEBUG_S_SUBSECTION.LINES:
{
CV_LineSection sec;
sec.off = subsectionBits.ReadUInt32();
sec.sec = subsectionBits.ReadUInt16();
sec.flags = subsectionBits.ReadUInt16();
sec.cod = subsectionBits.ReadUInt32();
PdbFunction func = FindFunction( funcs, sec.sec, sec.off );
// Count the line blocks.
List<PdbLines> blocks = new List<PdbLines>();
while(subsectionBits.IsEOF == false)
{
CV_SourceFile file;
file.index = subsectionBits.ReadUInt32();
file.count = subsectionBits.ReadUInt32();
file.linsiz = subsectionBits.ReadUInt32(); // Size of payload.
//
// Apparently, file.linsiz overestimates the size of the payload...
//
int linsiz = (int)file.count * (8 + ((sec.flags & 1) != 0 ? 4 : 0));
ArrayReader payloadBits = subsectionBits.CreateSubsetAndAdvance( linsiz );
PdbSource src = checks[(int)file.index];
PdbLines tmp = new PdbLines( src, file.count );
blocks.Add( tmp );
PdbLine[] lines = tmp.Lines;
ArrayReader plinBits = payloadBits.CreateSubsetAndAdvance( 8 * (int)file.count );
for(int i = 0; i < file.count; i++)
{
CV_Line line;
CV_Column column = new CV_Column();
line.offset = plinBits.ReadUInt32();
line.flags = plinBits.ReadUInt32();
uint delta = (line.flags & 0x7f000000) >> 24;
bool statement = ((line.flags & 0x80000000) == 0);
uint lineNo = line.flags & 0x00FFFFFF;
if((sec.flags & 1) != 0)
{
column.offColumnStart = payloadBits.ReadUInt16();
column.offColumnEnd = payloadBits.ReadUInt16();
}
lines[i] = new PdbLine( line.offset, lineNo, lineNo + delta, column.offColumnStart, column.offColumnEnd );
}
}
func.LineBlocks = blocks.ToArray();
break;
}
}
}
}
static PdbFunction[] LoadManagedFunctions( string module ,
ArrayReader bits ,
uint limit )
{
List<PdbFunction> funcList = new List<PdbFunction>();
while(bits.Position < limit)
{
ushort siz = bits.ReadUInt16();
ArrayReader subBits = bits.CreateSubsetAndAdvance( siz );
SYM rec = (SYM)subBits.ReadUInt16();
switch(rec)
{
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
{
ManProcSym proc = new ManProcSym();
proc.parent = subBits.ReadUInt32();
proc.end = subBits.ReadUInt32();
proc.next = subBits.ReadUInt32();
proc.len = subBits.ReadUInt32();
proc.dbgStart = subBits.ReadUInt32();
proc.dbgEnd = subBits.ReadUInt32();
proc.token = subBits.ReadUInt32();
proc.off = subBits.ReadUInt32();
proc.seg = subBits.ReadUInt16();
proc.flags = subBits.ReadUInt8 ();
proc.retReg = subBits.ReadUInt16();
proc.name = subBits.ReadZeroTerminatedUTF8String();
funcList.Add( new PdbFunction( module, proc, bits ) );
}
break;
default:
throw new PdbException( "Unknown SYMREC {0}", rec );
}
}
return funcList.ToArray();
}
static void LoadFuncsFromDbiModule( ArrayReader bits ,
DbiModuleInfo info ,
Dictionary<int,string> names ,
List<PdbFunction> funcList )
{
bits.Rewind();
int sig = bits.ReadInt32();
if(sig != 4)
{
throw new PdbException( "Invalid signature." );
}
PdbFunction[] funcs = LoadManagedFunctions( info.moduleName, bits, (uint)info.cbSyms );
if(funcs != null)
{
bits.Position = info.cbSyms + info.cbOldLines;
LoadManagedLines( funcs, names, bits, (uint)(info.cbSyms + info.cbOldLines + info.cbLines) );
for(int i = 0; i < funcs.Length; i++)
{
funcList.Add( funcs[i] );
}
}
}
static List<DbiModuleInfo> LoadDbiStream( ArrayReader bits ,
out ushort tokenRidMapStream )
{
DbiHeader dh = new DbiHeader( bits );
if(dh.sig != -1 || dh.ver != 19990903)
{
throw new PdbException( "Unsupported DBI Stream version" );
}
ArrayReader subBits;
// Read gpmod section.
List<DbiModuleInfo> modList = new List<DbiModuleInfo>();
subBits = bits.CreateSubsetAndAdvance( dh.gpmodiSize );
while(subBits.IsEOF == false)
{
modList.Add( new DbiModuleInfo( subBits ) );
}
// Skip the Section Contribution substream.
bits.Seek( dh.secconSize );
// Skip the Section Map substream.
bits.Seek( dh.secmapSize );
// Skip the File Info substream.
bits.Seek( dh.filinfSize );
// Skip the TSM substream.
bits.Seek( dh.tsmapSize );
// Skip the EC substream.
bits.Seek( dh.ecinfoSize );
// Read the optional header.
subBits = bits.CreateSubsetAndAdvance( dh.dbghdrSize );
DbgType idx = DbgType.dbgtypeFirst;
tokenRidMapStream = 0xFFFF;
while(subBits.IsEOF == false)
{
ushort stream = subBits.ReadUInt16();
if(idx == DbgType.dbgtypeTokenRidMap)
{
tokenRidMapStream = stream;
break;
}
idx++;
}
return modList;
}
static uint[] LoadTokenRidMap( ArrayReader bits )
{
return bits.ReadUInt32Array( bits.Length / 4 );
}
}
}
| |
using AjaxControlToolkit.Design;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxControlToolkit {
/// <summary>
/// PasswordStrength is an ASP.NET AJAX extender that can be attached to an ASP.NET TextBox control used for the entry of passwords.
/// The PasswordStrength extender shows the strength of the password in the TextBox and updates itself as a user types the password.
/// </summary>
[TargetControlType(typeof(TextBox))]
[Designer(typeof(PasswordStrengthExtenderDesigner))]
[ClientScriptResource("Sys.Extended.UI.PasswordStrengthExtenderBehavior", Constants.PasswordStrengthName)]
[RequiredScript(typeof(CommonToolkitScripts))]
[ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.PasswordStrengthName + Constants.IconPostfix)]
public class PasswordStrength : ExtenderControlBase {
const string _txtPasswordCssClass = "TextCssClass";
const string _barBorderCssClass = "BarBorderCssClass";
const string _barIndicatorCssClass = "BarIndicatorCssClass";
const string _strengthIndicatorType = "StrengthIndicatorType";
const string _displayPosition = "DisplayPosition";
const string _prefixText = "PrefixText";
const string _txtDisplayIndicators = "TextStrengthDescriptions";
const string _strengthStyles = "StrengthStyles";
const int _txtIndicatorsMinCount = 2; // Minimum number of textual descriptions
const int _txtIndicatorsMaxCount = 10; // Maximum number of textual descriptions.
const char _txtIndicatorDelimiter = ';'; // Text indicators are delimited with a semi colon
const string _preferredPasswordLength = "PreferredPasswordLength";
const string _minPasswordNumerics = "MinimumNumericCharacters";
const string _minPasswordSymbols = "MinimumSymbolCharacters";
const string _requiresUpperLowerCase = "RequiresUpperAndLowerCaseCharacters";
const string _minLowerCaseChars = "MinimumLowerCaseCharacters";
const string _minUpperCaseChars = "MinimumUpperCaseCharacters";
const string _helpHandleCssClass = "HelpHandleCssClass";
const string _helphandlePosition = "HelpHandlePosition";
const string _helpStatusLabelID = "HelpStatusLabelID";
const string _calcWeightings = "CalculationWeightings";
const string _prefixTextDefault = "Strength: ";
/// <summary>
/// Preferred length of the password
/// </summary>
/// <remarks>
/// Passwords could be less than this amount but wont reach the 100% calculation
/// if less than this count. This is used to calculate 50% of the percentage strength of the password
/// Ideally, a password should be 20 characters in length to be a strong password.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("preferredPasswordLength")]
public int PreferredPasswordLength {
get { return GetPropertyValue(_preferredPasswordLength, 0); }
set { SetPropertyValue(_preferredPasswordLength, value); }
}
/// <summary>
/// Minimum number of numeric characters
/// </summary>
/// <remarks>
/// If there are less than this property, then the password is not
/// considered strong. If there are equal to or more than this value,
/// then this will contribute 15% to the overall password strength percentage value.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("minimumNumericCharacters")]
public int MinimumNumericCharacters {
get { return GetPropertyValue(_minPasswordNumerics, 0); }
set { SetPropertyValue(_minPasswordNumerics, value); }
}
/// <summary>
/// A CSS class applied to the help element used to display a dialog box describing password requirements
/// </summary>
/// <remarks>
/// This is used so that the user can click on this image and get a display
/// on what is required to make the password strong according to the current properties
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue("")]
[ClientPropertyName("helpHandleCssClass")]
public string HelpHandleCssClass {
get { return GetPropertyValue(_helpHandleCssClass, String.Empty); }
set { SetPropertyValue(_helpHandleCssClass, value); }
}
/// <summary>
/// Positioning of the help handle element relative to the target control
/// </summary>
[ExtenderControlProperty()]
[DefaultValue(DisplayPosition.AboveRight)]
[ClientPropertyName("helpHandlePosition")]
public DisplayPosition HelpHandlePosition {
get { return GetPropertyValue(_helphandlePosition, DisplayPosition.AboveRight); }
set { SetPropertyValue(_helphandlePosition, value); }
}
/// <summary>
/// Control ID of the label used to display help text
/// </summary>
[IDReferenceProperty(typeof(Label))]
[DefaultValue("")]
[ExtenderControlProperty()]
[ClientPropertyName("helpStatusLabelID")]
public string HelpStatusLabelID {
get { return GetPropertyValue(_helpStatusLabelID, String.Empty); }
set { SetPropertyValue(_helpStatusLabelID, value); }
}
/// <summary>
/// Minimum number of symbol characters (ex. $ ^ *)
/// </summary>
/// <remarks>
/// If there are less than this property, then the password is not considered strong.
/// If there are equal to or more than this value, then this will contribute 15% to the overall
/// password strength percentage value.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("minimumSymbolCharacters")]
public int MinimumSymbolCharacters {
get { return GetPropertyValue(_minPasswordSymbols, 0); }
set { SetPropertyValue(_minPasswordSymbols, value); }
}
/// <summary>
/// Specifies whether mixed case characters are required
/// </summary>
/// <remarks>
/// Determines if mixed case passwords are required to be considered strong.
/// If true, then there must be at least one occurrence of mixed case
/// (upper and lower) letters in the password to be considered strong. If there is,
/// this will contribute 20% to the overall password strength percentage value.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(false)]
[ClientPropertyName("requiresUpperAndLowerCaseCharacters")]
public bool RequiresUpperAndLowerCaseCharacters {
get { return GetPropertyValue(_requiresUpperLowerCase, false); }
set { SetPropertyValue(_requiresUpperLowerCase, value); }
}
/// <summary>
/// CSS class applied to the text display when StrengthIndicatorType=Text
/// </summary>
[DefaultValue(null)]
[ExtenderControlProperty()]
[ClientPropertyName("textCssClass")]
public string TextCssClass {
get { return GetPropertyValue(_txtPasswordCssClass, (string)null); }
set { SetPropertyValue(_txtPasswordCssClass, value); }
}
/// <summary>
/// A CSS class applied to the bar indicator's border when StrengthIndicatorType=BarIndicator
/// </summary>
[DefaultValue(null)]
[ExtenderControlProperty()]
[ClientPropertyName("barBorderCssClass")]
public string BarBorderCssClass {
get { return GetPropertyValue(_barBorderCssClass, (string)null); }
set { SetPropertyValue(_barBorderCssClass, value); }
}
/// <summary>
/// A CSS class applied to the bar indicator's inner bar when StrengthIndicatorType=BarIndicator
/// </summary>
[DefaultValue(null)]
[ExtenderControlProperty()]
[ClientPropertyName("barIndicatorCssClass")]
public string BarIndicatorCssClass {
get { return GetPropertyValue(_barIndicatorCssClass, (string)null); }
set { SetPropertyValue(_barIndicatorCssClass, value); }
}
/// <summary>
/// Text prefixed to the display text when StrengthIndicatorType=Text
/// </summary>
[DefaultValue(_prefixTextDefault)]
[ExtenderControlProperty()]
[ClientPropertyName("prefixText")]
public string PrefixText {
get { return GetPropertyValue(_prefixText, _prefixTextDefault); }
set { SetPropertyValue(_prefixText, value); }
}
/// <summary>
/// Positioning of the strength indicator relative to the target control
/// </summary>
[DefaultValue(DisplayPosition.RightSide)]
[ExtenderControlProperty()]
[ClientPropertyName("displayPosition")]
public DisplayPosition DisplayPosition {
get { return GetPropertyValue(_displayPosition, DisplayPosition.RightSide); }
set { SetPropertyValue(_displayPosition, value); }
}
/// <summary>
/// Strength indicator type (Text or BarIndicator)
/// </summary>
/// <remarks>
/// BarIndicator - progress bar indicating password strength
/// Text - low, medium, high or excellent
/// </remarks>
[DefaultValue(StrengthIndicatorTypes.Text)]
[ExtenderControlProperty()]
[ClientPropertyName("strengthIndicatorType")]
public StrengthIndicatorTypes StrengthIndicatorType {
get { return GetPropertyValue(_strengthIndicatorType, StrengthIndicatorTypes.Text); }
set { SetPropertyValue(_strengthIndicatorType, value); }
}
/// <summary>
/// A list of semi-colon separated numeric values used to determine the weight of password strength's characteristic.
/// </summary>
/// <remarks>
/// There must be 4 values specified which must total 100.
/// The default weighting values are defined as 50;15;15;20.
/// This corresponds to password length is 50% of the strength calculation,
/// Numeric criteria is 15% of strength calculation, casing criteria is 15% of calculation,
/// and symbol criteria is 20% of calculation. So the format is 'A;B;C;D'
/// where A = length weighting, B = numeric weighting, C = casing weighting, D = symbol weighting.
/// </remarks>
[DefaultValue("")]
[ExtenderControlProperty()]
[ClientPropertyName("calculationWeightings")]
public string CalculationWeightings {
get { return GetPropertyValue(_calcWeightings, String.Empty); }
set {
if(String.IsNullOrEmpty(value))
SetPropertyValue(_calcWeightings, value);
else {
var total = 0;
if(value != null) {
var tmpList = value.Split(';');
foreach(var val in tmpList) {
int tmpVal;
if(Int32.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out tmpVal))
total += tmpVal;
}
}
if(total == 100)
SetPropertyValue(_calcWeightings, value);
else
throw new ArgumentException("There must be 4 Calculation Weighting items which must total 100");
}
}
}
/// <summary>
/// List of semi-colon separated descriptions used when StrengthIndicatorType=Text
/// (Minimum of 2, maximum of 10; order is weakest to strongest)
/// </summary>
/// <remarks>
/// Example: None;Weak;Medium;Strong;Excellent
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue("")]
[ClientPropertyName("textStrengthDescriptions")]
public string TextStrengthDescriptions {
get { return GetPropertyValue(_txtDisplayIndicators, String.Empty); }
set {
var valid = false;
if(!String.IsNullOrEmpty(value)) {
var txtItems = value.Split(_txtIndicatorDelimiter);
if(txtItems.Length >= _txtIndicatorsMinCount && txtItems.Length <= _txtIndicatorsMaxCount)
valid = true;
}
if(valid)
SetPropertyValue(_txtDisplayIndicators, value);
else {
var msg = String.Format(CultureInfo.CurrentCulture, "Invalid property specification for TextStrengthDescriptions property. Must be a string delimited with '{0}', contain a minimum of {1} entries, and a maximum of {2}.", _txtIndicatorDelimiter, _txtIndicatorsMinCount, _txtIndicatorsMaxCount);
throw new ArgumentException(msg);
}
}
}
/// <summary>
/// List of semi-colon separated CSS classes that are used depending on the password's strength.
/// </summary>
/// <remarks>
/// This property will override the BarIndicatorCssClass / TextIndicatorCssClass property if present.
/// The BarIndicatorCssClass / TextIndicatorCssClass property differs in that it attributes one
/// CSS style to the BarIndicator or Text Strength indicator (depending on which type is chosen)
/// regardless of password strength. This property will cause the style to change based on the password
/// strength and also to the number of styles specified in this property. For example, if 2 styles are
/// defined like StrengthStyles="style1;style2" then style1 is applied when the password strength is less
/// than 50%, and style2 is applied when password strength is >= 50%. This property can have up to 10 styles.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue("")]
[ClientPropertyName("strengthStyles")]
public string StrengthStyles {
get { return GetPropertyValue(_strengthStyles, String.Empty); }
set {
var valid = false;
if(!String.IsNullOrEmpty(value)) {
var styleItems = value.Split(_txtIndicatorDelimiter);
if(styleItems.Length <= _txtIndicatorsMaxCount) {
valid = true;
}
}
if(valid)
SetPropertyValue(_strengthStyles, value);
else {
var msg = String.Format(CultureInfo.CurrentCulture, "Invalid property specification for TextStrengthDescriptionStyles property. Must match the number of entries for the TextStrengthDescriptions property.");
throw new ArgumentException(msg);
}
}
}
/// <summary>
/// A minimum number of lowercase characters required when requiring
/// mixed case characters as part of your password strength considerations
/// </summary>
/// <remarks>
/// Only in effect if RequiresUpperAndLowerCaseCharacters property is true.
/// The default value is 0 which means this property is not in effect and
/// there is no minimum limit.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("minimumLowerCaseCharacters")]
public int MinimumLowerCaseCharacters {
get { return GetPropertyValue(_minLowerCaseChars, 0); }
set { SetPropertyValue(_minLowerCaseChars, value); }
}
/// <summary>
/// Minimum number of uppercase characters required when requiring mixed case
/// characters as part of your password strength considerations.
/// </summary>
/// <remarks>
/// Only in effect if RequiresUpperAndLowerCaseCharacters property is true.
/// The default value is 0 which means this property is not in effect and
/// there is no minimum limit.
/// </remarks>
[ExtenderControlProperty()]
[DefaultValue(0)]
[ClientPropertyName("minimumUpperCaseCharacters")]
public int MinimumUpperCaseCharacters {
get { return GetPropertyValue(_minUpperCaseChars, 0); }
set { SetPropertyValue(_minUpperCaseChars, value); }
}
/// <summary>
/// A semi-colon delimited string that specifies the styles applicable to each
/// string descriptions for the password strength when using a textual display
/// </summary>
/// <remarks>
/// Deprecated. Use StrengthStyles instead
/// </remarks>
[Obsolete("This property has been deprecated. Please use the StrengthStyles property instead.")]
[ExtenderControlProperty()]
[DefaultValue("")]
public string TextStrengthDescriptionStyles {
get { return StrengthStyles; }
set { StrengthStyles = value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Timers;
using System.Diagnostics;
namespace ASCOM.NexStar
{
[ComVisible(false)] // Form not registered for COM!
public partial class SetupDialogForm : Form
{
System.Timers.Timer tmr = new System.Timers.Timer();
DateTime dt;
public SetupDialogForm()
{
InitializeComponent();
foreach (string port in System.IO.Ports.SerialPort.GetPortNames())
{
comboBox1.Items.Add(port);
comboBox1.Sorted = true;
comboBox1.SelectedIndex = 0;
int p = Common.GetSerialPort();
if (p > 0 && p <= 256)
{
comboBox1.Text = "COM" + p;
}
}
text_lat.Text = Scope.Latitude.ToString();
text_long.Text = Scope.Longitude.ToString();
text_evel.Text = Scope.Elevation.ToString();
text_foc_len.Text = (Scope.FocalLength * 1000).ToString();
text_ap_obs.Text = Scope.ApertureObstruction.ToString();
text_ap_dia.Text = (Scope.ApertureDiameter * 1000).ToString();
dt = Common.GetLstDateTime();
tmr.Interval = 1000;
tmr.AutoReset = true;
tmr.Elapsed += new ElapsedEventHandler(tmr_Elapsed);
tmr.Start();
text_lst.Text = dt.ToString("HH:mm:ss");
comboBox2.Items.Add("Off");
comboBox2.Items.Add("Alt-Azm");
comboBox2.Items.Add("Eq North");
comboBox2.Items.Add("Eq South");
comboBox2.SelectedIndex = 0;
comboBox2.SelectedIndex = ((int)Scope.TrackingMode);
checkBox1.Checked = Scope.PecEnabled;
}
public void updatelst()
{
text_lst.Text = dt.ToString("HH:mm:ss");
}
void tmr_Elapsed(object sender, ElapsedEventArgs e)
{
/* add one sidereal second for every "normal" second */
dt = dt.AddMilliseconds(1002.737916);
text_lst.Invoke(new updatetextboxCallback(updatelst));
}
public delegate void updatetextboxCallback();
private void cmdOK_Click(object sender, EventArgs e)
{
double value = 0;
short pn = 0;
string p = "0";
if (!string.IsNullOrEmpty(comboBox1.Text))
{
p = comboBox1.Text;
}
Regex rgx = new Regex("[^0-9]");
p = rgx.Replace(p, "");
short.TryParse(p, out pn);
if (pn > 0 && pn <= 256)
{
Scope.ConnectedPort = pn;
}
double.TryParse(text_lat.Text, out value);
Scope.Latitude = value;
double.TryParse(text_long.Text, out value);
Scope.Longitude = value;
double.TryParse(text_evel.Text, out value);
Scope.Elevation = value;
double.TryParse(text_foc_len.Text, out value);
Scope.FocalLength = value / 1000;
/* caluclate aperture area */
double r = 0;
double.TryParse(text_ap_dia.Text.ToString(), out r);
r /= 2;
value = (r * r) * Math.PI;
double obs = 0;
double.TryParse(text_ap_obs.Text.ToString(), out obs);
Scope.ApertureObstruction = obs;
obs /= 100d;
value -= ((r * obs) * (r * obs)) * Math.PI;
Scope.ApertureArea = value / 1000000;
/* */
double.TryParse(text_ap_dia.Text, out value);
Scope.ApertureDiameter = value / 1000;
Scope.TrackingMode = (Common.eTrackingMode)comboBox2.SelectedIndex;
Scope.PecEnabled = checkBox1.Checked;
tmr.Stop();
tmr.Dispose();
Close();
}
private void cmdCancel_Click(object sender, EventArgs e)
{
tmr.Stop();
tmr.Dispose();
Close();
}
private void BrowseToAscom(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start("http://ascom-standards.org/");
}
catch (System.ComponentModel.Win32Exception noBrowser)
{
if (noBrowser.ErrorCode == -2147467259)
MessageBox.Show(noBrowser.Message);
}
catch (System.Exception other)
{
MessageBox.Show(other.Message);
}
}
private void SetupDialogForm_Load(object sender, EventArgs e)
{
}
/* allow only numbers in the text boxes */
private void text_ap_dia_Leave(object sender, EventArgs e)
{
if (text_ap_dia.Text == null ||
text_ap_dia.Text == String.Empty)
{
text_ap_dia.Text = "0";
}
if (text_ap_dia.Text != null ||
text_ap_dia.Text != String.Empty)
{
}
}
private void text_ap_dia_KeyPress(object sender, KeyPressEventArgs e)
{
if(!char.IsNumber(e.KeyChar) &&
!char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
private void text_foc_len_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) &&
!char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
private void text_evel_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) &&
!char.IsControl(e.KeyChar) &&
e.KeyChar != '-' &&
e.KeyChar != '.')
{
e.Handled = true;
}
}
private void text_lat_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) &&
!char.IsControl(e.KeyChar) &&
e.KeyChar != '-' &&
e.KeyChar != '.')
{
e.Handled = true;
}
}
private void text_long_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) &&
!char.IsControl(e.KeyChar) &&
e.KeyChar != '-' &&
e.KeyChar != '.')
{
e.Handled = true;
}
}
private void SetupDialogForm_FormClosing(object sender, FormClosingEventArgs e)
{
tmr.Stop();
tmr.Dispose();
}
private void text_ap_obs_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) &&
!char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
private void text_ap_obs_Leave(object sender, EventArgs e)
{
if (text_ap_obs.Text == null ||
text_ap_obs.Text == String.Empty)
{
text_ap_obs.Text = "0";
}
if (text_ap_obs.Text != null ||
text_ap_obs.Text != String.Empty)
{
}
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RoslynIntellisense
{
public static class ISymbolExtensions
{
public static INamedTypeSymbol GetRootType(this ISymbol symbol)
{
//itself if it is a type or containing type if a member
if (symbol is INamedTypeSymbol)
return (INamedTypeSymbol) symbol;
else
return symbol.ContainingType;
}
public static bool IsEnum(this INamedTypeSymbol symbol)
{
return symbol.BaseType != null && symbol.BaseType.GetFullName() == "System.Enum";
}
public static string GetDisplayGroup(this ISymbol symbol)
{
//<sorting>:<type>
if (symbol.IsConstructor()) return "1:C";
else if (symbol.IsDestructor()) return "2:D";
else if (symbol.IsField()) return "3:F";
else if (symbol.IsEvent()) return "4:E";
else if (symbol.IsProperty()) return "5:P";
else if (symbol.IsMethod()) return "6:M";
else if (symbol.IsOperator())
{
if (symbol.Name == "op_True" || symbol.Name == "op_False") return "7:O.2";
else return "7:O";
}
else if (symbol.IsConversion()) return "8:C";
return "9:G"; //generic
}
public static bool IsField(this ISymbol symbol)
{
return symbol.Kind == SymbolKind.Field;
}
public static bool IsProperty(this ISymbol symbol)
{
return symbol.Kind == SymbolKind.Property;
}
public static bool IsEvent(this ISymbol symbol)
{
return symbol.Kind == SymbolKind.Event;
}
public static bool IsMethod(this ISymbol symbol)
{
return symbol.Kind == SymbolKind.Method && ((IMethodSymbol) symbol).MethodKind == MethodKind.Ordinary;
}
static Dictionary<string, string> opNamesMap = new Dictionary<string, string>
{
{"op_Addition", "operator +" },
{"op_Subtraction", "operator -" },
{"op_Multiply", "operator *" },
{"op_Division", "operator /" },
{"op_Modulus", "operator %" },
{"op_BitwiseAnd", "operator &" },
{"op_BitwiseOr", "operator |" },
{"op_ExclusiveOr", "operator ^" },
{"op_LeftShift", "operator <<" },
{"op_RightShift", "operator >>" },
{"op_LogicalNot", "operator !" },
{"op_OnesComplement", "operator ~" },
{"op_Decrement", "operator --" },
{"op_Increment", "operator ++" },
{"op_Equality", "operator ==" },
{"op_Inequality", "operator !=" },
{"op_LessThan", "operator <" },
{"op_GreaterThan", "operator >" },
{"op_LessThanOrEqual", "operator <=" },
{"op_GreaterThanOrEqual", "operator >=" },
{"op_True", "operator true" },
{"op_False", "operator false" },
{"op_Implicit", "implicit operator" },
{"op_Explicit", "explicit operator" },
};
public static string GetDisplayName(this IMethodSymbol symbol)
{
if ((symbol.IsConversion() || symbol.IsOperator()) && opNamesMap.ContainsKey(symbol.Name))
return opNamesMap[symbol.Name];
else
return symbol.Name;
}
public static bool IsConstructor(this ISymbol symbol)
{
if (symbol.Kind != SymbolKind.Method) return false;
return symbol.Kind == SymbolKind.Method && ((IMethodSymbol) symbol).MethodKind == MethodKind.Constructor;
}
public static bool IsDestructor(this ISymbol symbol)
{
if (symbol.Kind != SymbolKind.Method) return false;
return symbol.Kind == SymbolKind.Method && ((IMethodSymbol) symbol).MethodKind == MethodKind.Destructor;
}
public static bool IsInterface(this INamedTypeSymbol symbol)
{
return symbol != null && symbol.TypeKind == TypeKind.Interface;
}
public static bool IsDelegate(this INamedTypeSymbol symbol)
{
return symbol != null && symbol.TypeKind == TypeKind.Delegate;
}
public static bool IsOperator(this ISymbol symbol)
{
if (symbol.Kind != SymbolKind.Method) return false;
var method = (IMethodSymbol) symbol;
return symbol.Kind == SymbolKind.Method && method.MethodKind == MethodKind.UserDefinedOperator;
}
public static bool IsConversion(this ISymbol symbol)
{
if (symbol.Kind != SymbolKind.Method) return false;
var method = (IMethodSymbol) symbol;
return symbol.Kind == SymbolKind.Method && method.MethodKind == MethodKind.Conversion;
}
public static string GetNamespace(this ISymbol type)
{
List<string> parts = new List<string>();
var nm = type.ContainingNamespace;
while (nm != null && nm.Name.HasText())
{
parts.Add(nm.Name);
nm = nm.ContainingNamespace;
}
parts.Reverse();
return string.Join(".", parts.ToArray());
}
public static string[] UsedNamespaces(this INamedTypeSymbol type)
{
var result = new List<string>();
Action<string> add = (string nms) => { if (nms.HasAny() && !result.Contains(nms)) result.Add(nms); };
foreach (var item in type.GetMembers())
{
if (item.Kind == SymbolKind.Field)
add((item as IFieldSymbol).Type.GetNamespace());
else if (item.Kind == SymbolKind.Property)
add((item as IPropertySymbol).Type.GetNamespace());
else if (item.Kind == SymbolKind.Event)
add((item as IEventSymbol).Type.GetNamespace());
else if (item.Kind == SymbolKind.Method)
{
var method = (item as IMethodSymbol);
add(method.ReturnType.GetNamespace());
if (method.TypeArguments.HasAny())
foreach (var a in method.TypeArguments)
add(a.GetNamespace());
if (method.Parameters.HasAny())
foreach (var a in method.TypeArguments)
add(a.GetNamespace());
}
}
return result.Distinct()
.Where(x => x != type.GetNamespace())
.ToArray();
}
public static string ToMinimalString(this ISymbol type)
{
if (type.ContainingSymbol != null && type.ContainingSymbol.Kind == SymbolKind.NamedType)
{
var nms = type.GetNamespace();
return type.ToDisplayString().Replace(nms + ".", "");
}
else
{
//doesnt handle nested classes
return type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
}
}
public static INamedTypeSymbol[] GetParentClasses(this ISymbol type)
{
var result = new List<INamedTypeSymbol>();
var parent = type.ContainingType;
while (parent != null)
{
result.Add(parent);
parent = parent.ContainingType;
}
return result.ToArray();
}
public static string GetFullName(this ISymbol type)
{
if (type == null) return null;
List<string> parts = new List<string>();
var nm = type.ContainingSymbol; //important: ContainingSymbol will cover both namespaces and nested type's parents
while (nm != null && nm.Name.HasText())
{
parts.Add(nm.Name);
nm = nm.ContainingSymbol;
}
parts.Reverse();
parts.Add(type.Name);
return string.Join(".", parts.ToArray());
}
public static string GetFullName(this BaseTypeDeclarationSyntax token)
{
if (token == null)
return "";
dynamic node = token;
if (node == null) return null;
List<string> parts = new List<string>();
parts.Add(node.Identifier.Text);
var parent = node.Parent;
while (parent != null && parent is BaseTypeDeclarationSyntax)
{
parts.Add(parent.Identifier.Text);
parent = parent.Parent;
}
parts.Reverse();
return string.Join(".", parts.ToArray());
}
public static string ToDisplayKind(this ISymbol symbol)
{
if (symbol is INamedTypeSymbol)
return (symbol as INamedTypeSymbol).TypeKind.ToString();
if (symbol is IMethodSymbol)
{
switch ((symbol as IMethodSymbol).MethodKind)
{
case MethodKind.LambdaMethod:
return "Lambda";
case MethodKind.Constructor:
return "Cosntructor";
case MethodKind.Destructor:
return "Destructor";
case MethodKind.ReducedExtension:
return "Extension Method";
case MethodKind.StaticConstructor:
return "Static Constructor";
case MethodKind.UserDefinedOperator:
case MethodKind.BuiltinOperator:
return "Operator";
case MethodKind.DeclareMethod:
default:
return "Method";
}
}
return symbol.Kind.ToString();
}
public static string[] GetUsingNamespace(this SyntaxNode syntax, string code)
{
var t = syntax.SyntaxTree.Options.DocumentationMode;
var namespaces = syntax.DescendantNodes()
.OfType<UsingDirectiveSyntax>()
.Select(x => x.GetText().ToString()
.Replace("using", "")
.Replace(";", "")
.Trim())
.ToArray();
return namespaces;
}
public static string ToDeclarationString(this IEnumerable<ITypeParameterSymbol> typeParameters)
{
if (typeParameters.HasAny())
{
string prms = typeParameters.Select(x => x.Name).JoinBy(", ");
return $"<{prms}>";
}
return "";
}
public static string ToInheritanceString(this INamedTypeSymbol type)
{
var code = new StringBuilder();
string baseType = null;
if (type.BaseType != null && !type.BaseType.GetFullName().OneOf("System.ValueType", "System.Object"))
baseType = type.BaseType.ToMinimalString();
if (baseType.HasAny())
code.Append(" : " + baseType);
if (type.AllInterfaces.HasAny())
{
if (baseType.HasAny())
code.Append(", ");
else
code.Append(": ");
code.Append(type.AllInterfaces.Select(x => x.Name).JoinBy(", "));
}
return code.ToString();
}
public static IMethodSymbol GetMethod(this INamedTypeSymbol type, string name)
{
return type.GetMembers(name).Cast<IMethodSymbol>().First();
}
public static string GetParametersString(this IMethodSymbol method)
{
var prms = "";
if (method.Parameters.HasAny())
prms = GetParametersString(method.OriginalDefinition.Parameters);
if (prms.Any() && method.IsExtensionMethod)
prms = "this " + prms;
return $"({prms})";
}
public static string GetIndexerParametersString(this IPropertySymbol method)
{
var prms = "";
if (method.Parameters.HasAny())
prms = GetParametersString(method.OriginalDefinition.Parameters);
return $"[{prms}]";
}
public static string GetParametersString(this IEnumerable<IParameterSymbol> parameters)
{
if (parameters.HasAny())
{
string prms = string.Join(", ", parameters
.Select(p =>
{
string refKind = "";
if (p.RefKind == RefKind.Ref)
refKind = "ref ";
else if (p.RefKind == RefKind.Out)
refKind = "out ";
if (p.IsParams)
refKind = "params " + refKind;
string defValue = "";
if (p.HasExplicitDefaultValue)
{
var val = p.ExplicitDefaultValue;
if (p.Type.GetFullName() == "System.Char")
val = $"'{val}'";
else if (p.Type.GetFullName() == "System.String")
val = $"\"{val}\"";
defValue = " = " + val;
}
return $"{refKind}{p.Type.ToMinimalString()} {p.Name}{defValue}";
})
.ToArray());
return prms;
}
return "";
}
public static string GetConstrains(this IEnumerable<ITypeParameterSymbol> typeParameters, bool singleLine = false)
{
var code = new StringBuilder();
if (typeParameters.HasAny())
foreach (var item in typeParameters)
{
var constrains = item.GetConstrains();
if (constrains.HasAny())
if (singleLine)
code.Append(" " + constrains);
else
code.Append(Environment.NewLine + " " + constrains);
}
return code.ToString();
}
public static string GetConstrains(this ITypeParameterSymbol symbol)
{
var items = new List<string>();
if (symbol.HasValueTypeConstraint) items.Add("struct");
if (symbol.HasReferenceTypeConstraint) items.Add("class");
if (symbol.HasConstructorConstraint) items.Add("new()");
items.AddRange(symbol.ConstraintTypes.Select(x => x.ToMinimalString()));
if (items.Any())
return $"where {symbol.Name}: {items.JoinBy(", ")}";
else
return "";
}
}
}
| |
using UnityEngine;
using System.Collections;
/// <summary>
/// Provides functionality to use sprites in your scenes that display a multi-coloured gradient
/// </summary>
public class OTGradientSprite : OTSprite
{
/// <summary>
/// Gradient orientation enumeration
/// </summary>
public enum GradientOrientation {
/// <summary>
/// Vertical gradient orientation
/// </summary>
Vertical,
/// <summary>
/// Horizontal gradient orientation
/// </summary>
Horizontal
}
//-----------------------------------------------------------------------------
// Editor settings
//-----------------------------------------------------------------------------
public GradientOrientation _gradientOrientation = GradientOrientation.Vertical;
//-----------------------------------------------------------------------------
// public attributes (get/set)
//-----------------------------------------------------------------------------
/// <summary>
/// Gets or sets the gradient orientation.
/// </summary>
/// <value>
/// The gradient orientation.
/// </value>
public GradientOrientation gradientOrientation
{
get
{
return _gradientOrientation;
}
set
{
if (value!=_gradientOrientation)
{
_gradientOrientation = value;
meshDirty = true;
isDirty = true;
Update();
}
}
}
public OTGradientSpriteColor[] _gradientColors;
/// <summary>
/// Gets or sets the gradient colors.
/// </summary>
/// <value>
/// An array with OTGradientSpriteColor elements
/// </value>
public OTGradientSpriteColor[] gradientColors
{
get
{
return _gradientColors;
}
set
{
_gradientColors = value;
meshDirty = true;
isDirty = true;
Update();
}
}
private OTGradientSpriteColor[] _gradientColors_;
private GradientOrientation _gradientOrientation_ = GradientOrientation.Vertical;
void GradientVerts(int vr, int vp, int pos)
{
if (_gradientOrientation == GradientOrientation.Horizontal)
{
float dd = (_meshsize_.x/100) * (_gradientColors[vr].position + pos);
verts[vp * 2] = new Vector3(mLeft + dd, mTop , 0); // top
verts[(vp * 2) +1] = new Vector3(mLeft + dd, mBottom , 0); // bottom
}
else
{
float dd = (_meshsize_.y/100) * (_gradientColors[vr].position + pos);
verts[vp * 2] = new Vector3(mLeft, mTop - dd , 0); // left
verts[(vp * 2) +1] = new Vector3(mRight, mTop - dd , 0); // right
}
}
Vector3[] verts = new Vector3[]{};
/// <exclude/>
protected override Mesh GetMesh()
{
Mesh mesh = InitMesh();
int count = _gradientColors.Length;
for (int vr=0; vr<_gradientColors.Length; vr++)
if (_gradientColors[vr].size>0)
count++;
verts = new Vector3[count * 2];
int vp = 0;
for (int vr=0; vr<_gradientColors.Length; vr++)
{
GradientVerts(vr,vp++,0);
if (_gradientColors[vr].size>0)
GradientVerts(vr,vp++,_gradientColors[vr].size);
}
mesh.vertices = verts;
int[] tris = new int[(count-1) * 6];
for (int vr=0; vr<count-1; vr++)
{
int vv = vr*2;
if (_gradientOrientation == GradientOrientation.Horizontal)
{
int[] _tris = new int[] { vv,vv+2,vv+3,vv+3,vv+1,vv };
_tris.CopyTo(tris, vr * 6);
}
else
{
int[] _tris = new int[] { vv,vv+1,vv+3,vv+3,vv+2,vv };
_tris.CopyTo(tris, vr * 6);
}
}
mesh.triangles = tris;
float[] gradientPositions = new float[count];
vp = 0;
for(int g = 0; g<gradientColors.Length; g++)
{
gradientPositions[vp] = gradientColors[g].position;
vp++;
if (gradientColors[g].size>0)
{
gradientPositions[vp] = gradientColors[g].position + gradientColors[g].size;
vp++;
}
}
mesh.uv = SpliceUV(
new Vector2[] {
new Vector2(0,1), new Vector2(1,1), new Vector2(1,0), new Vector2(0,0)
},gradientPositions, _gradientOrientation == GradientOrientation.Horizontal);
return mesh;
}
void CloneGradientColors()
{
_gradientColors_ = new OTGradientSpriteColor[_gradientColors.Length];
for (int c=0; c<_gradientColors.Length; c++)
{
_gradientColors_[c] = new OTGradientSpriteColor();
_gradientColors_[c].position = _gradientColors[c].position;
_gradientColors_[c].size = _gradientColors[c].size;
_gradientColors_[c].color = _gradientColors[c].color;
}
}
//-----------------------------------------------------------------------------
// overridden subclass methods
//-----------------------------------------------------------------------------
protected override void CheckDirty()
{
base.CheckDirty();
if (_gradientColors.Length!=_gradientColors_.Length || GradientMeshChanged() || _gradientOrientation_ != _gradientOrientation)
meshDirty = true;
else
if (GradientColorChanged())
isDirty = true;
}
protected override void CheckSettings()
{
base.CheckSettings();
if (_gradientColors.Length<2)
System.Array.Resize(ref _gradientColors,2);
}
protected override string GetTypeName()
{
return "Gradient";
}
/// <exclude/>
protected override void HandleUV()
{
if (spriteContainer != null && spriteContainer.isReady)
{
OTContainer.Frame frame = spriteContainer.GetFrame(frameIndex);
// adjust this sprites UV coords
if (frame.uv != null && mesh != null)
{
int count = _gradientColors.Length;
for (int vr=0; vr<_gradientColors.Length; vr++)
if (_gradientColors[vr].size>0)
count++;
// get positions for UV splicing
float[] gradientPositions = new float[count];
int vp = 0;
for(int g = 0; g<gradientColors.Length; g++)
{
gradientPositions[vp] = gradientColors[g].position;
vp++;
if (gradientColors[g].size>0)
{
gradientPositions[vp] = gradientColors[g].position + gradientColors[g].size;
vp++;
}
}
// splice UV that we got from the container.
mesh.uv = SpliceUV(frame.uv.Clone() as Vector2[],gradientPositions,gradientOrientation == GradientOrientation.Horizontal);
}
}
}
/// <exclude/>
protected override void Clean()
{
base.Clean();
if (mesh == null) return;
_gradientColors[0].position = 0;
_gradientColors[_gradientColors.Length-1].position = 100-_gradientColors[_gradientColors.Length-1].size;
CloneGradientColors();
_gradientOrientation_ = _gradientOrientation;
var colors = new Color[mesh.vertexCount];
int vp = 0;
for (int c=0; c<_gradientColors.Length; c++)
{
Color col = _gradientColors[c].color;
col.a = (col.a * alpha);
col.r = (col.r * tintColor.r);
col.g = (col.g * tintColor.g);
col.b = (col.b * tintColor.b);
if (vp < mesh.vertexCount/2)
{
colors[(vp*2)] = col;
colors[(vp*2)+1] = col;
}
vp++;
if (_gradientColors[c].size>0 && vp < mesh.vertexCount/2)
{
colors[(vp*2)] = col;
colors[(vp*2)+1] = col;
vp++;
}
}
mesh.colors = colors;
}
//-----------------------------------------------------------------------------
// class methods
//-----------------------------------------------------------------------------
bool GradientMeshChanged()
{
bool res = false;
for (int c = 0; c < _gradientColors.Length; c++)
{
if (_gradientColors[c].position < 0) _gradientColors[c].position = 0;
if (_gradientColors[c].position > 100) _gradientColors[c].position = 100;
if (_gradientColors[c].size < 0) _gradientColors[c].size = 0;
if (_gradientColors[c].size > 100) _gradientColors[c].size = 100;
if (_gradientColors[c].position+_gradientColors[c].size > 100)
_gradientColors[c].position = 100-_gradientColors[c].size;
if (_gradientColors[c].position!=_gradientColors_[c].position || _gradientColors[c].size!=_gradientColors_[c].size)
res = true;
}
return res;
}
bool GradientColorChanged()
{
for (int c = 0; c < _gradientColors.Length; c++)
{
if (!_gradientColors[c].color.Equals(_gradientColors_[c].color))
{
return true;
}
}
return false;
}
protected override void Awake()
{
CloneGradientColors();
_gradientOrientation_ = _gradientOrientation;
base.Awake();
}
new void Start()
{
base.Start();
}
// Update is called once per frame
new void Update()
{
base.Update();
}
}
/// <summary>
/// OT gradient sprite color element
/// </summary>
[System.Serializable]
public class OTGradientSpriteColor
{
/// <summary>
/// The position of the color (0-100)
/// </summary>
public int position = 0;
/// <summary>
/// The size of solid color area (0-100)
/// </summary>
public int size = 0;
/// <summary>
/// The color of this element
/// </summary>
public Color color = Color.white;
}
| |
//-----------------------------------------------------------------------
// <copyright file="VideoOverlayProvider.cs" company="Google">
//
// Copyright 2015 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>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using Tango;
namespace Tango
{
/// <summary>
/// C API wrapper for the Tango video overlay interface.
/// </summary>
public class VideoOverlayProvider
{
/// <summary>
/// Tango video overlay C callback function signature.
/// </summary>
/// <param name="callbackContext">Callback context.</param>
/// <param name="cameraId">Camera ID.</param>
/// <param name="image">Image.</param>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void TangoService_onImageAvailable(IntPtr callbackContext, Tango.TangoEnums.TangoCameraId cameraId, [In, Out] TangoImageBuffer image);
/// <summary>
/// Experimental API only, subject to change. Tango depth C callback function signature.
/// </summary>
/// <param name="callbackContext">Callback context.</param>
/// <param name="cameraId">Camera ID.</param>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void TangoService_onUnityFrameAvailable(IntPtr callbackContext, Tango.TangoEnums.TangoCameraId cameraId);
private static readonly string CLASS_NAME = "VideoOverlayProvider";
private static IntPtr callbackContext = IntPtr.Zero;
/// <summary>
/// Connect a Texture ID to a camera; the camera is selected by specifying a TangoCameraId.
///
/// Currently only TANGO_CAMERA_COLOR and TANGO_CAMERA_FISHEYE are supported. The texture must be the ID of a
/// texture that has been allocated and initialized by the calling application.
///
/// The first scan-line of the color image is reserved for metadata instead of image pixels.
/// </summary>
/// <param name="cameraId">
/// The ID of the camera to connect this texture to. Only TANGO_CAMERA_COLOR and TANGO_CAMERA_FISHEYE are
/// supported.
/// </param>
/// <param name="textureId">
/// The texture ID of the texture to connect the camera to. Must be a valid texture in the applicaton.
/// </param>
public static void ConnectTexture(TangoEnums.TangoCameraId cameraId, int textureId)
{
int returnValue = VideoOverlayAPI.TangoService_connectTextureId(cameraId, textureId);
if (returnValue != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log("VideoOverlayProvider.ConnectTexture() Texture was not connected to camera!");
}
}
/// <summary>
/// Update the texture that has been connected to camera referenced by TangoCameraId with the latest image
/// from the camera.
/// </summary>
/// <returns>The timestamp of the image that has been pushed to the connected texture.</returns>
/// <param name="cameraId">
/// The ID of the camera to connect this texture to. Only <code>TANGO_CAMERA_COLOR</code> and
/// <code>TANGO_CAMERA_FISHEYE</code> are supported.
/// </param>
public static double RenderLatestFrame(TangoEnums.TangoCameraId cameraId)
{
double timestamp = 0.0;
int returnValue = VideoOverlayAPI.TangoService_updateTexture(cameraId, ref timestamp);
if (returnValue != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log("VideoOverlayProvider.UpdateTexture() Texture was not updated by camera!");
}
return timestamp;
}
/// <summary>
/// Get the intrinsic calibration parameters for a given camera.
///
/// The intrinsics are as specified by the TangoCameraIntrinsics struct. Intrinsics are read from the
/// on-device intrinsics file (typically <code>/sdcard/config/calibration.xml</code>, but to ensure
/// compatibility applications should only access these parameters via the API), or default internal model
/// parameters corresponding to the device are used if the calibration.xml file is not found.
/// </summary>
/// <param name="cameraId">The camera ID to retrieve the calibration intrinsics for.</param>
/// <param name="intrinsics">A TangoCameraIntrinsics filled with calibration intrinsics for the camera.</param>
public static void GetIntrinsics(TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics)
{
int returnValue = VideoOverlayAPI.TangoService_getCameraIntrinsics(cameraId, intrinsics);
if (returnValue != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log("IntrinsicsProviderAPI.TangoService_getCameraIntrinsics() failed!");
}
}
/// <summary>
/// Experimental API only, subject to change. Connect a Texture IDs to a camera.
///
/// The camera is selected via TangoCameraId. Currently only TANGO_CAMERA_COLOR is supported. The texture
/// handles will be regenerated by the API on startup after which the application can use them, and will be
/// packed RGBA8888 data containing bytes of the image (so a single RGBA8888 will pack 4 neighbouring pixels).
/// If the config flag experimental_image_pixel_format is set to HAL_PIXEL_FORMAT_YCrCb_420_SP, texture_y will
/// pack 1280x720 pixels into a 320x720 RGBA8888 texture. texture_Cb and texture_Cr will contain copies of
/// the 2x2 downsampled interleaved UV planes packed similarly. If experimental_image_pixel_format is set to
/// HAL_PIXEL_FORMAT_YV12 then texture_y will have a stride of 1536 containing 1280 columns of data, packed
/// similarly in a RGBA8888 texture. texture_Cb and texture_Cr will be 2x2 downsampled versions of the same.
/// See YV12 and NV21 formats for details.
///
/// Note: The first scan-line of the color image is reserved for metadata instead of image pixels.
/// </summary>
/// <param name="cameraId">
/// The ID of the camera to connect this texture to. Only TANGO_CAMERA_COLOR and TANGO_CAMERA_FISHEYE are
/// supported.
/// </param>
/// <param name="textures">The texture IDs to use for the Y, Cb, and Cr planes.</param>
/// <param name="onUnityFrameAvailable">Callback.</param>
internal static void ExperimentalConnectTexture(TangoEnums.TangoCameraId cameraId, YUVTexture textures, TangoService_onUnityFrameAvailable onUnityFrameAvailable)
{
int returnValue = VideoOverlayAPI.TangoService_Experimental_connectTextureIdUnity(cameraId,
(uint)textures.m_videoOverlayTextureY.GetNativeTextureID(),
(uint)textures.m_videoOverlayTextureCb.GetNativeTextureID(),
(uint)textures.m_videoOverlayTextureCr.GetNativeTextureID(),
callbackContext,
onUnityFrameAvailable);
if (returnValue != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log("VideoOverlayProvider.ConnectTexture() Texture was not connected to camera!");
}
}
/// <summary>
/// Connect a callback to a camera for access to the pixels.
///
/// This is not recommended for display but for applications requiring access to the
/// <code>HAL_PIXEL_FORMAT_YV12</code> pixel data. The camera is selected via TangoCameraId. Currently only
/// <code>TANGO_CAMERA_COLOR</code> and <code>TANGO_CAMERA_FISHEYE</code> are supported.
///
/// The <i>onImageAvailable</i> callback will be called when a new frame is available from the camera. The
/// Enable Video Overlay option must be enabled for this to succeed.
///
/// Note: The first scan-line of the color image is reserved for metadata instead of image pixels.
/// </summary>
/// <param name="cameraId">
/// The ID of the camera to connect this texture to. Only <code>TANGO_CAMERA_COLOR</code> and
/// <code>TANGO_CAMERA_FISHEYE</code> are supported.
/// </param>
/// <param name="onImageAvailable">Function called when a new frame is available from the camera.</param>
internal static void SetCallback(TangoEnums.TangoCameraId cameraId, TangoService_onImageAvailable onImageAvailable)
{
int returnValue = VideoOverlayAPI.TangoService_connectOnFrameAvailable(cameraId, callbackContext, onImageAvailable);
if (returnValue == Tango.Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log(CLASS_NAME + ".SetCallback() Callback was set.");
}
else
{
Debug.Log(CLASS_NAME + ".SetCallback() Callback was not set!");
}
}
#region NATIVE_FUNCTIONS
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "C API Wrapper.")]
private struct VideoOverlayAPI
{
#if UNITY_ANDROID && !UNITY_EDITOR
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_connectTextureId(TangoEnums.TangoCameraId cameraId, int textureHandle);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_connectOnFrameAvailable(TangoEnums.TangoCameraId cameraId,
IntPtr context,
[In, Out] TangoService_onImageAvailable onImageAvailable);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_updateTexture(TangoEnums.TangoCameraId cameraId, ref double timestamp);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_getCameraIntrinsics(TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_Experimental_connectTextureIdUnity(TangoEnums.TangoCameraId id,
uint texture_y,
uint texture_Cb,
uint texture_Cr,
IntPtr context,
TangoService_onUnityFrameAvailable onUnityFrameAvailable);
#else
public static int TangoService_connectTextureId(TangoEnums.TangoCameraId cameraId, int textureHandle)
{
return Tango.Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_updateTexture(TangoEnums.TangoCameraId cameraId, ref double timestamp)
{
return Tango.Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_getCameraIntrinsics(TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_connectOnFrameAvailable(TangoEnums.TangoCameraId cameraId,
IntPtr context,
[In, Out] TangoService_onImageAvailable onImageAvailable)
{
return Tango.Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_Experimental_connectTextureIdUnity(TangoEnums.TangoCameraId id,
uint texture_y,
uint texture_Cb,
uint texture_Cr,
IntPtr context,
TangoService_onUnityFrameAvailable onUnityFrameAvailable)
{
return Tango.Common.ErrorType.TANGO_SUCCESS;
}
#endif
#endregion
}
}
/// <summary>
/// Wraps separate textures for Y, U, and V planes.
/// </summary>
public class YUVTexture
{
/// <summary>
/// The m_video overlay texture y.
/// Columns 1280/4 [bytes packed in RGBA channels]
/// Rows 720
/// This size is for a 1280x720 screen.
/// </summary>
public Texture2D m_videoOverlayTextureY;
/// <summary>
/// The m_video overlay texture cb.
/// Columns 640/4 [bytes packed in RGBA channels]
/// Rows 360
/// This size is for a 1280x720 screen.
/// </summary>
public Texture2D m_videoOverlayTextureCb;
/// <summary>
/// The m_video overlay texture cr.
/// Columns 640 * 2 / 4 [bytes packed in RGBA channels]
/// Rows 360
/// This size is for a 1280x720 screen.
/// </summary>
public Texture2D m_videoOverlayTextureCr;
/// <summary>
/// Initializes a new instance of the <see cref="Tango.YUVTexture"/> class.
/// NOTE : Texture resolutions will be reset by the API. The sizes passed
/// into the constructor are not guaranteed to persist when running on device.
/// </summary>
/// <param name="yPlaneWidth">Y plane width.</param>
/// <param name="yPlaneHeight">Y plane height.</param>
/// <param name="uvPlaneWidth">UV plane width.</param>
/// <param name="uvPlaneHeight">UV plane height.</param>
/// <param name="format">Format.</param>
/// <param name="mipmap">If set to <c>true</c> mipmap.</param>
public YUVTexture(int yPlaneWidth, int yPlaneHeight,
int uvPlaneWidth, int uvPlaneHeight,
TextureFormat format, bool mipmap)
{
m_videoOverlayTextureY = new Texture2D(yPlaneWidth, yPlaneHeight, format, mipmap);
m_videoOverlayTextureY.filterMode = FilterMode.Point;
m_videoOverlayTextureCb = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap);
m_videoOverlayTextureCb.filterMode = FilterMode.Point;
m_videoOverlayTextureCr = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap);
m_videoOverlayTextureCr.filterMode = FilterMode.Point;
}
/// <summary>
/// Resizes all yuv texture planes.
/// </summary>
/// <param name="yPlaneWidth">Y plane width.</param>
/// <param name="yPlaneHeight">Y plane height.</param>
/// <param name="uvPlaneWidth">Uv plane width.</param>
/// <param name="uvPlaneHeight">Uv plane height.</param>
public void ResizeAll(int yPlaneWidth, int yPlaneHeight,
int uvPlaneWidth, int uvPlaneHeight)
{
m_videoOverlayTextureY.Resize(yPlaneWidth, yPlaneHeight);
m_videoOverlayTextureCb.Resize(uvPlaneWidth, uvPlaneHeight);
m_videoOverlayTextureCr.Resize(uvPlaneWidth, uvPlaneHeight);
}
}
}
| |
namespace CocosSharp
{
public abstract class CCTransitionProgress : CCTransitionScene
{
const int SceneRadial = 0xc001;
protected float From;
protected float To;
protected CCNode SceneNodeContainerToBeModified;
#region Constructors
public CCTransitionProgress(float t, CCScene scene) : base(t, scene)
{
}
#endregion Constructors
protected override void InitialiseScenes()
{
if (Layer == null || Viewport == null)
return;
base.InitialiseScenes();
SetupTransition();
// create a transparent color layer
// in which we are going to add our rendertextures
var bounds = Layer.VisibleBoundsWorldspace;
CCRect viewportRect = Viewport.ViewportInPixels;
// create the second render texture for outScene
CCRenderTexture texture = new CCRenderTexture(bounds.Size, viewportRect.Size);
texture.Position = bounds.Center;
texture.AnchorPoint = CCPoint.AnchorMiddle;
// Temporarily add render texture to get layer/scene properties
AddChild(texture);
// Render outScene to its texturebuffer
texture.BeginWithClear(0, 0, 0, 1);
SceneNodeContainerToBeModified.Visit();
texture.End();
// No longer want to render texture
RemoveChild(texture);
// Since we've passed the outScene to the texture we don't need it.
if (SceneNodeContainerToBeModified == OutSceneNodeContainer)
{
HideOutShowIn();
}
CCProgressTimer node = ProgressTimerNodeWithRenderTexture(texture);
// create the blend action
var layerAction = new CCProgressFromTo(Duration, From, To);
// add the layer (which contains our two rendertextures) to the scene
AddChild(node, 2, SceneRadial);
// run the blend action
node.RunAction(layerAction);
}
// clean up on exit
public override void OnExit()
{
// remove our layer and release all containing objects
RemoveChildByTag(SceneRadial, true);
base.OnExit();
}
protected abstract CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture);
protected virtual void SetupTransition()
{
SceneNodeContainerToBeModified = OutSceneNodeContainer;
From = 100;
To = 0;
}
protected override void SceneOrder()
{
IsInSceneOnTop = false;
}
}
/** CCTransitionRadialCCW transition.
A counter colock-wise radial transition to the next scene
*/
public class CCTransitionProgressRadialCCW : CCTransitionProgress
{
public CCTransitionProgressRadialCCW(float t, CCScene scene) : base(t, scene)
{
}
protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture)
{
var bounds = Layer.VisibleBoundsWorldspace;
CCProgressTimer node = new CCProgressTimer(texture.Sprite);
// but it is flipped upside down so we flip the sprite
//node.Sprite.IsFlipY = true;
node.Type = CCProgressTimerType.Radial;
// Return the radial type that we want to use
node.ReverseDirection = false;
node.Percentage = 100;
node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2);
node.AnchorPoint = CCPoint.AnchorMiddle;
return node;
}
}
/** CCTransitionRadialCW transition.
A counter colock-wise radial transition to the next scene
*/
public class CCTransitionProgressRadialCW : CCTransitionProgress
{
public CCTransitionProgressRadialCW(float t, CCScene scene) : base(t, scene)
{
}
protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture)
{
var bounds = Layer.VisibleBoundsWorldspace;
CCProgressTimer node = new CCProgressTimer(texture.Sprite);
// but it is flipped upside down so we flip the sprite
//node.Sprite.IsFlipY = true;
node.Type = CCProgressTimerType.Radial;
// Return the radial type that we want to use
node.ReverseDirection = true;
node.Percentage = 100;
node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2);
node.AnchorPoint = CCPoint.AnchorMiddle;
return node;
}
}
/** CCTransitionProgressHorizontal transition.
A colock-wise radial transition to the next scene
*/
public class CCTransitionProgressHorizontal : CCTransitionProgress
{
public CCTransitionProgressHorizontal(float t, CCScene scene) : base(t, scene)
{
}
protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture)
{
var bounds = Layer.VisibleBoundsWorldspace;
CCProgressTimer node = new CCProgressTimer(texture.Sprite);
// but it is flipped upside down so we flip the sprite
//node.Sprite.IsFlipY = true;
node.Type = CCProgressTimerType.Bar;
node.Midpoint = new CCPoint(1, 0);
node.BarChangeRate = new CCPoint(1, 0);
node.Percentage = 100;
node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2);
node.AnchorPoint = CCPoint.AnchorMiddle;
return node;
}
}
public class CCTransitionProgressVertical : CCTransitionProgress
{
//OLD_TRANSITION_CREATE_FUNC(CCTransitionProgressVertical)
//TRANSITION_CREATE_FUNC(CCTransitionProgressVertical)
public CCTransitionProgressVertical(float t, CCScene scene) : base(t, scene)
{
}
protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture)
{
var bounds = Layer.VisibleBoundsWorldspace;
CCProgressTimer node = new CCProgressTimer(texture.Sprite);
// but it is flipped upside down so we flip the sprite
//node.Sprite.IsFlipY = true;
node.Type = CCProgressTimerType.Bar;
node.Midpoint = new CCPoint(0, 0);
node.BarChangeRate = new CCPoint(0, 1);
node.Percentage = 100;
node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2);
node.AnchorPoint = CCPoint.AnchorMiddle;
return node;
}
}
public class CCTransitionProgressInOut : CCTransitionProgress
{
public CCTransitionProgressInOut(float t, CCScene scene) : base(t, scene)
{
}
protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture)
{
var bounds = Layer.VisibleBoundsWorldspace;
CCProgressTimer node = new CCProgressTimer(texture.Sprite);
// but it is flipped upside down so we flip the sprite
//node.Sprite.IsFlipY = true;
node.Type = CCProgressTimerType.Bar;
node.Midpoint = new CCPoint(0.5f, 0.5f);
node.BarChangeRate = new CCPoint(1, 1);
node.Percentage = 0;
node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2);
node.AnchorPoint = CCPoint.AnchorMiddle;
return node;
}
protected override void SceneOrder()
{
IsInSceneOnTop = false;
}
protected override void SetupTransition()
{
SceneNodeContainerToBeModified = InSceneNodeContainer;
From = 0;
To = 100;
}
}
public class CCTransitionProgressOutIn : CCTransitionProgress
{
public CCTransitionProgressOutIn(float t, CCScene scene) : base(t, scene)
{
}
protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture)
{
var bounds = Layer.VisibleBoundsWorldspace;
CCProgressTimer node = new CCProgressTimer(texture.Sprite);
// but it is flipped upside down so we flip the sprite
//node.Sprite.IsFlipY = true;
node.Type = CCProgressTimerType.Bar;
node.Midpoint = new CCPoint(0.5f, 0.5f);
node.BarChangeRate = new CCPoint(1, 1);
node.Percentage = 100;
node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2);
node.AnchorPoint = CCPoint.AnchorMiddle;
return node;
}
}
}
| |
// <copyright file="RemoteWebElement.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// RemoteWebElement allows you to have access to specific items that are found on the page
/// </summary>
/// <seealso cref="IWebElement"/>
/// <seealso cref="ILocatable"/>
public class RemoteWebElement : IWebElement, IFindsByLinkText, IFindsById, IFindsByName, IFindsByTagName, IFindsByClassName, IFindsByXPath, IFindsByPartialLinkText, IFindsByCssSelector, IWrapsDriver, ILocatable, ITakesScreenshot, IWebElementReference
{
/// <summary>
/// The property name that represents a web element in the wire protocol.
/// </summary>
public const string ElementReferencePropertyName = "element-6066-11e4-a52e-4f735466cecf";
/// <summary>
/// The property name that represents a web element in the legacy dialect of the wire protocol.
/// </summary>
public const string LegacyElementReferencePropertyName = "ELEMENT";
private RemoteWebDriver driver;
private string elementId;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebElement"/> class.
/// </summary>
/// <param name="parentDriver">The <see cref="RemoteWebDriver"/> instance hosting this element.</param>
/// <param name="id">The ID assigned to the element.</param>
public RemoteWebElement(RemoteWebDriver parentDriver, string id)
{
this.driver = parentDriver;
this.elementId = id;
}
/// <summary>
/// Gets the <see cref="IWebDriver"/> used to find this element.
/// </summary>
public IWebDriver WrappedDriver
{
get { return this.driver; }
}
/// <summary>
/// Gets the tag name of this element.
/// </summary>
/// <remarks>
/// The <see cref="TagName"/> property returns the tag name of the
/// element, not the value of the name attribute. For example, it will return
/// "input" for an element specified by the HTML markup <input name="foo" />.
/// </remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string TagName
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.GetElementTagName, parameters);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets the innerText of this element, without any leading or trailing whitespace,
/// and with other whitespace collapsed.
/// </summary>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string Text
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.GetElementText, parameters);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets a value indicating whether or not this element is enabled.
/// </summary>
/// <remarks>The <see cref="Enabled"/> property will generally
/// return <see langword="true"/> for everything except explicitly disabled input elements.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual bool Enabled
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.IsElementEnabled, parameters);
return (bool)commandResponse.Value;
}
}
/// <summary>
/// Gets a value indicating whether or not this element is selected.
/// </summary>
/// <remarks>This operation only applies to input elements such as checkboxes,
/// options in a select element and radio buttons.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual bool Selected
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.IsElementSelected, parameters);
return (bool)commandResponse.Value;
}
}
/// <summary>
/// Gets a <see cref="Point"/> object containing the coordinates of the upper-left corner
/// of this element relative to the upper-left corner of the page.
/// </summary>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual Point Location
{
get
{
string getLocationCommand = DriverCommand.GetElementRect;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
Response commandResponse = this.Execute(getLocationCommand, parameters);
Dictionary<string, object> rawPoint = (Dictionary<string, object>)commandResponse.Value;
int x = Convert.ToInt32(rawPoint["x"], CultureInfo.InvariantCulture);
int y = Convert.ToInt32(rawPoint["y"], CultureInfo.InvariantCulture);
return new Point(x, y);
}
}
/// <summary>
/// Gets a <see cref="Size"/> object containing the height and width of this element.
/// </summary>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual Size Size
{
get
{
string getSizeCommand = DriverCommand.GetElementRect;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
Response commandResponse = this.Execute(getSizeCommand, parameters);
Dictionary<string, object> rawSize = (Dictionary<string, object>)commandResponse.Value;
int width = Convert.ToInt32(rawSize["width"], CultureInfo.InvariantCulture);
int height = Convert.ToInt32(rawSize["height"], CultureInfo.InvariantCulture);
return new Size(width, height);
}
}
/// <summary>
/// Gets a value indicating whether or not this element is displayed.
/// </summary>
/// <remarks>The <see cref="Displayed"/> property avoids the problem
/// of having to parse an element's "style" attribute to determine
/// visibility of an element.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual bool Displayed
{
get
{
Response commandResponse = null;
Dictionary<string, object> parameters = new Dictionary<string, object>();
string atom = GetAtom("isDisplayed.js");
parameters.Add("script", atom);
parameters.Add("args", new object[] { this.ToElementReference().ToDictionary() });
commandResponse = this.Execute(DriverCommand.ExecuteScript, parameters);
return (bool)commandResponse.Value;
}
}
/// <summary>
/// Gets the point where the element would be when scrolled into view.
/// </summary>
public virtual Point LocationOnScreenOnceScrolledIntoView
{
get
{
Dictionary<string, object> rawLocation;
object scriptResponse = this.driver.ExecuteScript("var rect = arguments[0].getBoundingClientRect(); return {'x': rect.left, 'y': rect.top};", this);
rawLocation = scriptResponse as Dictionary<string, object>;
int x = Convert.ToInt32(rawLocation["x"], CultureInfo.InvariantCulture);
int y = Convert.ToInt32(rawLocation["y"], CultureInfo.InvariantCulture);
return new Point(x, y);
}
}
/// <summary>
/// Gets the coordinates identifying the location of this element using
/// various frames of reference.
/// </summary>
public virtual ICoordinates Coordinates
{
get { return new RemoteCoordinates(this); }
}
/// <summary>
/// Gets the internal ID of the element.
/// </summary>
string IWebElementReference.ElementReferenceId
{
get { return this.elementId; }
}
/// <summary>
/// Gets the ID of the element
/// </summary>
/// <remarks>This property is internal to the WebDriver instance, and is
/// not intended to be used in your code. The element's ID has no meaning
/// outside of internal WebDriver usage, so it would be improper to scope
/// it as public. However, both subclasses of <see cref="RemoteWebElement"/>
/// and the parent driver hosting the element have a need to access the
/// internal element ID. Therefore, we have two properties returning the
/// same value, one scoped as internal, the other as protected.</remarks>
protected string Id
{
get { return this.elementId; }
}
/// <summary>
/// Clears the content of this element.
/// </summary>
/// <remarks>If this element is a text entry element, the <see cref="Clear"/>
/// method will clear the value. It has no effect on other elements. Text entry elements
/// are defined as elements with INPUT or TEXTAREA tags.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual void Clear()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
this.Execute(DriverCommand.ClearElement, parameters);
}
/// <summary>
/// Simulates typing text into the element.
/// </summary>
/// <param name="text">The text to type into the element.</param>
/// <remarks>The text to be typed may include special characters like arrow keys,
/// backspaces, function keys, and so on. Valid special keys are defined in
/// <see cref="Keys"/>.</remarks>
/// <seealso cref="Keys"/>
/// <exception cref="InvalidElementStateException">Thrown when the target element is not enabled.</exception>
/// <exception cref="ElementNotVisibleException">Thrown when the target element is not visible.</exception>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual void SendKeys(string text)
{
if (text == null)
{
throw new ArgumentNullException("text", "text cannot be null");
}
if (this.driver.FileDetector.IsFile(text))
{
text = this.UploadFile(text);
}
// N.B. The Java remote server expects a CharSequence as the value input to
// SendKeys. In JSON, these are serialized as an array of strings, with a
// single character to each element of the array. Thus, we must use ToCharArray()
// to get the same effect.
// TODO: Remove either "keysToSend" or "value" property, whichever is not the
// appropriate one for spec compliance.
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
parameters.Add("text", text);
parameters.Add("value", text.ToCharArray());
this.Execute(DriverCommand.SendKeysToElement, parameters);
}
/// <summary>
/// Submits this element to the web server.
/// </summary>
/// <remarks>If this current element is a form, or an element within a form,
/// then this will be submitted to the web server. If this causes the current
/// page to change, then this method will attempt to block until the new page
/// is loaded.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual void Submit()
{
string elementType = this.GetAttribute("type");
if (elementType != null && elementType == "submit")
{
this.Click();
}
else
{
IWebElement form = this.FindElement(By.XPath("./ancestor-or-self::form"));
this.driver.ExecuteScript(
"var e = arguments[0].ownerDocument.createEvent('Event');" +
"e.initEvent('submit', true, true);" +
"if (arguments[0].dispatchEvent(e)) { arguments[0].submit(); }", form);
}
}
/// <summary>
/// Clicks this element.
/// </summary>
/// <remarks>
/// Click this element. If the click causes a new page to load, the <see cref="Click"/>
/// method will attempt to block until the page has loaded. After calling the
/// <see cref="Click"/> method, you should discard all references to this
/// element unless you know that the element and the page will still be present.
/// Otherwise, any further operations performed on this element will have an undefined
/// behavior.
/// </remarks>
/// <exception cref="InvalidElementStateException">Thrown when the target element is not enabled.</exception>
/// <exception cref="ElementNotVisibleException">Thrown when the target element is not visible.</exception>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual void Click()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
this.Execute(DriverCommand.ClickElement, parameters);
}
/// <summary>
/// Gets the value of the specified attribute for this element.
/// </summary>
/// <param name="attributeName">The name of the attribute.</param>
/// <returns>The attribute's current value. Returns a <see langword="null"/> if the
/// value is not set.</returns>
/// <remarks>The <see cref="GetAttribute"/> method will return the current value
/// of the attribute, even if the value has been modified after the page has been
/// loaded. Note that the value of the following attributes will be returned even if
/// there is no explicit attribute on the element:
/// <list type="table">
/// <listheader>
/// <term>Attribute name</term>
/// <term>Value returned if not explicitly specified</term>
/// <term>Valid element types</term>
/// </listheader>
/// <item>
/// <description>checked</description>
/// <description>checked</description>
/// <description>Check Box</description>
/// </item>
/// <item>
/// <description>selected</description>
/// <description>selected</description>
/// <description>Options in Select elements</description>
/// </item>
/// <item>
/// <description>disabled</description>
/// <description>disabled</description>
/// <description>Input and other UI elements</description>
/// </item>
/// </list>
/// </remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string GetAttribute(string attributeName)
{
Response commandResponse = null;
string attributeValue = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
string atom = GetAtom("getAttribute.js");
parameters.Add("script", atom);
parameters.Add("args", new object[] { this.ToElementReference().ToDictionary(), attributeName });
commandResponse = this.Execute(DriverCommand.ExecuteScript, parameters);
if (commandResponse.Value == null)
{
attributeValue = null;
}
else
{
attributeValue = commandResponse.Value.ToString();
// Normalize string values of boolean results as lowercase.
if (commandResponse.Value is bool)
{
attributeValue = attributeValue.ToLowerInvariant();
}
}
return attributeValue;
}
/// <summary>
/// Gets the value of a JavaScript property of this element.
/// </summary>
/// <param name="propertyName">The name JavaScript the JavaScript property to get the value of.</param>
/// <returns>The JavaScript property's current value. Returns a <see langword="null"/> if the
/// value is not set or the property does not exist.</returns>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string GetProperty(string propertyName)
{
string propertyValue = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
parameters.Add("name", propertyName);
Response commandResponse = this.Execute(DriverCommand.GetElementProperty, parameters);
if (commandResponse.Value == null)
{
propertyValue = null;
}
else
{
propertyValue = commandResponse.Value.ToString();
}
return propertyValue;
}
/// <summary>
/// Gets the value of a CSS property of this element.
/// </summary>
/// <param name="propertyName">The name of the CSS property to get the value of.</param>
/// <returns>The value of the specified CSS property.</returns>
/// <remarks>The value returned by the <see cref="GetCssValue"/>
/// method is likely to be unpredictable in a cross-browser environment.
/// Color values should be returned as hex strings. For example, a
/// "background-color" property set as "green" in the HTML source, will
/// return "#008000" for its value.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string GetCssValue(string propertyName)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
parameters.Add("name", propertyName);
Response commandResponse = this.Execute(DriverCommand.GetElementValueOfCssProperty, parameters);
return commandResponse.Value.ToString();
}
/// <summary>
/// Finds all <see cref="IWebElement">IWebElements</see> within the current context
/// using the given mechanism.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElements(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElements(this);
}
/// <summary>
/// Finds the first <see cref="IWebElement"/> using the given method.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
/// <exception cref="NoSuchElementException">If no element matches the criteria.</exception>
public virtual IWebElement FindElement(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElement(this);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementByLinkText("linktext")
/// </code>
/// </example>
public virtual IWebElement FindElementByLinkText(string linkText)
{
return this.FindElement("link text", linkText);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByLinkText("linktext")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByLinkText(string linkText)
{
return this.FindElements("link text", linkText);
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the element</param>
/// <returns>IWebElement object so that you can interact with that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementById("id")
/// </code>
/// </example>
public virtual IWebElement FindElementById(string id)
{
return this.FindElement("css selector", "#" + RemoteWebDriver.EscapeCssSelector(id));
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the Element</param>
/// <returns>ReadOnlyCollection of Elements that match the object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsById("id")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsById(string id)
{
return this.FindElements("css selector", "#" + RemoteWebDriver.EscapeCssSelector(id));
}
/// <summary>
/// Finds the first of elements that match the name supplied
/// </summary>
/// <param name="name">Name of the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public virtual IWebElement FindElementByName(string name)
{
return this.FindElement("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds a list of elements that match the name supplied
/// </summary>
/// <param name="name">Name of element</param>
/// <returns>ReadOnlyCollect of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByName(string name)
{
return this.FindElements("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds the first of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">tag name of the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public virtual IWebElement FindElementByTagName(string tagName)
{
return this.FindElement("css selector", tagName);
}
/// <summary>
/// Finds a list of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">DOM Tag of the element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByTagName(string tagName)
{
return this.FindElements("css selector", tagName);
}
/// <summary>
/// Finds the first element in the page that matches the CSS Class supplied
/// </summary>
/// <param name="className">CSS class name of the element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementByClassName("classname")
/// </code>
/// </example>
public virtual IWebElement FindElementByClassName(string className)
{
return this.FindElement("css selector", "." + RemoteWebDriver.EscapeCssSelector(className));
}
/// <summary>
/// Finds a list of elements that match the class name supplied
/// </summary>
/// <param name="className">CSS class name of the elements on the page</param>
/// <returns>ReadOnlyCollection of IWebElement object so that you can interact with those objects</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByClassName(string className)
{
return this.FindElements("css selector", "." + RemoteWebDriver.EscapeCssSelector(className));
}
/// <summary>
/// Finds the first of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByXPath("//table/tbody/tr/td/a");
/// </code>
/// </example>
public virtual IWebElement FindElementByXPath(string xpath)
{
return this.FindElement("xpath", xpath);
}
/// <summary>
/// Finds a list of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to element on the page</param>
/// <returns>ReadOnlyCollection of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByXpath("//tr/td/a")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByXPath(string xpath)
{
return this.FindElements("xpath", xpath);
}
/// <summary>
/// Finds the first of elements that match the part of the link text supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByPartialLinkText("partOfLink")
/// </code>
/// </example>
public virtual IWebElement FindElementByPartialLinkText(string partialLinkText)
{
return this.FindElement("partial link text", partialLinkText);
}
/// <summary>
/// Finds a list of elements that match the link text supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByPartialLinkText("partOfTheLink")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByPartialLinkText(string partialLinkText)
{
return this.FindElements("partial link text", partialLinkText);
}
/// <summary>
/// Finds the first element matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The id to match.</param>
/// <returns>The first <see cref="IWebElement"/> matching the criteria.</returns>
public virtual IWebElement FindElementByCssSelector(string cssSelector)
{
return this.FindElement("css selector", cssSelector);
}
/// <summary>
/// Finds all elements matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The CSS selector to match.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> containing all
/// <see cref="IWebElement">IWebElements</see> matching the criteria.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElementsByCssSelector(string cssSelector)
{
return this.FindElements("css selector", cssSelector);
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of this element on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public virtual Screenshot GetScreenshot()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
// Get the screenshot as base64.
Response screenshotResponse = this.Execute(DriverCommand.ElementScreenshot, parameters);
string base64 = screenshotResponse.Value.ToString();
// ... and convert it.
return new Screenshot(base64);
}
/// <summary>
/// Returns a string that represents the current <see cref="RemoteWebElement"/>.
/// </summary>
/// <returns>A string that represents the current <see cref="RemoteWebElement"/>.</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Element (id = {0})", this.elementId);
}
/// <summary>
/// Method to get the hash code of the element
/// </summary>
/// <returns>Integer of the hash code for the element</returns>
public override int GetHashCode()
{
return this.elementId.GetHashCode();
}
/// <summary>
/// Compares if two elements are equal
/// </summary>
/// <param name="obj">Object to compare against</param>
/// <returns>A boolean if it is equal or not</returns>
public override bool Equals(object obj)
{
IWebElement other = obj as IWebElement;
if (other == null)
{
return false;
}
IWrapsElement objAsWrapsElement = obj as IWrapsElement;
if (objAsWrapsElement != null)
{
other = objAsWrapsElement.WrappedElement;
}
RemoteWebElement otherAsElement = other as RemoteWebElement;
if (otherAsElement == null)
{
return false;
}
if (this.elementId == otherAsElement.Id)
{
// For drivers that implement ID equality, we can check for equal IDs
// here, and expect them to be equal. There is a potential danger here
// where two different elements are assigned the same ID.
return true;
}
return false;
}
/// <summary>
/// Converts an object into an object that represents an element for the wire protocol.
/// </summary>
/// <returns>A <see cref="Dictionary{TKey, TValue}"/> that represents an element in the wire protocol.</returns>
Dictionary<string, object> IWebElementReference.ToDictionary()
{
Dictionary<string, object> elementDictionary = new Dictionary<string, object>();
elementDictionary.Add(ElementReferencePropertyName, this.elementId);
return elementDictionary;
}
/// <summary>
/// Finds a child element matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the element.</param>
/// <param name="value">The value to use to search for the element.</param>
/// <returns>The first <see cref="IWebElement"/> matching the given criteria.</returns>
protected virtual IWebElement FindElement(string mechanism, string value)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindChildElement, parameters);
return this.driver.GetElementFromResponse(commandResponse);
}
/// <summary>
/// Finds all child elements matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the elements.</param>
/// <param name="value">The value to use to search for the elements.</param>
/// <returns>A collection of all of the <see cref="IWebElement">IWebElements</see> matching the given criteria.</returns>
protected virtual ReadOnlyCollection<IWebElement> FindElements(string mechanism, string value) {
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindChildElements, parameters);
return this.driver.GetElementsFromResponse(commandResponse);
}
/// <summary>
/// Executes a command on this element using the specified parameters.
/// </summary>
/// <param name="commandToExecute">The <see cref="DriverCommand"/> to execute against this element.</param>
/// <param name="parameters">A <see cref="Dictionary{K, V}"/> containing names and values of the parameters for the command.</param>
/// <returns>The <see cref="Response"/> object containing the result of the command execution.</returns>
protected virtual Response Execute(string commandToExecute, Dictionary<string, object> parameters)
{
return this.driver.InternalExecute(commandToExecute, parameters);
}
private static string GetAtom(string atomResourceName)
{
string atom = string.Empty;
using (Stream atomStream = ResourceUtilities.GetResourceStream(atomResourceName, atomResourceName))
{
using (StreamReader atomReader = new StreamReader(atomStream))
{
atom = atomReader.ReadToEnd();
}
}
string wrappedAtom = string.Format(CultureInfo.InvariantCulture, "return ({0}).apply(null, arguments);", atom);
return wrappedAtom;
}
private string UploadFile(string localFile)
{
string base64zip = string.Empty;
try
{
using (MemoryStream fileUploadMemoryStream = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(fileUploadMemoryStream, ZipArchiveMode.Create))
{
string fileName = Path.GetFileName(localFile);
zipArchive.CreateEntryFromFile(localFile, fileName);
base64zip = Convert.ToBase64String(fileUploadMemoryStream.ToArray());
}
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("file", base64zip);
Response response = this.Execute(DriverCommand.UploadFile, parameters);
return response.Value.ToString();
}
catch (IOException e)
{
throw new WebDriverException("Cannot upload " + localFile, e);
}
}
private IWebElementReference ToElementReference()
{
return this as IWebElementReference;
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeFunction2))]
public sealed partial class CodeAccessorFunction : AbstractCodeElement, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2
{
internal static EnvDTE.CodeFunction Create(CodeModelState state, AbstractCodeMember parent, MethodKind kind)
{
var newElement = new CodeAccessorFunction(state, parent, kind);
return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(newElement);
}
private readonly ParentHandle<AbstractCodeMember> _parentHandle;
private readonly MethodKind _kind;
private CodeAccessorFunction(CodeModelState state, AbstractCodeMember parent, MethodKind kind)
: base(state, parent.FileCodeModel)
{
Debug.Assert(kind == MethodKind.EventAdd ||
kind == MethodKind.EventRaise ||
kind == MethodKind.EventRemove ||
kind == MethodKind.PropertyGet ||
kind == MethodKind.PropertySet);
_parentHandle = new ParentHandle<AbstractCodeMember>(parent);
_kind = kind;
}
private AbstractCodeMember ParentMember
{
get { return _parentHandle.Value; }
}
private bool IsPropertyAccessor()
{
return _kind == MethodKind.PropertyGet || _kind == MethodKind.PropertySet;
}
internal override bool TryLookupNode(out SyntaxNode node)
{
node = null;
var parentNode = _parentHandle.Value.LookupNode();
if (parentNode == null)
{
return false;
}
SyntaxNode accessorNode;
if (!CodeModelService.TryGetAccessorNode(parentNode, _kind, out accessorNode))
{
return false;
}
node = accessorNode;
return node != null;
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementFunction; }
}
public override object Parent
{
get { return _parentHandle.Value; }
}
public override EnvDTE.CodeElements Children
{
get { return EmptyCollection.Create(this.State, this); }
}
protected override string GetName()
{
return this.ParentMember.Name;
}
protected override void SetName(string value)
{
this.ParentMember.Name = value;
}
protected override string GetFullName()
{
return this.ParentMember.FullName;
}
public EnvDTE.CodeElements Attributes
{
get
{
return AttributeCollection.Create(this.State, this);
}
}
public EnvDTE.vsCMAccess Access
{
get
{
var node = LookupNode();
return CodeModelService.GetAccess(node);
}
set
{
UpdateNode(FileCodeModel.UpdateAccess, value);
}
}
public bool CanOverride
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
public string Comment
{
get
{
throw Exceptions.ThrowEFail();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public string DocComment
{
get
{
return string.Empty;
}
set
{
throw Exceptions.ThrowENotImpl();
}
}
public EnvDTE.vsCMFunction FunctionKind
{
get
{
var methodSymbol = LookupSymbol() as IMethodSymbol;
if (methodSymbol == null)
{
throw Exceptions.ThrowEUnexpected();
}
return CodeModelService.GetFunctionKind(methodSymbol);
}
}
public bool IsGeneric
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).IsGeneric;
}
else
{
return ((CodeEvent)this.ParentMember).IsGeneric;
}
}
}
public EnvDTE80.vsCMOverrideKind OverrideKind
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).OverrideKind;
}
else
{
return ((CodeEvent)this.ParentMember).OverrideKind;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).OverrideKind = value;
}
else
{
((CodeEvent)this.ParentMember).OverrideKind = value;
}
}
}
public bool IsOverloaded
{
get { return false; }
}
public bool IsShared
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).IsShared;
}
else
{
return ((CodeEvent)this.ParentMember).IsShared;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).IsShared = value;
}
else
{
((CodeEvent)this.ParentMember).IsShared = value;
}
}
}
public bool MustImplement
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).MustImplement;
}
else
{
return ((CodeEvent)this.ParentMember).MustImplement;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).MustImplement = value;
}
else
{
((CodeEvent)this.ParentMember).MustImplement = value;
}
}
}
public EnvDTE.CodeElements Overloads
{
get
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeElements Parameters
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).Parameters;
}
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeTypeRef Type
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).Type;
}
throw Exceptions.ThrowEFail();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
public EnvDTE.CodeParameter AddParameter(string name, object type, object position)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
public void RemoveParameter(object element)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
}
}
| |
/*=============================================================================
*
* (C) Copyright 2013, Michael Carlisle (mike.carlisle@thecodeking.co.uk)
*
* http://www.TheCodeKing.co.uk
*
* All rights reserved.
* The code and information is provided "as-is" without waranty of any kind,
* either expressed or implied.
*
*=============================================================================
*/
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using TheCodeKing.Utils.Contract;
using TheCodeKing.Utils.Serialization;
using XDMessaging.Messages;
namespace XDMessaging.Transport.WindowsMessaging
{
/// <summary>
/// The data struct that is passed between AppDomain boundaries for the Windows Messaging
/// implementation. This is sent as a delimited string containing the channel and message.
/// </summary>
internal class WinMsgDataGram : IDisposable
{
#region Constants and Fields
/// <summary>
/// The encapsulated basic DataGram instance.
/// </summary>
private readonly DataGram dataGram;
private readonly ISerializer serializer;
/// <summary>
/// Indicates whether this instance allocated the memory used by the dataStruct instance.
/// </summary>
private bool allocatedMemory;
/// <summary>
/// The native data struct used to pass the data between applications. This
/// contains a pointer to the data packet.
/// </summary>
private Native.COPYDATASTRUCT dataStruct;
#endregion
#region Constructors and Destructors
/// <summary>
/// Constructor which creates the data gram from a message and channel name.
/// </summary>
/// <param name = "serializer"></param>
/// <param name = "channel">The channel through which the message will be sent.</param>
/// <param name = "dataType">The type of the message used for deserialization hints.</param>
/// <param name = "message">The string message to send.</param>
internal WinMsgDataGram(ISerializer serializer, string channel, string dataType, string message)
{
Validate.That(serializer).IsNotNull();
this.serializer = serializer;
allocatedMemory = false;
dataStruct = new Native.COPYDATASTRUCT();
dataGram = new DataGram(channel, dataType, message);
}
/// <summary>
/// Constructor creates an instance of the class from a pointer address, and expands
/// the data packet into the originating channel name and message.
/// </summary>
/// <param name = "lpParam">A pointer the a COPYDATASTRUCT containing information required to
/// expand the DataGram.</param>
/// <param name = "serializer">Serializer to deserialize raw DataGram message.</param>
private WinMsgDataGram(IntPtr lpParam, ISerializer serializer)
{
Validate.That(serializer).IsNotNull();
this.serializer = serializer;
allocatedMemory = false;
dataStruct = (Native.COPYDATASTRUCT) Marshal.PtrToStructure(lpParam, typeof (Native.COPYDATASTRUCT));
var bytes = new byte[dataStruct.cbData];
Marshal.Copy(dataStruct.lpData, bytes, 0, dataStruct.cbData);
string rawmessage;
using (var stream = new MemoryStream(bytes))
{
var b = new BinaryFormatter();
rawmessage = (string) b.Deserialize(stream);
}
// use helper method to expand the raw message
dataGram = serializer.Deserialize<DataGram>(rawmessage);
}
#endregion
#region Properties
/// <summary>
/// Gets the channel name.
/// </summary>
public string Channel
{
get { return dataGram.Channel; }
}
/// <summary>
/// Gets the message.
/// </summary>
public string Message
{
get { return dataGram.Message; }
}
/// <summary>
/// Indicates whether the DataGram contains valid data.
/// </summary>
internal bool IsValid
{
get { return dataGram.IsValid; }
}
#endregion
#region Operators
/// <summary>
/// Allows implicit casting from WinMsgDataGram to DataGram.
/// </summary>
/// <param name = "dataGram"></param>
/// <returns></returns>
public static implicit operator DataGram(WinMsgDataGram dataGram)
{
return dataGram.dataGram;
}
#endregion
#region Public Methods
/// <summary>
/// Converts the instance to the string delimited format.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return dataGram.ToString();
}
#endregion
#region Implemented Interfaces
#region IDisposable
/// <summary>
/// Disposes of the unmanaged memory stored by the COPYDATASTRUCT instance
/// when data is passed between applications.
/// </summary>
public void Dispose()
{
// clean up unmanaged resources
if (dataStruct.lpData != IntPtr.Zero)
{
// only free memory if this instance created it (broadcast instance)
// don't free if we are just reading shared memory
if (allocatedMemory)
{
Marshal.FreeCoTaskMem(dataStruct.lpData);
}
dataStruct.lpData = IntPtr.Zero;
dataStruct.dwData = IntPtr.Zero;
dataStruct.cbData = 0;
}
}
#endregion
#endregion
#region Methods
/// <summary>
/// Creates an instance of a DataGram struct from a pointer to a COPYDATASTRUCT
/// object containing the address of the data.
/// </summary>
/// <param name = "lpParam">A pointer to a COPYDATASTRUCT object from which the DataGram data
/// can be derived.</param>
/// <param name = "serializer">A serializer used to deserialize the raw DataGram message.</param>
/// <returns>A DataGram instance containing a message, and the channel through which
/// it was sent.</returns>
internal static WinMsgDataGram FromPointer(IntPtr lpParam, ISerializer serializer)
{
return new WinMsgDataGram(lpParam, serializer);
}
/// <summary>
/// Pushes the DatGram's data into memory and returns a COPYDATASTRUCT instance with
/// a pointer to the data so it can be sent in a Windows Message and read by another application.
/// </summary>
/// <returns>A struct containing the pointer to this DataGram's data.</returns>
internal Native.COPYDATASTRUCT ToStruct()
{
string raw = serializer.Serialize(dataGram);
byte[] bytes;
// serialize data into stream
var b = new BinaryFormatter();
using (var stream = new MemoryStream())
{
b.Serialize(stream, raw);
stream.Flush();
var dataSize = (int) stream.Length;
// create byte array and get pointer to mem location
bytes = new byte[dataSize];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(bytes, 0, dataSize);
}
IntPtr ptrData = Marshal.AllocCoTaskMem(bytes.Length);
// flag that this instance dispose method needs to clean up the memory
allocatedMemory = true;
Marshal.Copy(bytes, 0, ptrData, bytes.Length);
dataStruct.cbData = bytes.Length;
dataStruct.dwData = IntPtr.Zero;
dataStruct.lpData = ptrData;
return dataStruct;
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// FlowResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Studio.V2
{
public class FlowResource : Resource
{
public sealed class StatusEnum : StringEnum
{
private StatusEnum(string value) : base(value) {}
public StatusEnum() {}
public static implicit operator StatusEnum(string value)
{
return new StatusEnum(value);
}
public static readonly StatusEnum Draft = new StatusEnum("draft");
public static readonly StatusEnum Published = new StatusEnum("published");
}
private static Request BuildCreateRequest(CreateFlowOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Studio,
"/v2/Flows",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a Flow.
/// </summary>
/// <param name="options"> Create Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static FlowResource Create(CreateFlowOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a Flow.
/// </summary>
/// <param name="options"> Create Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<FlowResource> CreateAsync(CreateFlowOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a Flow.
/// </summary>
/// <param name="friendlyName"> The string that you assigned to describe the Flow </param>
/// <param name="status"> The status of the Flow </param>
/// <param name="definition"> JSON representation of flow definition </param>
/// <param name="commitMessage"> Description of change made in the revision </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static FlowResource Create(string friendlyName,
FlowResource.StatusEnum status,
object definition,
string commitMessage = null,
ITwilioRestClient client = null)
{
var options = new CreateFlowOptions(friendlyName, status, definition){CommitMessage = commitMessage};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a Flow.
/// </summary>
/// <param name="friendlyName"> The string that you assigned to describe the Flow </param>
/// <param name="status"> The status of the Flow </param>
/// <param name="definition"> JSON representation of flow definition </param>
/// <param name="commitMessage"> Description of change made in the revision </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<FlowResource> CreateAsync(string friendlyName,
FlowResource.StatusEnum status,
object definition,
string commitMessage = null,
ITwilioRestClient client = null)
{
var options = new CreateFlowOptions(friendlyName, status, definition){CommitMessage = commitMessage};
return await CreateAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateFlowOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Update a Flow.
/// </summary>
/// <param name="options"> Update Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static FlowResource Update(UpdateFlowOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Update a Flow.
/// </summary>
/// <param name="options"> Update Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<FlowResource> UpdateAsync(UpdateFlowOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Update a Flow.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="status"> The status of the Flow </param>
/// <param name="friendlyName"> The string that you assigned to describe the Flow </param>
/// <param name="definition"> JSON representation of flow definition </param>
/// <param name="commitMessage"> Description of change made in the revision </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static FlowResource Update(string pathSid,
FlowResource.StatusEnum status,
string friendlyName = null,
object definition = null,
string commitMessage = null,
ITwilioRestClient client = null)
{
var options = new UpdateFlowOptions(pathSid, status){FriendlyName = friendlyName, Definition = definition, CommitMessage = commitMessage};
return Update(options, client);
}
#if !NET35
/// <summary>
/// Update a Flow.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="status"> The status of the Flow </param>
/// <param name="friendlyName"> The string that you assigned to describe the Flow </param>
/// <param name="definition"> JSON representation of flow definition </param>
/// <param name="commitMessage"> Description of change made in the revision </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<FlowResource> UpdateAsync(string pathSid,
FlowResource.StatusEnum status,
string friendlyName = null,
object definition = null,
string commitMessage = null,
ITwilioRestClient client = null)
{
var options = new UpdateFlowOptions(pathSid, status){FriendlyName = friendlyName, Definition = definition, CommitMessage = commitMessage};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadFlowOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Studio,
"/v2/Flows",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Flows.
/// </summary>
/// <param name="options"> Read Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static ResourceSet<FlowResource> Read(ReadFlowOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<FlowResource>.FromJson("flows", response.Content);
return new ResourceSet<FlowResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Flows.
/// </summary>
/// <param name="options"> Read Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<ResourceSet<FlowResource>> ReadAsync(ReadFlowOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<FlowResource>.FromJson("flows", response.Content);
return new ResourceSet<FlowResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Flows.
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static ResourceSet<FlowResource> Read(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadFlowOptions(){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Flows.
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<ResourceSet<FlowResource>> ReadAsync(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadFlowOptions(){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<FlowResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<FlowResource>.FromJson("flows", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<FlowResource> NextPage(Page<FlowResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Studio)
);
var response = client.Request(request);
return Page<FlowResource>.FromJson("flows", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<FlowResource> PreviousPage(Page<FlowResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Studio)
);
var response = client.Request(request);
return Page<FlowResource>.FromJson("flows", response.Content);
}
private static Request BuildFetchRequest(FetchFlowOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a specific Flow.
/// </summary>
/// <param name="options"> Fetch Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static FlowResource Fetch(FetchFlowOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Retrieve a specific Flow.
/// </summary>
/// <param name="options"> Fetch Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<FlowResource> FetchAsync(FetchFlowOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Retrieve a specific Flow.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static FlowResource Fetch(string pathSid, ITwilioRestClient client = null)
{
var options = new FetchFlowOptions(pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a specific Flow.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<FlowResource> FetchAsync(string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchFlowOptions(pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteFlowOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Delete a specific Flow.
/// </summary>
/// <param name="options"> Delete Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static bool Delete(DeleteFlowOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// Delete a specific Flow.
/// </summary>
/// <param name="options"> Delete Flow parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteFlowOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// Delete a specific Flow.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Flow </returns>
public static bool Delete(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteFlowOptions(pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// Delete a specific Flow.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Flow </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteFlowOptions(pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a FlowResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> FlowResource object represented by the provided JSON </returns>
public static FlowResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<FlowResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The string that you assigned to describe the Flow
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// JSON representation of flow definition
/// </summary>
[JsonProperty("definition")]
public object Definition { get; private set; }
/// <summary>
/// The status of the Flow
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public FlowResource.StatusEnum Status { get; private set; }
/// <summary>
/// The latest revision number of the Flow's definition
/// </summary>
[JsonProperty("revision")]
public int? Revision { get; private set; }
/// <summary>
/// Description of change made in the revision
/// </summary>
[JsonProperty("commit_message")]
public string CommitMessage { get; private set; }
/// <summary>
/// Boolean if the flow definition is valid
/// </summary>
[JsonProperty("valid")]
public bool? Valid { get; private set; }
/// <summary>
/// List of error in the flow definition
/// </summary>
[JsonProperty("errors")]
public List<object> Errors { get; private set; }
/// <summary>
/// List of warnings in the flow definition
/// </summary>
[JsonProperty("warnings")]
public List<object> Warnings { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The webhook_url
/// </summary>
[JsonProperty("webhook_url")]
public Uri WebhookUrl { get; private set; }
/// <summary>
/// The absolute URL of the resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// Nested resource URLs
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private FlowResource()
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.EventHub
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// EventHubsOperations operations.
/// </summary>
public partial interface IEventHubsOperations
{
/// <summary>
/// Gets all the Event Hubs in a Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Eventhub>>> ListByNamespaceWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a new Event Hub as a nested resource within a
/// Namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create an Event Hub resource.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Eventhub>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, Eventhub parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an Event Hub from the specified Namespace and resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets an Event Hubs description for the specified Event Hub.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<Eventhub>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the authorization rules for an Event Hub.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an AuthorizationRule for the specified Event
/// Hub.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorization rule name.
/// </param>
/// <param name='parameters'>
/// The shared access AuthorizationRule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, AuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets an AuthorizationRule for an Event Hub by rule name.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorization rule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an Event Hub AuthorizationRule.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorization rule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the ACS and SAS connection strings for the Event Hub.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorization rule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AccessKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Regenerates the ACS and SAS connection strings for the Event Hub.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group within the azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace name
/// </param>
/// <param name='eventHubName'>
/// The Event Hub name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorization rule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the AuthorizationRule Keys
/// (PrimaryKey/SecondaryKey).
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the Event Hubs in a Namespace.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<Eventhub>>> ListByNamespaceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the authorization rules for an Event Hub.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using System.Linq;
namespace FluentValidation.Tests
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
public class CollectionValidatorWithParentTests
{
Person person;
public CollectionValidatorWithParentTests()
{
person = new Person()
{
AnotherInt = 99,
Children = new List<Person>()
{
new Person() { Email = "person@email.com"}
},
Orders = new List<Order>()
{
new Order { ProductName = "email_that_does_not_belong_to_a_person", Amount = 99},
new Order { ProductName = "person@email.com", Amount = 1},
new Order { ProductName = "another_email_that_does_not_belong_to_a_person", Amount = 1},
}
};
}
[Fact]
public void Validates_collection()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
var results = validator.Validate(person);
results.Errors.Count.ShouldEqual(3);
results.Errors[1].PropertyName.ShouldEqual("Orders[0].ProductName");
results.Errors[2].PropertyName.ShouldEqual("Orders[2].ProductName");
}
[Fact]
public void Validates_collection_asynchronously()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new AsyncOrderValidator(y))
};
var results = validator.ValidateAsync(person).Result;
results.Errors.Count.ShouldEqual(3);
results.Errors[1].PropertyName.ShouldEqual("Orders[0].ProductName");
results.Errors[2].PropertyName.ShouldEqual("Orders[2].ProductName");
}
[Fact]
public void Collection_should_be_explicitly_included_with_expression()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
var results = validator.Validate(person, x => x.Orders);
results.Errors.Count.ShouldEqual(2);
}
[Fact]
public void Collection_should_be_explicitly_included_with_string()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
var results = validator.Validate(person, "Orders");
results.Errors.Count.ShouldEqual(2);
}
[Fact]
public void Collection_should_be_excluded()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
var results = validator.Validate(person, x => x.Forename);
results.Errors.Count.ShouldEqual(0);
}
[Fact]
public void Condition_should_work_with_child_collection()
{
var validator = new TestValidator() {
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)).When(x => x.Orders.Count == 4 /*there are only 3*/)
};
var result = validator.Validate(person);
result.IsValid.ShouldBeTrue();
}
[Fact]
public void Async_condition_should_work_with_child_collection() {
var validator = new TestValidator() {
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)).WhenAsync(x => TaskHelpers.FromResult(x.Orders.Count == 4 /*there are only 3*/))
};
var result = validator.ValidateAsync(person).Result;
result.IsValid.ShouldBeTrue();
}
[Fact]
public void Skips_null_items()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
person.Orders[0] = null;
var results = validator.Validate(person);
results.Errors.Count.ShouldEqual(2); //2 errors - 1 for person, 1 for 3rd Order.
}
[Fact]
public void Can_validate_collection_using_validator_for_base_type()
{
var validator = new TestValidator() {
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderInterfaceValidator(y))
};
var result = validator.Validate(person);
result.IsValid.ShouldBeFalse();
}
[Fact]
public void Can_specifiy_condition_for_individual_collection_elements()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Orders)
.SetCollectionValidator(y => new OrderValidator(y))
.Where(x => x.Amount != 1)
};
var results = validator.Validate(person);
results.Errors.Count.ShouldEqual(1);
}
[Fact]
public void Should_override_property_name()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
.OverridePropertyName("Orders2")
};
var results = validator.Validate(person);
results.Errors[0].PropertyName.ShouldEqual("Orders2[0].ProductName");
}
public class OrderValidator : AbstractValidator<Order>
{
public OrderValidator(Person person)
{
RuleFor(x => x.ProductName).Must(BeOneOfTheChildrensEmailAddress(person));
}
private Func<string, bool> BeOneOfTheChildrensEmailAddress(Person person)
{
return productName => person.Children.Any(child => child.Email == productName);
}
}
public class OrderInterfaceValidator : AbstractValidator<IOrder>
{
public OrderInterfaceValidator(Person person)
{
RuleFor(x => x.Amount).NotEqual(person.AnotherInt);
}
}
public class AsyncOrderValidator : AbstractValidator<Order>
{
public AsyncOrderValidator(Person person)
{
RuleFor(x => x.ProductName).MustAsync(BeOneOfTheChildrensEmailAddress(person));
}
private Func<string, CancellationToken, Task<bool>> BeOneOfTheChildrensEmailAddress(Person person)
{
return (productName, cancel) => TaskHelpers.FromResult(person.Children.Any(child => child.Email == productName));
}
}
}
}
| |
//
// DrawingPath.cs
//
// Author:
// Alex Corrado <corrado@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
namespace Xwt.Drawing
{
public class DrawingPath: XwtObject, IDisposable
{
DrawingPathBackendHandler handler;
public DrawingPath ()
{
handler = Toolkit.CurrentEngine.VectorImageRecorderContextHandler;
Backend = handler.CreatePath ();
Init ();
}
internal DrawingPath (object backend, Toolkit toolkit, DrawingPathBackendHandler h): base (backend, toolkit)
{
handler = h;
Init ();
}
void Init ()
{
if (handler.DisposeHandleOnUiThread)
ResourceManager.RegisterResource (Backend, handler.Dispose);
else
GC.SuppressFinalize (this);
}
public void Dispose ()
{
if (handler.DisposeHandleOnUiThread) {
GC.SuppressFinalize (this);
ResourceManager.FreeResource (Backend);
}
else
handler.Dispose (Backend);
}
~DrawingPath ()
{
ResourceManager.FreeResource (Backend);
}
/// <summary>
/// Copies the current drawing path.
/// </summary>
/// <returns>A new DrawingPath instance that is a copy of the current drawing path.</returns>
public DrawingPath CopyPath ()
{
return new DrawingPath (handler.CopyPath (Backend), ToolkitEngine, handler);
}
/// <summary>
/// Adds a circular arc of the given radius to the current path.
/// The arc is centered at (xc, yc),
/// begins at angle1 and proceeds in the direction
/// of increasing angles to end at angle2.
/// If angle2 is less than angle1,
/// it will be progressively increased by 1 degree until it is greater than angle1.
/// If there is a current point, an initial line segment will be added to the path
/// to connect the current point to the beginning of the arc.
/// If this initial line is undesired,
/// it can be avoided by calling NewPath() before calling Arc().
/// </summary>
/// <param name='xc'>
/// Xc.
/// </param>
/// <param name='yc'>
/// Yc.
/// </param>
/// <param name='radius'>
/// Radius.
/// </param>
/// <param name='angle1'>
/// Angle1 in degrees
/// </param>
/// <param name='angle2'>
/// Angle2 in degrees
/// </param>
public void Arc (double xc, double yc, double radius, double angle1, double angle2)
{
if (radius < 0)
throw new ArgumentException ("Radius must be greater than zero");
handler.Arc (Backend, xc, yc, radius, angle1, angle2);
}
/// <summary>
/// Adds a circular arc of the given radius to the current path.
/// The arc is centered at (xc, yc),
/// begins at angle1 and proceeds in the direction
/// of decreasing angles to end at angle2.
/// If angle2 is greater than angle1 it will be progressively decreased
/// by 1 degree until it is less than angle1.
/// If there is a current point, an initial line segment will be added to the path
/// to connect the current point to the beginning of the arc.
/// If this initial line is undesired,
/// it can be avoided by calling NewPath() before calling ArcNegative().
/// </summary>
/// <param name='xc'>
/// Xc.
/// </param>
/// <param name='yc'>
/// Yc.
/// </param>
/// <param name='radius'>
/// Radius.
/// </param>
/// <param name='angle1'>
/// Angle1 in degrees
/// </param>
/// <param name='angle2'>
/// Angle2 in degrees
/// </param>
public void ArcNegative (double xc, double yc, double radius, double angle1, double angle2)
{
handler.ArcNegative (Backend, xc, yc, radius, angle1, angle2);
}
public void ClosePath ()
{
handler.ClosePath (Backend);
}
public void CurveTo (Point p1, Point p2, Point p3)
{
CurveTo (p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y);
}
/// <summary>
/// Adds a cubic Bezier spline to the path from the current point to position (x3, y3) in user-space coordinates,
/// using (x1, y1) and (x2, y2) as the control points.
/// </summary>
/// <param name='x1'>
/// X1.
/// </param>
/// <param name='y1'>
/// Y1.
/// </param>
/// <param name='x2'>
/// X2.
/// </param>
/// <param name='y2'>
/// Y2.
/// </param>
/// <param name='x3'>
/// X3.
/// </param>
/// <param name='y3'>
/// Y3.
/// </param>
public void CurveTo (double x1, double y1, double x2, double y2, double x3, double y3)
{
handler.CurveTo (Backend, x1, y1, x2, y2, x3, y3);
}
public void LineTo (Point p)
{
LineTo (p.X, p.Y);
}
public void LineTo (double x, double y)
{
handler.LineTo (Backend, x, y);
}
public void MoveTo (Point p)
{
MoveTo (p.X, p.Y);
}
/// <summary>
/// If the current subpath is not empty, begin a new subpath.
/// After this call the current point will be (x, y).
/// </summary>
/// <param name='x'>
/// X.
/// </param>
/// <param name='y'>
/// Y.
/// </param>
public void MoveTo (double x, double y)
{
handler.MoveTo (Backend, x, y);
}
public void Rectangle (Rectangle rectangle)
{
Rectangle (rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
}
public void Rectangle (Point p, double width, double height)
{
Rectangle (p.X, p.Y, width, height);
}
public void Rectangle (double x, double y, double width, double height)
{
handler.Rectangle (Backend, x, y, width, height);
}
public void RoundRectangle (Rectangle rectangle, double radius)
{
RoundRectangle (rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, radius);
}
public void RoundRectangle (Point p, double width, double height, double radius)
{
RoundRectangle (p.X, p.Y, width, height, radius);
}
public void RoundRectangle (double x, double y, double width, double height, double radius)
{
if (radius > width - radius)
radius = width / 2;
if (radius > height - radius)
radius = height / 2;
// top-left corner
MoveTo (x + radius, y);
// top edge
LineTo (x + width - radius, y);
// top-right corner
if (radius > 0)
Arc (x + width - radius, y + radius, radius, -90, 0);
// right edge
LineTo (x + width, y + height - radius);
// bottom-right corner
if (radius > 0)
Arc (x + width - radius, y + height - radius, radius, 0, 90);
// bottom edge
LineTo (x + radius, y + height);
// bottom-left corner
if (radius > 0)
Arc (x + radius, y + height - radius, radius, 90, 180);
// left edge
LineTo (x, y + radius);
// top-left corner
if (radius > 0)
Arc (x + radius, y + radius, radius, 180, 270);
}
public void RelCurveTo (Distance d1, Distance d2, Distance d3)
{
RelCurveTo (d1.Dx, d1.Dy, d2.Dx, d2.Dy, d3.Dx, d3.Dy);
}
/// <summary>
/// Relative-coordinate version of curve_to().
/// All offsets are relative to the current point.
/// Adds a cubic Bezier spline to the path from the current point to a point offset
/// from the current point by (dx3, dy3), using points offset by (dx1, dy1) and (dx2, dy2)
/// as the control points. After this call the current point will be offset by (dx3, dy3).
/// Given a current point of (x, y), RelCurveTo(dx1, dy1, dx2, dy2, dx3, dy3)
/// is logically equivalent to CurveTo(x + dx1, y + dy1, x + dx2, y + dy2, x + dx3, y + dy3).
/// </summary>
/// <param name='dx1'>
/// Dx1.
/// </param>
/// <param name='dy1'>
/// Dy1.
/// </param>
/// <param name='dx2'>
/// Dx2.
/// </param>
/// <param name='dy2'>
/// Dy2.
/// </param>
/// <param name='dx3'>
/// Dx3.
/// </param>
/// <param name='dy3'>
/// Dy3.
/// </param>
public void RelCurveTo (double dx1, double dy1, double dx2, double dy2, double dx3, double dy3)
{
handler.RelCurveTo (Backend, dx1, dy1, dx2, dy2, dx3, dy3);
}
public void RelLineTo (Distance d)
{
RelLineTo (d.Dx, d.Dy);
}
/// <summary>
/// Adds a line to the path from the current point to a point that
/// is offset from the current point by (dx, dy) in user space.
/// After this call the current point will be offset by (dx, dy).
/// Given a current point of (x, y),
/// RelLineTo(dx, dy) is logically equivalent to LineTo(x + dx, y + dy).
/// </summary>
/// <param name='dx'>
/// Dx.
/// </param>
/// <param name='dy'>
/// Dy.
/// </param>
public void RelLineTo (double dx, double dy)
{
handler.RelLineTo (Backend, dx, dy);
}
/// <summary>
/// If the current subpath is not empty, begin a new subpath.
/// After this call the current point will offset by (x, y).
/// Given a current point of (x, y),
/// RelMoveTo(dx, dy) is logically equivalent to MoveTo(x + dx, y + dy).
/// </summary>
/// <param name='d'>
/// D.
/// </param>
public void RelMoveTo (Distance d)
{
RelMoveTo (d.Dx, d.Dy);
}
public void RelMoveTo (double dx, double dy)
{
handler.RelMoveTo (Backend, dx, dy);
}
/// <summary>
/// Appends the given path onto the current path.
/// </summary>
/// <param name='p'>
/// The path to append.
/// </param>
public void AppendPath (DrawingPath p)
{
if (p is Context)
throw new NotSupportedException ("Can't directly append a Context object to a path");
if (!(handler is VectorImageRecorderContextHandler) && (p.Backend is VectorBackend)) {
var c = (VectorBackend)p.Backend;
ToolkitEngine.VectorImageRecorderContextHandler.Draw (handler, Backend, c.ToVectorImageData ());
} else {
handler.AppendPath (Backend, p.Backend);
}
}
public bool IsPointInFill (Point p)
{
return IsPointInFill (p.X, p.Y);
}
/// <summary>
/// Tests whether the given point is inside the area that would be affected if the current path were filled.
/// </summary>
/// <returns>
/// <c>true</c> if the specified point would be in the fill; otherwise, <c>false</c>.
/// </returns>
/// <param name='x'>
/// The x coordinate.
/// </param>
/// <param name='y'>
/// The y coordinate.
/// </param>
public bool IsPointInFill (double x, double y)
{
return handler.IsPointInFill (Backend, x, y);
}
}
}
| |
using System;
using Rothko.UI.Model;
using Rothko.UI.Authoring.Interfaces.Services;
using Rothko.UI.Authoring.Interfaces.Views;
using System.Collections.Generic;
using Rothko.Model;
namespace Rothko.UI.Authoring.Presenters
{
public class EditAnimationPresenter
{
readonly IEditAnimationService _Service;
readonly IEditAnimationView _View;
AnimationFrame animationFrame = null;
public Animation Animation { get; set; }
public AnimationFrame AnimationFrame
{
get
{
return animationFrame;
}
set
{
animationFrame = value;
if (animationFrame != null)
_View.SetDuration(animationFrame.Duration);
}
}
public Asset Asset { get; set; }
public string AnimationName
{
get
{
return Animation.AnimationName;
}
set
{
Animation.AnimationName = value;
}
}
public List<AnimationFrame> Frames
{
get
{
return Animation.Frames;
}
set
{
Animation.Frames = value;
}
}
int _Duration;
public EditAnimationPresenter (
IEditAnimationService service,
IEditAnimationView view,
Animation originalAnimation)
{
_Service = service;
_View = view;
_Service.OnAssetsUpdated += (sender, e) => _View.FillList (_Service.GetAssets());
Animation = _Service.GetAnimationCopy(originalAnimation);
if (Animation.Frames == null)
Animation.Frames = new List<AnimationFrame>();
_View.SetAnimationName(Animation.AnimationName);
_View.FillList(_Service.GetAssets());
_View.FillList(Animation.Frames);
}
public void SetDuration(int duration)
{
_Duration = duration;
if (AnimationFrame != null)
AnimationFrame.Duration = duration;
}
AnimationFrame GetNewAnimationFrame()
{
return new AnimationFrame ()
{
IDAsset = Asset.ID,
Duration = _Duration
};
}
public void AddAssetBefore ()
{
if (Asset == null)
return;
if (AnimationFrame == null)
{
List<AnimationFrame> lstAnimationFrames = new List<AnimationFrame> (Animation.Frames);
Animation.Frames.Clear ();
Animation.Frames.Add (GetNewAnimationFrame ());
Animation.Frames.AddRange (lstAnimationFrames);
}
else
{
int animationFrameIndex = Animation.Frames.IndexOf(AnimationFrame);
List<AnimationFrame> lstAnimationFrames = Animation
.Frames.GetRange(animationFrameIndex, Animation.Frames.Count - animationFrameIndex);
Animation.Frames.RemoveRange(animationFrameIndex, Animation.Frames.Count - animationFrameIndex);
Animation.Frames.Add (GetNewAnimationFrame());
Animation.Frames.AddRange (lstAnimationFrames);
}
_View.FillList(Frames);
}
public void AddAssetAfter ()
{
if (Asset == null)
return;
if (AnimationFrame == null)
Animation.Frames.Add (GetNewAnimationFrame());
else
{
int animationFrameIndex = Animation.Frames.IndexOf(AnimationFrame);
List<AnimationFrame> lstAnimationFrames = Animation
.Frames.GetRange(animationFrameIndex + 1, Animation.Frames.Count - animationFrameIndex - 1);
Animation.Frames.RemoveRange(animationFrameIndex + 1, Animation.Frames.Count - animationFrameIndex - 1);
Animation.Frames.Add (GetNewAnimationFrame());
Animation.Frames.AddRange (lstAnimationFrames);
}
_View.FillList(Frames);
}
public void PushFrameDown()
{
if (AnimationFrame == null)
return;
int animationFrameIndex = Animation.Frames.IndexOf(AnimationFrame);
if (animationFrameIndex == Animation.Frames.Count - 1)
return;
Animation.Frames.Remove (AnimationFrame);
List<AnimationFrame> lstAnimationFrames = Animation
.Frames.GetRange(0, animationFrameIndex + 1);
Animation.Frames.RemoveRange(0, animationFrameIndex + 1);
List<AnimationFrame> lstAnimationFramesRest = new List<AnimationFrame>(Animation.Frames);
Animation.Frames.Clear();
Animation.Frames.AddRange (lstAnimationFrames);
Animation.Frames.Add (AnimationFrame);
Animation.Frames.AddRange (lstAnimationFramesRest);
_View.FillList(Frames);
}
public void PushFrameUp()
{
if (AnimationFrame == null)
return;
int animationFrameIndex = Animation.Frames.IndexOf(AnimationFrame);
if (animationFrameIndex == 0)
return;
Animation.Frames.Remove (AnimationFrame);
List<AnimationFrame> lstAnimationFrames = Animation
.Frames.GetRange(animationFrameIndex - 1, Animation.Frames.Count - animationFrameIndex + 1);
Animation.Frames.RemoveRange(animationFrameIndex - 1, Animation.Frames.Count - animationFrameIndex + 1);
Animation.Frames.Add (AnimationFrame);
Animation.Frames.AddRange (lstAnimationFrames);
_View.FillList(Frames);
}
public void RemoveFrame ()
{
if (AnimationFrame == null)
return;
_View.StopAnimation();
Animation.Frames.Remove(AnimationFrame);
AnimationFrame = null;
_View.FillList(Frames);
}
public ValidationResult Validate()
{
return _Service.Validate(Animation);
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Apache.Cordova {
// Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']"
[global::Android.Runtime.Register ("org/apache/cordova/PluginManager", DoNotGenerateAcw=true)]
public partial class PluginManager : global::Java.Lang.Object {
static IntPtr urlMap_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/field[@name='urlMap']"
[Register ("urlMap")]
protected global::System.Collections.IDictionary UrlMap {
get {
if (urlMap_jfieldId == IntPtr.Zero)
urlMap_jfieldId = JNIEnv.GetFieldID (class_ref, "urlMap", "Ljava/util/HashMap;");
IntPtr __ret = JNIEnv.GetObjectField (Handle, urlMap_jfieldId);
return global::Android.Runtime.JavaDictionary.FromJniHandle (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (urlMap_jfieldId == IntPtr.Zero)
urlMap_jfieldId = JNIEnv.GetFieldID (class_ref, "urlMap", "Ljava/util/HashMap;");
IntPtr native_value = global::Android.Runtime.JavaDictionary.ToLocalJniHandle (value);
JNIEnv.SetField (Handle, urlMap_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/apache/cordova/PluginManager", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (PluginManager); }
}
protected PluginManager (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static Delegate cb_addService_Ljava_lang_String_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetAddService_Ljava_lang_String_Ljava_lang_String_Handler ()
{
if (cb_addService_Ljava_lang_String_Ljava_lang_String_ == null)
cb_addService_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_AddService_Ljava_lang_String_Ljava_lang_String_);
return cb_addService_Ljava_lang_String_Ljava_lang_String_;
}
static void n_AddService_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer);
__this.AddService (p0, p1);
}
#pragma warning restore 0169
static IntPtr id_addService_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='addService' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String']]"
[Register ("addService", "(Ljava/lang/String;Ljava/lang/String;)V", "GetAddService_Ljava_lang_String_Ljava_lang_String_Handler")]
public virtual void AddService (string p0, string p1)
{
if (id_addService_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_addService_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "addService", "(Ljava/lang/String;Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_addService_Ljava_lang_String_Ljava_lang_String_, new JValue (native_p0), new JValue (native_p1));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "addService", "(Ljava/lang/String;Ljava/lang/String;)V"), new JValue (native_p0), new JValue (native_p1));
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
}
static Delegate cb_addService_Lorg_apache_cordova_PluginEntry_;
#pragma warning disable 0169
static Delegate GetAddService_Lorg_apache_cordova_PluginEntry_Handler ()
{
if (cb_addService_Lorg_apache_cordova_PluginEntry_ == null)
cb_addService_Lorg_apache_cordova_PluginEntry_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_AddService_Lorg_apache_cordova_PluginEntry_);
return cb_addService_Lorg_apache_cordova_PluginEntry_;
}
static void n_AddService_Lorg_apache_cordova_PluginEntry_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Apache.Cordova.PluginEntry p0 = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginEntry> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.AddService (p0);
}
#pragma warning restore 0169
static IntPtr id_addService_Lorg_apache_cordova_PluginEntry_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='addService' and count(parameter)=1 and parameter[1][@type='org.apache.cordova.PluginEntry']]"
[Register ("addService", "(Lorg/apache/cordova/PluginEntry;)V", "GetAddService_Lorg_apache_cordova_PluginEntry_Handler")]
public virtual void AddService (global::Org.Apache.Cordova.PluginEntry p0)
{
if (id_addService_Lorg_apache_cordova_PluginEntry_ == IntPtr.Zero)
id_addService_Lorg_apache_cordova_PluginEntry_ = JNIEnv.GetMethodID (class_ref, "addService", "(Lorg/apache/cordova/PluginEntry;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_addService_Lorg_apache_cordova_PluginEntry_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "addService", "(Lorg/apache/cordova/PluginEntry;)V"), new JValue (p0));
}
static Delegate cb_clearPluginObjects;
#pragma warning disable 0169
static Delegate GetClearPluginObjectsHandler ()
{
if (cb_clearPluginObjects == null)
cb_clearPluginObjects = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_ClearPluginObjects);
return cb_clearPluginObjects;
}
static void n_ClearPluginObjects (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.ClearPluginObjects ();
}
#pragma warning restore 0169
static IntPtr id_clearPluginObjects;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='clearPluginObjects' and count(parameter)=0]"
[Register ("clearPluginObjects", "()V", "GetClearPluginObjectsHandler")]
public virtual void ClearPluginObjects ()
{
if (id_clearPluginObjects == IntPtr.Zero)
id_clearPluginObjects = JNIEnv.GetMethodID (class_ref, "clearPluginObjects", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_clearPluginObjects);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "clearPluginObjects", "()V"));
}
static Delegate cb_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetExec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Handler ()
{
if (cb_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == null)
cb_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_Exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_);
return cb_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
}
static void n_Exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2, IntPtr native_p3)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer);
string p2 = JNIEnv.GetString (native_p2, JniHandleOwnership.DoNotTransfer);
string p3 = JNIEnv.GetString (native_p3, JniHandleOwnership.DoNotTransfer);
__this.Exec (p0, p1, p2, p3);
}
#pragma warning restore 0169
static IntPtr id_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='exec' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='java.lang.String']]"
[Register ("exec", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "GetExec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Handler")]
public virtual void Exec (string p0, string p1, string p2, string p3)
{
if (id_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "exec", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
IntPtr native_p2 = JNIEnv.NewString (p2);
IntPtr native_p3 = JNIEnv.NewString (p3);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_, new JValue (native_p0), new JValue (native_p1), new JValue (native_p2), new JValue (native_p3));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "exec", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"), new JValue (native_p0), new JValue (native_p1), new JValue (native_p2), new JValue (native_p3));
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
JNIEnv.DeleteLocalRef (native_p2);
JNIEnv.DeleteLocalRef (native_p3);
}
static Delegate cb_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z;
#pragma warning disable 0169
static Delegate GetExec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ZHandler ()
{
if (cb_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z == null)
cb_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, bool>) n_Exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z);
return cb_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z;
}
static void n_Exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2, IntPtr native_p3, bool p4)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer);
string p2 = JNIEnv.GetString (native_p2, JniHandleOwnership.DoNotTransfer);
string p3 = JNIEnv.GetString (native_p3, JniHandleOwnership.DoNotTransfer);
__this.Exec (p0, p1, p2, p3, p4);
}
#pragma warning restore 0169
static IntPtr id_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='exec' and count(parameter)=5 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='java.lang.String'] and parameter[5][@type='boolean']]"
[Register ("exec", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V", "GetExec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_ZHandler")]
public virtual void Exec (string p0, string p1, string p2, string p3, bool p4)
{
if (id_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z == IntPtr.Zero)
id_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z = JNIEnv.GetMethodID (class_ref, "exec", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
IntPtr native_p2 = JNIEnv.NewString (p2);
IntPtr native_p3 = JNIEnv.NewString (p3);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_exec_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Ljava_lang_String_Z, new JValue (native_p0), new JValue (native_p1), new JValue (native_p2), new JValue (native_p3), new JValue (p4));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "exec", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V"), new JValue (native_p0), new JValue (native_p1), new JValue (native_p2), new JValue (native_p3), new JValue (p4));
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
JNIEnv.DeleteLocalRef (native_p2);
JNIEnv.DeleteLocalRef (native_p3);
}
static Delegate cb_getPlugin_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetGetPlugin_Ljava_lang_String_Handler ()
{
if (cb_getPlugin_Ljava_lang_String_ == null)
cb_getPlugin_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_GetPlugin_Ljava_lang_String_);
return cb_getPlugin_Ljava_lang_String_;
}
static IntPtr n_GetPlugin_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.GetPlugin (p0));
return __ret;
}
#pragma warning restore 0169
static IntPtr id_getPlugin_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='getPlugin' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("getPlugin", "(Ljava/lang/String;)Lorg/apache/cordova/CordovaPlugin;", "GetGetPlugin_Ljava_lang_String_Handler")]
public virtual global::Org.Apache.Cordova.CordovaPlugin GetPlugin (string p0)
{
if (id_getPlugin_Ljava_lang_String_ == IntPtr.Zero)
id_getPlugin_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "getPlugin", "(Ljava/lang/String;)Lorg/apache/cordova/CordovaPlugin;");
IntPtr native_p0 = JNIEnv.NewString (p0);
global::Org.Apache.Cordova.CordovaPlugin __ret;
if (GetType () == ThresholdType)
__ret = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaPlugin> (JNIEnv.CallObjectMethod (Handle, id_getPlugin_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef);
else
__ret = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaPlugin> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getPlugin", "(Ljava/lang/String;)Lorg/apache/cordova/CordovaPlugin;"), new JValue (native_p0)), JniHandleOwnership.TransferLocalRef);
JNIEnv.DeleteLocalRef (native_p0);
return __ret;
}
static Delegate cb_init;
#pragma warning disable 0169
static Delegate GetInitHandler ()
{
if (cb_init == null)
cb_init = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Init);
return cb_init;
}
static void n_Init (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Init ();
}
#pragma warning restore 0169
static IntPtr id_init;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='init' and count(parameter)=0]"
[Register ("init", "()V", "GetInitHandler")]
public virtual void Init ()
{
if (id_init == IntPtr.Zero)
id_init = JNIEnv.GetMethodID (class_ref, "init", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_init);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "init", "()V"));
}
static Delegate cb_loadPlugins;
#pragma warning disable 0169
static Delegate GetLoadPluginsHandler ()
{
if (cb_loadPlugins == null)
cb_loadPlugins = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_LoadPlugins);
return cb_loadPlugins;
}
static void n_LoadPlugins (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.LoadPlugins ();
}
#pragma warning restore 0169
static IntPtr id_loadPlugins;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='loadPlugins' and count(parameter)=0]"
[Register ("loadPlugins", "()V", "GetLoadPluginsHandler")]
public virtual void LoadPlugins ()
{
if (id_loadPlugins == IntPtr.Zero)
id_loadPlugins = JNIEnv.GetMethodID (class_ref, "loadPlugins", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_loadPlugins);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "loadPlugins", "()V"));
}
static Delegate cb_onDestroy;
#pragma warning disable 0169
static Delegate GetOnDestroyHandler ()
{
if (cb_onDestroy == null)
cb_onDestroy = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_OnDestroy);
return cb_onDestroy;
}
static void n_OnDestroy (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnDestroy ();
}
#pragma warning restore 0169
static IntPtr id_onDestroy;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='onDestroy' and count(parameter)=0]"
[Register ("onDestroy", "()V", "GetOnDestroyHandler")]
public virtual void OnDestroy ()
{
if (id_onDestroy == IntPtr.Zero)
id_onDestroy = JNIEnv.GetMethodID (class_ref, "onDestroy", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onDestroy);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onDestroy", "()V"));
}
static Delegate cb_onNewIntent_Landroid_content_Intent_;
#pragma warning disable 0169
static Delegate GetOnNewIntent_Landroid_content_Intent_Handler ()
{
if (cb_onNewIntent_Landroid_content_Intent_ == null)
cb_onNewIntent_Landroid_content_Intent_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnNewIntent_Landroid_content_Intent_);
return cb_onNewIntent_Landroid_content_Intent_;
}
static void n_OnNewIntent_Landroid_content_Intent_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Android.Content.Intent p0 = global::Java.Lang.Object.GetObject<global::Android.Content.Intent> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.OnNewIntent (p0);
}
#pragma warning restore 0169
static IntPtr id_onNewIntent_Landroid_content_Intent_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='onNewIntent' and count(parameter)=1 and parameter[1][@type='android.content.Intent']]"
[Register ("onNewIntent", "(Landroid/content/Intent;)V", "GetOnNewIntent_Landroid_content_Intent_Handler")]
public virtual void OnNewIntent (global::Android.Content.Intent p0)
{
if (id_onNewIntent_Landroid_content_Intent_ == IntPtr.Zero)
id_onNewIntent_Landroid_content_Intent_ = JNIEnv.GetMethodID (class_ref, "onNewIntent", "(Landroid/content/Intent;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onNewIntent_Landroid_content_Intent_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onNewIntent", "(Landroid/content/Intent;)V"), new JValue (p0));
}
static Delegate cb_onOverrideUrlLoading_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetOnOverrideUrlLoading_Ljava_lang_String_Handler ()
{
if (cb_onOverrideUrlLoading_Ljava_lang_String_ == null)
cb_onOverrideUrlLoading_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_OnOverrideUrlLoading_Ljava_lang_String_);
return cb_onOverrideUrlLoading_Ljava_lang_String_;
}
static bool n_OnOverrideUrlLoading_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.OnOverrideUrlLoading (p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_onOverrideUrlLoading_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='onOverrideUrlLoading' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("onOverrideUrlLoading", "(Ljava/lang/String;)Z", "GetOnOverrideUrlLoading_Ljava_lang_String_Handler")]
public virtual bool OnOverrideUrlLoading (string p0)
{
if (id_onOverrideUrlLoading_Ljava_lang_String_ == IntPtr.Zero)
id_onOverrideUrlLoading_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "onOverrideUrlLoading", "(Ljava/lang/String;)Z");
IntPtr native_p0 = JNIEnv.NewString (p0);
bool __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.CallBooleanMethod (Handle, id_onOverrideUrlLoading_Ljava_lang_String_, new JValue (native_p0));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onOverrideUrlLoading", "(Ljava/lang/String;)Z"), new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
return __ret;
}
static Delegate cb_onPause_Z;
#pragma warning disable 0169
static Delegate GetOnPause_ZHandler ()
{
if (cb_onPause_Z == null)
cb_onPause_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_OnPause_Z);
return cb_onPause_Z;
}
static void n_OnPause_Z (IntPtr jnienv, IntPtr native__this, bool p0)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnPause (p0);
}
#pragma warning restore 0169
static IntPtr id_onPause_Z;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='onPause' and count(parameter)=1 and parameter[1][@type='boolean']]"
[Register ("onPause", "(Z)V", "GetOnPause_ZHandler")]
public virtual void OnPause (bool p0)
{
if (id_onPause_Z == IntPtr.Zero)
id_onPause_Z = JNIEnv.GetMethodID (class_ref, "onPause", "(Z)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onPause_Z, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onPause", "(Z)V"), new JValue (p0));
}
static Delegate cb_onReset;
#pragma warning disable 0169
static Delegate GetOnResetHandler ()
{
if (cb_onReset == null)
cb_onReset = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_OnReset);
return cb_onReset;
}
static void n_OnReset (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnReset ();
}
#pragma warning restore 0169
static IntPtr id_onReset;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='onReset' and count(parameter)=0]"
[Register ("onReset", "()V", "GetOnResetHandler")]
public virtual void OnReset ()
{
if (id_onReset == IntPtr.Zero)
id_onReset = JNIEnv.GetMethodID (class_ref, "onReset", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onReset);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onReset", "()V"));
}
static Delegate cb_onResume_Z;
#pragma warning disable 0169
static Delegate GetOnResume_ZHandler ()
{
if (cb_onResume_Z == null)
cb_onResume_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_OnResume_Z);
return cb_onResume_Z;
}
static void n_OnResume_Z (IntPtr jnienv, IntPtr native__this, bool p0)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnResume (p0);
}
#pragma warning restore 0169
static IntPtr id_onResume_Z;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='onResume' and count(parameter)=1 and parameter[1][@type='boolean']]"
[Register ("onResume", "(Z)V", "GetOnResume_ZHandler")]
public virtual void OnResume (bool p0)
{
if (id_onResume_Z == IntPtr.Zero)
id_onResume_Z = JNIEnv.GetMethodID (class_ref, "onResume", "(Z)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onResume_Z, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onResume", "(Z)V"), new JValue (p0));
}
static Delegate cb_postMessage_Ljava_lang_String_Ljava_lang_Object_;
#pragma warning disable 0169
static Delegate GetPostMessage_Ljava_lang_String_Ljava_lang_Object_Handler ()
{
if (cb_postMessage_Ljava_lang_String_Ljava_lang_Object_ == null)
cb_postMessage_Ljava_lang_String_Ljava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_PostMessage_Ljava_lang_String_Ljava_lang_Object_);
return cb_postMessage_Ljava_lang_String_Ljava_lang_Object_;
}
static IntPtr n_PostMessage_Ljava_lang_String_Ljava_lang_Object_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Object p1 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_p1, JniHandleOwnership.DoNotTransfer);
IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.PostMessage (p0, p1));
return __ret;
}
#pragma warning restore 0169
static IntPtr id_postMessage_Ljava_lang_String_Ljava_lang_Object_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='postMessage' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.Object']]"
[Register ("postMessage", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", "GetPostMessage_Ljava_lang_String_Ljava_lang_Object_Handler")]
public virtual global::Java.Lang.Object PostMessage (string p0, global::Java.Lang.Object p1)
{
if (id_postMessage_Ljava_lang_String_Ljava_lang_Object_ == IntPtr.Zero)
id_postMessage_Ljava_lang_String_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "postMessage", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
IntPtr native_p0 = JNIEnv.NewString (p0);
global::Java.Lang.Object __ret;
if (GetType () == ThresholdType)
__ret = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (Handle, id_postMessage_Ljava_lang_String_Ljava_lang_Object_, new JValue (native_p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef);
else
__ret = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "postMessage", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;"), new JValue (native_p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef);
JNIEnv.DeleteLocalRef (native_p0);
return __ret;
}
static Delegate cb_setPluginEntries_Ljava_util_List_;
#pragma warning disable 0169
static Delegate GetSetPluginEntries_Ljava_util_List_Handler ()
{
if (cb_setPluginEntries_Ljava_util_List_ == null)
cb_setPluginEntries_Ljava_util_List_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetPluginEntries_Ljava_util_List_);
return cb_setPluginEntries_Ljava_util_List_;
}
static void n_SetPluginEntries_Ljava_util_List_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
System.Collections.Generic.IList<Org.Apache.Cordova.PluginEntry> p0 = global::Android.Runtime.JavaList<global::Org.Apache.Cordova.PluginEntry>.FromJniHandle (native_p0, JniHandleOwnership.DoNotTransfer);
__this.SetPluginEntries (p0);
}
#pragma warning restore 0169
static IntPtr id_setPluginEntries_Ljava_util_List_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='setPluginEntries' and count(parameter)=1 and parameter[1][@type='java.util.List']]"
[Register ("setPluginEntries", "(Ljava/util/List;)V", "GetSetPluginEntries_Ljava_util_List_Handler")]
public virtual void SetPluginEntries (global::System.Collections.Generic.IList<global::Org.Apache.Cordova.PluginEntry> p0)
{
if (id_setPluginEntries_Ljava_util_List_ == IntPtr.Zero)
id_setPluginEntries_Ljava_util_List_ = JNIEnv.GetMethodID (class_ref, "setPluginEntries", "(Ljava/util/List;)V");
IntPtr native_p0 = global::Android.Runtime.JavaList<global::Org.Apache.Cordova.PluginEntry>.ToLocalJniHandle (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setPluginEntries_Ljava_util_List_, new JValue (native_p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setPluginEntries", "(Ljava/util/List;)V"), new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
}
static Delegate cb_startupPlugins;
#pragma warning disable 0169
static Delegate GetStartupPluginsHandler ()
{
if (cb_startupPlugins == null)
cb_startupPlugins = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_StartupPlugins);
return cb_startupPlugins;
}
static void n_StartupPlugins (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.PluginManager __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginManager> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.StartupPlugins ();
}
#pragma warning restore 0169
static IntPtr id_startupPlugins;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='PluginManager']/method[@name='startupPlugins' and count(parameter)=0]"
[Register ("startupPlugins", "()V", "GetStartupPluginsHandler")]
public virtual void StartupPlugins ()
{
if (id_startupPlugins == IntPtr.Zero)
id_startupPlugins = JNIEnv.GetMethodID (class_ref, "startupPlugins", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_startupPlugins);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "startupPlugins", "()V"));
}
}
}
| |
//
// System.Data.Odbc.OdbcCommand
//
// Authors:
// Brian Ritchie (brianlritchie@hotmail.com)
//
// Copyright (C) Brian Ritchie, 2002
//
//
// Copyright (C) 2004 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.ComponentModel;
using System.Data;
using System.Data.Common;
#if NET_2_0
using System.Data.ProviderBase;
#endif // NET_2_0
using System.Collections;
using System.Runtime.InteropServices;
namespace System.Data.Odbc
{
/// <summary>
/// Represents an SQL statement or stored procedure to execute against a data source.
/// </summary>
[DesignerAttribute ("Microsoft.VSDesigner.Data.VS.OdbcCommandDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
[ToolboxItemAttribute ("System.Drawing.Design.ToolboxItem, "+ Consts.AssemblySystem_Drawing)]
#if NET_2_0
public sealed class OdbcCommand : DbCommandBase, ICloneable
#else
public sealed class OdbcCommand : Component, ICloneable, IDbCommand
#endif //NET_2_0
{
#region Fields
#if ONLY_1_1
string commandText;
int timeout;
CommandType commandType;
#endif // ONLY_1_1
OdbcConnection connection;
OdbcTransaction transaction;
OdbcParameterCollection _parameters;
bool designTimeVisible;
bool prepared=false;
OdbcDataReader dataReader;
IntPtr hstmt;
#endregion // Fields
#region Constructors
public OdbcCommand ()
{
this.CommandText = String.Empty;
this.CommandTimeout = 30; // default timeout
this.CommandType = CommandType.Text;
Connection = null;
_parameters = new OdbcParameterCollection ();
Transaction = null;
designTimeVisible = false;
dataReader = null;
}
public OdbcCommand (string cmdText) : this ()
{
CommandText = cmdText;
}
public OdbcCommand (string cmdText, OdbcConnection connection)
: this (cmdText)
{
Connection = connection;
}
public OdbcCommand (string cmdText,
OdbcConnection connection,
OdbcTransaction transaction) : this (cmdText, connection)
{
this.Transaction = transaction;
}
#endregion // Constructors
#region Properties
internal IntPtr hStmt
{
get { return hstmt; }
}
#if ONLY_1_1
[OdbcCategory ("Data")]
[DefaultValue ("")]
[OdbcDescriptionAttribute ("Command text to execute")]
[EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
[RefreshPropertiesAttribute (RefreshProperties.All)]
public string CommandText
{
get {
return commandText;
}
set {
prepared=false;
commandText = value;
}
}
#else
[OdbcCategory ("Data")]
[DefaultValue ("")]
[OdbcDescriptionAttribute ("Command text to execute")]
[EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
[RefreshPropertiesAttribute (RefreshProperties.All)]
public override string CommandText
{
get {
return base.CommandText;
}
set {
prepared=false;
base.CommandText = value;
}
}
#endif // ONLY_1_1
#if ONLY_1_1
[OdbcDescriptionAttribute ("Time to wait for command to execute")]
[DefaultValue (30)]
public int CommandTimeout {
get {
return timeout;
}
set {
timeout = value;
}
}
[OdbcCategory ("Data")]
[DefaultValue ("Text")]
[OdbcDescriptionAttribute ("How to interpret the CommandText")]
[RefreshPropertiesAttribute (RefreshProperties.All)]
public CommandType CommandType {
get {
return commandType;
}
set {
commandType = value;
}
}
[OdbcCategory ("Behavior")]
[OdbcDescriptionAttribute ("Connection used by the command")]
[DefaultValue (null)]
[EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
public OdbcConnection Connection {
get {
return connection;
}
set {
connection = value;
}
}
#endif // ONLY_1_1
#if NET_2_0
public new OdbcConnection Connection
{
get { return DbConnection as OdbcConnection; }
set { DbConnection = value; }
}
#endif // NET_2_0
#if ONLY_1_1
[BrowsableAttribute (false)]
[DesignOnlyAttribute (true)]
[DefaultValue (true)]
public bool DesignTimeVisible {
get {
return designTimeVisible;
}
set {
designTimeVisible = value;
}
}
#endif // ONLY_1_1
[OdbcCategory ("Data")]
[OdbcDescriptionAttribute ("The parameters collection")]
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
public
#if NET_2_0
new
#endif // NET_2_0
OdbcParameterCollection Parameters {
get {
#if ONLY_1_1
return _parameters;
#else
return base.Parameters as OdbcParameterCollection;
#endif // ONLY_1_1
}
}
[BrowsableAttribute (false)]
[OdbcDescriptionAttribute ("The transaction used by the command")]
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
public
#if NET_2_0
new
#endif // NET_2_0
OdbcTransaction Transaction {
get {
return transaction;
}
set {
transaction = value;
}
}
#if ONLY_1_1
[OdbcCategory ("Behavior")]
[DefaultValue (UpdateRowSource.Both)]
[OdbcDescriptionAttribute ("When used by a DataAdapter.Update, how command results are applied to the current DataRow")]
public UpdateRowSource UpdatedRowSource {
[MonoTODO]
get {
throw new NotImplementedException ();
}
[MonoTODO]
set {
throw new NotImplementedException ();
}
}
IDbConnection IDbCommand.Connection {
get {
return Connection;
}
set {
Connection = (OdbcConnection) value;
}
}
#endif // ONLY_1_1
#if NET_2_0
protected override DbConnection DbConnection
{
get { return connection; }
set {
connection = (OdbcConnection) value;
}
}
#endif // NET_2_0
#if ONLY_1_1
IDataParameterCollection IDbCommand.Parameters {
get {
return Parameters;
}
}
#else
protected override DbParameterCollection DbParameterCollection
{
get { return _parameters as DbParameterCollection;}
}
#endif // NET_2_0
#if ONLY_1_1
IDbTransaction IDbCommand.Transaction {
get {
return (IDbTransaction) Transaction;
}
set {
if (value is OdbcTransaction)
{
Transaction = (OdbcTransaction)value;
}
else
{
throw new ArgumentException ();
}
}
}
#else
protected override DbTransaction DbTransaction
{
get { return transaction; }
set {
transaction = (OdbcTransaction)value;
}
}
#endif // ONLY_1_1
#endregion // Properties
#region Methods
public
#if NET_2_0
override
#endif // NET_2_0
void Cancel ()
{
if (hstmt!=IntPtr.Zero)
{
OdbcReturn Ret=libodbc.SQLCancel(hstmt);
if ((Ret!=OdbcReturn.Success) && (Ret!=OdbcReturn.SuccessWithInfo))
throw new OdbcException(new OdbcError("SQLCancel",OdbcHandleType.Stmt,hstmt));
}
else
throw new InvalidOperationException();
}
#if ONLY_1_1
IDbDataParameter IDbCommand.CreateParameter ()
{
return CreateParameter ();
}
public OdbcParameter CreateParameter ()
{
return new OdbcParameter ();
}
#else
protected override DbParameter CreateDbParameter ()
{
return CreateParameter ();
}
#endif // ONLY_1_1
[MonoTODO]
protected override void Dispose (bool disposing)
{
}
private void ExecSQL(string sql)
{
OdbcReturn ret;
if ((Parameters.Count>0) && !prepared)
Prepare();
if (prepared)
{
ret=libodbc.SQLExecute(hstmt);
if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
throw new OdbcException(new OdbcError("SQLExecute",OdbcHandleType.Stmt,hstmt));
}
else
{
ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt, Connection.hDbc, ref hstmt);
if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
throw new OdbcException(new OdbcError("SQLAllocHandle",OdbcHandleType.Dbc,Connection.hDbc));
ret=libodbc.SQLExecDirect(hstmt, sql, sql.Length);
if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
throw new OdbcException(new OdbcError("SQLExecDirect",OdbcHandleType.Stmt,hstmt));
}
}
public
#if NET_2_0
override
#endif // NET_2_0
int ExecuteNonQuery ()
{
return ExecuteNonQuery (true);
}
private int ExecuteNonQuery (bool freeHandle)
{
int records = 0;
if (Connection == null)
throw new InvalidOperationException ();
if (Connection.State == ConnectionState.Closed)
throw new InvalidOperationException ();
// FIXME: a third check is mentioned in .NET docs
ExecSQL(CommandText);
// .NET documentation says that except for INSERT, UPDATE and
// DELETE where the return value is the number of rows affected
// for the rest of the commands the return value is -1.
if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
(CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
(CommandText.ToUpper().IndexOf("DELETE")!=-1)) {
int numrows = 0;
OdbcReturn ret = libodbc.SQLRowCount(hstmt,ref numrows);
records = numrows;
}
else
records = -1;
if (freeHandle && !prepared) {
OdbcReturn ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, hstmt);
if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,hstmt));
}
return records;
}
public
#if NET_2_0
override
#endif // NET_2_0
void Prepare()
{
OdbcReturn ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt, Connection.hDbc, ref hstmt);
if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
throw new OdbcException(new OdbcError("SQLAllocHandle",OdbcHandleType.Dbc,Connection.hDbc));
ret=libodbc.SQLPrepare(hstmt, CommandText, CommandText.Length);
if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
throw new OdbcException(new OdbcError("SQLPrepare",OdbcHandleType.Stmt,hstmt));
int i=1;
foreach (OdbcParameter p in Parameters)
{
p.Bind(hstmt, i);
i++;
}
prepared=true;
}
public
#if NET_2_0
new
#endif // NET_2_0
OdbcDataReader ExecuteReader ()
{
return ExecuteReader (CommandBehavior.Default);
}
#if ONLY_1_1
IDataReader IDbCommand.ExecuteReader ()
{
return ExecuteReader ();
}
#else
protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
{
return ExecuteReader (behavior);
}
#endif // ONLY_1_1
public
#if NET_2_0
new
#endif // NET_2_0
OdbcDataReader ExecuteReader (CommandBehavior behavior)
{
ExecuteNonQuery(false);
dataReader=new OdbcDataReader(this,behavior);
return dataReader;
}
#if ONLY_1_1
IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
{
return ExecuteReader (behavior);
}
#endif // ONLY_1_1
#if ONLY_1_1
public object ExecuteScalar ()
{
object val = null;
OdbcDataReader reader=ExecuteReader();
try
{
if (reader.Read ())
val=reader[0];
}
finally
{
reader.Close();
}
return val;
}
#endif // ONLY_1_1
[MonoTODO]
object ICloneable.Clone ()
{
throw new NotImplementedException ();
}
public
#if NET_2_0
override
#endif // NET_2_0
void ResetCommandTimeout ()
{
CommandTimeout = 30;
}
#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 OLEDB.Test.ModuleCore;
using System.IO;
using System.Text;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
public partial class CReaderFactory : CFactory
{
//Enum defined for different API calls. This is superset of the actual reader types.
protected enum ReaderOverload
{
StreamReader,
StringReader,
FileStream,
MemoryStream,
CoreReader,
CustomReader
};
public enum ReadThru
{
XmlReader,
TextReader,
Stream
};
//The required objects that will be used during the variation processing.
private XmlReaderSettings _settings = new XmlReaderSettings();
private XmlReaderSettings _underlyingSettings = new XmlReaderSettings();
private Encoding _enc = null;
private Stream _stream = null;
private string _baseUri = null;
private TextReader _textReader = null;
private ReaderOverload _overload;
private XmlReader _factoryReader = null;
private XmlReader _underlyingReader = null;
protected short numEventHandlers = 0;
// Parse Optional data specific to reader tests.
protected override void PreTest()
{
SetupSettings();
Log("--Setup Settings Done");
SetupReadOverload();
Log("--Setup ReadOverload Done");
SetupEncoding();
Log("--Setup Encoding Done");
SetupBaseUri();
Log("--Setup BaseUri Done");
pstate = TestState.PreTest;
}
protected override void PostTest()
{
//Cleanup and release files you may hold.
if (_stream != null)
_stream.Dispose();
if (_textReader != null)
_textReader.Dispose();
if (_underlyingReader != null)
_underlyingReader.Dispose();
if (_factoryReader != null)
_factoryReader.Dispose();
pstate = TestState.Complete;
}
/// <summary>
/// This method will test the read based on different settings.
/// It will call the correct overload and set the state properly.
/// </summary>
protected override void Test()
{
CError.WriteLine("Testing : " + TestFileName);
string tempStr = null;
switch (_overload)
{
case ReaderOverload.StreamReader:
_textReader = new StreamReader(FilePathUtil.getStream(GetFile(TestFileName)));
CreateReader(ReadThru.TextReader);
break;
case ReaderOverload.StringReader:
StreamReader sr = new StreamReader(FilePathUtil.getStream(GetFile(TestFileName)));
tempStr = sr.ReadToEnd();
sr.Dispose();
_textReader = new StringReader(tempStr);
CreateReader(ReadThru.TextReader);
break;
case ReaderOverload.FileStream:
_stream = FilePathUtil.getStream(TestFileName);
CreateReader(ReadThru.Stream);
break;
case ReaderOverload.MemoryStream:
StreamReader sr1 = new StreamReader(FilePathUtil.getStream(GetFile(TestFileName)));
tempStr = sr1.ReadToEnd();
sr1.Dispose();
byte[] bits = _enc.GetBytes(tempStr);
_stream = new MemoryStream(bits);
CreateReader(ReadThru.Stream);
break;
case ReaderOverload.CoreReader:
_underlyingSettings.DtdProcessing = DtdProcessing.Ignore;
_underlyingSettings.ConformanceLevel = _settings.ConformanceLevel;
StringReader strr = new StringReader(new StreamReader(FilePathUtil.getStream(GetFile(TestFileName))).ReadToEnd());
_underlyingReader = ReaderHelper.CreateReader(_overload.ToString(),
strr,
false,
null,
_underlyingSettings,
(_settings.ConformanceLevel == ConformanceLevel.Fragment)); //should this be settings or underlyingSettings?
CError.Compare(_underlyingReader != null, "ReaderHelper returned null Reader");
CreateReader(ReadThru.XmlReader);
break;
case ReaderOverload.CustomReader:
if (AsyncUtil.IsAsyncEnabled)
{
pstate = TestState.Skip;
return;
}
if (_settings.ConformanceLevel != ConformanceLevel.Fragment)
_underlyingReader = new CustomReader(FilePathUtil.getStream(GetFile(TestFileName)), false);
else
_underlyingReader = new CustomReader(FilePathUtil.getStream(GetFile(TestFileName)), true);
CError.Compare(_underlyingReader != null, "ReaderHelper returned null Reader");
CreateReader(ReadThru.XmlReader);
break;
default:
throw new CTestFailedException("Unknown ReaderOverload: " + _overload);
}
if (_underlyingReader != null)
CError.WriteLineIgnore("Type of Reader : " + _underlyingReader.GetType());
if (pstate == TestState.Pass) return;
CError.Compare(pstate, TestState.CreateSuccess, "Invalid State after Create: " + pstate);
//By this time the factory Reader is already set up correctly. So we must go Consume it now.
CError.Compare(pstate != TestState.Pass && pstate == TestState.CreateSuccess, "Invalid state before Consuming Reader: " + pstate);
//Call TestReader to Consume Reader;
TestReader();
if (pstate == TestState.Pass) return;
CError.Compare(pstate != TestState.Pass && pstate == TestState.Consume, "Invalid state after Consuming Reader: " + pstate);
}
protected void TestReader()
{
pstate = TestState.Consume;
try
{
ConsumeReader(_factoryReader);
if (!IsVariationValid)
{
//Invalid Case didn't throw exception.
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException("Invalid Variation didn't throw exception");
}
else
{
pstate = TestState.Pass;
}
}
finally
{
if (_factoryReader != null)
_factoryReader.Dispose();
}
//If you are not in PASS state at this point you are in Error.
if (pstate != TestState.Pass)
pstate = TestState.Error;
}
protected void CompareSettings()
{
Log("Comparing ErrorSettings");
XmlReaderSettings actual = _factoryReader.Settings;
if (actual == null)
throw new CTestFailedException("Factory Reader Settings returned null");
CError.Compare(actual.CheckCharacters, _settings.CheckCharacters, "CheckCharacters");
CError.Compare(actual.IgnoreComments, _settings.IgnoreComments, "IgnoreComments");
CError.Compare(actual.IgnoreProcessingInstructions, _settings.IgnoreProcessingInstructions, "IgnorePI");
CError.Compare(actual.IgnoreWhitespace, _settings.IgnoreWhitespace, "IgnoreWhitespace");
CError.Compare(actual.LineNumberOffset, _settings.LineNumberOffset, "LinenumberOffset");
CError.Compare(actual.LinePositionOffset, _settings.LinePositionOffset, "LinePositionOffset");
}
protected void ConsumeReader(XmlReader reader)
{
while (reader.Read())
{
string x = reader.Name + reader.NodeType + reader.Value;
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.HasAttributes)
{
reader.MoveToFirstAttribute();
int index = 0;
reader.MoveToAttribute(index);
index++;
while (reader.MoveToNextAttribute())
{
string name = reader.Name;
string value;
value = reader.GetAttribute(index);
value = reader.GetAttribute(name);
value = reader.GetAttribute(name, null);
reader.ReadAttributeValue();
reader.MoveToAttribute(index);
reader.MoveToAttribute(name, null);
index++;
}
}
}
if (reader.NodeType == XmlNodeType.EndElement)
{
reader.Skip();
}
}
}
/// <summary>
/// This method calls the Create Method on the XmlReader and puts the state in CreateSuccess or TestPass.
/// It goes in PASS also if the reader threw an expected error. In all other cases it should throw
/// TestFailedException.
/// </summary>
/// <param name="readThru">This param determines which overload to call.
/// In future on multiple overloads we can make this param
/// an enum which can be set using the spec file data</param>
protected void CreateReader(ReadThru readThru)
{
// Assumption is that the Create method doesn't throw NullReferenceException and
// it is not the goal of this framework to test if they are thrown anywhere.
// but if they are thrown that's a problem and they shouldn't be caught but exposed.
try
{
switch (readThru)
{
case ReadThru.TextReader:
_factoryReader = ReaderHelper.Create(_textReader, _settings, _baseUri);
break;
case ReadThru.XmlReader:
_factoryReader = ReaderHelper.Create(_underlyingReader, _settings);
break;
case ReadThru.Stream:
_factoryReader = ReaderHelper.Create(_stream, _settings);
break;
default:
throw new CTestFailedException("Unknown ReadThru type: " + readThru);
}
pstate = TestState.CreateSuccess;
}
catch (ArgumentNullException ane)
{
Log(ane.Message);
Log(ane.StackTrace);
if (!IsVariationValid)
{
if (!CheckException(ane))
{
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException(
"Argument Null Exception Thrown in CreateMethod, is your variation data correct?");
}
else
{
//This means that the Exception was checked and everything is fine.
pstate = TestState.Pass;
}
}
else
{
pstate = TestState.Error;
DumpVariationInfo();
throw new CTestFailedException(
"Argument Null Exception Thrown in CreateMethod, is your variation data correct?");
}
}
}
/// <summary>
/// Setup Settings basically reads the variation info and populates the info block.
/// <ConformanceLevel>Fragment</ConformanceLevel>
/// <CheckCharacters>true</CheckCharacters>
/// <ReaderType>Dtd</ReaderType>
/// <NameTable>new</NameTable>
/// <LineNumberOffset>1</LineNumberOffset>
/// <LinePositionOffset>0</LinePositionOffset>
/// <IgnoreInlineSchema>false</IgnoreInlineSchema>
/// <IgnoreSchemaLocation>true</IgnoreSchemaLocation>
/// <IgnoreIdentityConstraints>false</IgnoreIdentityConstraints>
/// <IgnoreValidationWarnings>true</IgnoreValidationWarnings>
/// <Schemas>2</Schemas>
/// <ValidationEventHandler>0</ValidationEventHandler>
/// <ProhibitDtd>true</ProhibitDtd>
/// <IgnoreWS>false</IgnoreWS>
/// <IgnorePI>true</IgnorePI>
/// <IgnoreCS>true</IgnoreCS>
/// </summary>
private void SetupSettings()
{
_settings = new XmlReaderSettings();
_callbackWarningCount1 = 0;
_callbackWarningCount2 = 0;
_callbackErrorCount1 = 0;
_callbackErrorCount2 = 0;
//Conformance Level
_settings.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), ReadFilterCriteria("ConformanceLevel", true));
//CheckCharacters
_settings.CheckCharacters = Boolean.Parse(ReadFilterCriteria("CheckCharacters", true));
//Reader Type : Parse and then set the Xsd or Dtd validation accordingly.
string readertype = ReadFilterCriteria("ReaderType", true);
switch (readertype)
{
case "Dtd":
case "Xsd":
case "Binary":
throw new CTestSkippedException("Skipped: ReaderType " + readertype);
case "Core":
break;
default:
throw new CTestFailedException("Unexpected ReaderType Criteria");
}
//Nametable
string nt = ReadFilterCriteria("NameTable", true);
switch (nt)
{
case "new":
_settings.NameTable = new NameTable();
break;
case "null":
_settings.NameTable = null;
break;
case "custom":
_settings.NameTable = new MyNameTable();
break;
default:
throw new CTestFailedException("Unexpected Nametable Criteria : " + nt);
}
//Line number
_settings.LineNumberOffset = Int32.Parse(ReadFilterCriteria("LineNumberOffset", true));
//Line position
_settings.LinePositionOffset = Int32.Parse(ReadFilterCriteria("LinePositionOffset", true));
_settings.IgnoreProcessingInstructions = Boolean.Parse(ReadFilterCriteria("IgnorePI", true));
_settings.IgnoreComments = Boolean.Parse(ReadFilterCriteria("IgnoreComments", true));
_settings.IgnoreWhitespace = Boolean.Parse(ReadFilterCriteria("IgnoreWhiteSpace", true));
}//End of SetupSettings
//Validation Event Handlers and their Counts for Reader to verify
private int _callbackWarningCount1 = 0;
private int _callbackWarningCount2 = 0;
private int _callbackErrorCount1 = 0;
private int _callbackErrorCount2 = 0;
public int EventWarningCount1
{
get { return _callbackWarningCount1; }
}
public int EventWarningCount2
{
get { return _callbackWarningCount2; }
}
public int EventErrorCount1
{
get { return _callbackErrorCount1; }
}
public int EventErrorCount2
{
get { return _callbackErrorCount2; }
}
/// <summary>
/// Sets up the Correct Read Overload Method to be called.
/// </summary>
public void SetupReadOverload()
{
string ol = ReadFilterCriteria("Load", true);
if (ol == "HTTPStream" || ol == "FileName" || ol == "XmlTextReader" || ol == "XmlValidatingReader" || ol == "CoreValidatingReader"
|| ol == "CoreXsdReader" || ol == "XmlBinaryReader" || ol == "XPathNavigatorReader" || ol == "XmlNodeReader" || ol == "XmlNodeReaderDD"
|| ol == "XsltReader")
{
throw new CTestSkippedException("Skipped: OverLoad " + ol);
}
_overload = (ReaderOverload)Enum.Parse(typeof(ReaderOverload), ol);
}
public void SetupBaseUri()
{
string bUri = ReadFilterCriteria("BaseUri", true);
switch (bUri)
{
case "valid":
_baseUri = GetPath(TestFileName, false);
Log("Setting baseuri = " + _baseUri);
break;
case "~null":
break;
default:
_baseUri = "";
break;
}
}
public void SetupEncoding()
{
string strEnc = ReadFilterCriteria("Encoding", true);
if (strEnc != "~null")
_enc = Encoding.GetEncoding(strEnc);
}
//Custom Nametable
public class MyNameTable : XmlNameTable
{
private NameTable _nt = new NameTable();
public override string Get(string array)
{
return _nt.Get(array);
}
public override string Get(char[] array, int offset, int length)
{
return _nt.Get(array, offset, length);
}
public override string Add(string array)
{
return _nt.Add(array);
}
public override string Add(char[] array, int offset, int length)
{
return _nt.Add(array, offset, length);
}
}
}
}
| |
// ORIGINAL SOURCES > http://ncase.me/sight-and-light/
// Converted to Unity > http://unitycoder.com/blog/2014/10/12/2d-visibility-shadow-for-unity-indie/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Visibility2D
{
public class ShadowCasting2D : MonoBehaviour
{
List<Segment2D> segments = new List<Segment2D>(); // wall line segments
List<float> uniqueAngles = new List<float>(); // wall angles
List<Vector3> uniquePoints = new List<Vector3>(); // wall points
List<Intersection> intersects = new List<Intersection>(); // returned line intersects
Mesh lightMesh;
MeshFilter meshFilter;
GameObject go;
// DEBUGGING
// System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
//public GUIText stats;
// INIT
void Awake()
{
lightMesh = new Mesh();
meshFilter = GetComponent<MeshFilter>();
CollectVertices ();
} // Awake
// Main loop
void Update ()
{
// DEBUGGING
//stopwatch.Start();
// Get mouse position
Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,10));
// Move "player" to mouse position
transform.position = mousePos;
// Get all angles
uniqueAngles.Clear();
for(var j=0;j<uniquePoints.Count;j++)
{
float angle = Mathf.Atan2(uniquePoints[j].y-mousePos.y,uniquePoints[j].x-mousePos.x);
uniqueAngles.Add(angle-0.00001f);
uniqueAngles.Add(angle);
uniqueAngles.Add(angle+0.00001f);
}
// Rays in all directions
intersects.Clear();
for(var j=0;j<uniqueAngles.Count;j++)
{
float angle = uniqueAngles[j];
// Calculate dx & dy from angle
float dx = Mathf.Cos(angle);
float dy = Mathf.Sin(angle);
// Ray from center of screen to mouse
Ray2D ray = new Ray2D(new Vector2(mousePos.x,mousePos.y), new Vector2(mousePos.x+dx,mousePos.y+dy));
// Find CLOSEST intersection
Intersection closestIntersect = new Intersection();
bool founded = false;
for(int i=0;i<segments.Count;i++)
{
Intersection intersect = getIntersection(ray,segments[i]);
if(intersect.v==null) continue;
// if(!closestIntersect.v==null || intersect.angle<closestIntersect.angle)
if(!founded || intersect.angle<closestIntersect.angle)
{
founded = true;
closestIntersect=intersect;
}
} // for segments
// Intersect angle
if(closestIntersect==null) continue;
closestIntersect.angle = angle;
// Add to list of intersects
intersects.Add(closestIntersect);
} // for uniqueAngles
// Sort intersects by angle
intersects.Sort((x, y) =>{ return Comparer<float?>.Default.Compare(x.angle, y.angle); });
// Mesh generation
List<Vector3> verts = new List<Vector3>();
List<int> tris = new List<int>();
verts.Clear();
tris.Clear();
// TODO: UV's
// Place first vertex at mouse position ("dummy triangulation")
verts.Add(transform.InverseTransformPoint(transform.position));
for(var i=0;i<intersects.Count;i++)
{
if (intersects[i].v!=null)
{
verts.Add(transform.InverseTransformPoint((Vector3)intersects[i].v));
verts.Add(transform.InverseTransformPoint((Vector3)intersects[(i+1) % intersects.Count].v));
//GLDebug.DrawLine((Vector3)intersects[i].v,(Vector3)intersects[(i+1) % intersects.Count].v,Color.red,0,false);
}
} // for intersects
// Build triangle list
for(var i=0;i<verts.Count+1;i++)
{
tris.Add((i+1) % verts.Count);
tris.Add((i) % verts.Count);
tris.Add(0);
}
// Create mesh
lightMesh.Clear();
lightMesh.vertices = verts.ToArray();
lightMesh.triangles = tris.ToArray();
lightMesh.RecalculateNormals(); // FIXME: no need if no lights..or just assign fixed value..
meshFilter.mesh = lightMesh;
// Debug lines from mouse to intersection
/*
for(var i=0;i<intersects.Count;i++)
{
if (intersects[i].v!=null)
{
GLDebug.DrawLine(new Vector3(mousePos.x,mousePos.y,0),(Vector3)intersects[i].v,Color.red,0,false);
}
}
*/
// DEBUG TIMER
//stopwatch.Stop();
//Debug.Log("Stopwatch: " + stopwatch.Elapsed);
// Debug.Log("Stopwatch: " + stopwatch.ElapsedMilliseconds);
//stats.text = ""+stopwatch.ElapsedMilliseconds+"ms";
//stopwatch.Reset();
} // Update
void CollectVertices ()
{
// Collect all gameobjects, with tag Wall
GameObject[] gos = GameObject.FindGameObjectsWithTag("Wall");
// Get all vertices from those gameobjects
// WARNING: Should only use 2D objects, like unity Quads for now..
foreach (GameObject go in gos)
{
Mesh goMesh = go.GetComponent<MeshFilter>().mesh;
int[] tris = goMesh.triangles;
List<int> uniqueTris = new List<int>();
uniqueTris.Clear();
// Collect unique tri's
for (int i = 0; i < tris.Length; i++)
{
if (!uniqueTris.Contains(tris[i]))
{
uniqueTris.Add(tris[i]);
}
} // for tris
// Sort by pseudoangle
List<pseudoObj> all = new List<pseudoObj>();
for (int n=0;n<uniqueTris.Count;n++)
{
float x= goMesh.vertices[uniqueTris[n]].x;
float y= goMesh.vertices[uniqueTris[n]].y;
float a = copysign(1-x/(Mathf.Abs (x)+Mathf.Abs(y)),y);
pseudoObj o = new pseudoObj();
o.pAngle = a;
o.point = goMesh.vertices[uniqueTris[n]];
all.Add(o);
}
// Actual sorting
all.Sort(delegate(pseudoObj c1, pseudoObj c2) { return c1.pAngle.CompareTo(c2.pAngle); });
// Get unique vertices to list
List<Vector3> uniqueVerts = new List<Vector3>();
uniqueTris.Clear();
for (int n=0;n<all.Count;n++)
{
uniqueVerts.Add(all[n].point);
}
// Add world borders
int tempRange = 990;
Camera cam = Camera.main;
Vector3 b1 = cam.ScreenToWorldPoint(new Vector3(-tempRange, -tempRange, Camera.main.nearClipPlane + 0.1f+tempRange)); // bottom left
Vector3 b2 = cam.ScreenToWorldPoint(new Vector3(-tempRange, cam.pixelHeight+tempRange, cam.nearClipPlane + 0.1f+tempRange)); // top left
Vector3 b3 = cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth+tempRange, cam.pixelHeight, cam.nearClipPlane + 0.1f+tempRange)); // top right
Vector3 b4 = cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth+tempRange, -tempRange, cam.nearClipPlane + 0.1f+tempRange)); // bottom right
// Get world borders as vertices
Segment2D seg1 = new Segment2D();
seg1.a = new Vector2(b1.x,b1.y);
seg1.b = new Vector2(b2.x,b2.y);
segments.Add(seg1);
seg1.a = new Vector2(b2.x,b2.y);
seg1.b = new Vector2(b3.x,b3.y);
segments.Add(seg1);
seg1.a = new Vector2(b3.x,b3.y);
seg1.b = new Vector2(b4.x,b4.y);
segments.Add(seg1);
seg1.a = new Vector2(b4.x,b4.y);
seg1.b = new Vector2(b1.x,b1.y);
segments.Add(seg1);
// Get segments from unique vertices
for (int n=0;n<uniqueVerts.Count;n++)
{
// Segment start
Vector3 wPos1 = go.transform.TransformPoint(uniqueVerts[n]);
// Segment end
Vector3 wPos2 = go.transform.TransformPoint(uniqueVerts[(n+1) % uniqueVerts.Count]);
// TODO: duplicate of unique verts?
uniquePoints.Add(wPos1);
Segment2D seg = new Segment2D();
seg.a = new Vector2(wPos1.x,wPos1.y);
seg.b = new Vector2(wPos2.x, wPos2.y);
segments.Add(seg);
//GLDebug.DrawLine(wPos1, wPos2,Color.white,10);
}
} // foreach gameobject
} // CollectVertices
// Find intersection of RAY & SEGMENT
Intersection getIntersection(Ray2D ray, Segment2D segment)
{
Intersection o = new Intersection();
// RAY in parametric: Point + Delta*T1
float r_px = ray.a.x;
float r_py = ray.a.y;
float r_dx = ray.b.x-ray.a.x;
float r_dy = ray.b.y-ray.a.y;
// SEGMENT in parametric: Point + Delta*T2
float s_px = segment.a.x;
float s_py = segment.a.y;
float s_dx = segment.b.x-segment.a.x;
float s_dy = segment.b.y-segment.a.y;
// Are they parallel? If so, no intersect
var r_mag = Mathf.Sqrt(r_dx*r_dx+r_dy*r_dy);
var s_mag = Mathf.Sqrt(s_dx*s_dx+s_dy*s_dy);
if(r_dx/r_mag==s_dx/s_mag && r_dy/r_mag==s_dy/s_mag) // Unit vectors are the same
{
return o;
}
// SOLVE FOR T1 & T2
// r_px+r_dx*T1 = s_px+s_dx*T2 && r_py+r_dy*T1 = s_py+s_dy*T2
// ==> T1 = (s_px+s_dx*T2-r_px)/r_dx = (s_py+s_dy*T2-r_py)/r_dy
// ==> s_px*r_dy + s_dx*T2*r_dy - r_px*r_dy = s_py*r_dx + s_dy*T2*r_dx - r_py*r_dx
// ==> T2 = (r_dx*(s_py-r_py) + r_dy*(r_px-s_px))/(s_dx*r_dy - s_dy*r_dx)
var T2 = (r_dx*(s_py-r_py) + r_dy*(r_px-s_px))/(s_dx*r_dy - s_dy*r_dx);
var T1 = (s_px+s_dx*T2-r_px)/r_dx;
// Must be within parametic whatevers for RAY/SEGMENT
if(T1<0) return o;
if(T2<0 || T2>1) return o;
o.v = new Vector3(r_px+r_dx*T1, r_py+r_dy*T1, 0);
o.angle = T1;
// Return the POINT OF INTERSECTION
return o;
} // getIntersection
// *** Helper functions ***
// http://stackoverflow.com/questions/16542042/fastest-way-to-sort-vectors-by-angle-without-actually-computing-that-angle
float pseudoAngle(float dx,float dy)
{
float ax = Mathf.Abs(dx);
float ay = Mathf.Abs(dy);
float p = dy/(ax+ay);
if (dx < 0) p = 2 - p;
//# elif dy < 0: p = 4 + p
return p;
}
// http://stackoverflow.com/a/1905142
// TODO: not likely needed to use this..
float copysign(float a,float b)
{
return (a*Mathf.Sign(b));
}
} // Class
} // Namespace
| |
// CRC32.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-August-02 18:25:54>
//
// ------------------------------------------------------------------
//
// This module defines the CRC32 class, which can do the CRC32 algorithm, using
// arbitrary starting polynomials, and bit reversal. The bit reversal is what
// distinguishes this CRC-32 used in BZip2 from the CRC-32 that is used in PKZIP
// files, or GZIP files. This class does both.
//
// ------------------------------------------------------------------
using System;
using Interop = System.Runtime.InteropServices;
namespace Ionic.Crc
{
/// <summary>
/// Computes a CRC-32. The CRC-32 algorithm is parameterized - you
/// can set the polynomial and enable or disable bit
/// reversal. This can be used for GZIP, BZip2, or ZIP.
/// </summary>
/// <remarks>
/// This type is used internally by DotNetZip; it is generally not used
/// directly by applications wishing to create, read, or manipulate zip
/// archive files.
/// </remarks>
public class CRC32
{
/// <summary>
/// Indicates the total number of bytes applied to the CRC.
/// </summary>
public Int64 TotalBytesRead
{
get
{
return _TotalBytesRead;
}
}
/// <summary>
/// Indicates the current CRC for all blocks slurped in.
/// </summary>
public Int32 Crc32Result
{
get
{
return unchecked((Int32)(~_register));
}
}
/// <summary>
/// Returns the CRC32 for the specified stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32(System.IO.Stream input)
{
return GetCrc32AndCopy(input, null);
}
/// <summary>
/// Returns the CRC32 for the specified stream, and writes the input into the
/// output stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <param name="output">The stream into which to deflate the input</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
{
if (input == null)
throw new Exception("The input stream must not be null.");
unchecked
{
byte[] buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
_TotalBytesRead = 0;
int count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
while (count > 0)
{
SlurpBlock(buffer, 0, count);
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
}
return (Int32)(~_register);
}
}
/// <summary>
/// Get the CRC32 for the given (word,byte) combo. This is a
/// computation defined by PKzip for PKZIP 2.0 (weak) encryption.
/// </summary>
/// <param name="W">The word to start with.</param>
/// <param name="B">The byte to combine it with.</param>
/// <returns>The CRC-ized result.</returns>
public Int32 ComputeCrc32(Int32 W, byte B)
{
return _InternalComputeCrc32((UInt32)W, B);
}
internal Int32 _InternalComputeCrc32(UInt32 W, byte B)
{
return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8));
}
/// <summary>
/// Update the value for the running CRC32 using the given block of bytes.
/// This is useful when using the CRC32() class in a Stream.
/// </summary>
/// <param name="block">block of bytes to slurp</param>
/// <param name="offset">starting point in the block</param>
/// <param name="count">how many bytes within the block to slurp</param>
public void SlurpBlock(byte[] block, int offset, int count)
{
if (block == null)
throw new Exception("The data buffer must not be null.");
// bzip algorithm
for (int i = 0; i < count; i++)
{
int x = offset + i;
byte b = block[x];
if (this.reverseBits)
{
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
}
_TotalBytesRead += count;
}
/// <summary>
/// Process one byte in the CRC.
/// </summary>
/// <param name = "b">the byte to include into the CRC . </param>
public void UpdateCRC(byte b)
{
if (this.reverseBits)
{
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
}
/// <summary>
/// Process a run of N identical bytes into the CRC.
/// </summary>
/// <remarks>
/// <para>
/// This method serves as an optimization for updating the CRC when a
/// run of identical bytes is found. Rather than passing in a buffer of
/// length n, containing all identical bytes b, this method accepts the
/// byte value and the length of the (virtual) buffer - the length of
/// the run.
/// </para>
/// </remarks>
/// <param name = "b">the byte to include into the CRC. </param>
/// <param name = "n">the number of times that byte should be repeated. </param>
public void UpdateCRC(byte b, int n)
{
while (n-- > 0)
{
if (this.reverseBits)
{
uint temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[(temp >= 0)
? temp
: (temp + 256)];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[(temp >= 0)
? temp
: (temp + 256)];
}
}
}
private static uint ReverseBits(uint data)
{
unchecked
{
uint ret = data;
ret = (ret & 0x55555555) << 1 | (ret >> 1) & 0x55555555;
ret = (ret & 0x33333333) << 2 | (ret >> 2) & 0x33333333;
ret = (ret & 0x0F0F0F0F) << 4 | (ret >> 4) & 0x0F0F0F0F;
ret = (ret << 24) | ((ret & 0xFF00) << 8) | ((ret >> 8) & 0xFF00) | (ret >> 24);
return ret;
}
}
private static byte ReverseBits(byte data)
{
unchecked
{
uint u = (uint)data * 0x00020202;
uint m = 0x01044010;
uint s = u & m;
uint t = (u << 2) & (m << 1);
return (byte)((0x01001001 * (s + t)) >> 24);
}
}
private void GenerateLookupTable()
{
crc32Table = new UInt32[256];
unchecked
{
UInt32 dwCrc;
byte i = 0;
do
{
dwCrc = i;
for (byte j = 8; j > 0; j--)
{
if ((dwCrc & 1) == 1)
{
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
}
else
{
dwCrc >>= 1;
}
}
if (reverseBits)
{
crc32Table[ReverseBits(i)] = ReverseBits(dwCrc);
}
else
{
crc32Table[i] = dwCrc;
}
i++;
} while (i!=0);
}
#if VERBOSE
Console.WriteLine();
Console.WriteLine("private static readonly UInt32[] crc32Table = {");
for (int i = 0; i < crc32Table.Length; i+=4)
{
Console.Write(" ");
for (int j=0; j < 4; j++)
{
Console.Write(" 0x{0:X8}U,", crc32Table[i+j]);
}
Console.WriteLine();
}
Console.WriteLine("};");
Console.WriteLine();
#endif
}
private uint gf2_matrix_times(uint[] matrix, uint vec)
{
uint sum = 0;
int i=0;
while (vec != 0)
{
if ((vec & 0x01)== 0x01)
sum ^= matrix[i];
vec >>= 1;
i++;
}
return sum;
}
private void gf2_matrix_square(uint[] square, uint[] mat)
{
for (int i = 0; i < 32; i++)
square[i] = gf2_matrix_times(mat, mat[i]);
}
/// <summary>
/// Combines the given CRC32 value with the current running total.
/// </summary>
/// <remarks>
/// This is useful when using a divide-and-conquer approach to
/// calculating a CRC. Multiple threads can each calculate a
/// CRC32 on a segment of the data, and then combine the
/// individual CRC32 values at the end.
/// </remarks>
/// <param name="crc">the crc value to be combined with this one</param>
/// <param name="length">the length of data the CRC value was calculated on</param>
public void Combine(int crc, int length)
{
uint[] even = new uint[32]; // even-power-of-two zeros operator
uint[] odd = new uint[32]; // odd-power-of-two zeros operator
if (length == 0)
return;
uint crc1= ~_register;
uint crc2= (uint) crc;
// put operator for one zero bit in odd
odd[0] = this.dwPolynomial; // the CRC-32 polynomial
uint row = 1;
for (int i = 1; i < 32; i++)
{
odd[i] = row;
row <<= 1;
}
// put operator for two zero bits in even
gf2_matrix_square(even, odd);
// put operator for four zero bits in odd
gf2_matrix_square(odd, even);
uint len2 = (uint) length;
// apply len2 zeros to crc1 (first square will put the operator for one
// zero byte, eight zero bits, in even)
do {
// apply zeros operator for this bit of len2
gf2_matrix_square(even, odd);
if ((len2 & 1)== 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
if (len2 == 0)
break;
// another iteration of the loop with odd and even swapped
gf2_matrix_square(odd, even);
if ((len2 & 1)==1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
} while (len2 != 0);
crc1 ^= crc2;
_register= ~crc1;
//return (int) crc1;
return;
}
/// <summary>
/// Create an instance of the CRC32 class using the default settings: no
/// bit reversal, and a polynomial of 0xEDB88320.
/// </summary>
public CRC32() : this(false)
{
}
/// <summary>
/// Create an instance of the CRC32 class, specifying whether to reverse
/// data bits or not.
/// </summary>
/// <param name='reverseBits'>
/// specify true if the instance should reverse data bits.
/// </param>
/// <remarks>
/// <para>
/// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
/// want a CRC32 with compatibility with BZip2, you should pass true
/// here. In the CRC-32 used by GZIP and PKZIP, the bits are not
/// reversed; Therefore if you want a CRC32 with compatibility with
/// those, you should pass false.
/// </para>
/// </remarks>
public CRC32(bool reverseBits) :
this( unchecked((int)0xEDB88320), reverseBits)
{
}
/// <summary>
/// Create an instance of the CRC32 class, specifying the polynomial and
/// whether to reverse data bits or not.
/// </summary>
/// <param name='polynomial'>
/// The polynomial to use for the CRC, expressed in the reversed (LSB)
/// format: the highest ordered bit in the polynomial value is the
/// coefficient of the 0th power; the second-highest order bit is the
/// coefficient of the 1 power, and so on. Expressed this way, the
/// polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320.
/// </param>
/// <param name='reverseBits'>
/// specify true if the instance should reverse data bits.
/// </param>
///
/// <remarks>
/// <para>
/// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
/// want a CRC32 with compatibility with BZip2, you should pass true
/// here for the <c>reverseBits</c> parameter. In the CRC-32 used by
/// GZIP and PKZIP, the bits are not reversed; Therefore if you want a
/// CRC32 with compatibility with those, you should pass false for the
/// <c>reverseBits</c> parameter.
/// </para>
/// </remarks>
public CRC32(int polynomial, bool reverseBits)
{
this.reverseBits = reverseBits;
this.dwPolynomial = (uint) polynomial;
this.GenerateLookupTable();
}
/// <summary>
/// Reset the CRC-32 class - clear the CRC "remainder register."
/// </summary>
/// <remarks>
/// <para>
/// Use this when employing a single instance of this class to compute
/// multiple, distinct CRCs on multiple, distinct data blocks.
/// </para>
/// </remarks>
public void Reset()
{
_register = 0xFFFFFFFFU;
}
// private member vars
private UInt32 dwPolynomial;
private Int64 _TotalBytesRead;
private bool reverseBits;
private UInt32[] crc32Table;
private const int BUFFER_SIZE = 8192;
private UInt32 _register = 0xFFFFFFFFU;
}
/// <summary>
/// A Stream that calculates a CRC32 (a checksum) on all bytes read,
/// or on all bytes written.
/// </summary>
///
/// <remarks>
/// <para>
/// This class can be used to verify the CRC of a ZipEntry when
/// reading from a stream, or to calculate a CRC when writing to a
/// stream. The stream should be used to either read, or write, but
/// not both. If you intermix reads and writes, the results are not
/// defined.
/// </para>
///
/// <para>
/// This class is intended primarily for use internally by the
/// DotNetZip library.
/// </para>
/// </remarks>
public class CrcCalculatorStream : System.IO.Stream, System.IDisposable
{
private static readonly Int64 UnsetLengthLimit = -99;
internal System.IO.Stream _innerStream;
private CRC32 _Crc32;
private Int64 _lengthLimit = -99;
private bool _leaveOpen;
/// <summary>
/// The default constructor.
/// </summary>
/// <remarks>
/// <para>
/// Instances returned from this constructor will leave the underlying
/// stream open upon Close(). The stream uses the default CRC32
/// algorithm, which implies a polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
public CrcCalculatorStream(System.IO.Stream stream)
: this(true, CrcCalculatorStream.UnsetLengthLimit, stream, null)
{
}
/// <summary>
/// The constructor allows the caller to specify how to handle the
/// underlying stream at close.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen)
: this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream, null)
{
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// <para>
/// Instances returned from this constructor will leave the underlying
/// stream open upon Close().
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length)
: this(true, length, stream, null)
{
if (length < 0)
throw new ArgumentException("length");
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read, as well as whether to keep the underlying stream open upon
/// Close().
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen)
: this(leaveOpen, length, stream, null)
{
if (length < 0)
throw new ArgumentException("length");
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read, as well as whether to keep the underlying stream open upon
/// Close(), and the CRC32 instance to use.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the specified CRC32 instance, which allows the
/// application to specify how the CRC gets calculated.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
/// <param name="crc32">the CRC32 instance to use to calculate the CRC32</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen,
CRC32 crc32)
: this(leaveOpen, length, stream, crc32)
{
if (length < 0)
throw new ArgumentException("length");
}
// This ctor is private - no validation is done here. This is to allow the use
// of a (specific) negative value for the _lengthLimit, to indicate that there
// is no length set. So we validate the length limit in those ctors that use an
// explicit param, otherwise we don't validate, because it could be our special
// value.
private CrcCalculatorStream
(bool leaveOpen, Int64 length, System.IO.Stream stream, CRC32 crc32)
: base()
{
_innerStream = stream;
_Crc32 = crc32 ?? new CRC32();
_lengthLimit = length;
_leaveOpen = leaveOpen;
}
/// <summary>
/// Gets the total number of bytes run through the CRC32 calculator.
/// </summary>
///
/// <remarks>
/// This is either the total number of bytes read, or the total number of
/// bytes written, depending on the direction of this stream.
/// </remarks>
public Int64 TotalBytesSlurped
{
get { return _Crc32.TotalBytesRead; }
}
/// <summary>
/// Provides the current CRC for all blocks slurped in.
/// </summary>
/// <remarks>
/// <para>
/// The running total of the CRC is kept as data is written or read
/// through the stream. read this property after all reads or writes to
/// get an accurate CRC for the entire stream.
/// </para>
/// </remarks>
public Int32 Crc
{
get { return _Crc32.Crc32Result; }
}
/// <summary>
/// Indicates whether the underlying stream will be left open when the
/// <c>CrcCalculatorStream</c> is Closed.
/// </summary>
/// <remarks>
/// <para>
/// Set this at any point before calling <see cref="Close()"/>.
/// </para>
/// </remarks>
public bool LeaveOpen
{
get { return _leaveOpen; }
set { _leaveOpen = value; }
}
/// <summary>
/// Read from the stream
/// </summary>
/// <param name="buffer">the buffer to read</param>
/// <param name="offset">the offset at which to start</param>
/// <param name="count">the number of bytes to read</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
int bytesToRead = count;
// Need to limit the # of bytes returned, if the stream is intended to have
// a definite length. This is especially useful when returning a stream for
// the uncompressed data directly to the application. The app won't
// necessarily read only the UncompressedSize number of bytes. For example
// wrapping the stream returned from OpenReader() into a StreadReader() and
// calling ReadToEnd() on it, We can "over-read" the zip data and get a
// corrupt string. The length limits that, prevents that problem.
if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit)
{
if (_Crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF
Int64 bytesRemaining = _lengthLimit - _Crc32.TotalBytesRead;
if (bytesRemaining < count) bytesToRead = (int)bytesRemaining;
}
int n = _innerStream.Read(buffer, offset, bytesToRead);
if (n > 0) _Crc32.SlurpBlock(buffer, offset, n);
return n;
}
/// <summary>
/// Write to the stream.
/// </summary>
/// <param name="buffer">the buffer from which to write</param>
/// <param name="offset">the offset at which to start writing</param>
/// <param name="count">the number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (count > 0) _Crc32.SlurpBlock(buffer, offset, count);
_innerStream.Write(buffer, offset, count);
}
/// <summary>
/// Indicates whether the stream supports reading.
/// </summary>
public override bool CanRead
{
get { return _innerStream.CanRead; }
}
/// <summary>
/// Indicates whether the stream supports seeking.
/// </summary>
/// <remarks>
/// <para>
/// Always returns false.
/// </para>
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream supports writing.
/// </summary>
public override bool CanWrite
{
get { return _innerStream.CanWrite; }
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
_innerStream.Flush();
}
/// <summary>
/// Returns the length of the underlying stream.
/// </summary>
public override long Length
{
get
{
if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit)
return _innerStream.Length;
else return _lengthLimit;
}
}
/// <summary>
/// The getter for this property returns the total bytes read.
/// If you use the setter, it will throw
/// <see cref="NotSupportedException"/>.
/// </summary>
public override long Position
{
get { return _Crc32.TotalBytesRead; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Seeking is not supported on this stream. This method always throws
/// <see cref="NotSupportedException"/>
/// </summary>
/// <param name="offset">N/A</param>
/// <param name="origin">N/A</param>
/// <returns>N/A</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws
/// <see cref="NotSupportedException"/>
/// </summary>
/// <param name="value">N/A</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
System.IO.Stream _innerStream = this._innerStream;
if (_innerStream != null)
{
try
{
if (!_leaveOpen)
_innerStream.Dispose();
}
finally
{
this._innerStream = null;
}
}
}
base.Dispose(disposing);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace Northwind
{
/// <summary>
/// Strongly-typed collection for the ProductCategoryMap class.
/// </summary>
[Serializable]
public partial class ProductCategoryMapCollection : ActiveList<ProductCategoryMap, ProductCategoryMapCollection>
{
public ProductCategoryMapCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ProductCategoryMapCollection</returns>
public ProductCategoryMapCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ProductCategoryMap o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Product_Category_Map table.
/// </summary>
[Serializable]
public partial class ProductCategoryMap : ActiveRecord<ProductCategoryMap>, IActiveRecord
{
#region .ctors and Default Settings
public ProductCategoryMap()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ProductCategoryMap(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ProductCategoryMap(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ProductCategoryMap(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Product_Category_Map", TableType.Table, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema);
colvarCategoryID.ColumnName = "CategoryID";
colvarCategoryID.DataType = DbType.Int32;
colvarCategoryID.MaxLength = 0;
colvarCategoryID.AutoIncrement = false;
colvarCategoryID.IsNullable = false;
colvarCategoryID.IsPrimaryKey = true;
colvarCategoryID.IsForeignKey = true;
colvarCategoryID.IsReadOnly = false;
colvarCategoryID.DefaultSetting = @"";
colvarCategoryID.ForeignKeyTableName = "Categories";
schema.Columns.Add(colvarCategoryID);
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 0;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = false;
colvarProductID.IsPrimaryKey = true;
colvarProductID.IsForeignKey = true;
colvarProductID.IsReadOnly = false;
colvarProductID.DefaultSetting = @"";
colvarProductID.ForeignKeyTableName = "Products";
schema.Columns.Add(colvarProductID);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Product_Category_Map",schema);
}
}
#endregion
#region Props
[XmlAttribute("CategoryID")]
[Bindable(true)]
public int CategoryID
{
get { return GetColumnValue<int>(Columns.CategoryID); }
set { SetColumnValue(Columns.CategoryID, value); }
}
[XmlAttribute("ProductID")]
[Bindable(true)]
public int ProductID
{
get { return GetColumnValue<int>(Columns.ProductID); }
set { SetColumnValue(Columns.ProductID, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a Category ActiveRecord object related to this ProductCategoryMap
///
/// </summary>
public Northwind.Category Category
{
get { return Northwind.Category.FetchByID(this.CategoryID); }
set { SetColumnValue("CategoryID", value.CategoryID); }
}
/// <summary>
/// Returns a Product ActiveRecord object related to this ProductCategoryMap
///
/// </summary>
public Northwind.Product Product
{
get { return Northwind.Product.FetchByID(this.ProductID); }
set { SetColumnValue("ProductID", value.ProductID); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varCategoryID,int varProductID)
{
ProductCategoryMap item = new ProductCategoryMap();
item.CategoryID = varCategoryID;
item.ProductID = varProductID;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varCategoryID,int varProductID)
{
ProductCategoryMap item = new ProductCategoryMap();
item.CategoryID = varCategoryID;
item.ProductID = varProductID;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn CategoryIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn ProductIDColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string CategoryID = @"CategoryID";
public static string ProductID = @"ProductID";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.